github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/crypto/secp256k1/curve.go (about)

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