github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/crypto/secp256k1/curve.go (about)

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