1// Copyright 2016 The go-ethereum Authors
2// This file is part of the go-ethereum library.
3//
4// The go-ethereum library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU Lesser General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// The go-ethereum library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU Lesser General Public License for more details.
13//
14// You should have received a copy of the GNU Lesser General Public License
15// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16
17package types
18
19import (
20	"crypto/ecdsa"
21	"errors"
22	"fmt"
23	"math/big"
24
25	"github.com/ethereum/go-ethereum/common"
26	"github.com/ethereum/go-ethereum/crypto"
27	"github.com/ethereum/go-ethereum/params"
28)
29
30var ErrInvalidChainId = errors.New("invalid chain id for signer")
31
32// sigCache is used to cache the derived sender and contains
33// the signer used to derive it.
34type sigCache struct {
35	signer Signer
36	from   common.Address
37}
38
39// MakeSigner returns a Signer based on the given chain config and block number.
40func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
41	var signer Signer
42	switch {
43	case config.IsLondon(blockNumber):
44		signer = NewLondonSigner(config.ChainID)
45	case config.IsBerlin(blockNumber):
46		signer = NewEIP2930Signer(config.ChainID)
47	case config.IsEIP155(blockNumber):
48		signer = NewEIP155Signer(config.ChainID)
49	case config.IsHomestead(blockNumber):
50		signer = HomesteadSigner{}
51	default:
52		signer = FrontierSigner{}
53	}
54	return signer
55}
56
57// LatestSigner returns the 'most permissive' Signer available for the given chain
58// configuration. Specifically, this enables support of EIP-155 replay protection and
59// EIP-2930 access list transactions when their respective forks are scheduled to occur at
60// any block number in the chain config.
61//
62// Use this in transaction-handling code where the current block number is unknown. If you
63// have the current block number available, use MakeSigner instead.
64func LatestSigner(config *params.ChainConfig) Signer {
65	if config.ChainID != nil {
66		if config.LondonBlock != nil {
67			return NewLondonSigner(config.ChainID)
68		}
69		if config.BerlinBlock != nil {
70			return NewEIP2930Signer(config.ChainID)
71		}
72		if config.EIP155Block != nil {
73			return NewEIP155Signer(config.ChainID)
74		}
75	}
76	return HomesteadSigner{}
77}
78
79// LatestSignerForChainID returns the 'most permissive' Signer available. Specifically,
80// this enables support for EIP-155 replay protection and all implemented EIP-2718
81// transaction types if chainID is non-nil.
82//
83// Use this in transaction-handling code where the current block number and fork
84// configuration are unknown. If you have a ChainConfig, use LatestSigner instead.
85// If you have a ChainConfig and know the current block number, use MakeSigner instead.
86func LatestSignerForChainID(chainID *big.Int) Signer {
87	if chainID == nil {
88		return HomesteadSigner{}
89	}
90	return NewLondonSigner(chainID)
91}
92
93// SignTx signs the transaction using the given signer and private key.
94func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) {
95	h := s.Hash(tx)
96	sig, err := crypto.Sign(h[:], prv)
97	if err != nil {
98		return nil, err
99	}
100	return tx.WithSignature(s, sig)
101}
102
103// SignNewTx creates a transaction and signs it.
104func SignNewTx(prv *ecdsa.PrivateKey, s Signer, txdata TxData) (*Transaction, error) {
105	tx := NewTx(txdata)
106	h := s.Hash(tx)
107	sig, err := crypto.Sign(h[:], prv)
108	if err != nil {
109		return nil, err
110	}
111	return tx.WithSignature(s, sig)
112}
113
114// MustSignNewTx creates a transaction and signs it.
115// This panics if the transaction cannot be signed.
116func MustSignNewTx(prv *ecdsa.PrivateKey, s Signer, txdata TxData) *Transaction {
117	tx, err := SignNewTx(prv, s, txdata)
118	if err != nil {
119		panic(err)
120	}
121	return tx
122}
123
124// Sender returns the address derived from the signature (V, R, S) using secp256k1
125// elliptic curve and an error if it failed deriving or upon an incorrect
126// signature.
127//
128// Sender may cache the address, allowing it to be used regardless of
129// signing method. The cache is invalidated if the cached signer does
130// not match the signer used in the current call.
131func Sender(signer Signer, tx *Transaction) (common.Address, error) {
132	if sc := tx.from.Load(); sc != nil {
133		sigCache := sc.(sigCache)
134		// If the signer used to derive from in a previous
135		// call is not the same as used current, invalidate
136		// the cache.
137		if sigCache.signer.Equal(signer) {
138			return sigCache.from, nil
139		}
140	}
141
142	addr, err := signer.Sender(tx)
143	if err != nil {
144		return common.Address{}, err
145	}
146	tx.from.Store(sigCache{signer: signer, from: addr})
147	return addr, nil
148}
149
150// Signer encapsulates transaction signature handling. The name of this type is slightly
151// misleading because Signers don't actually sign, they're just for validating and
152// processing of signatures.
153//
154// Note that this interface is not a stable API and may change at any time to accommodate
155// new protocol rules.
156type Signer interface {
157	// Sender returns the sender address of the transaction.
158	Sender(tx *Transaction) (common.Address, error)
159
160	// SignatureValues returns the raw R, S, V values corresponding to the
161	// given signature.
162	SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error)
163	ChainID() *big.Int
164
165	// Hash returns 'signature hash', i.e. the transaction hash that is signed by the
166	// private key. This hash does not uniquely identify the transaction.
167	Hash(tx *Transaction) common.Hash
168
169	// Equal returns true if the given signer is the same as the receiver.
170	Equal(Signer) bool
171}
172
173type londonSigner struct{ eip2930Signer }
174
175// NewLondonSigner returns a signer that accepts
176// - EIP-1559 dynamic fee transactions
177// - EIP-2930 access list transactions,
178// - EIP-155 replay protected transactions, and
179// - legacy Homestead transactions.
180func NewLondonSigner(chainId *big.Int) Signer {
181	return londonSigner{eip2930Signer{NewEIP155Signer(chainId)}}
182}
183
184func (s londonSigner) Sender(tx *Transaction) (common.Address, error) {
185	if tx.Type() != DynamicFeeTxType {
186		return s.eip2930Signer.Sender(tx)
187	}
188	V, R, S := tx.RawSignatureValues()
189	// DynamicFee txs are defined to use 0 and 1 as their recovery
190	// id, add 27 to become equivalent to unprotected Homestead signatures.
191	V = new(big.Int).Add(V, big.NewInt(27))
192	if tx.ChainId().Cmp(s.chainId) != 0 {
193		return common.Address{}, ErrInvalidChainId
194	}
195	return recoverPlain(s.Hash(tx), R, S, V, true)
196}
197
198func (s londonSigner) Equal(s2 Signer) bool {
199	x, ok := s2.(londonSigner)
200	return ok && x.chainId.Cmp(s.chainId) == 0
201}
202
203func (s londonSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
204	txdata, ok := tx.inner.(*DynamicFeeTx)
205	if !ok {
206		return s.eip2930Signer.SignatureValues(tx, sig)
207	}
208	// Check that chain ID of tx matches the signer. We also accept ID zero here,
209	// because it indicates that the chain ID was not specified in the tx.
210	if txdata.ChainID.Sign() != 0 && txdata.ChainID.Cmp(s.chainId) != 0 {
211		return nil, nil, nil, ErrInvalidChainId
212	}
213	R, S, _ = decodeSignature(sig)
214	V = big.NewInt(int64(sig[64]))
215	return R, S, V, nil
216}
217
218// Hash returns the hash to be signed by the sender.
219// It does not uniquely identify the transaction.
220func (s londonSigner) Hash(tx *Transaction) common.Hash {
221	if tx.Type() != DynamicFeeTxType {
222		return s.eip2930Signer.Hash(tx)
223	}
224	return prefixedRlpHash(
225		tx.Type(),
226		[]interface{}{
227			s.chainId,
228			tx.Nonce(),
229			tx.GasTipCap(),
230			tx.GasFeeCap(),
231			tx.Gas(),
232			tx.To(),
233			tx.Value(),
234			tx.Data(),
235			tx.AccessList(),
236		})
237}
238
239type eip2930Signer struct{ EIP155Signer }
240
241// NewEIP2930Signer returns a signer that accepts EIP-2930 access list transactions,
242// EIP-155 replay protected transactions, and legacy Homestead transactions.
243func NewEIP2930Signer(chainId *big.Int) Signer {
244	return eip2930Signer{NewEIP155Signer(chainId)}
245}
246
247func (s eip2930Signer) ChainID() *big.Int {
248	return s.chainId
249}
250
251func (s eip2930Signer) Equal(s2 Signer) bool {
252	x, ok := s2.(eip2930Signer)
253	return ok && x.chainId.Cmp(s.chainId) == 0
254}
255
256func (s eip2930Signer) Sender(tx *Transaction) (common.Address, error) {
257	V, R, S := tx.RawSignatureValues()
258	switch tx.Type() {
259	case LegacyTxType:
260		if !tx.Protected() {
261			return HomesteadSigner{}.Sender(tx)
262		}
263		V = new(big.Int).Sub(V, s.chainIdMul)
264		V.Sub(V, big8)
265	case AccessListTxType:
266		// AL txs are defined to use 0 and 1 as their recovery
267		// id, add 27 to become equivalent to unprotected Homestead signatures.
268		V = new(big.Int).Add(V, big.NewInt(27))
269	default:
270		return common.Address{}, ErrTxTypeNotSupported
271	}
272	if tx.ChainId().Cmp(s.chainId) != 0 {
273		return common.Address{}, ErrInvalidChainId
274	}
275	return recoverPlain(s.Hash(tx), R, S, V, true)
276}
277
278func (s eip2930Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
279	switch txdata := tx.inner.(type) {
280	case *LegacyTx:
281		return s.EIP155Signer.SignatureValues(tx, sig)
282	case *AccessListTx:
283		// Check that chain ID of tx matches the signer. We also accept ID zero here,
284		// because it indicates that the chain ID was not specified in the tx.
285		if txdata.ChainID.Sign() != 0 && txdata.ChainID.Cmp(s.chainId) != 0 {
286			return nil, nil, nil, ErrInvalidChainId
287		}
288		R, S, _ = decodeSignature(sig)
289		V = big.NewInt(int64(sig[64]))
290	default:
291		return nil, nil, nil, ErrTxTypeNotSupported
292	}
293	return R, S, V, nil
294}
295
296// Hash returns the hash to be signed by the sender.
297// It does not uniquely identify the transaction.
298func (s eip2930Signer) Hash(tx *Transaction) common.Hash {
299	switch tx.Type() {
300	case LegacyTxType:
301		return rlpHash([]interface{}{
302			tx.Nonce(),
303			tx.GasPrice(),
304			tx.Gas(),
305			tx.To(),
306			tx.Value(),
307			tx.Data(),
308			s.chainId, uint(0), uint(0),
309		})
310	case AccessListTxType:
311		return prefixedRlpHash(
312			tx.Type(),
313			[]interface{}{
314				s.chainId,
315				tx.Nonce(),
316				tx.GasPrice(),
317				tx.Gas(),
318				tx.To(),
319				tx.Value(),
320				tx.Data(),
321				tx.AccessList(),
322			})
323	default:
324		// This _should_ not happen, but in case someone sends in a bad
325		// json struct via RPC, it's probably more prudent to return an
326		// empty hash instead of killing the node with a panic
327		//panic("Unsupported transaction type: %d", tx.typ)
328		return common.Hash{}
329	}
330}
331
332// EIP155Signer implements Signer using the EIP-155 rules. This accepts transactions which
333// are replay-protected as well as unprotected homestead transactions.
334type EIP155Signer struct {
335	chainId, chainIdMul *big.Int
336}
337
338func NewEIP155Signer(chainId *big.Int) EIP155Signer {
339	if chainId == nil {
340		chainId = new(big.Int)
341	}
342	return EIP155Signer{
343		chainId:    chainId,
344		chainIdMul: new(big.Int).Mul(chainId, big.NewInt(2)),
345	}
346}
347
348func (s EIP155Signer) ChainID() *big.Int {
349	return s.chainId
350}
351
352func (s EIP155Signer) Equal(s2 Signer) bool {
353	eip155, ok := s2.(EIP155Signer)
354	return ok && eip155.chainId.Cmp(s.chainId) == 0
355}
356
357var big8 = big.NewInt(8)
358
359func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error) {
360	if tx.Type() != LegacyTxType {
361		return common.Address{}, ErrTxTypeNotSupported
362	}
363	if !tx.Protected() {
364		return HomesteadSigner{}.Sender(tx)
365	}
366	if tx.ChainId().Cmp(s.chainId) != 0 {
367		return common.Address{}, ErrInvalidChainId
368	}
369	V, R, S := tx.RawSignatureValues()
370	V = new(big.Int).Sub(V, s.chainIdMul)
371	V.Sub(V, big8)
372	return recoverPlain(s.Hash(tx), R, S, V, true)
373}
374
375// SignatureValues returns signature values. This signature
376// needs to be in the [R || S || V] format where V is 0 or 1.
377func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
378	if tx.Type() != LegacyTxType {
379		return nil, nil, nil, ErrTxTypeNotSupported
380	}
381	R, S, V = decodeSignature(sig)
382	if s.chainId.Sign() != 0 {
383		V = big.NewInt(int64(sig[64] + 35))
384		V.Add(V, s.chainIdMul)
385	}
386	return R, S, V, nil
387}
388
389// Hash returns the hash to be signed by the sender.
390// It does not uniquely identify the transaction.
391func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
392	return rlpHash([]interface{}{
393		tx.Nonce(),
394		tx.GasPrice(),
395		tx.Gas(),
396		tx.To(),
397		tx.Value(),
398		tx.Data(),
399		s.chainId, uint(0), uint(0),
400	})
401}
402
403// HomesteadTransaction implements TransactionInterface using the
404// homestead rules.
405type HomesteadSigner struct{ FrontierSigner }
406
407func (s HomesteadSigner) ChainID() *big.Int {
408	return nil
409}
410
411func (s HomesteadSigner) Equal(s2 Signer) bool {
412	_, ok := s2.(HomesteadSigner)
413	return ok
414}
415
416// SignatureValues returns signature values. This signature
417// needs to be in the [R || S || V] format where V is 0 or 1.
418func (hs HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
419	return hs.FrontierSigner.SignatureValues(tx, sig)
420}
421
422func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) {
423	if tx.Type() != LegacyTxType {
424		return common.Address{}, ErrTxTypeNotSupported
425	}
426	v, r, s := tx.RawSignatureValues()
427	return recoverPlain(hs.Hash(tx), r, s, v, true)
428}
429
430type FrontierSigner struct{}
431
432func (s FrontierSigner) ChainID() *big.Int {
433	return nil
434}
435
436func (s FrontierSigner) Equal(s2 Signer) bool {
437	_, ok := s2.(FrontierSigner)
438	return ok
439}
440
441func (fs FrontierSigner) Sender(tx *Transaction) (common.Address, error) {
442	if tx.Type() != LegacyTxType {
443		return common.Address{}, ErrTxTypeNotSupported
444	}
445	v, r, s := tx.RawSignatureValues()
446	return recoverPlain(fs.Hash(tx), r, s, v, false)
447}
448
449// SignatureValues returns signature values. This signature
450// needs to be in the [R || S || V] format where V is 0 or 1.
451func (fs FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
452	if tx.Type() != LegacyTxType {
453		return nil, nil, nil, ErrTxTypeNotSupported
454	}
455	r, s, v = decodeSignature(sig)
456	return r, s, v, nil
457}
458
459// Hash returns the hash to be signed by the sender.
460// It does not uniquely identify the transaction.
461func (fs FrontierSigner) Hash(tx *Transaction) common.Hash {
462	return rlpHash([]interface{}{
463		tx.Nonce(),
464		tx.GasPrice(),
465		tx.Gas(),
466		tx.To(),
467		tx.Value(),
468		tx.Data(),
469	})
470}
471
472func decodeSignature(sig []byte) (r, s, v *big.Int) {
473	if len(sig) != crypto.SignatureLength {
474		panic(fmt.Sprintf("wrong size for signature: got %d, want %d", len(sig), crypto.SignatureLength))
475	}
476	r = new(big.Int).SetBytes(sig[:32])
477	s = new(big.Int).SetBytes(sig[32:64])
478	v = new(big.Int).SetBytes([]byte{sig[64] + 27})
479	return r, s, v
480}
481
482func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) {
483	if Vb.BitLen() > 8 {
484		return common.Address{}, ErrInvalidSig
485	}
486	V := byte(Vb.Uint64() - 27)
487	if !crypto.ValidateSignatureValues(V, R, S, homestead) {
488		return common.Address{}, ErrInvalidSig
489	}
490	// encode the signature in uncompressed format
491	r, s := R.Bytes(), S.Bytes()
492	sig := make([]byte, crypto.SignatureLength)
493	copy(sig[32-len(r):32], r)
494	copy(sig[64-len(s):64], s)
495	sig[64] = V
496	// recover the public key from the signature
497	pub, err := crypto.Ecrecover(sighash[:], sig)
498	if err != nil {
499		return common.Address{}, err
500	}
501	if len(pub) == 0 || pub[0] != 4 {
502		return common.Address{}, errors.New("invalid public key")
503	}
504	var addr common.Address
505	copy(addr[:], crypto.Keccak256(pub[1:])[12:])
506	return addr, nil
507}
508
509// deriveChainId derives the chain id from the given v parameter
510func deriveChainId(v *big.Int) *big.Int {
511	if v.BitLen() <= 64 {
512		v := v.Uint64()
513		if v == 27 || v == 28 {
514			return new(big.Int)
515		}
516		return new(big.Int).SetUint64((v - 35) / 2)
517	}
518	v = new(big.Int).Sub(v, big.NewInt(35))
519	return v.Div(v, big.NewInt(2))
520}
521