Module: BitcoinCigs

Extended by:
MathHelper
Defined in:
lib/bitcoin_cigs.rb,
lib/bitcoin_cigs/error.rb,
lib/bitcoin_cigs/point.rb,
lib/bitcoin_cigs/base_58.rb,
lib/bitcoin_cigs/version.rb,
lib/bitcoin_cigs/curve_fp.rb,
lib/bitcoin_cigs/public_key.rb,
lib/bitcoin_cigs/math_helper.rb

Defined Under Namespace

Modules: MathHelper Classes: Base58, CurveFp, Error, Point, PublicKey

Constant Summary collapse

P =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
R =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
B =
0x0000000000000000000000000000000000000000000000000000000000000007
A =
0x0000000000000000000000000000000000000000000000000000000000000000
Gx =
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy =
0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
CURVE_SECP256K1 =
::BitcoinCigs::CurveFp.new(P, A, B)
GENERATOR_SECP256K1 =
::BitcoinCigs::Point.new(CURVE_SECP256K1, Gx, Gy, R)
VERSION =
"0.0.1"

Class Method Summary collapse

Methods included from MathHelper

inverse_mod, leftmost_bit, ripemd160, sha256, sqrt_mod, str_to_num

Class Method Details

.verify_message(address, signature, message) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/bitcoin_cigs.rb', line 24

def verify_message(address, signature, message)
  begin
    verify_message!(address, signature, message)
    true
  rescue ::BitcoinCigs::Error
    false
  end
end

.verify_message!(address, signature, message) ⇒ Object



33
34
35
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
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/bitcoin_cigs.rb', line 33

def verify_message!(address, signature, message)
  network_version = str_to_num(::BitcoinCigs::Base58.decode(address)) >> (8 * 24)

  message = calculate_hash(format_message_to_sign(message))

  curve = CURVE_SECP256K1
  g = GENERATOR_SECP256K1
  a, b, p = curve.a, curve.b, curve.p
  
  order = g.order
  
  sig = Base64.decode64(signature)
  raise ::BitcoinCigs::Error.new("Bad signature") if sig.size != 65
  
  hb = sig[0].ord
  r, s = [sig[1...33], sig[33...65]].collect { |s| str_to_num(s) }
  
  
  raise ::BitcoinCigs::Error.new("Bad first byte") if hb < 27 || hb >= 35
  
  compressed = false
  if hb >= 31
    compressed = true
    hb -= 4
  end
  
  recid = hb - 27
  x = (r + (recid / 2) * order) % p
  y2 = ((x ** 3 % p) + a * x + b) % p
  yomy = sqrt_mod(y2, p)
  if (yomy - recid) % 2 == 0
    y = yomy
  else
    y = p - yomy
  end
  
  r_point = ::BitcoinCigs::Point.new(curve, x, y, order)
  e = str_to_num(message)
  minus_e = -e % order
  
  inv_r = inverse_mod(r, order)
  q = (r_point * s + g * minus_e) * inv_r
  

  public_key = ::BitcoinCigs::PublicKey.new(g, q, compressed)
  addr = public_key_to_bc_address(public_key.ser(), network_version)
  raise ::BitcoinCigs::Error.new("Bad address. Signing: #{addr}, Received: #{address}") if address != addr
  
  nil
end