Module: Bitcoin::Secp256k1::Ruby

Defined in:
lib/block_io/extended_bitcoinrb.rb

Class Method Summary collapse

Class Method Details

.sign_ecdsa(data, privkey, extra_entropy) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/block_io/extended_bitcoinrb.rb', line 36

def sign_ecdsa(data, privkey, extra_entropy)
  privkey = privkey.htb
  private_key = ECDSA::Format::IntegerOctetString.decode(privkey)
  extra_entropy ||= ''
  nonce = RFC6979.generate_rfc6979_nonce(privkey + data, extra_entropy)

  # port form ecdsa gem.
  r_point = GROUP.new_point(nonce)

  point_field = ECDSA::PrimeField.new(GROUP.order)
  r = point_field.mod(r_point.x)
  return nil if r.zero?

  rec = r_point.y & 1
  
  e = ECDSA.normalize_digest(data, GROUP.bit_length)
  s = point_field.mod(point_field.inverse(nonce) * (e + r * private_key))

  # covert to low-s
  if s > (GROUP.order / 2)
    s = GROUP.order - s
    rec = r_point.y & 1
  end
  
  return nil if s.zero?

  signature = ECDSA::Signature.new(r, s).to_der

  # these lines lead to performance issues
  #        public_key = Bitcoin::Key.new(priv_key: privkey.bth, :key_type => Bitcoin::Key::TYPES[:compressed]).pubkey # get rid of the key_type warning
  #        raise 'Creation of signature failed.' unless Bitcoin::Secp256k1::Ruby.verify_sig(data, signature, public_key)
  
  [signature, rec]
end