bn256.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package bn256 implements a particular bilinear group at the 128-bit security level.
  5. //
  6. // Bilinear groups are the basis of many of the new cryptographic protocols
  7. // that have been proposed over the past decade. They consist of a triplet of
  8. // groups (G₁, G₂ and GT) such that there exists a function e(g₁ˣ,g₂ʸ)=gTˣʸ
  9. // (where gₓ is a generator of the respective group). That function is called
  10. // a pairing function.
  11. //
  12. // This package specifically implements the Optimal Ate pairing over a 256-bit
  13. // Barreto-Naehrig curve as described in
  14. // http://cryptojedi.org/papers/dclxvi-20100714.pdf. Its output is compatible
  15. // with the implementation described in that paper.
  16. package bn256
  17. import (
  18. "crypto/rand"
  19. "errors"
  20. "io"
  21. "math/big"
  22. )
  23. // BUG(agl): this implementation is not constant time.
  24. // TODO(agl): keep GF(p²) elements in Mongomery form.
  25. // G1 is an abstract cyclic group. The zero value is suitable for use as the
  26. // output of an operation, but cannot be used as an input.
  27. type G1 struct {
  28. p *curvePoint
  29. }
  30. // RandomG1 returns x and g₁ˣ where x is a random, non-zero number read from r.
  31. func RandomG1(r io.Reader) (*big.Int, *G1, error) {
  32. var k *big.Int
  33. var err error
  34. for {
  35. k, err = rand.Int(r, Order)
  36. if err != nil {
  37. return nil, nil, err
  38. }
  39. if k.Sign() > 0 {
  40. break
  41. }
  42. }
  43. return k, new(G1).ScalarBaseMult(k), nil
  44. }
  45. func (g *G1) String() string {
  46. return "bn256.G1" + g.p.String()
  47. }
  48. // CurvePoints returns p's curve points in big integer
  49. func (e *G1) CurvePoints() (*big.Int, *big.Int, *big.Int, *big.Int) {
  50. return e.p.x, e.p.y, e.p.z, e.p.t
  51. }
  52. // ScalarBaseMult sets e to g*k where g is the generator of the group and
  53. // then returns e.
  54. func (e *G1) ScalarBaseMult(k *big.Int) *G1 {
  55. if e.p == nil {
  56. e.p = newCurvePoint(nil)
  57. }
  58. e.p.Mul(curveGen, k, new(bnPool))
  59. return e
  60. }
  61. // ScalarMult sets e to a*k and then returns e.
  62. func (e *G1) ScalarMult(a *G1, k *big.Int) *G1 {
  63. if e.p == nil {
  64. e.p = newCurvePoint(nil)
  65. }
  66. e.p.Mul(a.p, k, new(bnPool))
  67. return e
  68. }
  69. // Add sets e to a+b and then returns e.
  70. // BUG(agl): this function is not complete: a==b fails.
  71. func (e *G1) Add(a, b *G1) *G1 {
  72. if e.p == nil {
  73. e.p = newCurvePoint(nil)
  74. }
  75. e.p.Add(a.p, b.p, new(bnPool))
  76. return e
  77. }
  78. // Neg sets e to -a and then returns e.
  79. func (e *G1) Neg(a *G1) *G1 {
  80. if e.p == nil {
  81. e.p = newCurvePoint(nil)
  82. }
  83. e.p.Negative(a.p)
  84. return e
  85. }
  86. // Marshal converts n to a byte slice.
  87. func (n *G1) Marshal() []byte {
  88. n.p.MakeAffine(nil)
  89. xBytes := new(big.Int).Mod(n.p.x, P).Bytes()
  90. yBytes := new(big.Int).Mod(n.p.y, P).Bytes()
  91. // Each value is a 256-bit number.
  92. const numBytes = 256 / 8
  93. ret := make([]byte, numBytes*2)
  94. copy(ret[1*numBytes-len(xBytes):], xBytes)
  95. copy(ret[2*numBytes-len(yBytes):], yBytes)
  96. return ret
  97. }
  98. // Unmarshal sets e to the result of converting the output of Marshal back into
  99. // a group element and then returns e.
  100. func (e *G1) Unmarshal(m []byte) ([]byte, error) {
  101. // Each value is a 256-bit number.
  102. const numBytes = 256 / 8
  103. if len(m) != 2*numBytes {
  104. return nil, errors.New("bn256: not enough data")
  105. }
  106. // Unmarshal the points and check their caps
  107. if e.p == nil {
  108. e.p = newCurvePoint(nil)
  109. }
  110. e.p.x.SetBytes(m[0*numBytes : 1*numBytes])
  111. if e.p.x.Cmp(P) >= 0 {
  112. return nil, errors.New("bn256: coordinate exceeds modulus")
  113. }
  114. e.p.y.SetBytes(m[1*numBytes : 2*numBytes])
  115. if e.p.y.Cmp(P) >= 0 {
  116. return nil, errors.New("bn256: coordinate exceeds modulus")
  117. }
  118. // Ensure the point is on the curve
  119. if e.p.x.Sign() == 0 && e.p.y.Sign() == 0 {
  120. // This is the point at infinity.
  121. e.p.y.SetInt64(1)
  122. e.p.z.SetInt64(0)
  123. e.p.t.SetInt64(0)
  124. } else {
  125. e.p.z.SetInt64(1)
  126. e.p.t.SetInt64(1)
  127. if !e.p.IsOnCurve() {
  128. return nil, errors.New("bn256: malformed point")
  129. }
  130. }
  131. return m[2*numBytes:], nil
  132. }
  133. // G2 is an abstract cyclic group. The zero value is suitable for use as the
  134. // output of an operation, but cannot be used as an input.
  135. type G2 struct {
  136. p *twistPoint
  137. }
  138. // RandomG1 returns x and g₂ˣ where x is a random, non-zero number read from r.
  139. func RandomG2(r io.Reader) (*big.Int, *G2, error) {
  140. var k *big.Int
  141. var err error
  142. for {
  143. k, err = rand.Int(r, Order)
  144. if err != nil {
  145. return nil, nil, err
  146. }
  147. if k.Sign() > 0 {
  148. break
  149. }
  150. }
  151. return k, new(G2).ScalarBaseMult(k), nil
  152. }
  153. func (g *G2) String() string {
  154. return "bn256.G2" + g.p.String()
  155. }
  156. // CurvePoints returns the curve points of p which includes the real
  157. // and imaginary parts of the curve point.
  158. func (e *G2) CurvePoints() (*gfP2, *gfP2, *gfP2, *gfP2) {
  159. return e.p.x, e.p.y, e.p.z, e.p.t
  160. }
  161. // ScalarBaseMult sets e to g*k where g is the generator of the group and
  162. // then returns out.
  163. func (e *G2) ScalarBaseMult(k *big.Int) *G2 {
  164. if e.p == nil {
  165. e.p = newTwistPoint(nil)
  166. }
  167. e.p.Mul(twistGen, k, new(bnPool))
  168. return e
  169. }
  170. // ScalarMult sets e to a*k and then returns e.
  171. func (e *G2) ScalarMult(a *G2, k *big.Int) *G2 {
  172. if e.p == nil {
  173. e.p = newTwistPoint(nil)
  174. }
  175. e.p.Mul(a.p, k, new(bnPool))
  176. return e
  177. }
  178. // Add sets e to a+b and then returns e.
  179. // BUG(agl): this function is not complete: a==b fails.
  180. func (e *G2) Add(a, b *G2) *G2 {
  181. if e.p == nil {
  182. e.p = newTwistPoint(nil)
  183. }
  184. e.p.Add(a.p, b.p, new(bnPool))
  185. return e
  186. }
  187. // Marshal converts n into a byte slice.
  188. func (n *G2) Marshal() []byte {
  189. n.p.MakeAffine(nil)
  190. xxBytes := new(big.Int).Mod(n.p.x.x, P).Bytes()
  191. xyBytes := new(big.Int).Mod(n.p.x.y, P).Bytes()
  192. yxBytes := new(big.Int).Mod(n.p.y.x, P).Bytes()
  193. yyBytes := new(big.Int).Mod(n.p.y.y, P).Bytes()
  194. // Each value is a 256-bit number.
  195. const numBytes = 256 / 8
  196. ret := make([]byte, numBytes*4)
  197. copy(ret[1*numBytes-len(xxBytes):], xxBytes)
  198. copy(ret[2*numBytes-len(xyBytes):], xyBytes)
  199. copy(ret[3*numBytes-len(yxBytes):], yxBytes)
  200. copy(ret[4*numBytes-len(yyBytes):], yyBytes)
  201. return ret
  202. }
  203. // Unmarshal sets e to the result of converting the output of Marshal back into
  204. // a group element and then returns e.
  205. func (e *G2) Unmarshal(m []byte) ([]byte, error) {
  206. // Each value is a 256-bit number.
  207. const numBytes = 256 / 8
  208. if len(m) != 4*numBytes {
  209. return nil, errors.New("bn256: not enough data")
  210. }
  211. // Unmarshal the points and check their caps
  212. if e.p == nil {
  213. e.p = newTwistPoint(nil)
  214. }
  215. e.p.x.x.SetBytes(m[0*numBytes : 1*numBytes])
  216. if e.p.x.x.Cmp(P) >= 0 {
  217. return nil, errors.New("bn256: coordinate exceeds modulus")
  218. }
  219. e.p.x.y.SetBytes(m[1*numBytes : 2*numBytes])
  220. if e.p.x.y.Cmp(P) >= 0 {
  221. return nil, errors.New("bn256: coordinate exceeds modulus")
  222. }
  223. e.p.y.x.SetBytes(m[2*numBytes : 3*numBytes])
  224. if e.p.y.x.Cmp(P) >= 0 {
  225. return nil, errors.New("bn256: coordinate exceeds modulus")
  226. }
  227. e.p.y.y.SetBytes(m[3*numBytes : 4*numBytes])
  228. if e.p.y.y.Cmp(P) >= 0 {
  229. return nil, errors.New("bn256: coordinate exceeds modulus")
  230. }
  231. // Ensure the point is on the curve
  232. if e.p.x.x.Sign() == 0 &&
  233. e.p.x.y.Sign() == 0 &&
  234. e.p.y.x.Sign() == 0 &&
  235. e.p.y.y.Sign() == 0 {
  236. // This is the point at infinity.
  237. e.p.y.SetOne()
  238. e.p.z.SetZero()
  239. e.p.t.SetZero()
  240. } else {
  241. e.p.z.SetOne()
  242. e.p.t.SetOne()
  243. if !e.p.IsOnCurve() {
  244. return nil, errors.New("bn256: malformed point")
  245. }
  246. }
  247. return m[4*numBytes:], nil
  248. }
  249. // GT is an abstract cyclic group. The zero value is suitable for use as the
  250. // output of an operation, but cannot be used as an input.
  251. type GT struct {
  252. p *gfP12
  253. }
  254. func (g *GT) String() string {
  255. return "bn256.GT" + g.p.String()
  256. }
  257. // ScalarMult sets e to a*k and then returns e.
  258. func (e *GT) ScalarMult(a *GT, k *big.Int) *GT {
  259. if e.p == nil {
  260. e.p = newGFp12(nil)
  261. }
  262. e.p.Exp(a.p, k, new(bnPool))
  263. return e
  264. }
  265. // Add sets e to a+b and then returns e.
  266. func (e *GT) Add(a, b *GT) *GT {
  267. if e.p == nil {
  268. e.p = newGFp12(nil)
  269. }
  270. e.p.Mul(a.p, b.p, new(bnPool))
  271. return e
  272. }
  273. // Neg sets e to -a and then returns e.
  274. func (e *GT) Neg(a *GT) *GT {
  275. if e.p == nil {
  276. e.p = newGFp12(nil)
  277. }
  278. e.p.Invert(a.p, new(bnPool))
  279. return e
  280. }
  281. // Marshal converts n into a byte slice.
  282. func (n *GT) Marshal() []byte {
  283. n.p.Minimal()
  284. xxxBytes := n.p.x.x.x.Bytes()
  285. xxyBytes := n.p.x.x.y.Bytes()
  286. xyxBytes := n.p.x.y.x.Bytes()
  287. xyyBytes := n.p.x.y.y.Bytes()
  288. xzxBytes := n.p.x.z.x.Bytes()
  289. xzyBytes := n.p.x.z.y.Bytes()
  290. yxxBytes := n.p.y.x.x.Bytes()
  291. yxyBytes := n.p.y.x.y.Bytes()
  292. yyxBytes := n.p.y.y.x.Bytes()
  293. yyyBytes := n.p.y.y.y.Bytes()
  294. yzxBytes := n.p.y.z.x.Bytes()
  295. yzyBytes := n.p.y.z.y.Bytes()
  296. // Each value is a 256-bit number.
  297. const numBytes = 256 / 8
  298. ret := make([]byte, numBytes*12)
  299. copy(ret[1*numBytes-len(xxxBytes):], xxxBytes)
  300. copy(ret[2*numBytes-len(xxyBytes):], xxyBytes)
  301. copy(ret[3*numBytes-len(xyxBytes):], xyxBytes)
  302. copy(ret[4*numBytes-len(xyyBytes):], xyyBytes)
  303. copy(ret[5*numBytes-len(xzxBytes):], xzxBytes)
  304. copy(ret[6*numBytes-len(xzyBytes):], xzyBytes)
  305. copy(ret[7*numBytes-len(yxxBytes):], yxxBytes)
  306. copy(ret[8*numBytes-len(yxyBytes):], yxyBytes)
  307. copy(ret[9*numBytes-len(yyxBytes):], yyxBytes)
  308. copy(ret[10*numBytes-len(yyyBytes):], yyyBytes)
  309. copy(ret[11*numBytes-len(yzxBytes):], yzxBytes)
  310. copy(ret[12*numBytes-len(yzyBytes):], yzyBytes)
  311. return ret
  312. }
  313. // Unmarshal sets e to the result of converting the output of Marshal back into
  314. // a group element and then returns e.
  315. func (e *GT) Unmarshal(m []byte) (*GT, bool) {
  316. // Each value is a 256-bit number.
  317. const numBytes = 256 / 8
  318. if len(m) != 12*numBytes {
  319. return nil, false
  320. }
  321. if e.p == nil {
  322. e.p = newGFp12(nil)
  323. }
  324. e.p.x.x.x.SetBytes(m[0*numBytes : 1*numBytes])
  325. e.p.x.x.y.SetBytes(m[1*numBytes : 2*numBytes])
  326. e.p.x.y.x.SetBytes(m[2*numBytes : 3*numBytes])
  327. e.p.x.y.y.SetBytes(m[3*numBytes : 4*numBytes])
  328. e.p.x.z.x.SetBytes(m[4*numBytes : 5*numBytes])
  329. e.p.x.z.y.SetBytes(m[5*numBytes : 6*numBytes])
  330. e.p.y.x.x.SetBytes(m[6*numBytes : 7*numBytes])
  331. e.p.y.x.y.SetBytes(m[7*numBytes : 8*numBytes])
  332. e.p.y.y.x.SetBytes(m[8*numBytes : 9*numBytes])
  333. e.p.y.y.y.SetBytes(m[9*numBytes : 10*numBytes])
  334. e.p.y.z.x.SetBytes(m[10*numBytes : 11*numBytes])
  335. e.p.y.z.y.SetBytes(m[11*numBytes : 12*numBytes])
  336. return e, true
  337. }
  338. // Pair calculates an Optimal Ate pairing.
  339. func Pair(g1 *G1, g2 *G2) *GT {
  340. return &GT{optimalAte(g2.p, g1.p, new(bnPool))}
  341. }
  342. // PairingCheck calculates the Optimal Ate pairing for a set of points.
  343. func PairingCheck(a []*G1, b []*G2) bool {
  344. pool := new(bnPool)
  345. acc := newGFp12(pool)
  346. acc.SetOne()
  347. for i := 0; i < len(a); i++ {
  348. if a[i].p.IsInfinity() || b[i].p.IsInfinity() {
  349. continue
  350. }
  351. acc.Mul(acc, miller(b[i].p, a[i].p, pool), pool)
  352. }
  353. ret := finalExponentiation(acc, pool)
  354. acc.Put(pool)
  355. return ret.IsOne()
  356. }
  357. // bnPool implements a tiny cache of *big.Int objects that's used to reduce the
  358. // number of allocations made during processing.
  359. type bnPool struct {
  360. bns []*big.Int
  361. count int
  362. }
  363. func (pool *bnPool) Get() *big.Int {
  364. if pool == nil {
  365. return new(big.Int)
  366. }
  367. pool.count++
  368. l := len(pool.bns)
  369. if l == 0 {
  370. return new(big.Int)
  371. }
  372. bn := pool.bns[l-1]
  373. pool.bns = pool.bns[:l-1]
  374. return bn
  375. }
  376. func (pool *bnPool) Put(bn *big.Int) {
  377. if pool == nil {
  378. return
  379. }
  380. pool.bns = append(pool.bns, bn)
  381. pool.count--
  382. }
  383. func (pool *bnPool) Count() int {
  384. return pool.count
  385. }