github.com/consensys/gnark-crypto@v0.14.0/field/goldilocks/element.go (about)

     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  
    15  // Code generated by consensys/gnark-crypto DO NOT EDIT
    16  
    17  package goldilocks
    18  
    19  import (
    20  	"crypto/rand"
    21  	"encoding/binary"
    22  	"errors"
    23  	"io"
    24  	"math/big"
    25  	"math/bits"
    26  	"reflect"
    27  	"strconv"
    28  	"strings"
    29  
    30  	"github.com/bits-and-blooms/bitset"
    31  	"github.com/consensys/gnark-crypto/field/hash"
    32  	"github.com/consensys/gnark-crypto/field/pool"
    33  )
    34  
    35  // Element represents a field element stored on 1 words (uint64)
    36  //
    37  // Element are assumed to be in Montgomery form in all methods.
    38  //
    39  // Modulus q =
    40  //
    41  //	q[base10] = 18446744069414584321
    42  //	q[base16] = 0xffffffff00000001
    43  //
    44  // # Warning
    45  //
    46  // This code has not been audited and is provided as-is. In particular, there is no security guarantees such as constant time implementation or side-channel attack resistance.
    47  type Element [1]uint64
    48  
    49  const (
    50  	Limbs = 1  // number of 64 bits words needed to represent a Element
    51  	Bits  = 64 // number of bits needed to represent a Element
    52  	Bytes = 8  // number of bytes needed to represent a Element
    53  )
    54  
    55  // Field modulus q
    56  const (
    57  	q0 uint64 = 18446744069414584321
    58  	q  uint64 = q0
    59  )
    60  
    61  var qElement = Element{
    62  	q0,
    63  }
    64  
    65  var _modulus big.Int // q stored as big.Int
    66  
    67  // Modulus returns q as a big.Int
    68  //
    69  //	q[base10] = 18446744069414584321
    70  //	q[base16] = 0xffffffff00000001
    71  func Modulus() *big.Int {
    72  	return new(big.Int).Set(&_modulus)
    73  }
    74  
    75  // q + r'.r = 1, i.e., qInvNeg = - q⁻¹ mod r
    76  // used for Montgomery reduction
    77  const qInvNeg uint64 = 18446744069414584319
    78  
    79  func init() {
    80  	_modulus.SetString("ffffffff00000001", 16)
    81  }
    82  
    83  // NewElement returns a new Element from a uint64 value
    84  //
    85  // it is equivalent to
    86  //
    87  //	var v Element
    88  //	v.SetUint64(...)
    89  func NewElement(v uint64) Element {
    90  	z := Element{v}
    91  	z.Mul(&z, &rSquare)
    92  	return z
    93  }
    94  
    95  // SetUint64 sets z to v and returns z
    96  func (z *Element) SetUint64(v uint64) *Element {
    97  	//  sets z LSB to v (non-Montgomery form) and convert z to Montgomery form
    98  	*z = Element{v}
    99  	return z.Mul(z, &rSquare) // z.toMont()
   100  }
   101  
   102  // SetInt64 sets z to v and returns z
   103  func (z *Element) SetInt64(v int64) *Element {
   104  
   105  	// absolute value of v
   106  	m := v >> 63
   107  	z.SetUint64(uint64((v ^ m) - m))
   108  
   109  	if m != 0 {
   110  		// v is negative
   111  		z.Neg(z)
   112  	}
   113  
   114  	return z
   115  }
   116  
   117  // Set z = x and returns z
   118  func (z *Element) Set(x *Element) *Element {
   119  	z[0] = x[0]
   120  	return z
   121  }
   122  
   123  // SetInterface converts provided interface into Element
   124  // returns an error if provided type is not supported
   125  // supported types:
   126  //
   127  //	Element
   128  //	*Element
   129  //	uint64
   130  //	int
   131  //	string (see SetString for valid formats)
   132  //	*big.Int
   133  //	big.Int
   134  //	[]byte
   135  func (z *Element) SetInterface(i1 interface{}) (*Element, error) {
   136  	if i1 == nil {
   137  		return nil, errors.New("can't set goldilocks.Element with <nil>")
   138  	}
   139  
   140  	switch c1 := i1.(type) {
   141  	case Element:
   142  		return z.Set(&c1), nil
   143  	case *Element:
   144  		if c1 == nil {
   145  			return nil, errors.New("can't set goldilocks.Element with <nil>")
   146  		}
   147  		return z.Set(c1), nil
   148  	case uint8:
   149  		return z.SetUint64(uint64(c1)), nil
   150  	case uint16:
   151  		return z.SetUint64(uint64(c1)), nil
   152  	case uint32:
   153  		return z.SetUint64(uint64(c1)), nil
   154  	case uint:
   155  		return z.SetUint64(uint64(c1)), nil
   156  	case uint64:
   157  		return z.SetUint64(c1), nil
   158  	case int8:
   159  		return z.SetInt64(int64(c1)), nil
   160  	case int16:
   161  		return z.SetInt64(int64(c1)), nil
   162  	case int32:
   163  		return z.SetInt64(int64(c1)), nil
   164  	case int64:
   165  		return z.SetInt64(c1), nil
   166  	case int:
   167  		return z.SetInt64(int64(c1)), nil
   168  	case string:
   169  		return z.SetString(c1)
   170  	case *big.Int:
   171  		if c1 == nil {
   172  			return nil, errors.New("can't set goldilocks.Element with <nil>")
   173  		}
   174  		return z.SetBigInt(c1), nil
   175  	case big.Int:
   176  		return z.SetBigInt(&c1), nil
   177  	case []byte:
   178  		return z.SetBytes(c1), nil
   179  	default:
   180  		return nil, errors.New("can't set goldilocks.Element from type " + reflect.TypeOf(i1).String())
   181  	}
   182  }
   183  
   184  // SetZero z = 0
   185  func (z *Element) SetZero() *Element {
   186  	z[0] = 0
   187  	return z
   188  }
   189  
   190  // SetOne z = 1 (in Montgomery form)
   191  func (z *Element) SetOne() *Element {
   192  	z[0] = 4294967295
   193  	return z
   194  }
   195  
   196  // Div z = x*y⁻¹ (mod q)
   197  func (z *Element) Div(x, y *Element) *Element {
   198  	var yInv Element
   199  	yInv.Inverse(y)
   200  	z.Mul(x, &yInv)
   201  	return z
   202  }
   203  
   204  // Equal returns z == x; constant-time
   205  func (z *Element) Equal(x *Element) bool {
   206  	return z.NotEqual(x) == 0
   207  }
   208  
   209  // NotEqual returns 0 if and only if z == x; constant-time
   210  func (z *Element) NotEqual(x *Element) uint64 {
   211  	return (z[0] ^ x[0])
   212  }
   213  
   214  // IsZero returns z == 0
   215  func (z *Element) IsZero() bool {
   216  	return (z[0]) == 0
   217  }
   218  
   219  // IsOne returns z == 1
   220  func (z *Element) IsOne() bool {
   221  	return z[0] == 4294967295
   222  }
   223  
   224  // IsUint64 reports whether z can be represented as an uint64.
   225  func (z *Element) IsUint64() bool {
   226  	return true
   227  }
   228  
   229  // Uint64 returns the uint64 representation of x. If x cannot be represented in a uint64, the result is undefined.
   230  func (z *Element) Uint64() uint64 {
   231  	return z.Bits()[0]
   232  }
   233  
   234  // FitsOnOneWord reports whether z words (except the least significant word) are 0
   235  //
   236  // It is the responsibility of the caller to convert from Montgomery to Regular form if needed.
   237  func (z *Element) FitsOnOneWord() bool {
   238  	return true
   239  }
   240  
   241  // Cmp compares (lexicographic order) z and x and returns:
   242  //
   243  //	-1 if z <  x
   244  //	 0 if z == x
   245  //	+1 if z >  x
   246  func (z *Element) Cmp(x *Element) int {
   247  	_z := z.Bits()
   248  	_x := x.Bits()
   249  	if _z[0] > _x[0] {
   250  		return 1
   251  	} else if _z[0] < _x[0] {
   252  		return -1
   253  	}
   254  	return 0
   255  }
   256  
   257  // LexicographicallyLargest returns true if this element is strictly lexicographically
   258  // larger than its negation, false otherwise
   259  func (z *Element) LexicographicallyLargest() bool {
   260  	// adapted from github.com/zkcrypto/bls12_381
   261  	// we check if the element is larger than (q-1) / 2
   262  	// if z - (((q -1) / 2) + 1) have no underflow, then z > (q-1) / 2
   263  
   264  	_z := z.Bits()
   265  
   266  	var b uint64
   267  	_, b = bits.Sub64(_z[0], 9223372034707292161, 0)
   268  
   269  	return b == 0
   270  }
   271  
   272  // SetRandom sets z to a uniform random value in [0, q).
   273  //
   274  // This might error only if reading from crypto/rand.Reader errors,
   275  // in which case, value of z is undefined.
   276  func (z *Element) SetRandom() (*Element, error) {
   277  	// this code is generated for all modulus
   278  	// and derived from go/src/crypto/rand/util.go
   279  
   280  	// l is number of limbs * 8; the number of bytes needed to reconstruct 1 uint64
   281  	const l = 8
   282  
   283  	// bitLen is the maximum bit length needed to encode a value < q.
   284  	const bitLen = 64
   285  
   286  	// k is the maximum byte length needed to encode a value < q.
   287  	const k = (bitLen + 7) / 8
   288  
   289  	// b is the number of bits in the most significant byte of q-1.
   290  	b := uint(bitLen % 8)
   291  	if b == 0 {
   292  		b = 8
   293  	}
   294  
   295  	var bytes [l]byte
   296  
   297  	for {
   298  		// note that bytes[k:l] is always 0
   299  		if _, err := io.ReadFull(rand.Reader, bytes[:k]); err != nil {
   300  			return nil, err
   301  		}
   302  
   303  		// Clear unused bits in in the most significant byte to increase probability
   304  		// that the candidate is < q.
   305  		bytes[k-1] &= uint8(int(1<<b) - 1)
   306  		z[0] = binary.LittleEndian.Uint64(bytes[0:8])
   307  
   308  		if !z.smallerThanModulus() {
   309  			continue // ignore the candidate and re-sample
   310  		}
   311  
   312  		return z, nil
   313  	}
   314  }
   315  
   316  // smallerThanModulus returns true if z < q
   317  // This is not constant time
   318  func (z *Element) smallerThanModulus() bool {
   319  	return z[0] < q
   320  }
   321  
   322  // One returns 1
   323  func One() Element {
   324  	var one Element
   325  	one.SetOne()
   326  	return one
   327  }
   328  
   329  // Halve sets z to z / 2 (mod q)
   330  func (z *Element) Halve() {
   331  	var carry uint64
   332  
   333  	if z[0]&1 == 1 {
   334  		// z = z + q
   335  		z[0], carry = bits.Add64(z[0], q0, 0)
   336  
   337  	}
   338  	// z = z >> 1
   339  	z[0] >>= 1
   340  
   341  	if carry != 0 {
   342  		// when we added q, the result was larger than our available limbs
   343  		// when we shift right, we need to set the highest bit
   344  		z[0] |= (1 << 63)
   345  	}
   346  
   347  }
   348  
   349  // fromMont converts z in place (i.e. mutates) from Montgomery to regular representation
   350  // sets and returns z = z * 1
   351  func (z *Element) fromMont() *Element {
   352  	fromMont(z)
   353  	return z
   354  }
   355  
   356  // Add z = x + y (mod q)
   357  func (z *Element) Add(x, y *Element) *Element {
   358  
   359  	var carry uint64
   360  	z[0], carry = bits.Add64(x[0], y[0], 0)
   361  	if carry != 0 || z[0] >= q {
   362  		z[0] -= q
   363  	}
   364  	return z
   365  }
   366  
   367  // Double z = x + x (mod q), aka Lsh 1
   368  func (z *Element) Double(x *Element) *Element {
   369  	if x[0]&(1<<63) == (1 << 63) {
   370  		// if highest bit is set, then we have a carry to x + x, we shift and subtract q
   371  		z[0] = (x[0] << 1) - q
   372  	} else {
   373  		// highest bit is not set, but x + x can still be >= q
   374  		z[0] = (x[0] << 1)
   375  		if z[0] >= q {
   376  			z[0] -= q
   377  		}
   378  	}
   379  	return z
   380  }
   381  
   382  // Sub z = x - y (mod q)
   383  func (z *Element) Sub(x, y *Element) *Element {
   384  	var b uint64
   385  	z[0], b = bits.Sub64(x[0], y[0], 0)
   386  	if b != 0 {
   387  		z[0] += q
   388  	}
   389  	return z
   390  }
   391  
   392  // Neg z = q - x
   393  func (z *Element) Neg(x *Element) *Element {
   394  	if x.IsZero() {
   395  		z.SetZero()
   396  		return z
   397  	}
   398  	z[0] = q - x[0]
   399  	return z
   400  }
   401  
   402  // Select is a constant-time conditional move.
   403  // If c=0, z = x0. Else z = x1
   404  func (z *Element) Select(c int, x0 *Element, x1 *Element) *Element {
   405  	cC := uint64((int64(c) | -int64(c)) >> 63) // "canonicized" into: 0 if c=0, -1 otherwise
   406  	z[0] = x0[0] ^ cC&(x0[0]^x1[0])
   407  	return z
   408  }
   409  
   410  // _mulGeneric is unoptimized textbook CIOS
   411  // it is a fallback solution on x86 when ADX instruction set is not available
   412  // and is used for testing purposes.
   413  func _mulGeneric(z, x, y *Element) {
   414  
   415  	// Implements CIOS multiplication -- section 2.3.2 of Tolga Acar's thesis
   416  	// https://www.microsoft.com/en-us/research/wp-content/uploads/1998/06/97Acar.pdf
   417  	//
   418  	// The algorithm:
   419  	//
   420  	// for i=0 to N-1
   421  	// 		C := 0
   422  	// 		for j=0 to N-1
   423  	// 			(C,t[j]) := t[j] + x[j]*y[i] + C
   424  	// 		(t[N+1],t[N]) := t[N] + C
   425  	//
   426  	// 		C := 0
   427  	// 		m := t[0]*q'[0] mod D
   428  	// 		(C,_) := t[0] + m*q[0]
   429  	// 		for j=1 to N-1
   430  	// 			(C,t[j-1]) := t[j] + m*q[j] + C
   431  	//
   432  	// 		(C,t[N-1]) := t[N] + C
   433  	// 		t[N] := t[N+1] + C
   434  	//
   435  	// → N is the number of machine words needed to store the modulus q
   436  	// → D is the word size. For example, on a 64-bit architecture D is 2	64
   437  	// → x[i], y[i], q[i] is the ith word of the numbers x,y,q
   438  	// → q'[0] is the lowest word of the number -q⁻¹ mod r. This quantity is pre-computed, as it does not depend on the inputs.
   439  	// → t is a temporary array of size N+2
   440  	// → C, S are machine words. A pair (C,S) refers to (hi-bits, lo-bits) of a two-word number
   441  
   442  	var t [2]uint64
   443  	var D uint64
   444  	var m, C uint64
   445  	// -----------------------------------
   446  	// First loop
   447  
   448  	C, t[0] = bits.Mul64(y[0], x[0])
   449  
   450  	t[1], D = bits.Add64(t[1], C, 0)
   451  
   452  	// m = t[0]n'[0] mod W
   453  	m = t[0] * qInvNeg
   454  
   455  	// -----------------------------------
   456  	// Second loop
   457  	C = madd0(m, q0, t[0])
   458  
   459  	t[0], C = bits.Add64(t[1], C, 0)
   460  	t[1], _ = bits.Add64(0, D, C)
   461  
   462  	if t[1] != 0 {
   463  		// we need to reduce, we have a result on 2 words
   464  		z[0], _ = bits.Sub64(t[0], q0, 0)
   465  		return
   466  	}
   467  
   468  	// copy t into z
   469  	z[0] = t[0]
   470  
   471  	// if z ⩾ q → z -= q
   472  	if !z.smallerThanModulus() {
   473  		z[0] -= q
   474  	}
   475  }
   476  
   477  func _fromMontGeneric(z *Element) {
   478  	// the following lines implement z = z * 1
   479  	// with a modified CIOS montgomery multiplication
   480  	// see Mul for algorithm documentation
   481  	{
   482  		// m = z[0]n'[0] mod W
   483  		m := z[0] * qInvNeg
   484  		C := madd0(m, q0, z[0])
   485  		z[0] = C
   486  	}
   487  
   488  	// if z ⩾ q → z -= q
   489  	if !z.smallerThanModulus() {
   490  		z[0] -= q
   491  	}
   492  }
   493  
   494  func _reduceGeneric(z *Element) {
   495  
   496  	// if z ⩾ q → z -= q
   497  	if !z.smallerThanModulus() {
   498  		z[0] -= q
   499  	}
   500  }
   501  
   502  // BatchInvert returns a new slice with every element inverted.
   503  // Uses Montgomery batch inversion trick
   504  func BatchInvert(a []Element) []Element {
   505  	res := make([]Element, len(a))
   506  	if len(a) == 0 {
   507  		return res
   508  	}
   509  
   510  	zeroes := bitset.New(uint(len(a)))
   511  	accumulator := One()
   512  
   513  	for i := 0; i < len(a); i++ {
   514  		if a[i].IsZero() {
   515  			zeroes.Set(uint(i))
   516  			continue
   517  		}
   518  		res[i] = accumulator
   519  		accumulator.Mul(&accumulator, &a[i])
   520  	}
   521  
   522  	accumulator.Inverse(&accumulator)
   523  
   524  	for i := len(a) - 1; i >= 0; i-- {
   525  		if zeroes.Test(uint(i)) {
   526  			continue
   527  		}
   528  		res[i].Mul(&res[i], &accumulator)
   529  		accumulator.Mul(&accumulator, &a[i])
   530  	}
   531  
   532  	return res
   533  }
   534  
   535  func _butterflyGeneric(a, b *Element) {
   536  	t := *a
   537  	a.Add(a, b)
   538  	b.Sub(&t, b)
   539  }
   540  
   541  // BitLen returns the minimum number of bits needed to represent z
   542  // returns 0 if z == 0
   543  func (z *Element) BitLen() int {
   544  	return bits.Len64(z[0])
   545  }
   546  
   547  // Hash msg to count prime field elements.
   548  // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-06#section-5.2
   549  func Hash(msg, dst []byte, count int) ([]Element, error) {
   550  	// 128 bits of security
   551  	// L = ceil((ceil(log2(p)) + k) / 8), where k is the security parameter = 128
   552  	const Bytes = 1 + (Bits-1)/8
   553  	const L = 16 + Bytes
   554  
   555  	lenInBytes := count * L
   556  	pseudoRandomBytes, err := hash.ExpandMsgXmd(msg, dst, lenInBytes)
   557  	if err != nil {
   558  		return nil, err
   559  	}
   560  
   561  	// get temporary big int from the pool
   562  	vv := pool.BigInt.Get()
   563  
   564  	res := make([]Element, count)
   565  	for i := 0; i < count; i++ {
   566  		vv.SetBytes(pseudoRandomBytes[i*L : (i+1)*L])
   567  		res[i].SetBigInt(vv)
   568  	}
   569  
   570  	// release object into pool
   571  	pool.BigInt.Put(vv)
   572  
   573  	return res, nil
   574  }
   575  
   576  // Exp z = xᵏ (mod q)
   577  func (z *Element) Exp(x Element, k *big.Int) *Element {
   578  	if k.IsUint64() && k.Uint64() == 0 {
   579  		return z.SetOne()
   580  	}
   581  
   582  	e := k
   583  	if k.Sign() == -1 {
   584  		// negative k, we invert
   585  		// if k < 0: xᵏ (mod q) == (x⁻¹)ᵏ (mod q)
   586  		x.Inverse(&x)
   587  
   588  		// we negate k in a temp big.Int since
   589  		// Int.Bit(_) of k and -k is different
   590  		e = pool.BigInt.Get()
   591  		defer pool.BigInt.Put(e)
   592  		e.Neg(k)
   593  	}
   594  
   595  	z.Set(&x)
   596  
   597  	for i := e.BitLen() - 2; i >= 0; i-- {
   598  		z.Square(z)
   599  		if e.Bit(i) == 1 {
   600  			z.Mul(z, &x)
   601  		}
   602  	}
   603  
   604  	return z
   605  }
   606  
   607  // rSquare where r is the Montgommery constant
   608  // see section 2.3.2 of Tolga Acar's thesis
   609  // https://www.microsoft.com/en-us/research/wp-content/uploads/1998/06/97Acar.pdf
   610  var rSquare = Element{
   611  	18446744065119617025,
   612  }
   613  
   614  // toMont converts z to Montgomery form
   615  // sets and returns z = z * r²
   616  func (z *Element) toMont() *Element {
   617  	return z.Mul(z, &rSquare)
   618  }
   619  
   620  // String returns the decimal representation of z as generated by
   621  // z.Text(10).
   622  func (z *Element) String() string {
   623  	return z.Text(10)
   624  }
   625  
   626  // toBigInt returns z as a big.Int in Montgomery form
   627  func (z *Element) toBigInt(res *big.Int) *big.Int {
   628  	var b [Bytes]byte
   629  	binary.BigEndian.PutUint64(b[0:8], z[0])
   630  
   631  	return res.SetBytes(b[:])
   632  }
   633  
   634  // Text returns the string representation of z in the given base.
   635  // Base must be between 2 and 36, inclusive. The result uses the
   636  // lower-case letters 'a' to 'z' for digit values 10 to 35.
   637  // No prefix (such as "0x") is added to the string. If z is a nil
   638  // pointer it returns "<nil>".
   639  // If base == 10 and -z fits in a uint16 prefix "-" is added to the string.
   640  func (z *Element) Text(base int) string {
   641  	if base < 2 || base > 36 {
   642  		panic("invalid base")
   643  	}
   644  	if z == nil {
   645  		return "<nil>"
   646  	}
   647  
   648  	const maxUint16 = 65535
   649  	if base == 10 {
   650  		var zzNeg Element
   651  		zzNeg.Neg(z)
   652  		zzNeg.fromMont()
   653  		if zzNeg[0] <= maxUint16 && zzNeg[0] != 0 {
   654  			return "-" + strconv.FormatUint(zzNeg[0], base)
   655  		}
   656  	}
   657  	zz := z.Bits()
   658  	return strconv.FormatUint(zz[0], base)
   659  }
   660  
   661  // BigInt sets and return z as a *big.Int
   662  func (z *Element) BigInt(res *big.Int) *big.Int {
   663  	_z := *z
   664  	_z.fromMont()
   665  	return _z.toBigInt(res)
   666  }
   667  
   668  // ToBigIntRegular returns z as a big.Int in regular form
   669  //
   670  // Deprecated: use BigInt(*big.Int) instead
   671  func (z Element) ToBigIntRegular(res *big.Int) *big.Int {
   672  	z.fromMont()
   673  	return z.toBigInt(res)
   674  }
   675  
   676  // Bits provides access to z by returning its value as a little-endian [1]uint64 array.
   677  // Bits is intended to support implementation of missing low-level Element
   678  // functionality outside this package; it should be avoided otherwise.
   679  func (z *Element) Bits() [1]uint64 {
   680  	_z := *z
   681  	fromMont(&_z)
   682  	return _z
   683  }
   684  
   685  // Bytes returns the value of z as a big-endian byte array
   686  func (z *Element) Bytes() (res [Bytes]byte) {
   687  	BigEndian.PutElement(&res, *z)
   688  	return
   689  }
   690  
   691  // Marshal returns the value of z as a big-endian byte slice
   692  func (z *Element) Marshal() []byte {
   693  	b := z.Bytes()
   694  	return b[:]
   695  }
   696  
   697  // Unmarshal is an alias for SetBytes, it sets z to the value of e.
   698  func (z *Element) Unmarshal(e []byte) {
   699  	z.SetBytes(e)
   700  }
   701  
   702  // SetBytes interprets e as the bytes of a big-endian unsigned integer,
   703  // sets z to that value, and returns z.
   704  func (z *Element) SetBytes(e []byte) *Element {
   705  	if len(e) == Bytes {
   706  		// fast path
   707  		v, err := BigEndian.Element((*[Bytes]byte)(e))
   708  		if err == nil {
   709  			*z = v
   710  			return z
   711  		}
   712  	}
   713  
   714  	// slow path.
   715  	// get a big int from our pool
   716  	vv := pool.BigInt.Get()
   717  	vv.SetBytes(e)
   718  
   719  	// set big int
   720  	z.SetBigInt(vv)
   721  
   722  	// put temporary object back in pool
   723  	pool.BigInt.Put(vv)
   724  
   725  	return z
   726  }
   727  
   728  // SetBytesCanonical interprets e as the bytes of a big-endian 8-byte integer.
   729  // If e is not a 8-byte slice or encodes a value higher than q,
   730  // SetBytesCanonical returns an error.
   731  func (z *Element) SetBytesCanonical(e []byte) error {
   732  	if len(e) != Bytes {
   733  		return errors.New("invalid goldilocks.Element encoding")
   734  	}
   735  	v, err := BigEndian.Element((*[Bytes]byte)(e))
   736  	if err != nil {
   737  		return err
   738  	}
   739  	*z = v
   740  	return nil
   741  }
   742  
   743  // SetBigInt sets z to v and returns z
   744  func (z *Element) SetBigInt(v *big.Int) *Element {
   745  	z.SetZero()
   746  
   747  	var zero big.Int
   748  
   749  	// fast path
   750  	c := v.Cmp(&_modulus)
   751  	if c == 0 {
   752  		// v == 0
   753  		return z
   754  	} else if c != 1 && v.Cmp(&zero) != -1 {
   755  		// 0 < v < q
   756  		return z.setBigInt(v)
   757  	}
   758  
   759  	// get temporary big int from the pool
   760  	vv := pool.BigInt.Get()
   761  
   762  	// copy input + modular reduction
   763  	vv.Mod(v, &_modulus)
   764  
   765  	// set big int byte value
   766  	z.setBigInt(vv)
   767  
   768  	// release object into pool
   769  	pool.BigInt.Put(vv)
   770  	return z
   771  }
   772  
   773  // setBigInt assumes 0 ⩽ v < q
   774  func (z *Element) setBigInt(v *big.Int) *Element {
   775  	vBits := v.Bits()
   776  
   777  	if bits.UintSize == 64 {
   778  		for i := 0; i < len(vBits); i++ {
   779  			z[i] = uint64(vBits[i])
   780  		}
   781  	} else {
   782  		for i := 0; i < len(vBits); i++ {
   783  			if i%2 == 0 {
   784  				z[i/2] = uint64(vBits[i])
   785  			} else {
   786  				z[i/2] |= uint64(vBits[i]) << 32
   787  			}
   788  		}
   789  	}
   790  
   791  	return z.toMont()
   792  }
   793  
   794  // SetString creates a big.Int with number and calls SetBigInt on z
   795  //
   796  // The number prefix determines the actual base: A prefix of
   797  // ”0b” or ”0B” selects base 2, ”0”, ”0o” or ”0O” selects base 8,
   798  // and ”0x” or ”0X” selects base 16. Otherwise, the selected base is 10
   799  // and no prefix is accepted.
   800  //
   801  // For base 16, lower and upper case letters are considered the same:
   802  // The letters 'a' to 'f' and 'A' to 'F' represent digit values 10 to 15.
   803  //
   804  // An underscore character ”_” may appear between a base
   805  // prefix and an adjacent digit, and between successive digits; such
   806  // underscores do not change the value of the number.
   807  // Incorrect placement of underscores is reported as a panic if there
   808  // are no other errors.
   809  //
   810  // If the number is invalid this method leaves z unchanged and returns nil, error.
   811  func (z *Element) SetString(number string) (*Element, error) {
   812  	// get temporary big int from the pool
   813  	vv := pool.BigInt.Get()
   814  
   815  	if _, ok := vv.SetString(number, 0); !ok {
   816  		return nil, errors.New("Element.SetString failed -> can't parse number into a big.Int " + number)
   817  	}
   818  
   819  	z.SetBigInt(vv)
   820  
   821  	// release object into pool
   822  	pool.BigInt.Put(vv)
   823  
   824  	return z, nil
   825  }
   826  
   827  // MarshalJSON returns json encoding of z (z.Text(10))
   828  // If z == nil, returns null
   829  func (z *Element) MarshalJSON() ([]byte, error) {
   830  	if z == nil {
   831  		return []byte("null"), nil
   832  	}
   833  	const maxSafeBound = 15 // we encode it as number if it's small
   834  	s := z.Text(10)
   835  	if len(s) <= maxSafeBound {
   836  		return []byte(s), nil
   837  	}
   838  	var sbb strings.Builder
   839  	sbb.WriteByte('"')
   840  	sbb.WriteString(s)
   841  	sbb.WriteByte('"')
   842  	return []byte(sbb.String()), nil
   843  }
   844  
   845  // UnmarshalJSON accepts numbers and strings as input
   846  // See Element.SetString for valid prefixes (0x, 0b, ...)
   847  func (z *Element) UnmarshalJSON(data []byte) error {
   848  	s := string(data)
   849  	if len(s) > Bits*3 {
   850  		return errors.New("value too large (max = Element.Bits * 3)")
   851  	}
   852  
   853  	// we accept numbers and strings, remove leading and trailing quotes if any
   854  	if len(s) > 0 && s[0] == '"' {
   855  		s = s[1:]
   856  	}
   857  	if len(s) > 0 && s[len(s)-1] == '"' {
   858  		s = s[:len(s)-1]
   859  	}
   860  
   861  	// get temporary big int from the pool
   862  	vv := pool.BigInt.Get()
   863  
   864  	if _, ok := vv.SetString(s, 0); !ok {
   865  		return errors.New("can't parse into a big.Int: " + s)
   866  	}
   867  
   868  	z.SetBigInt(vv)
   869  
   870  	// release object into pool
   871  	pool.BigInt.Put(vv)
   872  	return nil
   873  }
   874  
   875  // A ByteOrder specifies how to convert byte slices into a Element
   876  type ByteOrder interface {
   877  	Element(*[Bytes]byte) (Element, error)
   878  	PutElement(*[Bytes]byte, Element)
   879  	String() string
   880  }
   881  
   882  // BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.
   883  var BigEndian bigEndian
   884  
   885  type bigEndian struct{}
   886  
   887  // Element interpret b is a big-endian 8-byte slice.
   888  // If b encodes a value higher than q, Element returns error.
   889  func (bigEndian) Element(b *[Bytes]byte) (Element, error) {
   890  	var z Element
   891  	z[0] = binary.BigEndian.Uint64((*b)[0:8])
   892  
   893  	if !z.smallerThanModulus() {
   894  		return Element{}, errors.New("invalid goldilocks.Element encoding")
   895  	}
   896  
   897  	z.toMont()
   898  	return z, nil
   899  }
   900  
   901  func (bigEndian) PutElement(b *[Bytes]byte, e Element) {
   902  	e.fromMont()
   903  	binary.BigEndian.PutUint64((*b)[0:8], e[0])
   904  }
   905  
   906  func (bigEndian) String() string { return "BigEndian" }
   907  
   908  // LittleEndian is the little-endian implementation of ByteOrder and AppendByteOrder.
   909  var LittleEndian littleEndian
   910  
   911  type littleEndian struct{}
   912  
   913  func (littleEndian) Element(b *[Bytes]byte) (Element, error) {
   914  	var z Element
   915  	z[0] = binary.LittleEndian.Uint64((*b)[0:8])
   916  
   917  	if !z.smallerThanModulus() {
   918  		return Element{}, errors.New("invalid goldilocks.Element encoding")
   919  	}
   920  
   921  	z.toMont()
   922  	return z, nil
   923  }
   924  
   925  func (littleEndian) PutElement(b *[Bytes]byte, e Element) {
   926  	e.fromMont()
   927  	binary.LittleEndian.PutUint64((*b)[0:8], e[0])
   928  }
   929  
   930  func (littleEndian) String() string { return "LittleEndian" }
   931  
   932  // Legendre returns the Legendre symbol of z (either +1, -1, or 0.)
   933  func (z *Element) Legendre() int {
   934  	var l Element
   935  	// z^((q-1)/2)
   936  	l.expByLegendreExp(*z)
   937  
   938  	if l.IsZero() {
   939  		return 0
   940  	}
   941  
   942  	// if l == 1
   943  	if l.IsOne() {
   944  		return 1
   945  	}
   946  	return -1
   947  }
   948  
   949  // Sqrt z = √x (mod q)
   950  // if the square root doesn't exist (x is not a square mod q)
   951  // Sqrt leaves z unchanged and returns nil
   952  func (z *Element) Sqrt(x *Element) *Element {
   953  	// q ≡ 1 (mod 4)
   954  	// see modSqrtTonelliShanks in math/big/int.go
   955  	// using https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   956  
   957  	var y, b, t, w Element
   958  	// w = x^((s-1)/2))
   959  	w.expBySqrtExp(*x)
   960  
   961  	// y = x^((s+1)/2)) = w * x
   962  	y.Mul(x, &w)
   963  
   964  	// b = xˢ = w * w * x = y * x
   965  	b.Mul(&w, &y)
   966  
   967  	// g = nonResidue ^ s
   968  	var g = Element{
   969  		15733474329512464024,
   970  	}
   971  	r := uint64(32)
   972  
   973  	// compute legendre symbol
   974  	// t = x^((q-1)/2) = r-1 squaring of xˢ
   975  	t = b
   976  	for i := uint64(0); i < r-1; i++ {
   977  		t.Square(&t)
   978  	}
   979  	if t.IsZero() {
   980  		return z.SetZero()
   981  	}
   982  	if !t.IsOne() {
   983  		// t != 1, we don't have a square root
   984  		return nil
   985  	}
   986  	for {
   987  		var m uint64
   988  		t = b
   989  
   990  		// for t != 1
   991  		for !t.IsOne() {
   992  			t.Square(&t)
   993  			m++
   994  		}
   995  
   996  		if m == 0 {
   997  			return z.Set(&y)
   998  		}
   999  		// t = g^(2^(r-m-1)) (mod q)
  1000  		ge := int(r - m - 1)
  1001  		t = g
  1002  		for ge > 0 {
  1003  			t.Square(&t)
  1004  			ge--
  1005  		}
  1006  
  1007  		g.Square(&t)
  1008  		y.Mul(&y, &t)
  1009  		b.Mul(&b, &g)
  1010  		r = m
  1011  	}
  1012  }
  1013  
  1014  // Inverse z = x⁻¹ (mod q)
  1015  //
  1016  // if x == 0, sets and returns z = x
  1017  func (z *Element) Inverse(x *Element) *Element {
  1018  	// Algorithm 16 in "Efficient Software-Implementation of Finite Fields with Applications to Cryptography"
  1019  	const q uint64 = q0
  1020  	if x.IsZero() {
  1021  		z.SetZero()
  1022  		return z
  1023  	}
  1024  
  1025  	var r, s, u, v uint64
  1026  	u = q
  1027  	s = 18446744065119617025 // s = r²
  1028  	r = 0
  1029  	v = x[0]
  1030  
  1031  	var carry, borrow uint64
  1032  
  1033  	for (u != 1) && (v != 1) {
  1034  		for v&1 == 0 {
  1035  			v >>= 1
  1036  			if s&1 == 0 {
  1037  				s >>= 1
  1038  			} else {
  1039  				s, carry = bits.Add64(s, q, 0)
  1040  				s >>= 1
  1041  				if carry != 0 {
  1042  					s |= (1 << 63)
  1043  				}
  1044  			}
  1045  		}
  1046  		for u&1 == 0 {
  1047  			u >>= 1
  1048  			if r&1 == 0 {
  1049  				r >>= 1
  1050  			} else {
  1051  				r, carry = bits.Add64(r, q, 0)
  1052  				r >>= 1
  1053  				if carry != 0 {
  1054  					r |= (1 << 63)
  1055  				}
  1056  			}
  1057  		}
  1058  		if v >= u {
  1059  			v -= u
  1060  			s, borrow = bits.Sub64(s, r, 0)
  1061  			if borrow == 1 {
  1062  				s += q
  1063  			}
  1064  		} else {
  1065  			u -= v
  1066  			r, borrow = bits.Sub64(r, s, 0)
  1067  			if borrow == 1 {
  1068  				r += q
  1069  			}
  1070  		}
  1071  	}
  1072  
  1073  	if u == 1 {
  1074  		z[0] = r
  1075  	} else {
  1076  		z[0] = s
  1077  	}
  1078  
  1079  	return z
  1080  }