github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/crypto/secp256k1/curve.go (about)

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Copyright 2011 ThePiachu. All rights reserved.
     3  //
     4  // Redistribution and use in source and binary forms, with or without
     5  // modification, are permitted provided that the following conditions are
     6  // met:
     7  //
     8  // * Redistributions of source code must retain the above copyright
     9  //   notice, this list of conditions and the following disclaimer.
    10  // * Redistributions in binary form must reproduce the above
    11  //   copyright notice, this list of conditions and the following disclaimer
    12  //   in the documentation and/or other materials provided with the
    13  //   distribution.
    14  // * Neither the name of Google Inc. nor the names of its
    15  //   contributors may be used to endorse or promote products derived from
    16  //   this software without specific prior written permission.
    17  // * The name of ThePiachu may not be used to endorse or promote products
    18  //   derived from this software without specific prior written permission.
    19  //
    20  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    21  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    22  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    23  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    24  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    25  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    26  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    27  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    28  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    29  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    30  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    31  
    32  package secp256k1
    33  
    34  import (
    35  	"crypto/elliptic"
    36  	"math/big"
    37  	"unsafe"
    38  
    39  	"github.com/vntchain/go-vnt/common/math"
    40  )
    41  
    42  /*
    43  #include "libsecp256k1/include/secp256k1.h"
    44  extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned char *point, const unsigned char *scalar);
    45  */
    46  import "C"
    47  
    48  // This code is from https://github.com/ThePiachu/GoBit and implements
    49  // several Koblitz elliptic curves over prime fields.
    50  //
    51  // The curve methods, internally, on Jacobian coordinates. For a given
    52  // (x, y) position on the curve, the Jacobian coordinates are (x1, y1,
    53  // z1) where x = x1/z1² and y = y1/z1³. The greatest speedups come
    54  // when the whole calculation can be performed within the transform
    55  // (as in ScalarMult and ScalarBaseMult). But even for Add and Double,
    56  // it's faster to apply and reverse the transform than to operate in
    57  // affine coordinates.
    58  
    59  // A BitCurve represents a Koblitz Curve with a=0.
    60  // See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
    61  type BitCurve struct {
    62  	P       *big.Int // the order of the underlying field
    63  	N       *big.Int // the order of the base point
    64  	B       *big.Int // the constant of the BitCurve equation
    65  	Gx, Gy  *big.Int // (x,y) of the base point
    66  	BitSize int      // the size of the underlying field
    67  }
    68  
    69  func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
    70  	return &elliptic.CurveParams{
    71  		P:       BitCurve.P,
    72  		N:       BitCurve.N,
    73  		B:       BitCurve.B,
    74  		Gx:      BitCurve.Gx,
    75  		Gy:      BitCurve.Gy,
    76  		BitSize: BitCurve.BitSize,
    77  	}
    78  }
    79  
    80  // IsOnCurve returns true if the given (x,y) lies on the BitCurve.
    81  func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
    82  	// y² = x³ + b
    83  	y2 := new(big.Int).Mul(y, y) //y²
    84  	y2.Mod(y2, BitCurve.P)       //y²%P
    85  
    86  	x3 := new(big.Int).Mul(x, x) //x²
    87  	x3.Mul(x3, x)                //x³
    88  
    89  	x3.Add(x3, BitCurve.B) //x³+B
    90  	x3.Mod(x3, BitCurve.P) //(x³+B)%P
    91  
    92  	return x3.Cmp(y2) == 0
    93  }
    94  
    95  //TODO: double check if the function is okay
    96  // affineFromJacobian reverses the Jacobian transform. See the comment at the
    97  // top of the file.
    98  func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
    99  	zinv := new(big.Int).ModInverse(z, BitCurve.P)
   100  	zinvsq := new(big.Int).Mul(zinv, zinv)
   101  
   102  	xOut = new(big.Int).Mul(x, zinvsq)
   103  	xOut.Mod(xOut, BitCurve.P)
   104  	zinvsq.Mul(zinvsq, zinv)
   105  	yOut = new(big.Int).Mul(y, zinvsq)
   106  	yOut.Mod(yOut, BitCurve.P)
   107  	return
   108  }
   109  
   110  // Add returns the sum of (x1,y1) and (x2,y2)
   111  func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
   112  	z := new(big.Int).SetInt64(1)
   113  	return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
   114  }
   115  
   116  // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
   117  // (x2, y2, z2) and returns their sum, also in Jacobian form.
   118  func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
   119  	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
   120  	z1z1 := new(big.Int).Mul(z1, z1)
   121  	z1z1.Mod(z1z1, BitCurve.P)
   122  	z2z2 := new(big.Int).Mul(z2, z2)
   123  	z2z2.Mod(z2z2, BitCurve.P)
   124  
   125  	u1 := new(big.Int).Mul(x1, z2z2)
   126  	u1.Mod(u1, BitCurve.P)
   127  	u2 := new(big.Int).Mul(x2, z1z1)
   128  	u2.Mod(u2, BitCurve.P)
   129  	h := new(big.Int).Sub(u2, u1)
   130  	if h.Sign() == -1 {
   131  		h.Add(h, BitCurve.P)
   132  	}
   133  	i := new(big.Int).Lsh(h, 1)
   134  	i.Mul(i, i)
   135  	j := new(big.Int).Mul(h, i)
   136  
   137  	s1 := new(big.Int).Mul(y1, z2)
   138  	s1.Mul(s1, z2z2)
   139  	s1.Mod(s1, BitCurve.P)
   140  	s2 := new(big.Int).Mul(y2, z1)
   141  	s2.Mul(s2, z1z1)
   142  	s2.Mod(s2, BitCurve.P)
   143  	r := new(big.Int).Sub(s2, s1)
   144  	if r.Sign() == -1 {
   145  		r.Add(r, BitCurve.P)
   146  	}
   147  	r.Lsh(r, 1)
   148  	v := new(big.Int).Mul(u1, i)
   149  
   150  	x3 := new(big.Int).Set(r)
   151  	x3.Mul(x3, x3)
   152  	x3.Sub(x3, j)
   153  	x3.Sub(x3, v)
   154  	x3.Sub(x3, v)
   155  	x3.Mod(x3, BitCurve.P)
   156  
   157  	y3 := new(big.Int).Set(r)
   158  	v.Sub(v, x3)
   159  	y3.Mul(y3, v)
   160  	s1.Mul(s1, j)
   161  	s1.Lsh(s1, 1)
   162  	y3.Sub(y3, s1)
   163  	y3.Mod(y3, BitCurve.P)
   164  
   165  	z3 := new(big.Int).Add(z1, z2)
   166  	z3.Mul(z3, z3)
   167  	z3.Sub(z3, z1z1)
   168  	if z3.Sign() == -1 {
   169  		z3.Add(z3, BitCurve.P)
   170  	}
   171  	z3.Sub(z3, z2z2)
   172  	if z3.Sign() == -1 {
   173  		z3.Add(z3, BitCurve.P)
   174  	}
   175  	z3.Mul(z3, h)
   176  	z3.Mod(z3, BitCurve.P)
   177  
   178  	return x3, y3, z3
   179  }
   180  
   181  // Double returns 2*(x,y)
   182  func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
   183  	z1 := new(big.Int).SetInt64(1)
   184  	return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
   185  }
   186  
   187  // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
   188  // returns its double, also in Jacobian form.
   189  func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
   190  	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
   191  
   192  	a := new(big.Int).Mul(x, x) //X1²
   193  	b := new(big.Int).Mul(y, y) //Y1²
   194  	c := new(big.Int).Mul(b, b) //B²
   195  
   196  	d := new(big.Int).Add(x, b) //X1+B
   197  	d.Mul(d, d)                 //(X1+B)²
   198  	d.Sub(d, a)                 //(X1+B)²-A
   199  	d.Sub(d, c)                 //(X1+B)²-A-C
   200  	d.Mul(d, big.NewInt(2))     //2*((X1+B)²-A-C)
   201  
   202  	e := new(big.Int).Mul(big.NewInt(3), a) //3*A
   203  	f := new(big.Int).Mul(e, e)             //E²
   204  
   205  	x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
   206  	x3.Sub(f, x3)                            //F-2*D
   207  	x3.Mod(x3, BitCurve.P)
   208  
   209  	y3 := new(big.Int).Sub(d, x3)                  //D-X3
   210  	y3.Mul(e, y3)                                  //E*(D-X3)
   211  	y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
   212  	y3.Mod(y3, BitCurve.P)
   213  
   214  	z3 := new(big.Int).Mul(y, z) //Y1*Z1
   215  	z3.Mul(big.NewInt(2), z3)    //3*Y1*Z1
   216  	z3.Mod(z3, BitCurve.P)
   217  
   218  	return x3, y3, z3
   219  }
   220  
   221  func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) {
   222  	// Ensure scalar is exactly 32 bytes. We pad always, even if
   223  	// scalar is 32 bytes long, to avoid a timing side channel.
   224  	if len(scalar) > 32 {
   225  		panic("can't handle scalars > 256 bits")
   226  	}
   227  	// NOTE: potential timing issue
   228  	padded := make([]byte, 32)
   229  	copy(padded[32-len(scalar):], scalar)
   230  	scalar = padded
   231  
   232  	// Do the multiplication in C, updating point.
   233  	point := make([]byte, 64)
   234  	math.ReadBits(Bx, point[:32])
   235  	math.ReadBits(By, point[32:])
   236  	pointPtr := (*C.uchar)(unsafe.Pointer(&point[0]))
   237  	scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0]))
   238  	res := C.secp256k1_ext_scalar_mul(context, pointPtr, scalarPtr)
   239  
   240  	// Unpack the result and clear temporaries.
   241  	x := new(big.Int).SetBytes(point[:32])
   242  	y := new(big.Int).SetBytes(point[32:])
   243  	for i := range point {
   244  		point[i] = 0
   245  	}
   246  	for i := range padded {
   247  		scalar[i] = 0
   248  	}
   249  	if res != 1 {
   250  		return nil, nil
   251  	}
   252  	return x, y
   253  }
   254  
   255  // ScalarBaseMult returns k*G, where G is the base point of the group and k is
   256  // an integer in big-endian form.
   257  func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
   258  	return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
   259  }
   260  
   261  // Marshal converts a point into the form specified in section 4.3.6 of ANSI
   262  // X9.62.
   263  func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
   264  	byteLen := (BitCurve.BitSize + 7) >> 3
   265  	ret := make([]byte, 1+2*byteLen)
   266  	ret[0] = 4 // uncompressed point flag
   267  	math.ReadBits(x, ret[1:1+byteLen])
   268  	math.ReadBits(y, ret[1+byteLen:])
   269  	return ret
   270  }
   271  
   272  // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
   273  // error, x = nil.
   274  func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
   275  	byteLen := (BitCurve.BitSize + 7) >> 3
   276  	if len(data) != 1+2*byteLen {
   277  		return
   278  	}
   279  	if data[0] != 4 { // uncompressed form
   280  		return
   281  	}
   282  	x = new(big.Int).SetBytes(data[1 : 1+byteLen])
   283  	y = new(big.Int).SetBytes(data[1+byteLen:])
   284  	return
   285  }
   286  
   287  var theCurve = new(BitCurve)
   288  
   289  func init() {
   290  	// See SEC 2 section 2.7.1
   291  	// curve parameters taken from:
   292  	// http://www.secg.org/collateral/sec2_final.pdf
   293  	theCurve.P = math.MustParseBig256("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F")
   294  	theCurve.N = math.MustParseBig256("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")
   295  	theCurve.B = math.MustParseBig256("0x0000000000000000000000000000000000000000000000000000000000000007")
   296  	theCurve.Gx = math.MustParseBig256("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")
   297  	theCurve.Gy = math.MustParseBig256("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")
   298  	theCurve.BitSize = 256
   299  }
   300  
   301  // S256 returns a BitCurve which implements secp256k1.
   302  func S256() *BitCurve {
   303  	return theCurve
   304  }