github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/crypto/koblitz/btcec.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Copyright 2011 ThePiachu. All rights reserved. 3 // Copyright 2013-2014 The btcsuite developers 4 // Use of this source code is governed by an ISC 5 // license that can be found in the LICENSE file. 6 7 package koblitz 8 9 // References: 10 // [SECG]: Recommended Elliptic Curve Domain Parameters 11 // http://www.secg.org/sec2-v2.pdf 12 // 13 // [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone) 14 15 // This package operates, internally, on Jacobian coordinates. For a given 16 // (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1) 17 // where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole 18 // calculation can be performed within the transform (as in ScalarMult and 19 // ScalarBaseMult). But even for Add and Double, it's faster to apply and 20 // reverse the transform than to operate in affine coordinates. 21 22 import ( 23 "crypto/elliptic" 24 "math/big" 25 "sync" 26 ) 27 28 var ( 29 // fieldOne is simply the integer 1 in field representation. It is 30 // used to avoid needing to create it multiple times during the internal 31 // arithmetic. 32 fieldOne = new(fieldVal).SetInt(1) 33 ) 34 35 // KoblitzCurve supports a koblitz curve implementation that fits the ECC Curve 36 // interface from crypto/elliptic. 37 type KoblitzCurve struct { 38 *elliptic.CurveParams 39 q *big.Int 40 H int // cofactor of the curve. 41 42 // byteSize is simply the bit size / 8 and is provided for convenience 43 // since it is calculated repeatedly. 44 byteSize int 45 46 // bytePoints 47 bytePoints *[32][256][3]fieldVal 48 49 // The next 6 values are used specifically for endomorphism 50 // optimizations in ScalarMult. 51 52 // lambda must fulfill lambda^3 = 1 mod N where N is the order of G. 53 lambda *big.Int 54 55 // beta must fulfill beta^3 = 1 mod P where P is the prime field of the 56 // curve. 57 beta *fieldVal 58 59 // See the EndomorphismVectors in gensecp256k1.go to see how these are 60 // derived. 61 a1 *big.Int 62 b1 *big.Int 63 a2 *big.Int 64 b2 *big.Int 65 } 66 67 // Params returns the parameters for the curve. 68 func (curve *KoblitzCurve) Params() *elliptic.CurveParams { 69 return curve.CurveParams 70 } 71 72 // bigAffineToField takes an affine point (x, y) as big integers and converts 73 // it to an affine point as field values. 74 func (curve *KoblitzCurve) bigAffineToField(x, y *big.Int) (*fieldVal, *fieldVal) { 75 x3, y3 := new(fieldVal), new(fieldVal) 76 x3.SetByteSlice(x.Bytes()) 77 y3.SetByteSlice(y.Bytes()) 78 79 return x3, y3 80 } 81 82 // fieldJacobianToBigAffine takes a Jacobian point (x, y, z) as field values and 83 // converts it to an affine point as big integers. 84 func (curve *KoblitzCurve) fieldJacobianToBigAffine(x, y, z *fieldVal) (*big.Int, *big.Int) { 85 // Inversions are expensive and both point addition and point doubling 86 // are faster when working with points that have a z value of one. So, 87 // if the point needs to be converted to affine, go ahead and normalize 88 // the point itself at the same time as the calculation is the same. 89 var zInv, tempZ fieldVal 90 zInv.Set(z).Inverse() // zInv = Z^-1 91 tempZ.SquareVal(&zInv) // tempZ = Z^-2 92 x.Mul(&tempZ) // X = X/Z^2 (mag: 1) 93 y.Mul(tempZ.Mul(&zInv)) // Y = Y/Z^3 (mag: 1) 94 z.SetInt(1) // Z = 1 (mag: 1) 95 96 // Normalize the x and y values. 97 x.Normalize() 98 y.Normalize() 99 100 // Convert the field values for the now affine point to big.Ints. 101 x3, y3 := new(big.Int), new(big.Int) 102 x3.SetBytes(x.Bytes()[:]) 103 y3.SetBytes(y.Bytes()[:]) 104 return x3, y3 105 } 106 107 // IsOnCurve returns boolean if the point (x,y) is on the curve. 108 // Part of the elliptic.Curve interface. This function differs from the 109 // crypto/elliptic algorithm since a = 0 not -3. 110 func (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bool { 111 // Convert big ints to field values for faster arithmetic. 112 fx, fy := curve.bigAffineToField(x, y) 113 114 // Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7 115 y2 := new(fieldVal).SquareVal(fy).Normalize() 116 result := new(fieldVal).SquareVal(fx).Mul(fx).AddInt(7).Normalize() 117 return y2.Equals(result) 118 } 119 120 // addZ1AndZ2EqualsOne adds two Jacobian points that are already known to have 121 // z values of 1 and stores the result in (x3, y3, z3). That is to say 122 // (x1, y1, 1) + (x2, y2, 1) = (x3, y3, z3). It performs faster addition than 123 // the generic add routine since less arithmetic is needed due to the ability to 124 // avoid the z value multiplications. 125 func (curve *KoblitzCurve) addZ1AndZ2EqualsOne(x1, y1, z1, x2, y2, x3, y3, z3 *fieldVal) { 126 // To compute the point addition efficiently, this implementation splits 127 // the equation into intermediate elements which are used to minimize 128 // the number of field multiplications using the method shown at: 129 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-mmadd-2007-bl 130 // 131 // In particular it performs the calculations using the following: 132 // H = X2-X1, HH = H^2, I = 4*HH, J = H*I, r = 2*(Y2-Y1), V = X1*I 133 // X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*Y1*J, Z3 = 2*H 134 // 135 // This results in a cost of 4 field multiplications, 2 field squarings, 136 // 6 field additions, and 5 integer multiplications. 137 138 // When the x coordinates are the same for two points on the curve, the 139 // y coordinates either must be the same, in which case it is point 140 // doubling, or they are opposite and the result is the point at 141 // infinity per the group law for elliptic curve cryptography. 142 x1.Normalize() 143 y1.Normalize() 144 x2.Normalize() 145 y2.Normalize() 146 if x1.Equals(x2) { 147 if y1.Equals(y2) { 148 // Since x1 == x2 and y1 == y2, point doubling must be 149 // done, otherwise the addition would end up dividing 150 // by zero. 151 curve.doubleJacobian(x1, y1, z1, x3, y3, z3) 152 return 153 } 154 155 // Since x1 == x2 and y1 == -y2, the sum is the point at 156 // infinity per the group law. 157 x3.SetInt(0) 158 y3.SetInt(0) 159 z3.SetInt(0) 160 return 161 } 162 163 // Calculate X3, Y3, and Z3 according to the intermediate elements 164 // breakdown above. 165 var h, i, j, r, v fieldVal 166 var negJ, neg2V, negX3 fieldVal 167 h.Set(x1).Negate(1).Add(x2) // H = X2-X1 (mag: 3) 168 i.SquareVal(&h).MulInt(4) // I = 4*H^2 (mag: 4) 169 j.Mul2(&h, &i) // J = H*I (mag: 1) 170 r.Set(y1).Negate(1).Add(y2).MulInt(2) // r = 2*(Y2-Y1) (mag: 6) 171 v.Mul2(x1, &i) // V = X1*I (mag: 1) 172 negJ.Set(&j).Negate(1) // negJ = -J (mag: 2) 173 neg2V.Set(&v).MulInt(2).Negate(2) // neg2V = -(2*V) (mag: 3) 174 x3.Set(&r).Square().Add(&negJ).Add(&neg2V) // X3 = r^2-J-2*V (mag: 6) 175 negX3.Set(x3).Negate(6) // negX3 = -X3 (mag: 7) 176 j.Mul(y1).MulInt(2).Negate(2) // J = -(2*Y1*J) (mag: 3) 177 y3.Set(&v).Add(&negX3).Mul(&r).Add(&j) // Y3 = r*(V-X3)-2*Y1*J (mag: 4) 178 z3.Set(&h).MulInt(2) // Z3 = 2*H (mag: 6) 179 180 // Normalize the resulting field values to a magnitude of 1 as needed. 181 x3.Normalize() 182 y3.Normalize() 183 z3.Normalize() 184 } 185 186 // addZ1EqualsZ2 adds two Jacobian points that are already known to have the 187 // same z value and stores the result in (x3, y3, z3). That is to say 188 // (x1, y1, z1) + (x2, y2, z1) = (x3, y3, z3). It performs faster addition than 189 // the generic add routine since less arithmetic is needed due to the known 190 // equivalence. 191 func (curve *KoblitzCurve) addZ1EqualsZ2(x1, y1, z1, x2, y2, x3, y3, z3 *fieldVal) { 192 // To compute the point addition efficiently, this implementation splits 193 // the equation into intermediate elements which are used to minimize 194 // the number of field multiplications using a slightly modified version 195 // of the method shown at: 196 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-mmadd-2007-bl 197 // 198 // In particular it performs the calculations using the following: 199 // A = X2-X1, B = A^2, C=Y2-Y1, D = C^2, E = X1*B, F = X2*B 200 // X3 = D-E-F, Y3 = C*(E-X3)-Y1*(F-E), Z3 = Z1*A 201 // 202 // This results in a cost of 5 field multiplications, 2 field squarings, 203 // 9 field additions, and 0 integer multiplications. 204 205 // When the x coordinates are the same for two points on the curve, the 206 // y coordinates either must be the same, in which case it is point 207 // doubling, or they are opposite and the result is the point at 208 // infinity per the group law for elliptic curve cryptography. 209 x1.Normalize() 210 y1.Normalize() 211 x2.Normalize() 212 y2.Normalize() 213 if x1.Equals(x2) { 214 if y1.Equals(y2) { 215 // Since x1 == x2 and y1 == y2, point doubling must be 216 // done, otherwise the addition would end up dividing 217 // by zero. 218 curve.doubleJacobian(x1, y1, z1, x3, y3, z3) 219 return 220 } 221 222 // Since x1 == x2 and y1 == -y2, the sum is the point at 223 // infinity per the group law. 224 x3.SetInt(0) 225 y3.SetInt(0) 226 z3.SetInt(0) 227 return 228 } 229 230 // Calculate X3, Y3, and Z3 according to the intermediate elements 231 // breakdown above. 232 var a, b, c, d, e, f fieldVal 233 var negX1, negY1, negE, negX3 fieldVal 234 negX1.Set(x1).Negate(1) // negX1 = -X1 (mag: 2) 235 negY1.Set(y1).Negate(1) // negY1 = -Y1 (mag: 2) 236 a.Set(&negX1).Add(x2) // A = X2-X1 (mag: 3) 237 b.SquareVal(&a) // B = A^2 (mag: 1) 238 c.Set(&negY1).Add(y2) // C = Y2-Y1 (mag: 3) 239 d.SquareVal(&c) // D = C^2 (mag: 1) 240 e.Mul2(x1, &b) // E = X1*B (mag: 1) 241 negE.Set(&e).Negate(1) // negE = -E (mag: 2) 242 f.Mul2(x2, &b) // F = X2*B (mag: 1) 243 x3.Add2(&e, &f).Negate(3).Add(&d) // X3 = D-E-F (mag: 5) 244 negX3.Set(x3).Negate(5).Normalize() // negX3 = -X3 (mag: 1) 245 y3.Set(y1).Mul(f.Add(&negE)).Negate(3) // Y3 = -(Y1*(F-E)) (mag: 4) 246 y3.Add(e.Add(&negX3).Mul(&c)) // Y3 = C*(E-X3)+Y3 (mag: 5) 247 z3.Mul2(z1, &a) // Z3 = Z1*A (mag: 1) 248 249 // Normalize the resulting field values to a magnitude of 1 as needed. 250 x3.Normalize() 251 y3.Normalize() 252 } 253 254 // addZ2EqualsOne adds two Jacobian points when the second point is already 255 // known to have a z value of 1 (and the z value for the first point is not 1) 256 // and stores the result in (x3, y3, z3). That is to say (x1, y1, z1) + 257 // (x2, y2, 1) = (x3, y3, z3). It performs faster addition than the generic 258 // add routine since less arithmetic is needed due to the ability to avoid 259 // multiplications by the second point's z value. 260 func (curve *KoblitzCurve) addZ2EqualsOne(x1, y1, z1, x2, y2, x3, y3, z3 *fieldVal) { 261 // To compute the point addition efficiently, this implementation splits 262 // the equation into intermediate elements which are used to minimize 263 // the number of field multiplications using the method shown at: 264 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl 265 // 266 // In particular it performs the calculations using the following: 267 // Z1Z1 = Z1^2, U2 = X2*Z1Z1, S2 = Y2*Z1*Z1Z1, H = U2-X1, HH = H^2, 268 // I = 4*HH, J = H*I, r = 2*(S2-Y1), V = X1*I 269 // X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*Y1*J, Z3 = (Z1+H)^2-Z1Z1-HH 270 // 271 // This results in a cost of 7 field multiplications, 4 field squarings, 272 // 9 field additions, and 4 integer multiplications. 273 274 // When the x coordinates are the same for two points on the curve, the 275 // y coordinates either must be the same, in which case it is point 276 // doubling, or they are opposite and the result is the point at 277 // infinity per the group law for elliptic curve cryptography. Since 278 // any number of Jacobian coordinates can represent the same affine 279 // point, the x and y values need to be converted to like terms. Due to 280 // the assumption made for this function that the second point has a z 281 // value of 1 (z2=1), the first point is already "converted". 282 var z1z1, u2, s2 fieldVal 283 x1.Normalize() 284 y1.Normalize() 285 z1z1.SquareVal(z1) // Z1Z1 = Z1^2 (mag: 1) 286 u2.Set(x2).Mul(&z1z1).Normalize() // U2 = X2*Z1Z1 (mag: 1) 287 s2.Set(y2).Mul(&z1z1).Mul(z1).Normalize() // S2 = Y2*Z1*Z1Z1 (mag: 1) 288 if x1.Equals(&u2) { 289 if y1.Equals(&s2) { 290 // Since x1 == x2 and y1 == y2, point doubling must be 291 // done, otherwise the addition would end up dividing 292 // by zero. 293 curve.doubleJacobian(x1, y1, z1, x3, y3, z3) 294 return 295 } 296 297 // Since x1 == x2 and y1 == -y2, the sum is the point at 298 // infinity per the group law. 299 x3.SetInt(0) 300 y3.SetInt(0) 301 z3.SetInt(0) 302 return 303 } 304 305 // Calculate X3, Y3, and Z3 according to the intermediate elements 306 // breakdown above. 307 var h, hh, i, j, r, rr, v fieldVal 308 var negX1, negY1, negX3 fieldVal 309 negX1.Set(x1).Negate(1) // negX1 = -X1 (mag: 2) 310 h.Add2(&u2, &negX1) // H = U2-X1 (mag: 3) 311 hh.SquareVal(&h) // HH = H^2 (mag: 1) 312 i.Set(&hh).MulInt(4) // I = 4 * HH (mag: 4) 313 j.Mul2(&h, &i) // J = H*I (mag: 1) 314 negY1.Set(y1).Negate(1) // negY1 = -Y1 (mag: 2) 315 r.Set(&s2).Add(&negY1).MulInt(2) // r = 2*(S2-Y1) (mag: 6) 316 rr.SquareVal(&r) // rr = r^2 (mag: 1) 317 v.Mul2(x1, &i) // V = X1*I (mag: 1) 318 x3.Set(&v).MulInt(2).Add(&j).Negate(3) // X3 = -(J+2*V) (mag: 4) 319 x3.Add(&rr) // X3 = r^2+X3 (mag: 5) 320 negX3.Set(x3).Negate(5) // negX3 = -X3 (mag: 6) 321 y3.Set(y1).Mul(&j).MulInt(2).Negate(2) // Y3 = -(2*Y1*J) (mag: 3) 322 y3.Add(v.Add(&negX3).Mul(&r)) // Y3 = r*(V-X3)+Y3 (mag: 4) 323 z3.Add2(z1, &h).Square() // Z3 = (Z1+H)^2 (mag: 1) 324 z3.Add(z1z1.Add(&hh).Negate(2)) // Z3 = Z3-(Z1Z1+HH) (mag: 4) 325 326 // Normalize the resulting field values to a magnitude of 1 as needed. 327 x3.Normalize() 328 y3.Normalize() 329 z3.Normalize() 330 } 331 332 // addGeneric adds two Jacobian points (x1, y1, z1) and (x2, y2, z2) without any 333 // assumptions about the z values of the two points and stores the result in 334 // (x3, y3, z3). That is to say (x1, y1, z1) + (x2, y2, z2) = (x3, y3, z3). It 335 // is the slowest of the add routines due to requiring the most arithmetic. 336 func (curve *KoblitzCurve) addGeneric(x1, y1, z1, x2, y2, z2, x3, y3, z3 *fieldVal) { 337 // To compute the point addition efficiently, this implementation splits 338 // the equation into intermediate elements which are used to minimize 339 // the number of field multiplications using the method shown at: 340 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl 341 // 342 // In particular it performs the calculations using the following: 343 // Z1Z1 = Z1^2, Z2Z2 = Z2^2, U1 = X1*Z2Z2, U2 = X2*Z1Z1, S1 = Y1*Z2*Z2Z2 344 // S2 = Y2*Z1*Z1Z1, H = U2-U1, I = (2*H)^2, J = H*I, r = 2*(S2-S1) 345 // V = U1*I 346 // X3 = r^2-J-2*V, Y3 = r*(V-X3)-2*S1*J, Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2)*H 347 // 348 // This results in a cost of 11 field multiplications, 5 field squarings, 349 // 9 field additions, and 4 integer multiplications. 350 351 // When the x coordinates are the same for two points on the curve, the 352 // y coordinates either must be the same, in which case it is point 353 // doubling, or they are opposite and the result is the point at 354 // infinity. Since any number of Jacobian coordinates can represent the 355 // same affine point, the x and y values need to be converted to like 356 // terms. 357 var z1z1, z2z2, u1, u2, s1, s2 fieldVal 358 z1z1.SquareVal(z1) // Z1Z1 = Z1^2 (mag: 1) 359 z2z2.SquareVal(z2) // Z2Z2 = Z2^2 (mag: 1) 360 u1.Set(x1).Mul(&z2z2).Normalize() // U1 = X1*Z2Z2 (mag: 1) 361 u2.Set(x2).Mul(&z1z1).Normalize() // U2 = X2*Z1Z1 (mag: 1) 362 s1.Set(y1).Mul(&z2z2).Mul(z2).Normalize() // S1 = Y1*Z2*Z2Z2 (mag: 1) 363 s2.Set(y2).Mul(&z1z1).Mul(z1).Normalize() // S2 = Y2*Z1*Z1Z1 (mag: 1) 364 if u1.Equals(&u2) { 365 if s1.Equals(&s2) { 366 // Since x1 == x2 and y1 == y2, point doubling must be 367 // done, otherwise the addition would end up dividing 368 // by zero. 369 curve.doubleJacobian(x1, y1, z1, x3, y3, z3) 370 return 371 } 372 373 // Since x1 == x2 and y1 == -y2, the sum is the point at 374 // infinity per the group law. 375 x3.SetInt(0) 376 y3.SetInt(0) 377 z3.SetInt(0) 378 return 379 } 380 381 // Calculate X3, Y3, and Z3 according to the intermediate elements 382 // breakdown above. 383 var h, i, j, r, rr, v fieldVal 384 var negU1, negS1, negX3 fieldVal 385 negU1.Set(&u1).Negate(1) // negU1 = -U1 (mag: 2) 386 h.Add2(&u2, &negU1) // H = U2-U1 (mag: 3) 387 i.Set(&h).MulInt(2).Square() // I = (2*H)^2 (mag: 2) 388 j.Mul2(&h, &i) // J = H*I (mag: 1) 389 negS1.Set(&s1).Negate(1) // negS1 = -S1 (mag: 2) 390 r.Set(&s2).Add(&negS1).MulInt(2) // r = 2*(S2-S1) (mag: 6) 391 rr.SquareVal(&r) // rr = r^2 (mag: 1) 392 v.Mul2(&u1, &i) // V = U1*I (mag: 1) 393 x3.Set(&v).MulInt(2).Add(&j).Negate(3) // X3 = -(J+2*V) (mag: 4) 394 x3.Add(&rr) // X3 = r^2+X3 (mag: 5) 395 negX3.Set(x3).Negate(5) // negX3 = -X3 (mag: 6) 396 y3.Mul2(&s1, &j).MulInt(2).Negate(2) // Y3 = -(2*S1*J) (mag: 3) 397 y3.Add(v.Add(&negX3).Mul(&r)) // Y3 = r*(V-X3)+Y3 (mag: 4) 398 z3.Add2(z1, z2).Square() // Z3 = (Z1+Z2)^2 (mag: 1) 399 z3.Add(z1z1.Add(&z2z2).Negate(2)) // Z3 = Z3-(Z1Z1+Z2Z2) (mag: 4) 400 z3.Mul(&h) // Z3 = Z3*H (mag: 1) 401 402 // Normalize the resulting field values to a magnitude of 1 as needed. 403 x3.Normalize() 404 y3.Normalize() 405 } 406 407 // addJacobian adds the passed Jacobian points (x1, y1, z1) and (x2, y2, z2) 408 // together and stores the result in (x3, y3, z3). 409 func (curve *KoblitzCurve) addJacobian(x1, y1, z1, x2, y2, z2, x3, y3, z3 *fieldVal) { 410 // A point at infinity is the identity according to the group law for 411 // elliptic curve cryptography. Thus, ∞ + P = P and P + ∞ = P. 412 if (x1.IsZero() && y1.IsZero()) || z1.IsZero() { 413 x3.Set(x2) 414 y3.Set(y2) 415 z3.Set(z2) 416 return 417 } 418 if (x2.IsZero() && y2.IsZero()) || z2.IsZero() { 419 x3.Set(x1) 420 y3.Set(y1) 421 z3.Set(z1) 422 return 423 } 424 425 // Faster point addition can be achieved when certain assumptions are 426 // met. For example, when both points have the same z value, arithmetic 427 // on the z values can be avoided. This section thus checks for these 428 // conditions and calls an appropriate add function which is accelerated 429 // by using those assumptions. 430 z1.Normalize() 431 z2.Normalize() 432 isZ1One := z1.Equals(fieldOne) 433 isZ2One := z2.Equals(fieldOne) 434 switch { 435 case isZ1One && isZ2One: 436 curve.addZ1AndZ2EqualsOne(x1, y1, z1, x2, y2, x3, y3, z3) 437 return 438 case z1.Equals(z2): 439 curve.addZ1EqualsZ2(x1, y1, z1, x2, y2, x3, y3, z3) 440 return 441 case isZ2One: 442 curve.addZ2EqualsOne(x1, y1, z1, x2, y2, x3, y3, z3) 443 return 444 } 445 446 // None of the above assumptions are true, so fall back to generic 447 // point addition. 448 curve.addGeneric(x1, y1, z1, x2, y2, z2, x3, y3, z3) 449 } 450 451 // Add returns the sum of (x1,y1) and (x2,y2). Part of the elliptic.Curve 452 // interface. 453 func (curve *KoblitzCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { 454 // A point at infinity is the identity according to the group law for 455 // elliptic curve cryptography. Thus, ∞ + P = P and P + ∞ = P. 456 if x1.Sign() == 0 && y1.Sign() == 0 { 457 return x2, y2 458 } 459 if x2.Sign() == 0 && y2.Sign() == 0 { 460 return x1, y1 461 } 462 463 // Convert the affine coordinates from big integers to field values 464 // and do the point addition in Jacobian projective space. 465 fx1, fy1 := curve.bigAffineToField(x1, y1) 466 fx2, fy2 := curve.bigAffineToField(x2, y2) 467 fx3, fy3, fz3 := new(fieldVal), new(fieldVal), new(fieldVal) 468 fOne := new(fieldVal).SetInt(1) 469 curve.addJacobian(fx1, fy1, fOne, fx2, fy2, fOne, fx3, fy3, fz3) 470 471 // Convert the Jacobian coordinate field values back to affine big 472 // integers. 473 return curve.fieldJacobianToBigAffine(fx3, fy3, fz3) 474 } 475 476 // doubleZ1EqualsOne performs point doubling on the passed Jacobian point 477 // when the point is already known to have a z value of 1 and stores 478 // the result in (x3, y3, z3). That is to say (x3, y3, z3) = 2*(x1, y1, 1). It 479 // performs faster point doubling than the generic routine since less arithmetic 480 // is needed due to the ability to avoid multiplication by the z value. 481 func (curve *KoblitzCurve) doubleZ1EqualsOne(x1, y1, x3, y3, z3 *fieldVal) { 482 // This function uses the assumptions that z1 is 1, thus the point 483 // doubling formulas reduce to: 484 // 485 // X3 = (3*X1^2)^2 - 8*X1*Y1^2 486 // Y3 = (3*X1^2)*(4*X1*Y1^2 - X3) - 8*Y1^4 487 // Z3 = 2*Y1 488 // 489 // To compute the above efficiently, this implementation splits the 490 // equation into intermediate elements which are used to minimize the 491 // number of field multiplications in favor of field squarings which 492 // are roughly 35% faster than field multiplications with the current 493 // implementation at the time this was written. 494 // 495 // This uses a slightly modified version of the method shown at: 496 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl 497 // 498 // In particular it performs the calculations using the following: 499 // A = X1^2, B = Y1^2, C = B^2, D = 2*((X1+B)^2-A-C) 500 // E = 3*A, F = E^2, X3 = F-2*D, Y3 = E*(D-X3)-8*C 501 // Z3 = 2*Y1 502 // 503 // This results in a cost of 1 field multiplication, 5 field squarings, 504 // 6 field additions, and 5 integer multiplications. 505 var a, b, c, d, e, f fieldVal 506 z3.Set(y1).MulInt(2) // Z3 = 2*Y1 (mag: 2) 507 a.SquareVal(x1) // A = X1^2 (mag: 1) 508 b.SquareVal(y1) // B = Y1^2 (mag: 1) 509 c.SquareVal(&b) // C = B^2 (mag: 1) 510 b.Add(x1).Square() // B = (X1+B)^2 (mag: 1) 511 d.Set(&a).Add(&c).Negate(2) // D = -(A+C) (mag: 3) 512 d.Add(&b).MulInt(2) // D = 2*(B+D)(mag: 8) 513 e.Set(&a).MulInt(3) // E = 3*A (mag: 3) 514 f.SquareVal(&e) // F = E^2 (mag: 1) 515 x3.Set(&d).MulInt(2).Negate(16) // X3 = -(2*D) (mag: 17) 516 x3.Add(&f) // X3 = F+X3 (mag: 18) 517 f.Set(x3).Negate(18).Add(&d).Normalize() // F = D-X3 (mag: 1) 518 y3.Set(&c).MulInt(8).Negate(8) // Y3 = -(8*C) (mag: 9) 519 y3.Add(f.Mul(&e)) // Y3 = E*F+Y3 (mag: 10) 520 521 // Normalize the field values back to a magnitude of 1. 522 x3.Normalize() 523 y3.Normalize() 524 z3.Normalize() 525 } 526 527 // doubleGeneric performs point doubling on the passed Jacobian point without 528 // any assumptions about the z value and stores the result in (x3, y3, z3). 529 // That is to say (x3, y3, z3) = 2*(x1, y1, z1). It is the slowest of the point 530 // doubling routines due to requiring the most arithmetic. 531 func (curve *KoblitzCurve) doubleGeneric(x1, y1, z1, x3, y3, z3 *fieldVal) { 532 // Point doubling formula for Jacobian coordinates for the secp256k1 533 // curve: 534 // X3 = (3*X1^2)^2 - 8*X1*Y1^2 535 // Y3 = (3*X1^2)*(4*X1*Y1^2 - X3) - 8*Y1^4 536 // Z3 = 2*Y1*Z1 537 // 538 // To compute the above efficiently, this implementation splits the 539 // equation into intermediate elements which are used to minimize the 540 // number of field multiplications in favor of field squarings which 541 // are roughly 35% faster than field multiplications with the current 542 // implementation at the time this was written. 543 // 544 // This uses a slightly modified version of the method shown at: 545 // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l 546 // 547 // In particular it performs the calculations using the following: 548 // A = X1^2, B = Y1^2, C = B^2, D = 2*((X1+B)^2-A-C) 549 // E = 3*A, F = E^2, X3 = F-2*D, Y3 = E*(D-X3)-8*C 550 // Z3 = 2*Y1*Z1 551 // 552 // This results in a cost of 1 field multiplication, 5 field squarings, 553 // 6 field additions, and 5 integer multiplications. 554 var a, b, c, d, e, f fieldVal 555 z3.Mul2(y1, z1).MulInt(2) // Z3 = 2*Y1*Z1 (mag: 2) 556 a.SquareVal(x1) // A = X1^2 (mag: 1) 557 b.SquareVal(y1) // B = Y1^2 (mag: 1) 558 c.SquareVal(&b) // C = B^2 (mag: 1) 559 b.Add(x1).Square() // B = (X1+B)^2 (mag: 1) 560 d.Set(&a).Add(&c).Negate(2) // D = -(A+C) (mag: 3) 561 d.Add(&b).MulInt(2) // D = 2*(B+D)(mag: 8) 562 e.Set(&a).MulInt(3) // E = 3*A (mag: 3) 563 f.SquareVal(&e) // F = E^2 (mag: 1) 564 x3.Set(&d).MulInt(2).Negate(16) // X3 = -(2*D) (mag: 17) 565 x3.Add(&f) // X3 = F+X3 (mag: 18) 566 f.Set(x3).Negate(18).Add(&d).Normalize() // F = D-X3 (mag: 1) 567 y3.Set(&c).MulInt(8).Negate(8) // Y3 = -(8*C) (mag: 9) 568 y3.Add(f.Mul(&e)) // Y3 = E*F+Y3 (mag: 10) 569 570 // Normalize the field values back to a magnitude of 1. 571 x3.Normalize() 572 y3.Normalize() 573 z3.Normalize() 574 } 575 576 // doubleJacobian doubles the passed Jacobian point (x1, y1, z1) and stores the 577 // result in (x3, y3, z3). 578 func (curve *KoblitzCurve) doubleJacobian(x1, y1, z1, x3, y3, z3 *fieldVal) { 579 // Doubling a point at infinity is still infinity. 580 if y1.IsZero() || z1.IsZero() { 581 x3.SetInt(0) 582 y3.SetInt(0) 583 z3.SetInt(0) 584 return 585 } 586 587 // Slightly faster point doubling can be achieved when the z value is 1 588 // by avoiding the multiplication on the z value. This section calls 589 // a point doubling function which is accelerated by using that 590 // assumption when possible. 591 if z1.Normalize().Equals(fieldOne) { 592 curve.doubleZ1EqualsOne(x1, y1, x3, y3, z3) 593 return 594 } 595 596 // Fall back to generic point doubling which works with arbitrary z 597 // values. 598 curve.doubleGeneric(x1, y1, z1, x3, y3, z3) 599 } 600 601 // Double returns 2*(x1,y1). Part of the elliptic.Curve interface. 602 func (curve *KoblitzCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { 603 if y1.Sign() == 0 { 604 return new(big.Int), new(big.Int) 605 } 606 607 // Convert the affine coordinates from big integers to field values 608 // and do the point doubling in Jacobian projective space. 609 fx1, fy1 := curve.bigAffineToField(x1, y1) 610 fx3, fy3, fz3 := new(fieldVal), new(fieldVal), new(fieldVal) 611 fOne := new(fieldVal).SetInt(1) 612 curve.doubleJacobian(fx1, fy1, fOne, fx3, fy3, fz3) 613 614 // Convert the Jacobian coordinate field values back to affine big 615 // integers. 616 return curve.fieldJacobianToBigAffine(fx3, fy3, fz3) 617 } 618 619 // splitK returns a balanced length-two representation of k and their signs. 620 // This is algorithm 3.74 from [GECC]. 621 // 622 // One thing of note about this algorithm is that no matter what c1 and c2 are, 623 // the final equation of k = k1 + k2 * lambda (mod n) will hold. This is 624 // provable mathematically due to how a1/b1/a2/b2 are computed. 625 // 626 // c1 and c2 are chosen to minimize the max(k1,k2). 627 func (curve *KoblitzCurve) splitK(k []byte) ([]byte, []byte, int, int) { 628 // All math here is done with big.Int, which is slow. 629 // At some point, it might be useful to write something similar to 630 // fieldVal but for N instead of P as the prime field if this ends up 631 // being a bottleneck. 632 bigIntK := new(big.Int) 633 c1, c2 := new(big.Int), new(big.Int) 634 tmp1, tmp2 := new(big.Int), new(big.Int) 635 k1, k2 := new(big.Int), new(big.Int) 636 637 bigIntK.SetBytes(k) 638 // c1 = round(b2 * k / n) from step 4. 639 // Rounding isn't really necessary and costs too much, hence skipped 640 c1.Mul(curve.b2, bigIntK) 641 c1.Div(c1, curve.N) 642 // c2 = round(b1 * k / n) from step 4 (sign reversed to optimize one step) 643 // Rounding isn't really necessary and costs too much, hence skipped 644 c2.Mul(curve.b1, bigIntK) 645 c2.Div(c2, curve.N) 646 // k1 = k - c1 * a1 - c2 * a2 from step 5 (note c2's sign is reversed) 647 tmp1.Mul(c1, curve.a1) 648 tmp2.Mul(c2, curve.a2) 649 k1.Sub(bigIntK, tmp1) 650 k1.Add(k1, tmp2) 651 // k2 = - c1 * b1 - c2 * b2 from step 5 (note c2's sign is reversed) 652 tmp1.Mul(c1, curve.b1) 653 tmp2.Mul(c2, curve.b2) 654 k2.Sub(tmp2, tmp1) 655 656 // Note Bytes() throws out the sign of k1 and k2. This matters 657 // since k1 and/or k2 can be negative. Hence, we pass that 658 // back separately. 659 return k1.Bytes(), k2.Bytes(), k1.Sign(), k2.Sign() 660 } 661 662 // moduloReduce reduces k from more than 32 bytes to 32 bytes and under. This 663 // is done by doing a simple modulo curve.N. We can do this since G^N = 1 and 664 // thus any other valid point on the elliptic curve has the same order. 665 func (curve *KoblitzCurve) moduloReduce(k []byte) []byte { 666 // Since the order of G is curve.N, we can use a much smaller number 667 // by doing modulo curve.N 668 if len(k) > curve.byteSize { 669 // Reduce k by performing modulo curve.N. 670 tmpK := new(big.Int).SetBytes(k) 671 tmpK.Mod(tmpK, curve.N) 672 return tmpK.Bytes() 673 } 674 675 return k 676 } 677 678 // NAF takes a positive integer k and returns the Non-Adjacent Form (NAF) as two 679 // byte slices. The first is where 1s will be. The second is where -1s will 680 // be. NAF is convenient in that on average, only 1/3rd of its values are 681 // non-zero. This is algorithm 3.30 from [GECC]. 682 // 683 // Essentially, this makes it possible to minimize the number of operations 684 // since the resulting ints returned will be at least 50% 0s. 685 func NAF(k []byte) ([]byte, []byte) { 686 // The essence of this algorithm is that whenever we have consecutive 1s 687 // in the binary, we want to put a -1 in the lowest bit and get a bunch 688 // of 0s up to the highest bit of consecutive 1s. This is due to this 689 // identity: 690 // 2^n + 2^(n-1) + 2^(n-2) + ... + 2^(n-k) = 2^(n+1) - 2^(n-k) 691 // 692 // The algorithm thus may need to go 1 more bit than the length of the 693 // bits we actually have, hence bits being 1 bit longer than was 694 // necessary. Since we need to know whether adding will cause a carry, 695 // we go from right-to-left in this addition. 696 var carry, curIsOne, nextIsOne bool 697 // these default to zero 698 retPos := make([]byte, len(k)+1) 699 retNeg := make([]byte, len(k)+1) 700 for i := len(k) - 1; i >= 0; i-- { 701 curByte := k[i] 702 for j := uint(0); j < 8; j++ { 703 curIsOne = curByte&1 == 1 704 if j == 7 { 705 if i == 0 { 706 nextIsOne = false 707 } else { 708 nextIsOne = k[i-1]&1 == 1 709 } 710 } else { 711 nextIsOne = curByte&2 == 2 712 } 713 if carry { 714 if curIsOne { 715 // This bit is 1, so continue to carry 716 // and don't need to do anything. 717 } else { 718 // We've hit a 0 after some number of 719 // 1s. 720 if nextIsOne { 721 // Start carrying again since 722 // a new sequence of 1s is 723 // starting. 724 retNeg[i+1] += 1 << j 725 } else { 726 // Stop carrying since 1s have 727 // stopped. 728 carry = false 729 retPos[i+1] += 1 << j 730 } 731 } 732 } else if curIsOne { 733 if nextIsOne { 734 // If this is the start of at least 2 735 // consecutive 1s, set the current one 736 // to -1 and start carrying. 737 retNeg[i+1] += 1 << j 738 carry = true 739 } else { 740 // This is a singleton, not consecutive 741 // 1s. 742 retPos[i+1] += 1 << j 743 } 744 } 745 curByte >>= 1 746 } 747 } 748 if carry { 749 retPos[0] = 1 750 } 751 752 return retPos, retNeg 753 } 754 755 // ScalarMult returns k*(Bx, By) where k is a big endian integer. 756 // Part of the elliptic.Curve interface. 757 func (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { 758 // Point Q = ∞ (point at infinity). 759 qx, qy, qz := new(fieldVal), new(fieldVal), new(fieldVal) 760 761 // Decompose K into k1 and k2 in order to halve the number of EC ops. 762 // See Algorithm 3.74 in [GECC]. 763 k1, k2, signK1, signK2 := curve.splitK(curve.moduloReduce(k)) 764 765 // The main equation here to remember is: 766 // k * P = k1 * P + k2 * ϕ(P) 767 // 768 // P1 below is P in the equation, P2 below is ϕ(P) in the equation 769 p1x, p1y := curve.bigAffineToField(Bx, By) 770 p1yNeg := new(fieldVal).NegateVal(p1y, 1) 771 p1z := new(fieldVal).SetInt(1) 772 773 // NOTE: ϕ(x,y) = (βx,y). The Jacobian z coordinate is 1, so this math 774 // goes through. 775 p2x := new(fieldVal).Mul2(p1x, curve.beta) 776 p2y := new(fieldVal).Set(p1y) 777 p2yNeg := new(fieldVal).NegateVal(p2y, 1) 778 p2z := new(fieldVal).SetInt(1) 779 780 // Flip the positive and negative values of the points as needed 781 // depending on the signs of k1 and k2. As mentioned in the equation 782 // above, each of k1 and k2 are multiplied by the respective point. 783 // Since -k * P is the same thing as k * -P, and the group law for 784 // elliptic curves states that P(x, y) = -P(x, -y), it's faster and 785 // simplifies the code to just make the point negative. 786 if signK1 == -1 { 787 p1y, p1yNeg = p1yNeg, p1y 788 } 789 if signK2 == -1 { 790 p2y, p2yNeg = p2yNeg, p2y 791 } 792 793 // NAF versions of k1 and k2 should have a lot more zeros. 794 // 795 // The Pos version of the bytes contain the +1s and the Neg versions 796 // contain the -1s. 797 k1PosNAF, k1NegNAF := NAF(k1) 798 k2PosNAF, k2NegNAF := NAF(k2) 799 k1Len := len(k1PosNAF) 800 k2Len := len(k2PosNAF) 801 802 m := k1Len 803 if m < k2Len { 804 m = k2Len 805 } 806 807 // Add left-to-right using the NAF optimization. See algorithm 3.77 808 // from [GECC]. This should be faster overall since there will be a lot 809 // more instances of 0, hence reducing the number of Jacobian additions 810 // at the cost of 1 possible extra doubling. 811 var k1BytePos, k1ByteNeg, k2BytePos, k2ByteNeg byte 812 for i := 0; i < m; i++ { 813 // Since we're going left-to-right, pad the front with 0s. 814 if i < m-k1Len { 815 k1BytePos = 0 816 k1ByteNeg = 0 817 } else { 818 k1BytePos = k1PosNAF[i-(m-k1Len)] 819 k1ByteNeg = k1NegNAF[i-(m-k1Len)] 820 } 821 if i < m-k2Len { 822 k2BytePos = 0 823 k2ByteNeg = 0 824 } else { 825 k2BytePos = k2PosNAF[i-(m-k2Len)] 826 k2ByteNeg = k2NegNAF[i-(m-k2Len)] 827 } 828 829 for j := 7; j >= 0; j-- { 830 // Q = 2 * Q 831 curve.doubleJacobian(qx, qy, qz, qx, qy, qz) 832 833 if k1BytePos&0x80 == 0x80 { 834 curve.addJacobian(qx, qy, qz, p1x, p1y, p1z, 835 qx, qy, qz) 836 } else if k1ByteNeg&0x80 == 0x80 { 837 curve.addJacobian(qx, qy, qz, p1x, p1yNeg, p1z, 838 qx, qy, qz) 839 } 840 841 if k2BytePos&0x80 == 0x80 { 842 curve.addJacobian(qx, qy, qz, p2x, p2y, p2z, 843 qx, qy, qz) 844 } else if k2ByteNeg&0x80 == 0x80 { 845 curve.addJacobian(qx, qy, qz, p2x, p2yNeg, p2z, 846 qx, qy, qz) 847 } 848 k1BytePos <<= 1 849 k1ByteNeg <<= 1 850 k2BytePos <<= 1 851 k2ByteNeg <<= 1 852 } 853 } 854 855 // Convert the Jacobian coordinate field values back to affine big.Ints. 856 return curve.fieldJacobianToBigAffine(qx, qy, qz) 857 } 858 859 // ScalarBaseMult returns k*G where G is the base point of the group and k is a 860 // big endian integer. 861 // Part of the elliptic.Curve interface. 862 func (curve *KoblitzCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { 863 newK := curve.moduloReduce(k) 864 diff := len(curve.bytePoints) - len(newK) 865 866 // Point Q = ∞ (point at infinity). 867 qx, qy, qz := new(fieldVal), new(fieldVal), new(fieldVal) 868 869 // curve.bytePoints has all 256 byte points for each 8-bit window. The 870 // strategy is to add up the byte points. This is best understood by 871 // expressing k in base-256 which it already sort of is. 872 // Each "digit" in the 8-bit window can be looked up using bytePoints 873 // and added together. 874 for i, byteVal := range newK { 875 p := curve.bytePoints[diff+i][byteVal] 876 curve.addJacobian(qx, qy, qz, &p[0], &p[1], &p[2], qx, qy, qz) 877 } 878 return curve.fieldJacobianToBigAffine(qx, qy, qz) 879 } 880 881 // QPlus1Div4 returns the Q+1/4 constant for the curve for use in calculating 882 // square roots via exponention. 883 func (curve *KoblitzCurve) QPlus1Div4() *big.Int { 884 return curve.q 885 } 886 887 var initonce sync.Once 888 var secp256k1 KoblitzCurve 889 890 func initAll() { 891 initS256() 892 } 893 894 // fromHex converts the passed hex string into a big integer pointer and will 895 // panic is there is an error. This is only provided for the hard-coded 896 // constants so errors in the source code can bet detected. It will only (and 897 // must only) be called for initialization purposes. 898 func fromHex(s string) *big.Int { 899 r, ok := new(big.Int).SetString(s, 16) 900 if !ok { 901 panic("invalid hex in source file: " + s) 902 } 903 return r 904 } 905 906 func initS256() { 907 // Curve parameters taken from [SECG] section 2.4.1. 908 secp256k1.CurveParams = new(elliptic.CurveParams) 909 secp256k1.P = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F") 910 secp256k1.N = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") 911 secp256k1.B = fromHex("0000000000000000000000000000000000000000000000000000000000000007") 912 secp256k1.Gx = fromHex("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798") 913 secp256k1.Gy = fromHex("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8") 914 secp256k1.BitSize = 256 915 secp256k1.H = 1 916 secp256k1.q = new(big.Int).Div(new(big.Int).Add(secp256k1.P, 917 big.NewInt(1)), big.NewInt(4)) 918 919 // Provided for convenience since this gets computed repeatedly. 920 secp256k1.byteSize = secp256k1.BitSize / 8 921 922 // Deserialize and set the pre-computed table used to accelerate scalar 923 // base multiplication. This is hard-coded data, so any errors are 924 // panics because it means something is wrong in the source code. 925 if err := loadS256BytePoints(); err != nil { 926 panic(err) 927 } 928 929 // Next 6 constants are from Hal Finney's bitcointalk.org post: 930 // https://bitcointalk.org/index.php?topic=3238.msg45565#msg45565 931 // May he rest in peace. 932 // 933 // They have also been independently derived from the code in the 934 // EndomorphismVectors function in gensecp256k1.go. 935 secp256k1.lambda = fromHex("5363AD4CC05C30E0A5261C028812645A122E22EA20816678DF02967C1B23BD72") 936 secp256k1.beta = new(fieldVal).SetHex("7AE96A2B657C07106E64479EAC3434E99CF0497512F58995C1396C28719501EE") 937 secp256k1.a1 = fromHex("3086D221A7D46BCDE86C90E49284EB15") 938 secp256k1.b1 = fromHex("-E4437ED6010E88286F547FA90ABFE4C3") 939 secp256k1.a2 = fromHex("114CA50F7A8E2F3F657C1108D9D44CFD8") 940 secp256k1.b2 = fromHex("3086D221A7D46BCDE86C90E49284EB15") 941 942 // Alternatively, we can use the parameters below, however, they seem 943 // to be about 8% slower. 944 // secp256k1.lambda = fromHex("AC9C52B33FA3CF1F5AD9E3FD77ED9BA4A880B9FC8EC739C2E0CFC810B51283CE") 945 // secp256k1.beta = new(fieldVal).SetHex("851695D49A83F8EF919BB86153CBCB16630FB68AED0A766A3EC693D68E6AFA40") 946 // secp256k1.a1 = fromHex("E4437ED6010E88286F547FA90ABFE4C3") 947 // secp256k1.b1 = fromHex("-3086D221A7D46BCDE86C90E49284EB15") 948 // secp256k1.a2 = fromHex("3086D221A7D46BCDE86C90E49284EB15") 949 // secp256k1.b2 = fromHex("114CA50F7A8E2F3F657C1108D9D44CFD8") 950 } 951 952 // S256 returns a Curve which implements secp256k1. 953 func S256() *KoblitzCurve { 954 initonce.Do(initAll) 955 return &secp256k1 956 }