github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/btcec/signature.go (about)

     1  // Copyright (c) 2013-2014 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package btcec
     7  
     8  import (
     9  	"bytes"
    10  	"crypto/ecdsa"
    11  	"crypto/elliptic"
    12  	"crypto/hmac"
    13  	"errors"
    14  	"fmt"
    15  	"hash"
    16  	"math/big"
    17  
    18  	"github.com/btcsuite/fastsha256"
    19  )
    20  
    21  // Errors returned by canonicalPadding.
    22  var (
    23  	errNegativeValue          = errors.New("value may be interpreted as negative")
    24  	errExcessivelyPaddedValue = errors.New("value is excessively padded")
    25  )
    26  
    27  // Signature is a type representing an ecdsa signature.
    28  type Signature struct {
    29  	R *big.Int
    30  	S *big.Int
    31  }
    32  
    33  var (
    34  	// Curve order and halforder, used to tame ECDSA malleability (see BIP-0062)
    35  	order     = new(big.Int).Set(S256().N)
    36  	halforder = new(big.Int).Rsh(order, 1)
    37  
    38  	// Used in RFC6979 implementation when testing the nonce for correctness
    39  	one = big.NewInt(1)
    40  
    41  	// oneInitializer is used to fill a byte slice with byte 0x01.  It is provided
    42  	// here to avoid the need to create it multiple times.
    43  	oneInitializer = []byte{0x01}
    44  )
    45  
    46  // Serialize returns the ECDSA signature in the more strict DER format.  Note
    47  // that the serialized bytes returned do not include the appended hash type
    48  // used in Bitcoin signature scripts.
    49  //
    50  // encoding/asn1 is broken so we hand roll this output:
    51  //
    52  // 0x30 <length> 0x02 <length r> r 0x02 <length s> s
    53  func (sig *Signature) Serialize() []byte {
    54  	// low 'S' malleability breaker
    55  	sigS := sig.S
    56  	if sigS.Cmp(halforder) == 1 {
    57  		sigS = new(big.Int).Sub(order, sigS)
    58  	}
    59  	// Ensure the encoded bytes for the r and s values are canonical and
    60  	// thus suitable for DER encoding.
    61  	rb := canonicalizeInt(sig.R)
    62  	sb := canonicalizeInt(sigS)
    63  
    64  	// total length of returned signature is 1 byte for each magic and
    65  	// length (6 total), plus lengths of r and s
    66  	length := 6 + len(rb) + len(sb)
    67  	b := make([]byte, length, length)
    68  
    69  	b[0] = 0x30
    70  	b[1] = byte(length - 2)
    71  	b[2] = 0x02
    72  	b[3] = byte(len(rb))
    73  	offset := copy(b[4:], rb) + 4
    74  	b[offset] = 0x02
    75  	b[offset+1] = byte(len(sb))
    76  	copy(b[offset+2:], sb)
    77  	return b
    78  }
    79  
    80  // Verify calls ecdsa.Verify to verify the signature of hash using the public
    81  // key.  It returns true if the signature is valid, false otherwise.
    82  func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
    83  	return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
    84  }
    85  
    86  // IsEqual compares this Signature instance to the one passed, returning true
    87  // if both Signatures are equivalent. A signature is equivalent to another, if
    88  // they both have the same scalar value for R and S.
    89  func (sig *Signature) IsEqual(otherSig *Signature) bool {
    90  	return sig.R.Cmp(otherSig.R) == 0 &&
    91  		sig.S.Cmp(otherSig.S) == 0
    92  }
    93  
    94  func parseSig(sigStr []byte, curve elliptic.Curve, der bool) (*Signature, error) {
    95  	// Originally this code used encoding/asn1 in order to parse the
    96  	// signature, but a number of problems were found with this approach.
    97  	// Despite the fact that signatures are stored as DER, the difference
    98  	// between go's idea of a bignum (and that they have sign) doesn't agree
    99  	// with the openssl one (where they do not). The above is true as of
   100  	// Go 1.1. In the end it was simpler to rewrite the code to explicitly
   101  	// understand the format which is this:
   102  	// 0x30 <length of whole message> <0x02> <length of R> <R> 0x2
   103  	// <length of S> <S>.
   104  
   105  	signature := &Signature{}
   106  
   107  	// minimal message is when both numbers are 1 bytes. adding up to:
   108  	// 0x30 + len + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte>
   109  	if len(sigStr) < 8 {
   110  		return nil, errors.New("malformed signature: too short")
   111  	}
   112  	// 0x30
   113  	index := 0
   114  	if sigStr[index] != 0x30 {
   115  		return nil, errors.New("malformed signature: no header magic")
   116  	}
   117  	index++
   118  	// length of remaining message
   119  	siglen := sigStr[index]
   120  	index++
   121  	if int(siglen+2) > len(sigStr) {
   122  		return nil, errors.New("malformed signature: bad length")
   123  	}
   124  	// trim the slice we're working on so we only look at what matters.
   125  	sigStr = sigStr[:siglen+2]
   126  
   127  	// 0x02
   128  	if sigStr[index] != 0x02 {
   129  		return nil,
   130  			errors.New("malformed signature: no 1st int marker")
   131  	}
   132  	index++
   133  
   134  	// Length of signature R.
   135  	rLen := int(sigStr[index])
   136  	// must be positive, must be able to fit in another 0x2, <len> <s>
   137  	// hence the -3. We assume that the length must be at least one byte.
   138  	index++
   139  	if rLen <= 0 || rLen > len(sigStr)-index-3 {
   140  		return nil, errors.New("malformed signature: bogus R length")
   141  	}
   142  
   143  	// Then R itself.
   144  	rBytes := sigStr[index : index+rLen]
   145  	if der {
   146  		switch err := canonicalPadding(rBytes); err {
   147  		case errNegativeValue:
   148  			return nil, errors.New("signature R is negative")
   149  		case errExcessivelyPaddedValue:
   150  			return nil, errors.New("signature R is excessively padded")
   151  		}
   152  	}
   153  	signature.R = new(big.Int).SetBytes(rBytes)
   154  	index += rLen
   155  	// 0x02. length already checked in previous if.
   156  	if sigStr[index] != 0x02 {
   157  		return nil, errors.New("malformed signature: no 2nd int marker")
   158  	}
   159  	index++
   160  
   161  	// Length of signature S.
   162  	sLen := int(sigStr[index])
   163  	index++
   164  	// S should be the rest of the string.
   165  	if sLen <= 0 || sLen > len(sigStr)-index {
   166  		return nil, errors.New("malformed signature: bogus S length")
   167  	}
   168  
   169  	// Then S itself.
   170  	sBytes := sigStr[index : index+sLen]
   171  	if der {
   172  		switch err := canonicalPadding(sBytes); err {
   173  		case errNegativeValue:
   174  			return nil, errors.New("signature S is negative")
   175  		case errExcessivelyPaddedValue:
   176  			return nil, errors.New("signature S is excessively padded")
   177  		}
   178  	}
   179  	signature.S = new(big.Int).SetBytes(sBytes)
   180  	index += sLen
   181  
   182  	// sanity check length parsing
   183  	if index != len(sigStr) {
   184  		return nil, fmt.Errorf("malformed signature: bad final length %v != %v",
   185  			index, len(sigStr))
   186  	}
   187  
   188  	// Verify also checks this, but we can be more sure that we parsed
   189  	// correctly if we verify here too.
   190  	// FWIW the ecdsa spec states that R and S must be | 1, N - 1 |
   191  	// but crypto/ecdsa only checks for Sign != 0. Mirror that.
   192  	if signature.R.Sign() != 1 {
   193  		return nil, errors.New("signature R isn't 1 or more")
   194  	}
   195  	if signature.S.Sign() != 1 {
   196  		return nil, errors.New("signature S isn't 1 or more")
   197  	}
   198  	if signature.R.Cmp(curve.Params().N) >= 0 {
   199  		return nil, errors.New("signature R is >= curve.N")
   200  	}
   201  	if signature.S.Cmp(curve.Params().N) >= 0 {
   202  		return nil, errors.New("signature S is >= curve.N")
   203  	}
   204  
   205  	return signature, nil
   206  }
   207  
   208  // ParseSignature parses a signature in BER format for the curve type `curve'
   209  // into a Signature type, perfoming some basic sanity checks.  If parsing
   210  // according to the more strict DER format is needed, use ParseDERSignature.
   211  func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
   212  	return parseSig(sigStr, curve, false)
   213  }
   214  
   215  // ParseDERSignature parses a signature in DER format for the curve type
   216  // `curve` into a Signature type.  If parsing according to the less strict
   217  // BER format is needed, use ParseSignature.
   218  func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
   219  	return parseSig(sigStr, curve, true)
   220  }
   221  
   222  // canonicalizeInt returns the bytes for the passed big integer adjusted as
   223  // necessary to ensure that a big-endian encoded integer can't possibly be
   224  // misinterpreted as a negative number.  This can happen when the most
   225  // significant bit is set, so it is padded by a leading zero byte in this case.
   226  // Also, the returned bytes will have at least a single byte when the passed
   227  // value is 0.  This is required for DER encoding.
   228  func canonicalizeInt(val *big.Int) []byte {
   229  	b := val.Bytes()
   230  	if len(b) == 0 {
   231  		b = []byte{0x00}
   232  	}
   233  	if b[0]&0x80 != 0 {
   234  		paddedBytes := make([]byte, len(b)+1)
   235  		copy(paddedBytes[1:], b)
   236  		b = paddedBytes
   237  	}
   238  	return b
   239  }
   240  
   241  // canonicalPadding checks whether a big-endian encoded integer could
   242  // possibly be misinterpreted as a negative number (even though OpenSSL
   243  // treats all numbers as unsigned), or if there is any unnecessary
   244  // leading zero padding.
   245  func canonicalPadding(b []byte) error {
   246  	switch {
   247  	case b[0]&0x80 == 0x80:
   248  		return errNegativeValue
   249  	case len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80:
   250  		return errExcessivelyPaddedValue
   251  	default:
   252  		return nil
   253  	}
   254  }
   255  
   256  // hashToInt converts a hash value to an integer. There is some disagreement
   257  // about how this is done. [NSA] suggests that this is done in the obvious
   258  // manner, but [SECG] truncates the hash to the bit-length of the curve order
   259  // first. We follow [SECG] because that's what OpenSSL does. Additionally,
   260  // OpenSSL right shifts excess bits from the number if the hash is too large
   261  // and we mirror that too.
   262  // This is borrowed from crypto/ecdsa.
   263  func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
   264  	orderBits := c.Params().N.BitLen()
   265  	orderBytes := (orderBits + 7) / 8
   266  	if len(hash) > orderBytes {
   267  		hash = hash[:orderBytes]
   268  	}
   269  
   270  	ret := new(big.Int).SetBytes(hash)
   271  	excess := len(hash)*8 - orderBits
   272  	if excess > 0 {
   273  		ret.Rsh(ret, uint(excess))
   274  	}
   275  	return ret
   276  }
   277  
   278  // recoverKeyFromSignature recoves a public key from the signature "sig" on the
   279  // given message hash "msg". Based on the algorithm found in section 5.1.5 of
   280  // SEC 1 Ver 2.0, page 47-48 (53 and 54 in the pdf). This performs the details
   281  // in the inner loop in Step 1. The counter provided is actually the j parameter
   282  // of the loop * 2 - on the first iteration of j we do the R case, else the -R
   283  // case in step 1.6. This counter is used in the bitcoin compressed signature
   284  // format and thus we match bitcoind's behaviour here.
   285  func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte,
   286  	iter int, doChecks bool) (*PublicKey, error) {
   287  	// 1.1 x = (n * i) + r
   288  	Rx := new(big.Int).Mul(curve.Params().N,
   289  		new(big.Int).SetInt64(int64(iter/2)))
   290  	Rx.Add(Rx, sig.R)
   291  	if Rx.Cmp(curve.Params().P) != -1 {
   292  		return nil, errors.New("calculated Rx is larger than curve P")
   293  	}
   294  
   295  	// convert 02<Rx> to point R. (step 1.2 and 1.3). If we are on an odd
   296  	// iteration then 1.6 will be done with -R, so we calculate the other
   297  	// term when uncompressing the point.
   298  	Ry, err := decompressPoint(curve, Rx, iter%2 == 1)
   299  	if err != nil {
   300  		return nil, err
   301  	}
   302  
   303  	// 1.4 Check n*R is point at infinity
   304  	if doChecks {
   305  		nRx, nRy := curve.ScalarMult(Rx, Ry, curve.Params().N.Bytes())
   306  		if nRx.Sign() != 0 || nRy.Sign() != 0 {
   307  			return nil, errors.New("n*R does not equal the point at infinity")
   308  		}
   309  	}
   310  
   311  	// 1.5 calculate e from message using the same algorithm as ecdsa
   312  	// signature calculation.
   313  	e := hashToInt(msg, curve)
   314  
   315  	// Step 1.6.1:
   316  	// We calculate the two terms sR and eG separately multiplied by the
   317  	// inverse of r (from the signature). We then add them to calculate
   318  	// Q = r^-1(sR-eG)
   319  	invr := new(big.Int).ModInverse(sig.R, curve.Params().N)
   320  
   321  	// first term.
   322  	invrS := new(big.Int).Mul(invr, sig.S)
   323  	invrS.Mod(invrS, curve.Params().N)
   324  	sRx, sRy := curve.ScalarMult(Rx, Ry, invrS.Bytes())
   325  
   326  	// second term.
   327  	e.Neg(e)
   328  	e.Mod(e, curve.Params().N)
   329  	e.Mul(e, invr)
   330  	e.Mod(e, curve.Params().N)
   331  	minuseGx, minuseGy := curve.ScalarBaseMult(e.Bytes())
   332  
   333  	// TODO(oga) this would be faster if we did a mult and add in one
   334  	// step to prevent the jacobian conversion back and forth.
   335  	Qx, Qy := curve.Add(sRx, sRy, minuseGx, minuseGy)
   336  
   337  	return &PublicKey{
   338  		Curve: curve,
   339  		X:     Qx,
   340  		Y:     Qy,
   341  	}, nil
   342  }
   343  
   344  // SignCompact produces a compact signature of the data in hash with the given
   345  // private key on the given koblitz curve. The isCompressed  parameter should
   346  // be used to detail if the given signature should reference a compressed
   347  // public key or not. If successful the bytes of the compact signature will be
   348  // returned in the format:
   349  // <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R><padded bytes for signature S>
   350  // where the R and S parameters are padde up to the bitlengh of the curve.
   351  func SignCompact(curve *KoblitzCurve, key *PrivateKey,
   352  	hash []byte, isCompressedKey bool) ([]byte, error) {
   353  	sig, err := key.Sign(hash)
   354  	if err != nil {
   355  		return nil, err
   356  	}
   357  
   358  	// bitcoind checks the bit length of R and S here. The ecdsa signature
   359  	// algorithm returns R and S mod N therefore they will be the bitsize of
   360  	// the curve, and thus correctly sized.
   361  	for i := 0; i < (curve.H+1)*2; i++ {
   362  		pk, err := recoverKeyFromSignature(curve, sig, hash, i, true)
   363  		if err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {
   364  			result := make([]byte, 1, 2*curve.byteSize+1)
   365  			result[0] = 27 + byte(i)
   366  			if isCompressedKey {
   367  				result[0] += 4
   368  			}
   369  			// Not sure this needs rounding but safer to do so.
   370  			curvelen := (curve.BitSize + 7) / 8
   371  
   372  			// Pad R and S to curvelen if needed.
   373  			bytelen := (sig.R.BitLen() + 7) / 8
   374  			if bytelen < curvelen {
   375  				result = append(result,
   376  					make([]byte, curvelen-bytelen)...)
   377  			}
   378  			result = append(result, sig.R.Bytes()...)
   379  
   380  			bytelen = (sig.S.BitLen() + 7) / 8
   381  			if bytelen < curvelen {
   382  				result = append(result,
   383  					make([]byte, curvelen-bytelen)...)
   384  			}
   385  			result = append(result, sig.S.Bytes()...)
   386  
   387  			return result, nil
   388  		}
   389  	}
   390  
   391  	return nil, errors.New("no valid solution for pubkey found")
   392  }
   393  
   394  // RecoverCompact verifies the compact signature "signature" of "hash" for the
   395  // Koblitz curve in "curve". If the signature matches then the recovered public
   396  // key will be returned as well as a boolen if the original key was compressed
   397  // or not, else an error will be returned.
   398  func RecoverCompact(curve *KoblitzCurve, signature,
   399  	hash []byte) (*PublicKey, bool, error) {
   400  	bitlen := (curve.BitSize + 7) / 8
   401  	if len(signature) != 1+bitlen*2 {
   402  		return nil, false, errors.New("invalid compact signature size")
   403  	}
   404  
   405  	iteration := int((signature[0] - 27) & ^byte(4))
   406  
   407  	// format is <header byte><bitlen R><bitlen S>
   408  	sig := &Signature{
   409  		R: new(big.Int).SetBytes(signature[1 : bitlen+1]),
   410  		S: new(big.Int).SetBytes(signature[bitlen+1:]),
   411  	}
   412  	// The iteration used here was encoded
   413  	key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false)
   414  	if err != nil {
   415  		return nil, false, err
   416  	}
   417  
   418  	return key, ((signature[0] - 27) & 4) == 4, nil
   419  }
   420  
   421  // signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62.
   422  func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {
   423  
   424  	privkey := privateKey.ToECDSA()
   425  	N := order
   426  	k := nonceRFC6979(privkey.D, hash)
   427  	inv := new(big.Int).ModInverse(k, N)
   428  	r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
   429  	if r.Cmp(N) == 1 {
   430  		r.Sub(r, N)
   431  	}
   432  
   433  	if r.Sign() == 0 {
   434  		return nil, errors.New("calculated R is zero")
   435  	}
   436  
   437  	e := hashToInt(hash, privkey.Curve)
   438  	s := new(big.Int).Mul(privkey.D, r)
   439  	s.Add(s, e)
   440  	s.Mul(s, inv)
   441  	s.Mod(s, N)
   442  
   443  	if s.Cmp(halforder) == 1 {
   444  		s.Sub(N, s)
   445  	}
   446  	if s.Sign() == 0 {
   447  		return nil, errors.New("calculated S is zero")
   448  	}
   449  	return &Signature{R: r, S: s}, nil
   450  }
   451  
   452  // nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979.
   453  // It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm.
   454  func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int {
   455  
   456  	curve := S256()
   457  	q := curve.Params().N
   458  	x := privkey
   459  	alg := fastsha256.New
   460  
   461  	qlen := q.BitLen()
   462  	holen := alg().Size()
   463  	rolen := (qlen + 7) >> 3
   464  	bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...)
   465  
   466  	// Step B
   467  	v := bytes.Repeat(oneInitializer, holen)
   468  
   469  	// Step C (Go zeroes the all allocated memory)
   470  	k := make([]byte, holen)
   471  
   472  	// Step D
   473  	k = mac(alg, k, append(append(v, 0x00), bx...))
   474  
   475  	// Step E
   476  	v = mac(alg, k, v)
   477  
   478  	// Step F
   479  	k = mac(alg, k, append(append(v, 0x01), bx...))
   480  
   481  	// Step G
   482  	v = mac(alg, k, v)
   483  
   484  	// Step H
   485  	for {
   486  		// Step H1
   487  		var t []byte
   488  
   489  		// Step H2
   490  		for len(t)*8 < qlen {
   491  			v = mac(alg, k, v)
   492  			t = append(t, v...)
   493  		}
   494  
   495  		// Step H3
   496  		secret := hashToInt(t, curve)
   497  		if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 {
   498  			return secret
   499  		}
   500  		k = mac(alg, k, append(v, 0x00))
   501  		v = mac(alg, k, v)
   502  	}
   503  }
   504  
   505  // mac returns an HMAC of the given key and message.
   506  func mac(alg func() hash.Hash, k, m []byte) []byte {
   507  	h := hmac.New(alg, k)
   508  	h.Write(m)
   509  	return h.Sum(nil)
   510  }
   511  
   512  // https://tools.ietf.org/html/rfc6979#section-2.3.3
   513  func int2octets(v *big.Int, rolen int) []byte {
   514  	out := v.Bytes()
   515  
   516  	// left pad with zeros if it's too short
   517  	if len(out) < rolen {
   518  		out2 := make([]byte, rolen)
   519  		copy(out2[rolen-len(out):], out)
   520  		return out2
   521  	}
   522  
   523  	// drop most significant bytes if it's too long
   524  	if len(out) > rolen {
   525  		out2 := make([]byte, rolen)
   526  		copy(out2, out[len(out)-rolen:])
   527  		return out2
   528  	}
   529  
   530  	return out
   531  }
   532  
   533  // https://tools.ietf.org/html/rfc6979#section-2.3.4
   534  func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte {
   535  	z1 := hashToInt(in, curve)
   536  	z2 := new(big.Int).Sub(z1, curve.Params().N)
   537  	if z2.Sign() < 0 {
   538  		return int2octets(z1, rolen)
   539  	}
   540  	return int2octets(z2, rolen)
   541  }