You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

759 lines
16 KiB

  1. // Copyright 2020 ConsenSys Software Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Code generated by consensys/gnark-crypto DO NOT EDIT
  15. package ffg
  16. // /!\ WARNING /!\
  17. // this code has not been audited and is provided as-is. In particular,
  18. // there is no security guarantees such as constant time implementation
  19. // or side-channel attack resistance
  20. // /!\ WARNING /!\
  21. import (
  22. "crypto/rand"
  23. "encoding/binary"
  24. "errors"
  25. "io"
  26. "math/big"
  27. "math/bits"
  28. "reflect"
  29. "strconv"
  30. "sync"
  31. )
  32. // Element represents a field element stored on 1 words (uint64)
  33. // Element are assumed to be in Montgomery form in all methods
  34. // field modulus q =
  35. //
  36. // 18446744069414584321
  37. type Element [1]uint64
  38. // Limbs number of 64 bits words needed to represent Element
  39. const Limbs = 1
  40. // Bits number bits needed to represent Element
  41. const Bits = 64
  42. // Bytes number bytes needed to represent Element
  43. const Bytes = Limbs * 8
  44. // field modulus stored as big.Int
  45. var _modulus big.Int
  46. // Modulus returns q as a big.Int
  47. // q =
  48. //
  49. // 18446744069414584321
  50. func Modulus() *big.Int {
  51. return new(big.Int).Set(&_modulus)
  52. }
  53. // q (modulus)
  54. var qElement = Element{
  55. 18446744069414584321,
  56. }
  57. // rSquare
  58. var rSquare = Element{
  59. 18446744065119617025,
  60. }
  61. var bigIntPool = sync.Pool{
  62. New: func() interface{} {
  63. return new(big.Int)
  64. },
  65. }
  66. func init() {
  67. _modulus.SetString("18446744069414584321", 10)
  68. }
  69. // NewElement returns a new Element
  70. func NewElement() *Element {
  71. return &Element{}
  72. }
  73. // NewElementFromUint64 returns a new Element from a uint64 value
  74. //
  75. // it is equivalent to
  76. // var v NewElement
  77. // v.SetUint64(...)
  78. func NewElementFromUint64(v uint64) *Element {
  79. z := Element{v}
  80. z.Mul(&z, &rSquare)
  81. return &z
  82. }
  83. // SetUint64 z = v, sets z LSB to v (non-Montgomery form) and convert z to Montgomery form
  84. func (z *Element) SetUint64(v uint64) *Element {
  85. *z = Element{v}
  86. return z.Mul(z, &rSquare) // z.ToMont()
  87. }
  88. // Set z = x
  89. func (z *Element) Set(x *Element) *Element {
  90. z[0] = x[0]
  91. return z
  92. }
  93. // SetInterface converts provided interface into Element
  94. // returns an error if provided type is not supported
  95. // supported types: Element, *Element, uint64, int, string (interpreted as base10 integer),
  96. // *big.Int, big.Int, []byte
  97. func (z *Element) SetInterface(i1 interface{}) (*Element, error) {
  98. switch c1 := i1.(type) {
  99. case Element:
  100. return z.Set(&c1), nil
  101. case *Element:
  102. return z.Set(c1), nil
  103. case uint64:
  104. return z.SetUint64(c1), nil
  105. case int:
  106. return z.SetString(strconv.Itoa(c1)), nil
  107. case string:
  108. return z.SetString(c1), nil
  109. case *big.Int:
  110. return z.SetBigInt(c1), nil
  111. case big.Int:
  112. return z.SetBigInt(&c1), nil
  113. case []byte:
  114. return z.SetBytes(c1), nil
  115. default:
  116. return nil, errors.New("can't set ffg.Element from type " + reflect.TypeOf(i1).String())
  117. }
  118. }
  119. // SetZero z = 0
  120. func (z *Element) SetZero() *Element {
  121. z[0] = 0
  122. return z
  123. }
  124. // SetOne z = 1 (in Montgomery form)
  125. func (z *Element) SetOne() *Element {
  126. z[0] = 4294967295
  127. return z
  128. }
  129. // Div z = x*y^-1 mod q
  130. func (z *Element) Div(x, y *Element) *Element {
  131. var yInv Element
  132. yInv.Inverse(y)
  133. z.Mul(x, &yInv)
  134. return z
  135. }
  136. // Bit returns the i'th bit, with lsb == bit 0.
  137. // It is the responsability of the caller to convert from Montgomery to Regular form if needed
  138. func (z *Element) Bit(i uint64) uint64 {
  139. j := i / 64
  140. if j >= 1 {
  141. return 0
  142. }
  143. return uint64(z[j] >> (i % 64) & 1)
  144. }
  145. // Equal returns z == x
  146. func (z *Element) Equal(x *Element) bool {
  147. return (z[0] == x[0])
  148. }
  149. // IsZero returns z == 0
  150. func (z *Element) IsZero() bool {
  151. return (z[0]) == 0
  152. }
  153. // IsUint64 returns true if z[0] >= 0 and all other words are 0
  154. func (z *Element) IsUint64() bool {
  155. return true
  156. }
  157. // Cmp compares (lexicographic order) z and x and returns:
  158. //
  159. // -1 if z < x
  160. // 0 if z == x
  161. // +1 if z > x
  162. //
  163. func (z *Element) Cmp(x *Element) int {
  164. _z := *z
  165. _x := *x
  166. _z.FromMont()
  167. _x.FromMont()
  168. if _z[0] > _x[0] {
  169. return 1
  170. } else if _z[0] < _x[0] {
  171. return -1
  172. }
  173. return 0
  174. }
  175. // LexicographicallyLargest returns true if this element is strictly lexicographically
  176. // larger than its negation, false otherwise
  177. func (z *Element) LexicographicallyLargest() bool {
  178. // adapted from github.com/zkcrypto/bls12_381
  179. // we check if the element is larger than (q-1) / 2
  180. // if z - (((q -1) / 2) + 1) have no underflow, then z > (q-1) / 2
  181. _z := *z
  182. _z.FromMont()
  183. var b uint64
  184. _, b = bits.Sub64(_z[0], 9223372034707292161, 0)
  185. return b == 0
  186. }
  187. // SetRandom sets z to a random element < q
  188. func (z *Element) SetRandom() (*Element, error) {
  189. var bytes [8]byte
  190. if _, err := io.ReadFull(rand.Reader, bytes[:]); err != nil {
  191. return nil, err
  192. }
  193. z[0] = binary.BigEndian.Uint64(bytes[0:8])
  194. z[0] %= 18446744069414584321
  195. // if z > q --> z -= q
  196. // note: this is NOT constant time
  197. if !(z[0] < 18446744069414584321) {
  198. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  199. }
  200. return z, nil
  201. }
  202. // One returns 1 (in montgommery form)
  203. func One() Element {
  204. var one Element
  205. one.SetOne()
  206. return one
  207. }
  208. // Halve sets z to z / 2 (mod p)
  209. func (z *Element) Halve() {
  210. var twoInv Element
  211. twoInv.SetOne().Double(&twoInv).Inverse(&twoInv)
  212. z.Mul(z, &twoInv)
  213. }
  214. // API with assembly impl
  215. // Mul z = x * y mod q
  216. // see https://hackmd.io/@zkteam/modular_multiplication
  217. func (z *Element) Mul(x, y *Element) *Element {
  218. mul(z, x, y)
  219. return z
  220. }
  221. // Square z = x * x mod q
  222. // see https://hackmd.io/@zkteam/modular_multiplication
  223. func (z *Element) Square(x *Element) *Element {
  224. mul(z, x, x)
  225. return z
  226. }
  227. // FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
  228. // sets and returns z = z * 1
  229. func (z *Element) FromMont() *Element {
  230. fromMont(z)
  231. return z
  232. }
  233. // Add z = x + y mod q
  234. func (z *Element) Add(x, y *Element) *Element {
  235. add(z, x, y)
  236. return z
  237. }
  238. // Double z = x + x mod q, aka Lsh 1
  239. func (z *Element) Double(x *Element) *Element {
  240. double(z, x)
  241. return z
  242. }
  243. // Sub z = x - y mod q
  244. func (z *Element) Sub(x, y *Element) *Element {
  245. sub(z, x, y)
  246. return z
  247. }
  248. // Neg z = q - x
  249. func (z *Element) Neg(x *Element) *Element {
  250. neg(z, x)
  251. return z
  252. }
  253. // Generic (no ADX instructions, no AMD64) versions of multiplication and squaring algorithms
  254. func _mulGeneric(z, x, y *Element) {
  255. var t [2]uint64
  256. var D uint64
  257. var m, C uint64
  258. // -----------------------------------
  259. // First loop
  260. C, t[0] = bits.Mul64(y[0], x[0])
  261. t[1], D = bits.Add64(t[1], C, 0)
  262. // m = t[0]n'[0] mod W
  263. m = t[0] * 18446744069414584319
  264. // -----------------------------------
  265. // Second loop
  266. C = madd0(m, 18446744069414584321, t[0])
  267. t[0], C = bits.Add64(t[1], C, 0)
  268. t[1], _ = bits.Add64(0, D, C)
  269. if t[1] != 0 {
  270. // we need to reduce, we have a result on 2 words
  271. z[0], _ = bits.Sub64(t[0], 18446744069414584321, 0)
  272. return
  273. }
  274. // copy t into z
  275. z[0] = t[0]
  276. // if z > q --> z -= q
  277. // note: this is NOT constant time
  278. if !(z[0] < 18446744069414584321) {
  279. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  280. }
  281. }
  282. func _fromMontGeneric(z *Element) {
  283. // the following lines implement z = z * 1
  284. // with a modified CIOS montgomery multiplication
  285. {
  286. // m = z[0]n'[0] mod W
  287. m := z[0] * 18446744069414584319
  288. C := madd0(m, 18446744069414584321, z[0])
  289. z[0] = C
  290. }
  291. // if z > q --> z -= q
  292. // note: this is NOT constant time
  293. if !(z[0] < 18446744069414584321) {
  294. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  295. }
  296. }
  297. func _addGeneric(z, x, y *Element) {
  298. var carry uint64
  299. z[0], carry = bits.Add64(x[0], y[0], 0)
  300. // if we overflowed the last addition, z >= q
  301. // if z >= q, z = z - q
  302. if carry != 0 {
  303. // we overflowed, so z >= q
  304. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  305. return
  306. }
  307. // if z > q --> z -= q
  308. // note: this is NOT constant time
  309. if !(z[0] < 18446744069414584321) {
  310. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  311. }
  312. }
  313. func _doubleGeneric(z, x *Element) {
  314. var carry uint64
  315. z[0], carry = bits.Add64(x[0], x[0], 0)
  316. // if we overflowed the last addition, z >= q
  317. // if z >= q, z = z - q
  318. if carry != 0 {
  319. // we overflowed, so z >= q
  320. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  321. return
  322. }
  323. // if z > q --> z -= q
  324. // note: this is NOT constant time
  325. if !(z[0] < 18446744069414584321) {
  326. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  327. }
  328. }
  329. func _subGeneric(z, x, y *Element) {
  330. var b uint64
  331. z[0], b = bits.Sub64(x[0], y[0], 0)
  332. if b != 0 {
  333. z[0], _ = bits.Add64(z[0], 18446744069414584321, 0)
  334. }
  335. }
  336. func _negGeneric(z, x *Element) {
  337. if x.IsZero() {
  338. z.SetZero()
  339. return
  340. }
  341. z[0], _ = bits.Sub64(18446744069414584321, x[0], 0)
  342. }
  343. func _reduceGeneric(z *Element) {
  344. // if z > q --> z -= q
  345. // note: this is NOT constant time
  346. if !(z[0] < 18446744069414584321) {
  347. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  348. }
  349. }
  350. func mulByConstant(z *Element, c uint8) {
  351. switch c {
  352. case 0:
  353. z.SetZero()
  354. return
  355. case 1:
  356. return
  357. case 2:
  358. z.Double(z)
  359. return
  360. case 3:
  361. _z := *z
  362. z.Double(z).Add(z, &_z)
  363. case 5:
  364. _z := *z
  365. z.Double(z).Double(z).Add(z, &_z)
  366. default:
  367. var y Element
  368. y.SetUint64(uint64(c))
  369. z.Mul(z, &y)
  370. }
  371. }
  372. // BatchInvert returns a new slice with every element inverted.
  373. // Uses Montgomery batch inversion trick
  374. func BatchInvert(a []Element) []Element {
  375. res := make([]Element, len(a))
  376. if len(a) == 0 {
  377. return res
  378. }
  379. zeroes := make([]bool, len(a))
  380. accumulator := One()
  381. for i := 0; i < len(a); i++ {
  382. if a[i].IsZero() {
  383. zeroes[i] = true
  384. continue
  385. }
  386. res[i] = accumulator
  387. accumulator.Mul(&accumulator, &a[i])
  388. }
  389. accumulator.Inverse(&accumulator)
  390. for i := len(a) - 1; i >= 0; i-- {
  391. if zeroes[i] {
  392. continue
  393. }
  394. res[i].Mul(&res[i], &accumulator)
  395. accumulator.Mul(&accumulator, &a[i])
  396. }
  397. return res
  398. }
  399. func _butterflyGeneric(a, b *Element) {
  400. t := *a
  401. a.Add(a, b)
  402. b.Sub(&t, b)
  403. }
  404. // BitLen returns the minimum number of bits needed to represent z
  405. // returns 0 if z == 0
  406. func (z *Element) BitLen() int {
  407. return bits.Len64(z[0])
  408. }
  409. // Exp z = x^exponent mod q
  410. func (z *Element) Exp(x Element, exponent *big.Int) *Element {
  411. var bZero big.Int
  412. if exponent.Cmp(&bZero) == 0 {
  413. return z.SetOne()
  414. }
  415. z.Set(&x)
  416. for i := exponent.BitLen() - 2; i >= 0; i-- {
  417. z.Square(z)
  418. if exponent.Bit(i) == 1 {
  419. z.Mul(z, &x)
  420. }
  421. }
  422. return z
  423. }
  424. // ToMont converts z to Montgomery form
  425. // sets and returns z = z * r^2
  426. func (z *Element) ToMont() *Element {
  427. return z.Mul(z, &rSquare)
  428. }
  429. // ToRegular returns z in regular form (doesn't mutate z)
  430. func (z Element) ToRegular() Element {
  431. return *z.FromMont()
  432. }
  433. // String returns the string form of an Element in Montgomery form
  434. func (z *Element) String() string {
  435. zz := *z
  436. zz.FromMont()
  437. if zz.IsUint64() {
  438. return strconv.FormatUint(zz[0], 10)
  439. } else {
  440. var zzNeg Element
  441. zzNeg.Neg(z)
  442. zzNeg.FromMont()
  443. if zzNeg.IsUint64() {
  444. return "-" + strconv.FormatUint(zzNeg[0], 10)
  445. }
  446. }
  447. vv := bigIntPool.Get().(*big.Int)
  448. defer bigIntPool.Put(vv)
  449. return zz.ToBigInt(vv).String()
  450. }
  451. // ToBigInt returns z as a big.Int in Montgomery form
  452. func (z *Element) ToBigInt(res *big.Int) *big.Int {
  453. var b [Limbs * 8]byte
  454. binary.BigEndian.PutUint64(b[0:8], z[0])
  455. return res.SetBytes(b[:])
  456. }
  457. // ToBigIntRegular returns z as a big.Int in regular form
  458. func (z Element) ToBigIntRegular(res *big.Int) *big.Int {
  459. z.FromMont()
  460. return z.ToBigInt(res)
  461. }
  462. // ToUint64Regular returns z as a uint64 in regular form
  463. func (z Element) ToUint64Regular() uint64 {
  464. z.FromMont()
  465. return z[0]
  466. }
  467. // Bytes returns the regular (non montgomery) value
  468. // of z as a big-endian byte array.
  469. func (z *Element) Bytes() (res [Limbs * 8]byte) {
  470. _z := z.ToRegular()
  471. binary.BigEndian.PutUint64(res[0:8], _z[0])
  472. return
  473. }
  474. // Marshal returns the regular (non montgomery) value
  475. // of z as a big-endian byte slice.
  476. func (z *Element) Marshal() []byte {
  477. b := z.Bytes()
  478. return b[:]
  479. }
  480. // SetBytes interprets e as the bytes of a big-endian unsigned integer,
  481. // sets z to that value (in Montgomery form), and returns z.
  482. func (z *Element) SetBytes(e []byte) *Element {
  483. // get a big int from our pool
  484. vv := bigIntPool.Get().(*big.Int)
  485. vv.SetBytes(e)
  486. // set big int
  487. z.SetBigInt(vv)
  488. // put temporary object back in pool
  489. bigIntPool.Put(vv)
  490. return z
  491. }
  492. // SetBigInt sets z to v (regular form) and returns z in Montgomery form
  493. func (z *Element) SetBigInt(v *big.Int) *Element {
  494. z.SetZero()
  495. var zero big.Int
  496. // fast path
  497. c := v.Cmp(&_modulus)
  498. if c == 0 {
  499. // v == 0
  500. return z
  501. } else if c != 1 && v.Cmp(&zero) != -1 {
  502. // 0 < v < q
  503. return z.setBigInt(v)
  504. }
  505. // get temporary big int from the pool
  506. vv := bigIntPool.Get().(*big.Int)
  507. // copy input + modular reduction
  508. vv.Set(v)
  509. vv.Mod(v, &_modulus)
  510. // set big int byte value
  511. z.setBigInt(vv)
  512. // release object into pool
  513. bigIntPool.Put(vv)
  514. return z
  515. }
  516. // setBigInt assumes 0 <= v < q
  517. func (z *Element) setBigInt(v *big.Int) *Element {
  518. vBits := v.Bits()
  519. if bits.UintSize == 64 {
  520. for i := 0; i < len(vBits); i++ {
  521. z[i] = uint64(vBits[i])
  522. }
  523. } else {
  524. for i := 0; i < len(vBits); i++ {
  525. if i%2 == 0 {
  526. z[i/2] = uint64(vBits[i])
  527. } else {
  528. z[i/2] |= uint64(vBits[i]) << 32
  529. }
  530. }
  531. }
  532. return z.ToMont()
  533. }
  534. // SetString creates a big.Int with s (in base 10) and calls SetBigInt on z
  535. func (z *Element) SetString(s string) *Element {
  536. // get temporary big int from the pool
  537. vv := bigIntPool.Get().(*big.Int)
  538. if _, ok := vv.SetString(s, 10); !ok {
  539. panic("Element.SetString failed -> can't parse number in base10 into a big.Int")
  540. }
  541. z.SetBigInt(vv)
  542. // release object into pool
  543. bigIntPool.Put(vv)
  544. return z
  545. }
  546. var (
  547. _bLegendreExponentElement *big.Int
  548. _bSqrtExponentElement *big.Int
  549. )
  550. func init() {
  551. _bLegendreExponentElement, _ = new(big.Int).SetString("7fffffff80000000", 16)
  552. const sqrtExponentElement = "7fffffff"
  553. _bSqrtExponentElement, _ = new(big.Int).SetString(sqrtExponentElement, 16)
  554. }
  555. // Legendre returns the Legendre symbol of z (either +1, -1, or 0.)
  556. func (z *Element) Legendre() int {
  557. var l Element
  558. // z^((q-1)/2)
  559. l.Exp(*z, _bLegendreExponentElement)
  560. if l.IsZero() {
  561. return 0
  562. }
  563. // if l == 1
  564. if l[0] == 4294967295 {
  565. return 1
  566. }
  567. return -1
  568. }
  569. // Sqrt z = √x mod q
  570. // if the square root doesn't exist (x is not a square mod q)
  571. // Sqrt leaves z unchanged and returns nil
  572. func (z *Element) Sqrt(x *Element) *Element {
  573. // q ≡ 1 (mod 4)
  574. // see modSqrtTonelliShanks in math/big/int.go
  575. // using https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
  576. var y, b, t, w Element
  577. // w = x^((s-1)/2))
  578. w.Exp(*x, _bSqrtExponentElement)
  579. // y = x^((s+1)/2)) = w * x
  580. y.Mul(x, &w)
  581. // b = x^s = w * w * x = y * x
  582. b.Mul(&w, &y)
  583. // g = nonResidue ^ s
  584. var g = Element{
  585. 15733474329512464024,
  586. }
  587. r := uint64(32)
  588. // compute legendre symbol
  589. // t = x^((q-1)/2) = r-1 squaring of x^s
  590. t = b
  591. for i := uint64(0); i < r-1; i++ {
  592. t.Square(&t)
  593. }
  594. if t.IsZero() {
  595. return z.SetZero()
  596. }
  597. if !(t[0] == 4294967295) {
  598. // t != 1, we don't have a square root
  599. return nil
  600. }
  601. for {
  602. var m uint64
  603. t = b
  604. // for t != 1
  605. for !(t[0] == 4294967295) {
  606. t.Square(&t)
  607. m++
  608. }
  609. if m == 0 {
  610. return z.Set(&y)
  611. }
  612. // t = g^(2^(r-m-1)) mod q
  613. ge := int(r - m - 1)
  614. t = g
  615. for ge > 0 {
  616. t.Square(&t)
  617. ge--
  618. }
  619. g.Square(&t)
  620. y.Mul(&y, &t)
  621. b.Mul(&b, &g)
  622. r = m
  623. }
  624. }
  625. // Inverse z = x^-1 mod q
  626. // note: allocates a big.Int (math/big)
  627. func (z *Element) Inverse(x *Element) *Element {
  628. var _xNonMont big.Int
  629. x.ToBigIntRegular(&_xNonMont)
  630. _xNonMont.ModInverse(&_xNonMont, Modulus())
  631. z.SetBigInt(&_xNonMont)
  632. return z
  633. }