github.com/niluplatform/go-nilu@v1.7.4-0.20200912082737-a0cb0776d52c/crypto/bn256/google/bn256.go (about)

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