curve.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Copyright 2011 ThePiachu. All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. // * The name of ThePiachu may not be used to endorse or promote products
  18. // derived from this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. package secp256k1
  32. import (
  33. "crypto/elliptic"
  34. "math/big"
  35. "unsafe"
  36. "github.com/ethereum/go-ethereum/common/math"
  37. )
  38. /*
  39. #include "libsecp256k1/include/secp256k1.h"
  40. extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned char *point, const unsigned char *scalar);
  41. */
  42. import "C"
  43. // This code is from https://github.com/ThePiachu/GoBit and implements
  44. // several Koblitz elliptic curves over prime fields.
  45. //
  46. // The curve methods, internally, on Jacobian coordinates. For a given
  47. // (x, y) position on the curve, the Jacobian coordinates are (x1, y1,
  48. // z1) where x = x1/z1² and y = y1/z1³. The greatest speedups come
  49. // when the whole calculation can be performed within the transform
  50. // (as in ScalarMult and ScalarBaseMult). But even for Add and Double,
  51. // it's faster to apply and reverse the transform than to operate in
  52. // affine coordinates.
  53. // A BitCurve represents a Koblitz Curve with a=0.
  54. // See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
  55. type BitCurve struct {
  56. P *big.Int // the order of the underlying field
  57. N *big.Int // the order of the base point
  58. B *big.Int // the constant of the BitCurve equation
  59. Gx, Gy *big.Int // (x,y) of the base point
  60. BitSize int // the size of the underlying field
  61. }
  62. func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
  63. return &elliptic.CurveParams{
  64. P: BitCurve.P,
  65. N: BitCurve.N,
  66. B: BitCurve.B,
  67. Gx: BitCurve.Gx,
  68. Gy: BitCurve.Gy,
  69. BitSize: BitCurve.BitSize,
  70. }
  71. }
  72. // IsOnCurve returns true if the given (x,y) lies on the BitCurve.
  73. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
  74. // y² = x³ + b
  75. y2 := new(big.Int).Mul(y, y) //y²
  76. y2.Mod(y2, BitCurve.P) //y²%P
  77. x3 := new(big.Int).Mul(x, x) //x²
  78. x3.Mul(x3, x) //x³
  79. x3.Add(x3, BitCurve.B) //x³+B
  80. x3.Mod(x3, BitCurve.P) //(x³+B)%P
  81. return x3.Cmp(y2) == 0
  82. }
  83. //TODO: double check if the function is okay
  84. // affineFromJacobian reverses the Jacobian transform. See the comment at the
  85. // top of the file.
  86. func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
  87. zinv := new(big.Int).ModInverse(z, BitCurve.P)
  88. zinvsq := new(big.Int).Mul(zinv, zinv)
  89. xOut = new(big.Int).Mul(x, zinvsq)
  90. xOut.Mod(xOut, BitCurve.P)
  91. zinvsq.Mul(zinvsq, zinv)
  92. yOut = new(big.Int).Mul(y, zinvsq)
  93. yOut.Mod(yOut, BitCurve.P)
  94. return
  95. }
  96. // Add returns the sum of (x1,y1) and (x2,y2)
  97. func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
  98. z := new(big.Int).SetInt64(1)
  99. return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
  100. }
  101. // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
  102. // (x2, y2, z2) and returns their sum, also in Jacobian form.
  103. func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
  104. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
  105. z1z1 := new(big.Int).Mul(z1, z1)
  106. z1z1.Mod(z1z1, BitCurve.P)
  107. z2z2 := new(big.Int).Mul(z2, z2)
  108. z2z2.Mod(z2z2, BitCurve.P)
  109. u1 := new(big.Int).Mul(x1, z2z2)
  110. u1.Mod(u1, BitCurve.P)
  111. u2 := new(big.Int).Mul(x2, z1z1)
  112. u2.Mod(u2, BitCurve.P)
  113. h := new(big.Int).Sub(u2, u1)
  114. if h.Sign() == -1 {
  115. h.Add(h, BitCurve.P)
  116. }
  117. i := new(big.Int).Lsh(h, 1)
  118. i.Mul(i, i)
  119. j := new(big.Int).Mul(h, i)
  120. s1 := new(big.Int).Mul(y1, z2)
  121. s1.Mul(s1, z2z2)
  122. s1.Mod(s1, BitCurve.P)
  123. s2 := new(big.Int).Mul(y2, z1)
  124. s2.Mul(s2, z1z1)
  125. s2.Mod(s2, BitCurve.P)
  126. r := new(big.Int).Sub(s2, s1)
  127. if r.Sign() == -1 {
  128. r.Add(r, BitCurve.P)
  129. }
  130. r.Lsh(r, 1)
  131. v := new(big.Int).Mul(u1, i)
  132. x3 := new(big.Int).Set(r)
  133. x3.Mul(x3, x3)
  134. x3.Sub(x3, j)
  135. x3.Sub(x3, v)
  136. x3.Sub(x3, v)
  137. x3.Mod(x3, BitCurve.P)
  138. y3 := new(big.Int).Set(r)
  139. v.Sub(v, x3)
  140. y3.Mul(y3, v)
  141. s1.Mul(s1, j)
  142. s1.Lsh(s1, 1)
  143. y3.Sub(y3, s1)
  144. y3.Mod(y3, BitCurve.P)
  145. z3 := new(big.Int).Add(z1, z2)
  146. z3.Mul(z3, z3)
  147. z3.Sub(z3, z1z1)
  148. if z3.Sign() == -1 {
  149. z3.Add(z3, BitCurve.P)
  150. }
  151. z3.Sub(z3, z2z2)
  152. if z3.Sign() == -1 {
  153. z3.Add(z3, BitCurve.P)
  154. }
  155. z3.Mul(z3, h)
  156. z3.Mod(z3, BitCurve.P)
  157. return x3, y3, z3
  158. }
  159. // Double returns 2*(x,y)
  160. func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
  161. z1 := new(big.Int).SetInt64(1)
  162. return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
  163. }
  164. // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
  165. // returns its double, also in Jacobian form.
  166. func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
  167. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
  168. a := new(big.Int).Mul(x, x) //X1²
  169. b := new(big.Int).Mul(y, y) //Y1²
  170. c := new(big.Int).Mul(b, b) //B²
  171. d := new(big.Int).Add(x, b) //X1+B
  172. d.Mul(d, d) //(X1+B)²
  173. d.Sub(d, a) //(X1+B)²-A
  174. d.Sub(d, c) //(X1+B)²-A-C
  175. d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
  176. e := new(big.Int).Mul(big.NewInt(3), a) //3*A
  177. f := new(big.Int).Mul(e, e) //E²
  178. x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
  179. x3.Sub(f, x3) //F-2*D
  180. x3.Mod(x3, BitCurve.P)
  181. y3 := new(big.Int).Sub(d, x3) //D-X3
  182. y3.Mul(e, y3) //E*(D-X3)
  183. y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
  184. y3.Mod(y3, BitCurve.P)
  185. z3 := new(big.Int).Mul(y, z) //Y1*Z1
  186. z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
  187. z3.Mod(z3, BitCurve.P)
  188. return x3, y3, z3
  189. }
  190. func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) {
  191. // Ensure scalar is exactly 32 bytes. We pad always, even if
  192. // scalar is 32 bytes long, to avoid a timing side channel.
  193. if len(scalar) > 32 {
  194. panic("can't handle scalars > 256 bits")
  195. }
  196. // NOTE: potential timing issue
  197. padded := make([]byte, 32)
  198. copy(padded[32-len(scalar):], scalar)
  199. scalar = padded
  200. // Do the multiplication in C, updating point.
  201. point := make([]byte, 64)
  202. math.ReadBits(Bx, point[:32])
  203. math.ReadBits(By, point[32:])
  204. pointPtr := (*C.uchar)(unsafe.Pointer(&point[0]))
  205. scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0]))
  206. res := C.secp256k1_ext_scalar_mul(context, pointPtr, scalarPtr)
  207. // Unpack the result and clear temporaries.
  208. x := new(big.Int).SetBytes(point[:32])
  209. y := new(big.Int).SetBytes(point[32:])
  210. for i := range point {
  211. point[i] = 0
  212. }
  213. for i := range padded {
  214. scalar[i] = 0
  215. }
  216. if res != 1 {
  217. return nil, nil
  218. }
  219. return x, y
  220. }
  221. // ScalarBaseMult returns k*G, where G is the base point of the group and k is
  222. // an integer in big-endian form.
  223. func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
  224. return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
  225. }
  226. // Marshal converts a point into the form specified in section 4.3.6 of ANSI
  227. // X9.62.
  228. func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
  229. byteLen := (BitCurve.BitSize + 7) >> 3
  230. ret := make([]byte, 1+2*byteLen)
  231. ret[0] = 4 // uncompressed point flag
  232. math.ReadBits(x, ret[1:1+byteLen])
  233. math.ReadBits(y, ret[1+byteLen:])
  234. return ret
  235. }
  236. // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
  237. // error, x = nil.
  238. func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
  239. byteLen := (BitCurve.BitSize + 7) >> 3
  240. if len(data) != 1+2*byteLen {
  241. return
  242. }
  243. if data[0] != 4 { // uncompressed form
  244. return
  245. }
  246. x = new(big.Int).SetBytes(data[1 : 1+byteLen])
  247. y = new(big.Int).SetBytes(data[1+byteLen:])
  248. return
  249. }
  250. var theCurve = new(BitCurve)
  251. func init() {
  252. // See SEC 2 section 2.7.1
  253. // curve parameters taken from:
  254. // http://www.secg.org/collateral/sec2_final.pdf
  255. theCurve.P = math.MustParseBig256("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F")
  256. theCurve.N = math.MustParseBig256("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")
  257. theCurve.B = math.MustParseBig256("0x0000000000000000000000000000000000000000000000000000000000000007")
  258. theCurve.Gx = math.MustParseBig256("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")
  259. theCurve.Gy = math.MustParseBig256("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")
  260. theCurve.BitSize = 256
  261. }
  262. // S256 returns a BitCurve which implements secp256k1.
  263. func S256() *BitCurve {
  264. return theCurve
  265. }