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.

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