Module: Runar::EC

Defined in:
lib/runar/ec.rb

Constant Summary collapse

EC_P =

secp256k1 curve parameters

0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
EC_N =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
EC_G_X =
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
EC_G_Y =
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
EC_G =
format('%064x', EC_G_X) + format('%064x', EC_G_Y)

Class Method Summary collapse

Class Method Details

.ec_add(a, b) ⇒ Object

Add two points.



124
125
126
127
128
129
# File 'lib/runar/ec.rb', line 124

def ec_add(a, b)
  x1, y1 = decode_point(a)
  x2, y2 = decode_point(b)
  rx, ry = point_add(x1, y1, x2, y2)
  encode_point(rx, ry)
end

.ec_encode_compressed(p) ⇒ Object

Encode point in compressed format (33 bytes = 66 hex chars).



150
151
152
153
154
# File 'lib/runar/ec.rb', line 150

def ec_encode_compressed(p)
  x, y = decode_point(p)
  prefix = y.even? ? '02' : '03'
  prefix + format('%064x', x)
end

.ec_make_point(x, y) ⇒ Object

Create a Point from x, y integer coordinates.



145
146
147
# File 'lib/runar/ec.rb', line 145

def ec_make_point(x, y)
  encode_point(x, y)
end

.ec_mod_reduce(value, m) ⇒ Object

Modular reduction.



119
120
121
# File 'lib/runar/ec.rb', line 119

def ec_mod_reduce(value, m)
  value % m
end

.ec_mul(p, k) ⇒ Object

Scalar multiplication.



132
133
134
135
136
# File 'lib/runar/ec.rb', line 132

def ec_mul(p, k)
  x, y = decode_point(p)
  rx, ry = point_mul(x, y, k)
  encode_point(rx, ry)
end

.ec_mul_gen(k) ⇒ Object

Scalar multiplication with generator point.



139
140
141
142
# File 'lib/runar/ec.rb', line 139

def ec_mul_gen(k)
  rx, ry = point_mul(EC_G_X, EC_G_Y, k)
  encode_point(rx, ry)
end

.ec_negate(p) ⇒ Object

Negate a point (reflect over x-axis).



113
114
115
116
# File 'lib/runar/ec.rb', line 113

def ec_negate(p)
  x, y = decode_point(p)
  encode_point(x, (EC_P - y) % EC_P)
end

.ec_on_curve(p) ⇒ Object

Check if point is on the secp256k1 curve.



103
104
105
106
107
108
109
110
# File 'lib/runar/ec.rb', line 103

def ec_on_curve(p)
  x, y = decode_point(p)
  return true if x == 0 && y == 0 # Point at infinity

  lhs = (y * y) % EC_P
  rhs = (x * x * x + 7) % EC_P
  lhs == rhs
end

.ec_point_x(p) ⇒ Object

Extract x-coordinate from Point as integer.



91
92
93
94
# File 'lib/runar/ec.rb', line 91

def ec_point_x(p)
  x, = decode_point(p)
  x
end

.ec_point_y(p) ⇒ Object

Extract y-coordinate from Point as integer.



97
98
99
100
# File 'lib/runar/ec.rb', line 97

def ec_point_y(p)
  _, y = decode_point(p)
  y
end