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.

769 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 () == 0
  156. return true
  157. }
  158. // Cmp compares (lexicographic order) z and x and returns:
  159. //
  160. // -1 if z < x
  161. // 0 if z == x
  162. // +1 if z > x
  163. //
  164. func (z *Element) Cmp(x *Element) int {
  165. _z := *z
  166. _x := *x
  167. _z.FromMont()
  168. _x.FromMont()
  169. if _z[0] > _x[0] {
  170. return 1
  171. } else if _z[0] < _x[0] {
  172. return -1
  173. }
  174. return 0
  175. }
  176. // LexicographicallyLargest returns true if this element is strictly lexicographically
  177. // larger than its negation, false otherwise
  178. func (z *Element) LexicographicallyLargest() bool {
  179. // adapted from github.com/zkcrypto/bls12_381
  180. // we check if the element is larger than (q-1) / 2
  181. // if z - (((q -1) / 2) + 1) have no underflow, then z > (q-1) / 2
  182. _z := *z
  183. _z.FromMont()
  184. var b uint64
  185. _, b = bits.Sub64(_z[0], 9223372034707292161, 0)
  186. return b == 0
  187. }
  188. // SetRandom sets z to a random element < q
  189. func (z *Element) SetRandom() (*Element, error) {
  190. var bytes [8]byte
  191. if _, err := io.ReadFull(rand.Reader, bytes[:]); err != nil {
  192. return nil, err
  193. }
  194. z[0] = binary.BigEndian.Uint64(bytes[0:8])
  195. z[0] %= 18446744069414584321
  196. // if z > q --> z -= q
  197. // note: this is NOT constant time
  198. if !(z[0] < 18446744069414584321) {
  199. // var b uint64
  200. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  201. }
  202. return z, nil
  203. }
  204. // One returns 1 (in montgommery form)
  205. func One() Element {
  206. var one Element
  207. one.SetOne()
  208. return one
  209. }
  210. // Halve sets z to z / 2 (mod p)
  211. func (z *Element) Halve() {
  212. var twoInv Element
  213. twoInv.SetOne().Double(&twoInv).Inverse(&twoInv)
  214. z.Mul(z, &twoInv)
  215. }
  216. // API with assembly impl
  217. // Mul z = x * y mod q
  218. // see https://hackmd.io/@zkteam/modular_multiplication
  219. func (z *Element) Mul(x, y *Element) *Element {
  220. mul(z, x, y)
  221. return z
  222. }
  223. // Square z = x * x mod q
  224. // see https://hackmd.io/@zkteam/modular_multiplication
  225. func (z *Element) Square(x *Element) *Element {
  226. mul(z, x, x)
  227. return z
  228. }
  229. // FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
  230. // sets and returns z = z * 1
  231. func (z *Element) FromMont() *Element {
  232. fromMont(z)
  233. return z
  234. }
  235. // Add z = x + y mod q
  236. func (z *Element) Add(x, y *Element) *Element {
  237. add(z, x, y)
  238. return z
  239. }
  240. // Double z = x + x mod q, aka Lsh 1
  241. func (z *Element) Double(x *Element) *Element {
  242. double(z, x)
  243. return z
  244. }
  245. // Sub z = x - y mod q
  246. func (z *Element) Sub(x, y *Element) *Element {
  247. sub(z, x, y)
  248. return z
  249. }
  250. // Neg z = q - x
  251. func (z *Element) Neg(x *Element) *Element {
  252. neg(z, x)
  253. return z
  254. }
  255. // Generic (no ADX instructions, no AMD64) versions of multiplication and squaring algorithms
  256. func _mulGeneric(z, x, y *Element) {
  257. var t [2]uint64
  258. var D uint64
  259. var m, C uint64
  260. // -----------------------------------
  261. // First loop
  262. C, t[0] = bits.Mul64(y[0], x[0])
  263. t[1], D = bits.Add64(t[1], C, 0)
  264. // m = t[0]n'[0] mod W
  265. m = t[0] * 18446744069414584319
  266. // -----------------------------------
  267. // Second loop
  268. C = madd0(m, 18446744069414584321, t[0])
  269. t[0], C = bits.Add64(t[1], C, 0)
  270. t[1], _ = bits.Add64(0, D, C)
  271. if t[1] != 0 {
  272. // we need to reduce, we have a result on 2 words
  273. // var b uint64
  274. z[0], _ = bits.Sub64(t[0], 18446744069414584321, 0)
  275. return
  276. }
  277. // copy t into z
  278. z[0] = t[0]
  279. // if z > q --> z -= q
  280. // note: this is NOT constant time
  281. if !(z[0] < 18446744069414584321) {
  282. // var b uint64
  283. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  284. }
  285. }
  286. func _fromMontGeneric(z *Element) {
  287. // the following lines implement z = z * 1
  288. // with a modified CIOS montgomery multiplication
  289. {
  290. // m = z[0]n'[0] mod W
  291. m := z[0] * 18446744069414584319
  292. C := madd0(m, 18446744069414584321, z[0])
  293. z[0] = C
  294. }
  295. // if z > q --> z -= q
  296. // note: this is NOT constant time
  297. if !(z[0] < 18446744069414584321) {
  298. // var b uint64
  299. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  300. }
  301. }
  302. func _addGeneric(z, x, y *Element) {
  303. var carry uint64
  304. z[0], carry = bits.Add64(x[0], y[0], 0)
  305. // if we overflowed the last addition, z >= q
  306. // if z >= q, z = z - q
  307. if carry != 0 {
  308. // we overflowed, so z >= q
  309. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  310. return
  311. }
  312. // if z > q --> z -= q
  313. // note: this is NOT constant time
  314. if !(z[0] < 18446744069414584321) {
  315. // var b uint64
  316. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  317. }
  318. }
  319. func _doubleGeneric(z, x *Element) {
  320. var carry uint64
  321. z[0], carry = bits.Add64(x[0], x[0], 0)
  322. // if we overflowed the last addition, z >= q
  323. // if z >= q, z = z - q
  324. if carry != 0 {
  325. // we overflowed, so z >= q
  326. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  327. return
  328. }
  329. // if z > q --> z -= q
  330. // note: this is NOT constant time
  331. if !(z[0] < 18446744069414584321) {
  332. // var b uint64
  333. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  334. }
  335. }
  336. func _subGeneric(z, x, y *Element) {
  337. var b uint64
  338. z[0], b = bits.Sub64(x[0], y[0], 0)
  339. if b != 0 {
  340. // var c uint64
  341. z[0], _ = bits.Add64(z[0], 18446744069414584321, 0)
  342. }
  343. }
  344. func _negGeneric(z, x *Element) {
  345. if x.IsZero() {
  346. z.SetZero()
  347. return
  348. }
  349. // var borrow uint64
  350. z[0], _ = bits.Sub64(18446744069414584321, x[0], 0)
  351. }
  352. func _reduceGeneric(z *Element) {
  353. // if z > q --> z -= q
  354. // note: this is NOT constant time
  355. if !(z[0] < 18446744069414584321) {
  356. // var b uint64
  357. z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
  358. }
  359. }
  360. func mulByConstant(z *Element, c uint8) {
  361. switch c {
  362. case 0:
  363. z.SetZero()
  364. return
  365. case 1:
  366. return
  367. case 2:
  368. z.Double(z)
  369. return
  370. case 3:
  371. _z := *z
  372. z.Double(z).Add(z, &_z)
  373. case 5:
  374. _z := *z
  375. z.Double(z).Double(z).Add(z, &_z)
  376. default:
  377. var y Element
  378. y.SetUint64(uint64(c))
  379. z.Mul(z, &y)
  380. }
  381. }
  382. // BatchInvert returns a new slice with every element inverted.
  383. // Uses Montgomery batch inversion trick
  384. func BatchInvert(a []Element) []Element {
  385. res := make([]Element, len(a))
  386. if len(a) == 0 {
  387. return res
  388. }
  389. zeroes := make([]bool, len(a))
  390. accumulator := One()
  391. for i := 0; i < len(a); i++ {
  392. if a[i].IsZero() {
  393. zeroes[i] = true
  394. continue
  395. }
  396. res[i] = accumulator
  397. accumulator.Mul(&accumulator, &a[i])
  398. }
  399. accumulator.Inverse(&accumulator)
  400. for i := len(a) - 1; i >= 0; i-- {
  401. if zeroes[i] {
  402. continue
  403. }
  404. res[i].Mul(&res[i], &accumulator)
  405. accumulator.Mul(&accumulator, &a[i])
  406. }
  407. return res
  408. }
  409. func _butterflyGeneric(a, b *Element) {
  410. t := *a
  411. a.Add(a, b)
  412. b.Sub(&t, b)
  413. }
  414. // BitLen returns the minimum number of bits needed to represent z
  415. // returns 0 if z == 0
  416. func (z *Element) BitLen() int {
  417. return bits.Len64(z[0])
  418. }
  419. // Exp z = x^exponent mod q
  420. func (z *Element) Exp(x Element, exponent *big.Int) *Element {
  421. var bZero big.Int
  422. if exponent.Cmp(&bZero) == 0 {
  423. return z.SetOne()
  424. }
  425. z.Set(&x)
  426. for i := exponent.BitLen() - 2; i >= 0; i-- {
  427. z.Square(z)
  428. if exponent.Bit(i) == 1 {
  429. z.Mul(z, &x)
  430. }
  431. }
  432. return z
  433. }
  434. // ToMont converts z to Montgomery form
  435. // sets and returns z = z * r^2
  436. func (z *Element) ToMont() *Element {
  437. return z.Mul(z, &rSquare)
  438. }
  439. // ToRegular returns z in regular form (doesn't mutate z)
  440. func (z Element) ToRegular() Element {
  441. return *z.FromMont()
  442. }
  443. // String returns the string form of an Element in Montgomery form
  444. func (z *Element) String() string {
  445. zz := *z
  446. zz.FromMont()
  447. if zz.IsUint64() {
  448. return strconv.FormatUint(zz[0], 10)
  449. } else {
  450. var zzNeg Element
  451. zzNeg.Neg(z)
  452. zzNeg.FromMont()
  453. if zzNeg.IsUint64() {
  454. return "-" + strconv.FormatUint(zzNeg[0], 10)
  455. }
  456. }
  457. vv := bigIntPool.Get().(*big.Int)
  458. defer bigIntPool.Put(vv)
  459. return zz.ToBigInt(vv).String()
  460. }
  461. // ToBigInt returns z as a big.Int in Montgomery form
  462. func (z *Element) ToBigInt(res *big.Int) *big.Int {
  463. var b [Limbs * 8]byte
  464. binary.BigEndian.PutUint64(b[0:8], z[0])
  465. return res.SetBytes(b[:])
  466. }
  467. // ToBigIntRegular returns z as a big.Int in regular form
  468. func (z Element) ToBigIntRegular(res *big.Int) *big.Int {
  469. z.FromMont()
  470. return z.ToBigInt(res)
  471. }
  472. // ToUint64Regular returns z as a uint64 in regular form
  473. func (z Element) ToUint64Regular() uint64 {
  474. z.FromMont()
  475. return z[0]
  476. }
  477. // Bytes returns the regular (non montgomery) value
  478. // of z as a big-endian byte array.
  479. func (z *Element) Bytes() (res [Limbs * 8]byte) {
  480. _z := z.ToRegular()
  481. binary.BigEndian.PutUint64(res[0:8], _z[0])
  482. return
  483. }
  484. // Marshal returns the regular (non montgomery) value
  485. // of z as a big-endian byte slice.
  486. func (z *Element) Marshal() []byte {
  487. b := z.Bytes()
  488. return b[:]
  489. }
  490. // SetBytes interprets e as the bytes of a big-endian unsigned integer,
  491. // sets z to that value (in Montgomery form), and returns z.
  492. func (z *Element) SetBytes(e []byte) *Element {
  493. // get a big int from our pool
  494. vv := bigIntPool.Get().(*big.Int)
  495. vv.SetBytes(e)
  496. // set big int
  497. z.SetBigInt(vv)
  498. // put temporary object back in pool
  499. bigIntPool.Put(vv)
  500. return z
  501. }
  502. // SetBigInt sets z to v (regular form) and returns z in Montgomery form
  503. func (z *Element) SetBigInt(v *big.Int) *Element {
  504. z.SetZero()
  505. var zero big.Int
  506. // fast path
  507. c := v.Cmp(&_modulus)
  508. if c == 0 {
  509. // v == 0
  510. return z
  511. } else if c != 1 && v.Cmp(&zero) != -1 {
  512. // 0 < v < q
  513. return z.setBigInt(v)
  514. }
  515. // get temporary big int from the pool
  516. vv := bigIntPool.Get().(*big.Int)
  517. // copy input + modular reduction
  518. vv.Set(v)
  519. vv.Mod(v, &_modulus)
  520. // set big int byte value
  521. z.setBigInt(vv)
  522. // release object into pool
  523. bigIntPool.Put(vv)
  524. return z
  525. }
  526. // setBigInt assumes 0 <= v < q
  527. func (z *Element) setBigInt(v *big.Int) *Element {
  528. vBits := v.Bits()
  529. if bits.UintSize == 64 {
  530. for i := 0; i < len(vBits); i++ {
  531. z[i] = uint64(vBits[i])
  532. }
  533. } else {
  534. for i := 0; i < len(vBits); i++ {
  535. if i%2 == 0 {
  536. z[i/2] = uint64(vBits[i])
  537. } else {
  538. z[i/2] |= uint64(vBits[i]) << 32
  539. }
  540. }
  541. }
  542. return z.ToMont()
  543. }
  544. // SetString creates a big.Int with s (in base 10) and calls SetBigInt on z
  545. func (z *Element) SetString(s string) *Element {
  546. // get temporary big int from the pool
  547. vv := bigIntPool.Get().(*big.Int)
  548. if _, ok := vv.SetString(s, 10); !ok {
  549. panic("Element.SetString failed -> can't parse number in base10 into a big.Int")
  550. }
  551. z.SetBigInt(vv)
  552. // release object into pool
  553. bigIntPool.Put(vv)
  554. return z
  555. }
  556. var (
  557. _bLegendreExponentElement *big.Int
  558. _bSqrtExponentElement *big.Int
  559. )
  560. func init() {
  561. _bLegendreExponentElement, _ = new(big.Int).SetString("7fffffff80000000", 16)
  562. const sqrtExponentElement = "7fffffff"
  563. _bSqrtExponentElement, _ = new(big.Int).SetString(sqrtExponentElement, 16)
  564. }
  565. // Legendre returns the Legendre symbol of z (either +1, -1, or 0.)
  566. func (z *Element) Legendre() int {
  567. var l Element
  568. // z^((q-1)/2)
  569. l.Exp(*z, _bLegendreExponentElement)
  570. if l.IsZero() {
  571. return 0
  572. }
  573. // if l == 1
  574. if l[0] == 4294967295 {
  575. return 1
  576. }
  577. return -1
  578. }
  579. // Sqrt z = √x mod q
  580. // if the square root doesn't exist (x is not a square mod q)
  581. // Sqrt leaves z unchanged and returns nil
  582. func (z *Element) Sqrt(x *Element) *Element {
  583. // q ≡ 1 (mod 4)
  584. // see modSqrtTonelliShanks in math/big/int.go
  585. // using https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
  586. var y, b, t, w Element
  587. // w = x^((s-1)/2))
  588. w.Exp(*x, _bSqrtExponentElement)
  589. // y = x^((s+1)/2)) = w * x
  590. y.Mul(x, &w)
  591. // b = x^s = w * w * x = y * x
  592. b.Mul(&w, &y)
  593. // g = nonResidue ^ s
  594. var g = Element{
  595. 15733474329512464024,
  596. }
  597. r := uint64(32)
  598. // compute legendre symbol
  599. // t = x^((q-1)/2) = r-1 squaring of x^s
  600. t = b
  601. for i := uint64(0); i < r-1; i++ {
  602. t.Square(&t)
  603. }
  604. if t.IsZero() {
  605. return z.SetZero()
  606. }
  607. if !(t[0] == 4294967295) {
  608. // t != 1, we don't have a square root
  609. return nil
  610. }
  611. for {
  612. var m uint64
  613. t = b
  614. // for t != 1
  615. for !(t[0] == 4294967295) {
  616. t.Square(&t)
  617. m++
  618. }
  619. if m == 0 {
  620. return z.Set(&y)
  621. }
  622. // t = g^(2^(r-m-1)) mod q
  623. ge := int(r - m - 1)
  624. t = g
  625. for ge > 0 {
  626. t.Square(&t)
  627. ge--
  628. }
  629. g.Square(&t)
  630. y.Mul(&y, &t)
  631. b.Mul(&b, &g)
  632. r = m
  633. }
  634. }
  635. // Inverse z = x^-1 mod q
  636. // note: allocates a big.Int (math/big)
  637. func (z *Element) Inverse(x *Element) *Element {
  638. var _xNonMont big.Int
  639. x.ToBigIntRegular(&_xNonMont)
  640. _xNonMont.ModInverse(&_xNonMont, Modulus())
  641. z.SetBigInt(&_xNonMont)
  642. return z
  643. }