Class: BitcoinCigs::PublicKey

Inherits:
Object
  • Object
show all
Includes:
CryptoHelper
Defined in:
lib/bitcoin_cigs/public_key.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CryptoHelper

#decode58, #decode64, #decode_hex, #encode58, #encode64, #inverse_mod, #leftmost_bit, #ripemd160, #sha256, #sqrt_mod, #str_to_num

Constructor Details

#initialize(generator, point, compressed) ⇒ PublicKey

Returns a new instance of PublicKey.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/bitcoin_cigs/public_key.rb', line 7

def initialize(generator, point, compressed)
  self.curve = generator.curve
  self.generator = generator
  self.point = point
  self.compressed = compressed
  
  n = generator.order
  
  raise ::BitcoinCigs::Error.new("Generator point must have order.") if n.nil?
  raise ::BitcoinCigs::Error.new("Generator point order is bad.") unless (point * n).infinite?
  if point.x < 0 || n <= point.x || point.y < 0 || n <= point.y
    raise ::BitcoinCigs::Error, "Generator point has x or y out of range."
  end
end

Instance Attribute Details

#compressedObject

Returns the value of attribute compressed.



5
6
7
# File 'lib/bitcoin_cigs/public_key.rb', line 5

def compressed
  @compressed
end

#curveObject

Returns the value of attribute curve.



5
6
7
# File 'lib/bitcoin_cigs/public_key.rb', line 5

def curve
  @curve
end

#generatorObject

Returns the value of attribute generator.



5
6
7
# File 'lib/bitcoin_cigs/public_key.rb', line 5

def generator
  @generator
end

#pointObject

Returns the value of attribute point.



5
6
7
# File 'lib/bitcoin_cigs/public_key.rb', line 5

def point
  @point
end

Instance Method Details

#serObject



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bitcoin_cigs/public_key.rb', line 42

def ser
  if compressed
    if point.y & 1 > 0
      key = '03%064x' % point.x
    else
      key = '02%064x' % point.x
    end
  else
    key = '04%064x%064x' % [point.x, point.y]
  end
  
  decode_hex(key)
end

#verify(hash, signature) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/bitcoin_cigs/public_key.rb', line 22

def verify(hash, signature)
  hash = str_to_num(hash) if hash.is_a?(String)
  
  g = generator
  n = g.order
  r = signature.r
  s = signature.s
  
  return false if r < 1 || r > n-1
  return false if s < 1 || s > n-1
    
  c = inverse_mod(s, n)
  u1 = (hash * c) % n
  u2 = (r * c) % n
  xy = g * u1 + point * u2
  v = xy.x % n
  
  v == r
end