class Tapyrus::Key

tapyrus key class

Constants

COMPACT_SIGNATURE_SIZE
COMPRESSED_PUBLIC_KEY_SIZE
MAX_PRIV_KEY_MOD_ORDER

Order of secp256k1's generator minus 1.

MIN_PRIV_KEY_MOD_ORDER
PUBLIC_KEY_SIZE
SIGNATURE_SIZE
SIG_ALGO
TYPES

Attributes

key_type[RW]
priv_key[RW]
pubkey[RW]
secp256k1_module[R]

Public Class Methods

compress_or_uncompress_pubkey?(pubkey) click to toggle source

check pubkey (hex) is compress or uncompress pubkey.

# File lib/tapyrus/key.rb, line 150
def self.compress_or_uncompress_pubkey?(pubkey)
  p = pubkey.htb
  return false if p.bytesize < COMPRESSED_PUBLIC_KEY_SIZE
  case p[0]
  when "\x04"
    return false unless p.bytesize == PUBLIC_KEY_SIZE
  when "\x02", "\x03"
    return false unless p.bytesize == COMPRESSED_PUBLIC_KEY_SIZE
  else
    return false
  end
  true
end
compress_pubkey?(pubkey) click to toggle source

check pubkey (hex) is compress pubkey.

# File lib/tapyrus/key.rb, line 165
def self.compress_pubkey?(pubkey)
  p = pubkey.htb
  p.bytesize == COMPRESSED_PUBLIC_KEY_SIZE && ["\x02", "\x03"].include?(p[0])
end
from_wif(wif) click to toggle source

import private key from wif format en.bitcoin.it/wiki/Wallet_import_format

# File lib/tapyrus/key.rb, line 61
def self.from_wif(wif)
  hex = Base58.decode(wif)
  raise ArgumentError, 'data is too short' if hex.htb.bytesize < 4
  version = hex[0..1]
  data = hex[2...-8].htb
  checksum = hex[-8..-1]
  raise ArgumentError, 'invalid version' unless version == Tapyrus.chain_params.privkey_version
  unless Tapyrus.calc_checksum(version + data.bth) == checksum
    raise ArgumentError, Errors::Messages::INVALID_CHECKSUM
  end
  key_len = data.bytesize
  if key_len == COMPRESSED_PUBLIC_KEY_SIZE && data[-1].unpack('C').first == 1
    key_type = TYPES[:compressed]
    data = data[0..-2]
  elsif key_len == 32
    key_type = TYPES[:uncompressed]
  else
    raise ArgumentError, 'Wrong number of bytes for a private key, not 32 or 33'
  end
  new(priv_key: data.bth, key_type: key_type)
end
generate(key_type = TYPES[:compressed]) click to toggle source

generate key pair

# File lib/tapyrus/key.rb, line 54
def self.generate(key_type = TYPES[:compressed])
  priv_key, pubkey = Tapyrus.secp_impl.generate_key_pair
  new(priv_key: priv_key, pubkey: pubkey, key_type: key_type)
end
low_signature?(sig) click to toggle source

check sig is low.

# File lib/tapyrus/key.rb, line 171
def self.low_signature?(sig)
  s = sig.unpack('C*')
  len_r = s[3]
  len_s = s[5 + len_r]
  val_s = s.slice(6 + len_r, len_s)

  # prettier-ignore
  max_mod_half_order = [
      0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
      0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
      0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d,
      0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b, 0x20, 0xa0
  ]
  compare_big_endian(val_s, [0]) > 0 && compare_big_endian(val_s, max_mod_half_order) <= 0
end
new(priv_key: nil, pubkey: nil, key_type: nil, compressed: true, allow_hybrid: false) click to toggle source

initialize private key @param [String] priv_key a private key with hex format. @param [String] pubkey a public key with hex format. @param [Integer] key_type a key type which determine address type. @param [Boolean] compressed [Deprecated] whether public key is compressed. @return [Tapyrus::Key] a key object.

# File lib/tapyrus/key.rb, line 32
def initialize(priv_key: nil, pubkey: nil, key_type: nil, compressed: true, allow_hybrid: false)
  if key_type.nil? && !compressed.nil? && pubkey.nil?
    puts '[Warning] Use key_type parameter instead of compressed. compressed parameter removed in the future.'
  end
  if key_type
    @key_type = key_type
    compressed = @key_type != TYPES[:uncompressed]
  else
    @key_type = compressed ? TYPES[:compressed] : TYPES[:uncompressed]
  end
  @secp256k1_module = Tapyrus.secp_impl
  @priv_key = priv_key
  raise ArgumentError, Errors::Messages::INVALID_PRIV_KEY unless validate_private_key_range(@priv_key) if @priv_key
  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
valid_signature_encoding?(sig, data_sig = false) click to toggle source

check sig is correct der encoding. This function is consensus-critical since BIP66. @param [String] sig a signature data with binary format. @param [Boolean] data_sig whether data signature or not. @return [Boolean] result

# File lib/tapyrus/key.rb, line 192
def self.valid_signature_encoding?(sig, data_sig = false)
  num_parts = data_sig ? 8 : 9
  size = data_sig ? 72 : 73

  return false if sig.bytesize < num_parts || sig.bytesize > size # Minimum and maximum size check

  s = sig.unpack('C*')

  return false if s[0] != 0x30 || s[1] != s.size - (data_sig ? 2 : 3) # A signature is of type 0x30 (compound). Make sure the length covers the entire signature.

  len_r = s[3]
  return false if 5 + len_r >= s.size # Make sure the length of the S element is still inside the signature.

  len_s = s[5 + len_r]
  return false unless len_r + len_s + (data_sig ? 6 : 7) == s.size #Verify that the length of the signature matches the sum of the length of the elements.

  return false unless s[2] == 0x02 # Check whether the R element is an integer.

  return false if len_r == 0 # Zero-length integers are not allowed for R.

  return false unless s[4] & 0x80 == 0 # Negative numbers are not allowed for R.

  # Null bytes at the start of R are not allowed, unless R would otherwise be interpreted as a negative number.
  return false if len_r > 1 && (s[4] == 0x00) && (s[5] & 0x80 == 0)

  return false unless s[len_r + 4] == 0x02 # Check whether the S element is an integer.

  return false if len_s == 0 # Zero-length integers are not allowed for S.
  return false unless (s[len_r + 6] & 0x80) == 0 # Negative numbers are not allowed for S.

  # Null bytes at the start of S are not allowed, unless S would otherwise be interpreted as a negative number.
  return false if len_s > 1 && (s[len_r + 6] == 0x00) && (s[len_r + 7] & 0x80 == 0)

  true
end

Private Class Methods

compare_big_endian(c1, c2) click to toggle source
# File lib/tapyrus/key.rb, line 235
def self.compare_big_endian(c1, c2)
  c1, c2 = c1.dup, c2.dup # Clone the arrays

  return 1 if c1.shift > 0 while c1.size > c2.size

  return -1 if c2.shift > 0 while c2.size > c1.size

  c1.size.times { |idx| return c1[idx] - c2[idx] if c1[idx] != c2[idx] }
  0
end

Public Instance Methods

compressed?() click to toggle source
# File lib/tapyrus/key.rb, line 137
def compressed?
  key_type != TYPES[:uncompressed]
end
fully_valid_pubkey?(allow_hybrid = false) click to toggle source

fully validate whether this is a valid public key (more expensive than IsValid())

# File lib/tapyrus/key.rb, line 229
def fully_valid_pubkey?(allow_hybrid = false)
  valid_pubkey? && secp256k1_module.parse_ec_pubkey?(pubkey, allow_hybrid)
end
hash160() click to toggle source

get hash160 public key.

# File lib/tapyrus/key.rb, line 127
def hash160
  Tapyrus.hash160(pubkey)
end
sign(data, low_r = true, extra_entropy = nil, algo: :ecdsa) click to toggle source

sign data with private key @param [String] data a data to be signed with binary format @param [Boolean] low_r flag to apply low-R. @param [String] extra_entropy the extra entropy for rfc6979. @param [Symbol] algo Algorithms used for verification. Either :ecdsa or :schnorr is supported. default value is :ecdsa. @return [String] signature data with binary format

# File lib/tapyrus/key.rb, line 98
def sign(data, low_r = true, extra_entropy = nil, algo: :ecdsa)
  raise ArgumentError, 'Unsupported algorithm has been specified.' unless SIG_ALGO.include?(algo)
  case algo
  when :ecdsa
    sign_ecdsa(data, low_r, extra_entropy)
  when :schnorr
    secp256k1_module.sign_data(data, priv_key, extra_entropy, algo: algo)
  else
    false
  end
end
to_p2pkh() click to toggle source

get pay to pubkey hash address @deprecated

# File lib/tapyrus/key.rb, line 133
def to_p2pkh
  Tapyrus::Script.to_p2pkh(hash160).addresses.first
end
to_point() click to toggle source

generate pubkey ec point @return [ECDSA::Point]

# File lib/tapyrus/key.rb, line 143
def to_point
  p = pubkey
  p ||= generate_pubkey(priv_key, compressed: compressed)
  ECDSA::Format::PointOctetString.decode(p.htb, Tapyrus::Secp256k1::GROUP)
end
to_wif() click to toggle source

export private key with wif format

# File lib/tapyrus/key.rb, line 84
def to_wif
  version = Tapyrus.chain_params.privkey_version
  hex = version + priv_key
  hex += '01' if compressed?
  hex += Tapyrus.calc_checksum(hex)
  Base58.encode(hex)
end
verify(sig, origin, algo: :ecdsa) click to toggle source

verify signature using public key @param [String] sig signature data with binary format @param [String] origin original message @param [Symbol] algo Algorithms used for verification. Either :ecdsa or :schnorr is supported. default value is :ecdsa. @return [Boolean] verify result

# File lib/tapyrus/key.rb, line 115
def verify(sig, origin, algo: :ecdsa)
  return false unless valid_pubkey?
  begin
    raise ArgumentError, 'Unsupported algorithm has been specified.' unless SIG_ALGO.include?(algo)
    sig = ecdsa_signature_parse_der_lax(sig) if algo == :ecdsa
    secp256k1_module.verify_sig(origin, sig, pubkey, algo: algo)
  rescue Exception
    false
  end
end

Private Instance Methods

ecdsa_signature_parse_der_lax(sig) click to toggle source

Supported violations include negative integers, excessive padding, garbage at the end, and overly long length descriptors. This is safe to use in Bitcoin because since the activation of BIP66, signatures are verified to be strict DER before being passed to this module, and we know it supports all violations present in the blockchain before that point.

# File lib/tapyrus/key.rb, line 265
def ecdsa_signature_parse_der_lax(sig)
  sig_array = sig.unpack('C*')
  len_r = sig_array[3]
  r = sig_array[4...(len_r + 4)].pack('C*').bth
  len_s = sig_array[len_r + 5]
  s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth
  ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der
end
generate_pubkey(privkey, compressed: true) click to toggle source

generate publick key from private key @param [String] privkey a private key with string format @param [Boolean] compressed pubkey compressed? @return [String] a pubkey which generate from privkey

# File lib/tapyrus/key.rb, line 250
def generate_pubkey(privkey, compressed: true)
  @secp256k1_module.generate_pubkey(privkey, compressed: compressed)
end
sig_has_low_r?(sig) click to toggle source

check whether the signature is low-R @param [String] sig the signature data @return [Boolean] result

# File lib/tapyrus/key.rb, line 281
def sig_has_low_r?(sig)
  sig[3].bth.to_i(16) == 0x20 && sig[4].bth.to_i(16) < 0x80
end
sign_ecdsa(data, low_r, extra_entropy) click to toggle source

generate ecdsa signature

# File lib/tapyrus/key.rb, line 286
def sign_ecdsa(data, low_r, extra_entropy)
  sig = secp256k1_module.sign_data(data, priv_key, extra_entropy, algo: :ecdsa)
  if low_r && !sig_has_low_r?(sig)
    counter = 1
    until sig_has_low_r?(sig)
      extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb
      sig = secp256k1_module.sign_data(data, priv_key, extra_entropy, algo: :ecdsa)
      counter += 1
    end
  end
  sig
end
valid_pubkey?() click to toggle source
# File lib/tapyrus/key.rb, line 274
def valid_pubkey?
  !pubkey.nil? && pubkey.size > 0
end
validate_private_key_range(private_key) click to toggle source

check private key range.

# File lib/tapyrus/key.rb, line 255
def validate_private_key_range(private_key)
  value = private_key.to_i(16)
  MIN_PRIV_KEY_MOD_ORDER <= value && value <= MAX_PRIV_KEY_MOD_ORDER
end