github.com/googgoog/go-ethereum@v1.9.7/core/types/transaction_signing.go (about) 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 17 package types 18 19 import ( 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 30 var ( 31 ErrInvalidChainId = errors.New("invalid chain id for signer") 32 ) 33 34 // sigCache is used to cache the derived sender and contains 35 // the signer used to derive it. 36 type sigCache struct { 37 signer Signer 38 from common.Address 39 } 40 41 // MakeSigner returns a Signer based on the given chain config and block number. 42 func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer { 43 var signer Signer 44 switch { 45 case config.IsEIP155(blockNumber): 46 signer = NewEIP155Signer(config.ChainID) 47 case config.IsHomestead(blockNumber): 48 signer = HomesteadSigner{} 49 default: 50 signer = FrontierSigner{} 51 } 52 return signer 53 } 54 55 // SignTx signs the transaction using the given signer and private key 56 func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) { 57 h := s.Hash(tx) 58 sig, err := crypto.Sign(h[:], prv) 59 if err != nil { 60 return nil, err 61 } 62 return tx.WithSignature(s, sig) 63 } 64 65 // Sender returns the address derived from the signature (V, R, S) using secp256k1 66 // elliptic curve and an error if it failed deriving or upon an incorrect 67 // signature. 68 // 69 // Sender may cache the address, allowing it to be used regardless of 70 // signing method. The cache is invalidated if the cached signer does 71 // not match the signer used in the current call. 72 func Sender(signer Signer, tx *Transaction) (common.Address, error) { 73 if sc := tx.from.Load(); sc != nil { 74 sigCache := sc.(sigCache) 75 // If the signer used to derive from in a previous 76 // call is not the same as used current, invalidate 77 // the cache. 78 if sigCache.signer.Equal(signer) { 79 return sigCache.from, nil 80 } 81 } 82 83 addr, err := signer.Sender(tx) 84 if err != nil { 85 return common.Address{}, err 86 } 87 tx.from.Store(sigCache{signer: signer, from: addr}) 88 return addr, nil 89 } 90 91 // Signer encapsulates transaction signature handling. Note that this interface is not a 92 // stable API and may change at any time to accommodate new protocol rules. 93 type Signer interface { 94 // Sender returns the sender address of the transaction. 95 Sender(tx *Transaction) (common.Address, error) 96 // SignatureValues returns the raw R, S, V values corresponding to the 97 // given signature. 98 SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) 99 // Hash returns the hash to be signed. 100 Hash(tx *Transaction) common.Hash 101 // Equal returns true if the given signer is the same as the receiver. 102 Equal(Signer) bool 103 } 104 105 // EIP155Transaction implements Signer using the EIP155 rules. 106 type EIP155Signer struct { 107 chainId, chainIdMul *big.Int 108 } 109 110 func NewEIP155Signer(chainId *big.Int) EIP155Signer { 111 if chainId == nil { 112 chainId = new(big.Int) 113 } 114 return EIP155Signer{ 115 chainId: chainId, 116 chainIdMul: new(big.Int).Mul(chainId, big.NewInt(2)), 117 } 118 } 119 120 func (s EIP155Signer) Equal(s2 Signer) bool { 121 eip155, ok := s2.(EIP155Signer) 122 return ok && eip155.chainId.Cmp(s.chainId) == 0 123 } 124 125 var big8 = big.NewInt(8) 126 127 func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error) { 128 if !tx.Protected() { 129 return HomesteadSigner{}.Sender(tx) 130 } 131 if tx.ChainId().Cmp(s.chainId) != 0 { 132 return common.Address{}, ErrInvalidChainId 133 } 134 V := new(big.Int).Sub(tx.data.V, s.chainIdMul) 135 V.Sub(V, big8) 136 return recoverPlain(s.Hash(tx), tx.data.R, tx.data.S, V, true) 137 } 138 139 // SignatureValues returns signature values. This signature 140 // needs to be in the [R || S || V] format where V is 0 or 1. 141 func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) { 142 R, S, V, err = HomesteadSigner{}.SignatureValues(tx, sig) 143 if err != nil { 144 return nil, nil, nil, err 145 } 146 if s.chainId.Sign() != 0 { 147 V = big.NewInt(int64(sig[64] + 35)) 148 V.Add(V, s.chainIdMul) 149 } 150 return R, S, V, nil 151 } 152 153 // Hash returns the hash to be signed by the sender. 154 // It does not uniquely identify the transaction. 155 func (s EIP155Signer) Hash(tx *Transaction) common.Hash { 156 return rlpHash([]interface{}{ 157 tx.data.AccountNonce, 158 tx.data.Price, 159 tx.data.GasLimit, 160 tx.data.Recipient, 161 tx.data.Amount, 162 tx.data.Payload, 163 s.chainId, uint(0), uint(0), 164 }) 165 } 166 167 // HomesteadTransaction implements TransactionInterface using the 168 // homestead rules. 169 type HomesteadSigner struct{ FrontierSigner } 170 171 func (s HomesteadSigner) Equal(s2 Signer) bool { 172 _, ok := s2.(HomesteadSigner) 173 return ok 174 } 175 176 // SignatureValues returns signature values. This signature 177 // needs to be in the [R || S || V] format where V is 0 or 1. 178 func (hs HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) { 179 return hs.FrontierSigner.SignatureValues(tx, sig) 180 } 181 182 func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) { 183 return recoverPlain(hs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, true) 184 } 185 186 type FrontierSigner struct{} 187 188 func (s FrontierSigner) Equal(s2 Signer) bool { 189 _, ok := s2.(FrontierSigner) 190 return ok 191 } 192 193 // SignatureValues returns signature values. This signature 194 // needs to be in the [R || S || V] format where V is 0 or 1. 195 func (fs FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) { 196 if len(sig) != crypto.SignatureLength { 197 panic(fmt.Sprintf("wrong size for signature: got %d, want %d", len(sig), crypto.SignatureLength)) 198 } 199 r = new(big.Int).SetBytes(sig[:32]) 200 s = new(big.Int).SetBytes(sig[32:64]) 201 v = new(big.Int).SetBytes([]byte{sig[64] + 27}) 202 return r, s, v, nil 203 } 204 205 // Hash returns the hash to be signed by the sender. 206 // It does not uniquely identify the transaction. 207 func (fs FrontierSigner) Hash(tx *Transaction) common.Hash { 208 return rlpHash([]interface{}{ 209 tx.data.AccountNonce, 210 tx.data.Price, 211 tx.data.GasLimit, 212 tx.data.Recipient, 213 tx.data.Amount, 214 tx.data.Payload, 215 }) 216 } 217 218 func (fs FrontierSigner) Sender(tx *Transaction) (common.Address, error) { 219 return recoverPlain(fs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, false) 220 } 221 222 func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) { 223 if Vb.BitLen() > 8 { 224 return common.Address{}, ErrInvalidSig 225 } 226 V := byte(Vb.Uint64() - 27) 227 if !crypto.ValidateSignatureValues(V, R, S, homestead) { 228 return common.Address{}, ErrInvalidSig 229 } 230 // encode the signature in uncompressed format 231 r, s := R.Bytes(), S.Bytes() 232 sig := make([]byte, crypto.SignatureLength) 233 copy(sig[32-len(r):32], r) 234 copy(sig[64-len(s):64], s) 235 sig[64] = V 236 // recover the public key from the signature 237 pub, err := crypto.Ecrecover(sighash[:], sig) 238 if err != nil { 239 return common.Address{}, err 240 } 241 if len(pub) == 0 || pub[0] != 4 { 242 return common.Address{}, errors.New("invalid public key") 243 } 244 var addr common.Address 245 copy(addr[:], crypto.Keccak256(pub[1:])[12:]) 246 return addr, nil 247 } 248 249 // deriveChainId derives the chain id from the given v parameter 250 func deriveChainId(v *big.Int) *big.Int { 251 if v.BitLen() <= 64 { 252 v := v.Uint64() 253 if v == 27 || v == 28 { 254 return new(big.Int) 255 } 256 return new(big.Int).SetUint64((v - 35) / 2) 257 } 258 v = new(big.Int).Sub(v, big.NewInt(35)) 259 return v.Div(v, big.NewInt(2)) 260 }