Method: Bitcoin::Key#initialize

Defined in:
lib/bitcoin/key.rb

#initialize(priv_key: nil, pubkey: nil, key_type: nil, compressed: true, allow_hybrid: false) ⇒ Bitcoin::Key

initialize private key

Parameters:

  • priv_key (String) (defaults to: nil)

    a private key with hex format.

  • pubkey (String) (defaults to: nil)

    a public key with hex format.

  • key_type (Integer) (defaults to: nil)

    a key type which determine address type.

  • compressed (Boolean) (defaults to: true)
    Deprecated

    whether public key is compressed.

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bitcoin/key.rb', line 32

def initialize(priv_key: nil, pubkey: nil, key_type: nil, compressed: true, allow_hybrid: false)
  if key_type
    @key_type = key_type
    compressed = @key_type != TYPES[:uncompressed]
  else
    if pubkey && compressed && pubkey.length != COMPRESSED_PUBLIC_KEY_SIZE * 2
      raise ArgumentError, "Invalid compressed pubkey length."
    end
    @key_type = compressed ? TYPES[:compressed] : TYPES[:uncompressed]
  end
  @secp256k1_module =  Bitcoin.secp_impl
  @priv_key = priv_key
  if @priv_key
    raise ArgumentError, 'Private key must be 32 bytes.' unless priv_key.htb.bytesize == 32
    raise ArgumentError, Errors::Messages::INVALID_PRIV_KEY unless validate_private_key_range(@priv_key)
  end
  if pubkey
    @pubkey = pubkey
  else
    @pubkey = generate_pubkey(priv_key, compressed: compressed) if priv_key
  end
  raise ArgumentError, Errors::Messages::INVALID_PUBLIC_KEY unless fully_valid_pubkey?(allow_hybrid)
end