1// Copyright (c) 2013-2017 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package btcec
6
7import (
8	"bytes"
9	"crypto/ecdsa"
10	"crypto/elliptic"
11	"crypto/hmac"
12	"crypto/sha256"
13	"errors"
14	"fmt"
15	"hash"
16	"math/big"
17)
18
19// Errors returned by canonicalPadding.
20var (
21	errNegativeValue          = errors.New("value may be interpreted as negative")
22	errExcessivelyPaddedValue = errors.New("value is excessively padded")
23)
24
25// Signature is a type representing an ecdsa signature.
26type Signature struct {
27	R *big.Int
28	S *big.Int
29}
30
31var (
32	// Used in RFC6979 implementation when testing the nonce for correctness
33	one = big.NewInt(1)
34
35	// oneInitializer is used to fill a byte slice with byte 0x01.  It is provided
36	// here to avoid the need to create it multiple times.
37	oneInitializer = []byte{0x01}
38)
39
40// Serialize returns the ECDSA signature in the more strict DER format.  Note
41// that the serialized bytes returned do not include the appended hash type
42// used in Bitcoin signature scripts.
43//
44// encoding/asn1 is broken so we hand roll this output:
45//
46// 0x30 <length> 0x02 <length r> r 0x02 <length s> s
47func (sig *Signature) Serialize() []byte {
48	// low 'S' malleability breaker
49	sigS := sig.S
50	if sigS.Cmp(S256().halfOrder) == 1 {
51		sigS = new(big.Int).Sub(S256().N, sigS)
52	}
53	// Ensure the encoded bytes for the r and s values are canonical and
54	// thus suitable for DER encoding.
55	rb := canonicalizeInt(sig.R)
56	sb := canonicalizeInt(sigS)
57
58	// total length of returned signature is 1 byte for each magic and
59	// length (6 total), plus lengths of r and s
60	length := 6 + len(rb) + len(sb)
61	b := make([]byte, length)
62
63	b[0] = 0x30
64	b[1] = byte(length - 2)
65	b[2] = 0x02
66	b[3] = byte(len(rb))
67	offset := copy(b[4:], rb) + 4
68	b[offset] = 0x02
69	b[offset+1] = byte(len(sb))
70	copy(b[offset+2:], sb)
71	return b
72}
73
74// Verify calls ecdsa.Verify to verify the signature of hash using the public
75// key.  It returns true if the signature is valid, false otherwise.
76func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
77	return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
78}
79
80// IsEqual compares this Signature instance to the one passed, returning true
81// if both Signatures are equivalent. A signature is equivalent to another, if
82// they both have the same scalar value for R and S.
83func (sig *Signature) IsEqual(otherSig *Signature) bool {
84	return sig.R.Cmp(otherSig.R) == 0 &&
85		sig.S.Cmp(otherSig.S) == 0
86}
87
88// MinSigLen is the minimum length of a DER encoded signature and is when both R
89// and S are 1 byte each.
90// 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte>
91const MinSigLen = 8
92
93func parseSig(sigStr []byte, curve elliptic.Curve, der bool) (*Signature, error) {
94	// Originally this code used encoding/asn1 in order to parse the
95	// signature, but a number of problems were found with this approach.
96	// Despite the fact that signatures are stored as DER, the difference
97	// between go's idea of a bignum (and that they have sign) doesn't agree
98	// with the openssl one (where they do not). The above is true as of
99	// Go 1.1. In the end it was simpler to rewrite the code to explicitly
100	// understand the format which is this:
101	// 0x30 <length of whole message> <0x02> <length of R> <R> 0x2
102	// <length of S> <S>.
103
104	signature := &Signature{}
105
106	if len(sigStr) < MinSigLen {
107		return nil, errors.New("malformed signature: too short")
108	}
109	// 0x30
110	index := 0
111	if sigStr[index] != 0x30 {
112		return nil, errors.New("malformed signature: no header magic")
113	}
114	index++
115	// length of remaining message
116	siglen := sigStr[index]
117	index++
118
119	// siglen should be less than the entire message and greater than
120	// the minimal message size.
121	if int(siglen+2) > len(sigStr) || int(siglen+2) < MinSigLen {
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.
211func 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.
218func 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.
228func 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.
245func 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.
263func 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 recovers a public key from the signature "sig" on the
279// given message hash "msg". Based on the algorithm found in section 4.1.6 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.
285func 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: 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.
351func 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.
398func 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.
422func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {
423
424	privkey := privateKey.ToECDSA()
425	N := S256().N
426	halfOrder := S256().halfOrder
427	k := nonceRFC6979(privkey.D, hash)
428	inv := new(big.Int).ModInverse(k, N)
429	r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
430	r.Mod(r, N)
431
432	if r.Sign() == 0 {
433		return nil, errors.New("calculated R is zero")
434	}
435
436	e := hashToInt(hash, privkey.Curve)
437	s := new(big.Int).Mul(privkey.D, r)
438	s.Add(s, e)
439	s.Mul(s, inv)
440	s.Mod(s, N)
441
442	if s.Cmp(halfOrder) == 1 {
443		s.Sub(N, s)
444	}
445	if s.Sign() == 0 {
446		return nil, errors.New("calculated S is zero")
447	}
448	return &Signature{R: r, S: s}, nil
449}
450
451// nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979.
452// It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm.
453func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int {
454
455	curve := S256()
456	q := curve.Params().N
457	x := privkey
458	alg := sha256.New
459
460	qlen := q.BitLen()
461	holen := alg().Size()
462	rolen := (qlen + 7) >> 3
463	bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...)
464
465	// Step B
466	v := bytes.Repeat(oneInitializer, holen)
467
468	// Step C (Go zeroes the all allocated memory)
469	k := make([]byte, holen)
470
471	// Step D
472	k = mac(alg, k, append(append(v, 0x00), bx...))
473
474	// Step E
475	v = mac(alg, k, v)
476
477	// Step F
478	k = mac(alg, k, append(append(v, 0x01), bx...))
479
480	// Step G
481	v = mac(alg, k, v)
482
483	// Step H
484	for {
485		// Step H1
486		var t []byte
487
488		// Step H2
489		for len(t)*8 < qlen {
490			v = mac(alg, k, v)
491			t = append(t, v...)
492		}
493
494		// Step H3
495		secret := hashToInt(t, curve)
496		if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 {
497			return secret
498		}
499		k = mac(alg, k, append(v, 0x00))
500		v = mac(alg, k, v)
501	}
502}
503
504// mac returns an HMAC of the given key and message.
505func mac(alg func() hash.Hash, k, m []byte) []byte {
506	h := hmac.New(alg, k)
507	h.Write(m)
508	return h.Sum(nil)
509}
510
511// https://tools.ietf.org/html/rfc6979#section-2.3.3
512func int2octets(v *big.Int, rolen int) []byte {
513	out := v.Bytes()
514
515	// left pad with zeros if it's too short
516	if len(out) < rolen {
517		out2 := make([]byte, rolen)
518		copy(out2[rolen-len(out):], out)
519		return out2
520	}
521
522	// drop most significant bytes if it's too long
523	if len(out) > rolen {
524		out2 := make([]byte, rolen)
525		copy(out2, out[len(out)-rolen:])
526		return out2
527	}
528
529	return out
530}
531
532// https://tools.ietf.org/html/rfc6979#section-2.3.4
533func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte {
534	z1 := hashToInt(in, curve)
535	z2 := new(big.Int).Sub(z1, curve.Params().N)
536	if z2.Sign() < 0 {
537		return int2octets(z1, rolen)
538	}
539	return int2octets(z2, rolen)
540}
541