github.com/klaytn/klaytn@v1.12.1/blockchain/types/transaction_signing.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from core/types/transaction_signing.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package types 22 23 import ( 24 "crypto/ecdsa" 25 "encoding/json" 26 "errors" 27 "fmt" 28 "math/big" 29 30 "github.com/klaytn/klaytn/blockchain/types/accountkey" 31 "github.com/klaytn/klaytn/common" 32 "github.com/klaytn/klaytn/crypto" 33 "github.com/klaytn/klaytn/params" 34 ) 35 36 var ( 37 ErrInvalidChainId = errors.New("invalid chain id for signer") 38 errNotTxInternalDataFrom = errors.New("not an TxInternalDataFrom") 39 ) 40 41 // sigCache is used to cache the derived sender and contains 42 // the signer used to derive it. 43 type sigCache struct { 44 signer Signer 45 from common.Address 46 } 47 48 // sigCachePubkey is used to cache the derived public key and contains 49 // the signer used to derive it. 50 type sigCachePubkey struct { 51 signer Signer 52 pubkey []*ecdsa.PublicKey 53 } 54 55 // MakeSigner returns a Signer based on the given chain config and block number. 56 func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer { 57 var signer Signer 58 59 if config.IsEthTxTypeForkEnabled(blockNumber) { 60 signer = NewLondonSigner(config.ChainID) 61 } else { 62 signer = NewEIP155Signer(config.ChainID) 63 } 64 65 return signer 66 } 67 68 // LatestSigner returns the 'most permissive' Signer available for the given chain 69 // configuration. Specifically, this enables support of EIP-155 replay protection and 70 // EIP-2930 access list transactions when their respective forks are scheduled to occur at 71 // any block number in the chain config. 72 // 73 // Use this in transaction-handling code where the current block number is unknown. If you 74 // have the current block number available, use MakeSigner instead. 75 func LatestSigner(config *params.ChainConfig) Signer { 76 // Be aware that it checks whether EthTxTypeCompatibleBlock is set, 77 // but doesn't check whether it is enabled on a specific block number. 78 if config.EthTxTypeCompatibleBlock != nil { 79 return NewLondonSigner(config.ChainID) 80 } 81 82 return NewEIP155Signer(config.ChainID) 83 } 84 85 // LatestSignerForChainID returns the 'most permissive' Signer available. Specifically, 86 // this enables support for EIP-155 replay protection and all implemented EIP-2718 87 // transaction types if chainID is non-nil. 88 // 89 // Use this in transaction-handling code where the current block number and fork 90 // configuration are unknown. If you have a ChainConfig, use LatestSigner instead. 91 // If you have a ChainConfig and know the current block number, use MakeSigner instead. 92 func LatestSignerForChainID(chainID *big.Int) Signer { 93 return NewLondonSigner(chainID) 94 } 95 96 // SignTx signs the transaction using the given signer and private key 97 func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) { 98 h := s.Hash(tx) 99 sig, err := crypto.Sign(h[:], prv) 100 if err != nil { 101 return nil, err 102 } 103 104 return tx.WithSignature(s, sig) 105 } 106 107 // SignTxAsFeePayer signs the transaction as a fee payer using the given signer and private key 108 func SignTxAsFeePayer(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) { 109 h, err := s.HashFeePayer(tx) 110 if err != nil { 111 return nil, err 112 } 113 sig, err := crypto.Sign(h[:], prv) 114 if err != nil { 115 return nil, err 116 } 117 return tx.WithFeePayerSignature(s, sig) 118 } 119 120 // AccountKeyPicker has a function GetKey() to retrieve an account key from statedb. 121 type AccountKeyPicker interface { 122 GetKey(address common.Address) accountkey.AccountKey 123 Exist(addr common.Address) bool 124 } 125 126 // Sender returns the address of the transaction. 127 // If an ethereum transaction, it calls SenderFrom(). 128 // Otherwise, it just returns tx.From() because the other transaction types have the field `from`. 129 // NOTE: this function should not be called if tx signature validation is required. 130 // In that situtation, you should call ValidateSender(). 131 func Sender(signer Signer, tx *Transaction) (common.Address, error) { 132 if tx.IsEthereumTransaction() { 133 return SenderFrom(signer, tx) 134 } 135 136 return tx.From() 137 } 138 139 // SenderFeePayer returns the fee payer address of the transaction. 140 // If the transaction is not a fee-delegated transaction, the fee payer is set to 141 // the address of the `from` of the transaction. 142 func SenderFeePayer(signer Signer, tx *Transaction) (common.Address, error) { 143 tf, ok := tx.data.(TxInternalDataFeePayer) 144 if !ok { 145 return Sender(signer, tx) 146 } 147 return tf.GetFeePayer(), nil 148 } 149 150 // SenderFeePayerPubkey returns the public key derived from the signature (V, R, S) using secp256k1 151 // elliptic curve and an error if it failed deriving or upon an incorrect 152 // signature. 153 // 154 // SenderFeePayerPubkey may cache the public key, allowing it to be used regardless of 155 // signing method. The cache is invalidated if the cached signer does 156 // not match the signer used in the current call. 157 func SenderFeePayerPubkey(signer Signer, tx *Transaction) ([]*ecdsa.PublicKey, error) { 158 if sc := tx.feePayer.Load(); sc != nil { 159 sigCache := sc.(sigCachePubkey) 160 // If the signer used to derive from in a previous 161 // call is not the same as used current, invalidate 162 // the cache. 163 if sigCache.signer.Equal(signer) { 164 return sigCache.pubkey, nil 165 } 166 } 167 168 pubkey, err := signer.SenderFeePayer(tx) 169 if err != nil { 170 return nil, err 171 } 172 173 tx.feePayer.Store(sigCachePubkey{signer: signer, pubkey: pubkey}) 174 return pubkey, nil 175 } 176 177 // SenderFrom returns the address derived from the signature (V, R, S) using secp256k1 178 // elliptic curve and an error if it failed deriving or upon an incorrect 179 // signature. 180 // 181 // SenderFrom may cache the address, allowing it to be used regardless of 182 // signing method. The cache is invalidated if the cached signer does 183 // not match the signer used in the current call. 184 func SenderFrom(signer Signer, tx *Transaction) (common.Address, error) { 185 if sc := tx.from.Load(); sc != nil { 186 sigCache := sc.(sigCache) 187 // If the signer used to derive from in a previous 188 // call is not the same as used current, invalidate 189 // the cache. 190 if sigCache.signer.Equal(signer) { 191 return sigCache.from, nil 192 } 193 } 194 195 addr, err := signer.Sender(tx) 196 if err != nil { 197 return common.Address{}, err 198 } 199 tx.from.Store(sigCache{signer: signer, from: addr}) 200 return addr, nil 201 } 202 203 // SenderPubkey returns the public key derived from the signature (V, R, S) using secp256k1 204 // elliptic curve and an error if it failed deriving or upon an incorrect 205 // signature. 206 // 207 // SenderPubkey may cache the public key, allowing it to be used regardless of 208 // signing method. The cache is invalidated if the cached signer does 209 // not match the signer used in the current call. 210 func SenderPubkey(signer Signer, tx *Transaction) ([]*ecdsa.PublicKey, error) { 211 if sc := tx.from.Load(); sc != nil { 212 sigCache := sc.(sigCachePubkey) 213 // If the signer used to derive from in a previous 214 // call is not the same as used current, invalidate 215 // the cache. 216 if sigCache.signer.Equal(signer) { 217 return sigCache.pubkey, nil 218 } 219 } 220 221 pubkey, err := signer.SenderPubkey(tx) 222 if err != nil { 223 return nil, err 224 } 225 tx.from.Store(sigCachePubkey{signer: signer, pubkey: pubkey}) 226 return pubkey, nil 227 } 228 229 // Signer encapsulates transaction signature handling. Note that this interface is not a 230 // stable API and may change at any time to accommodate new protocol rules. 231 type Signer interface { 232 // Sender returns the sender address of the transaction. 233 Sender(tx *Transaction) (common.Address, error) 234 // SenderPubkey returns the public key derived from tx signature and txhash. 235 SenderPubkey(tx *Transaction) ([]*ecdsa.PublicKey, error) 236 // SenderFeePayer returns the public key derived from tx signature and txhash. 237 SenderFeePayer(tx *Transaction) ([]*ecdsa.PublicKey, error) 238 // SignatureValues returns the raw R, S, V values corresponding to the 239 // given signature. 240 SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) 241 // ChainID returns the chain id. 242 ChainID() *big.Int 243 // Hash returns 'signature hash', i.e. the transaction hash that is signed by the 244 // private key. This hash does not uniquely identify the transaction. 245 Hash(tx *Transaction) common.Hash 246 // HashFeePayer returns the hash with a fee payer's address to be signed by a fee payer. 247 HashFeePayer(tx *Transaction) (common.Hash, error) 248 // Equal returns true if the given signer is the same as the receiver. 249 Equal(Signer) bool 250 } 251 252 type londonSigner struct{ eip2930Signer } 253 254 // NewLondonSigner returns a signer that accepts 255 // - EIP-1559 dynamic fee transactions, 256 // - EIP-2930 access list transactions and 257 // - EIP-155 replay protected transactions. 258 func NewLondonSigner(chainId *big.Int) Signer { 259 return londonSigner{eip2930Signer{NewEIP155Signer(chainId)}} 260 } 261 262 // ChainID returns the chain id. 263 func (s londonSigner) ChainID() *big.Int { 264 return s.chainId 265 } 266 267 // Equal returns true if the given signer is the same as the receiver. 268 func (s londonSigner) Equal(s2 Signer) bool { 269 x, ok := s2.(londonSigner) 270 return ok && x.chainId.Cmp(s.chainId) == 0 271 } 272 273 func (s londonSigner) Sender(tx *Transaction) (common.Address, error) { 274 if tx.Type() != TxTypeEthereumDynamicFee { 275 return s.eip2930Signer.Sender(tx) 276 } 277 278 if tx.ChainId().Cmp(s.chainId) != 0 { 279 return common.Address{}, ErrInvalidChainId 280 } 281 282 return tx.data.RecoverAddress(s.Hash(tx), true, func(v *big.Int) *big.Int { 283 // AL txs are defined to use 0 and 1 as their recovery 284 // id, add 27 to become equivalent to unprotected Homestead signatures. 285 V := new(big.Int).Add(v, big.NewInt(27)) 286 return V 287 }) 288 } 289 290 // SenderPubkey returns the public key derived from tx signature and txhash. 291 func (s londonSigner) SenderPubkey(tx *Transaction) ([]*ecdsa.PublicKey, error) { 292 if tx.Type() != TxTypeEthereumDynamicFee { 293 return s.eip2930Signer.SenderPubkey(tx) 294 } 295 296 if tx.ChainId().Cmp(s.chainId) != 0 { 297 return nil, ErrInvalidChainId 298 } 299 300 return tx.data.RecoverPubkey(s.Hash(tx), true, func(v *big.Int) *big.Int { 301 // AL txs are defined to use 0 and 1 as their recovery 302 // id, add 27 to become equivalent to unprotected Homestead signatures. 303 V := new(big.Int).Add(v, big.NewInt(27)) 304 return V 305 }) 306 } 307 308 // SenderFeePayer returns the public key derived from tx signature and txhash. 309 func (s londonSigner) SenderFeePayer(tx *Transaction) ([]*ecdsa.PublicKey, error) { 310 // EIP-1559(Dynamic fee transaction) tx don't supported fee-delegation. 311 return s.eip2930Signer.SenderFeePayer(tx) 312 } 313 314 // SignatureValues returns a new transaction with the given signature. This signature 315 // needs to be in the [R || S || V] format where V is 0 or 1. 316 func (s londonSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) { 317 if tx.Type() != TxTypeEthereumDynamicFee { 318 return s.eip2930Signer.SignatureValues(tx, sig) 319 } 320 321 if len(sig) != crypto.SignatureLength { 322 panic(fmt.Sprintf("wrong size for signature: got %d, want %d", len(sig), crypto.SignatureLength)) 323 } 324 325 // Check that chain ID of tx matches the signer. We also accept ID zero or nil here, 326 // because it indicates that the chain ID was not specified in the tx. 327 if tx.data.ChainId() != nil && tx.data.ChainId().Sign() != 0 && tx.data.ChainId().Cmp(s.ChainID()) != 0 { 328 return nil, nil, nil, ErrInvalidChainId 329 } 330 331 R = new(big.Int).SetBytes(sig[:32]) 332 S = new(big.Int).SetBytes(sig[32:64]) 333 V = big.NewInt(int64(sig[crypto.RecoveryIDOffset])) 334 335 return R, S, V, nil 336 } 337 338 // Hash returns the hash to be signed by the sender. 339 // It does not uniquely identify the transaction. 340 func (s londonSigner) Hash(tx *Transaction) common.Hash { 341 if tx.Type() != TxTypeEthereumDynamicFee { 342 return s.eip2930Signer.Hash(tx) 343 } 344 345 // infs[0] always has chainID 346 infs := tx.data.SerializeForSign() 347 chainID := tx.GetTxInternalData().ChainId() 348 if chainID == nil || chainID.BitLen() == 0 { 349 infs[0] = s.ChainID() 350 } 351 return prefixedRlpHash(byte(tx.Type()), infs) 352 } 353 354 // HashFeePayer returns the hash with a fee payer's address to be signed by a fee payer. 355 // It does not uniquely identify the transaction. 356 func (s londonSigner) HashFeePayer(tx *Transaction) (common.Hash, error) { 357 return s.eip2930Signer.HashFeePayer(tx) 358 } 359 360 type eip2930Signer struct{ EIP155Signer } 361 362 // NewEIP2930Signer returns a signer that accepts EIP-2930 access list transactions, 363 // EIP-155 replay protected transactions, and legacy transactions. 364 func NewEIP2930Signer(chainId *big.Int) Signer { 365 return eip2930Signer{NewEIP155Signer(chainId)} 366 } 367 368 // ChainID returns the chain id. 369 func (s eip2930Signer) ChainID() *big.Int { 370 return s.chainId 371 } 372 373 // Equal returns true if the given signer is the same as the receiver. 374 func (s eip2930Signer) Equal(s2 Signer) bool { 375 eip2930, ok := s2.(eip2930Signer) 376 return ok && eip2930.chainId.Cmp(s.chainId) == 0 377 } 378 379 // Sender returns the sender address of the transaction. 380 func (s eip2930Signer) Sender(tx *Transaction) (common.Address, error) { 381 if tx.Type() != TxTypeEthereumAccessList { 382 return s.EIP155Signer.Sender(tx) 383 } 384 385 if tx.ChainId().Cmp(s.chainId) != 0 { 386 return common.Address{}, ErrInvalidChainId 387 } 388 389 return tx.data.RecoverAddress(s.Hash(tx), true, func(v *big.Int) *big.Int { 390 // AL txs are defined to use 0 and 1 as their recovery 391 // id, add 27 to become equivalent to unprotected Homestead signatures. 392 V := new(big.Int).Add(v, big.NewInt(27)) 393 return V 394 }) 395 } 396 397 // SenderPubkey returns the public key derived from tx signature and txhash. 398 func (s eip2930Signer) SenderPubkey(tx *Transaction) ([]*ecdsa.PublicKey, error) { 399 if tx.Type() != TxTypeEthereumAccessList { 400 return s.EIP155Signer.SenderPubkey(tx) 401 } 402 403 if tx.ChainId().Cmp(s.chainId) != 0 { 404 return nil, ErrInvalidChainId 405 } 406 407 return tx.data.RecoverPubkey(s.Hash(tx), true, func(v *big.Int) *big.Int { 408 // AL txs are defined to use 0 and 1 as their recovery 409 // id, add 27 to become equivalent to unprotected Homestead signatures. 410 V := new(big.Int).Add(v, big.NewInt(27)) 411 return V 412 }) 413 } 414 415 // SenderFeePayer returns the public key derived from tx signature and txhash. 416 func (s eip2930Signer) SenderFeePayer(tx *Transaction) ([]*ecdsa.PublicKey, error) { 417 // EIP-2930(Optional access list transaction) tx don't supported fee-delegation. 418 return s.EIP155Signer.SenderFeePayer(tx) 419 } 420 421 // SignatureValues returns a new transaction with the given signature. This signature 422 // needs to be in the [R || S || V] format where V is 0 or 1. 423 func (s eip2930Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) { 424 if tx.Type() != TxTypeEthereumAccessList { 425 return s.EIP155Signer.SignatureValues(tx, sig) 426 } 427 428 // Check that chain ID of tx matches the signer. We also accept ID zero or nil here, 429 // because it indicates that the chain ID was not specified in the tx. 430 if tx.data.ChainId() != nil && tx.data.ChainId().Sign() != 0 && tx.data.ChainId().Cmp(s.ChainID()) != 0 { 431 return nil, nil, nil, ErrInvalidChainId 432 } 433 434 R, S, _ = decodeSignature(sig) 435 V = big.NewInt(int64(sig[64])) 436 437 return R, S, V, nil 438 } 439 440 // Hash returns the hash to be signed by the sender. 441 // It does not uniquely identify the transaction. 442 func (s eip2930Signer) Hash(tx *Transaction) common.Hash { 443 if tx.Type() != TxTypeEthereumAccessList { 444 return s.EIP155Signer.Hash(tx) 445 } 446 447 // infs[0] always has chainID 448 infs := tx.data.SerializeForSign() 449 chainID := tx.GetTxInternalData().ChainId() 450 if chainID == nil || chainID.BitLen() == 0 { 451 infs[0] = s.ChainID() 452 } 453 454 return prefixedRlpHash(byte(tx.Type()), infs) 455 } 456 457 // HashFeePayer returns the hash with a fee payer's address to be signed by a fee payer. 458 // It does not uniquely identify the transaction. 459 func (s eip2930Signer) HashFeePayer(tx *Transaction) (common.Hash, error) { 460 return s.EIP155Signer.HashFeePayer(tx) 461 } 462 463 type FrontierSigner struct{} 464 465 func (s FrontierSigner) ChainID() *big.Int { 466 return nil 467 } 468 469 func (s FrontierSigner) Equal(s2 Signer) bool { 470 _, ok := s2.(FrontierSigner) 471 return ok 472 } 473 474 func (fs FrontierSigner) Sender(tx *Transaction) (common.Address, error) { 475 if !tx.IsLegacyTransaction() { 476 return common.Address{}, ErrTxTypeNotSupported 477 } 478 sigs := tx.RawSignatureValues() 479 if len(sigs) != 1 { 480 return common.Address{}, ErrShouldBeSingleSignature 481 } 482 v, r, s := sigs[0].V, sigs[0].R, sigs[0].S 483 return recoverPlain(fs.Hash(tx), r, s, v, false) 484 } 485 486 func (fs FrontierSigner) SenderPubkey(tx *Transaction) ([]*ecdsa.PublicKey, error) { 487 return nil, ErrSenderPubkeyNotSupported 488 } 489 490 func (fs FrontierSigner) SenderFeePayer(tx *Transaction) ([]*ecdsa.PublicKey, error) { 491 return nil, ErrSenderFeePayerNotSupported 492 } 493 494 // SignatureValues returns signature values. This signature 495 // needs to be in the [R || S || V] format where V is 0 or 1. 496 func (fs FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) { 497 if tx.IsLegacyTransaction() { 498 return nil, nil, nil, ErrTxTypeNotSupported 499 } 500 r, s, v = decodeSignature(sig) 501 return r, s, v, nil 502 } 503 504 // Hash returns the hash to be signed by the sender. 505 // It does not uniquely identify the transaction. 506 func (fs FrontierSigner) Hash(tx *Transaction) common.Hash { 507 return rlpHash([]interface{}{ 508 tx.Nonce(), 509 tx.GasPrice(), 510 tx.Gas(), 511 tx.To(), 512 tx.Value(), 513 tx.Data(), 514 }) 515 } 516 517 func (fs FrontierSigner) HashFeePayer(tx *Transaction) (common.Hash, error) { 518 return common.Hash{}, ErrHashFeePayerNotSupported 519 } 520 521 // HomesteadTransaction implements TransactionInterface using the 522 // homestead rules. 523 type HomesteadSigner struct{ FrontierSigner } 524 525 func (s HomesteadSigner) ChainID() *big.Int { 526 return nil 527 } 528 529 func (s HomesteadSigner) Equal(s2 Signer) bool { 530 _, ok := s2.(HomesteadSigner) 531 return ok 532 } 533 534 // SignatureValues returns signature values. This signature 535 // needs to be in the [R || S || V] format where V is 0 or 1. 536 func (hs HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) { 537 return hs.FrontierSigner.SignatureValues(tx, sig) 538 } 539 540 func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) { 541 if !tx.IsLegacyTransaction() { 542 return common.Address{}, ErrTxTypeNotSupported 543 } 544 sigs := tx.RawSignatureValues() 545 if len(sigs) != 1 { 546 return common.Address{}, ErrShouldBeSingleSignature 547 } 548 v, r, s := sigs[0].V, sigs[0].R, sigs[0].S 549 550 return recoverPlain(hs.Hash(tx), r, s, v, true) 551 } 552 553 // EIP155Transaction implements Signer using the EIP155 rules. 554 type EIP155Signer struct { 555 chainId, chainIdMul *big.Int 556 } 557 558 func NewEIP155Signer(chainId *big.Int) EIP155Signer { 559 if chainId == nil { 560 chainId = new(big.Int) 561 } 562 return EIP155Signer{ 563 chainId: chainId, 564 chainIdMul: new(big.Int).Mul(chainId, common.Big2), 565 } 566 } 567 568 // ChainID returns the chain id. 569 func (s EIP155Signer) ChainID() *big.Int { 570 return s.chainId 571 } 572 573 func (s EIP155Signer) Equal(s2 Signer) bool { 574 eip155, ok := s2.(EIP155Signer) 575 return ok && eip155.chainId.Cmp(s.chainId) == 0 576 } 577 578 var big8 = big.NewInt(8) 579 580 func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error) { 581 if tx.IsEthTypedTransaction() { 582 return common.Address{}, ErrTxTypeNotSupported 583 } 584 585 if !tx.Protected() { 586 return HomesteadSigner{}.Sender(tx) 587 } 588 589 if !tx.IsLegacyTransaction() { 590 b, _ := json.Marshal(tx) 591 logger.Warn("No need to execute Sender!", "tx", string(b)) 592 } 593 594 if tx.ChainId().Cmp(s.chainId) != 0 { 595 return common.Address{}, ErrInvalidChainId 596 } 597 return tx.data.RecoverAddress(s.Hash(tx), true, func(v *big.Int) *big.Int { 598 V := new(big.Int).Sub(v, s.chainIdMul) 599 return V.Sub(V, big8) 600 }) 601 } 602 603 func (s EIP155Signer) SenderPubkey(tx *Transaction) ([]*ecdsa.PublicKey, error) { 604 if tx.IsEthTypedTransaction() { 605 return nil, ErrTxTypeNotSupported 606 } 607 608 if tx.IsLegacyTransaction() { 609 b, _ := json.Marshal(tx) 610 logger.Warn("No need to execute SenderPubkey!", "tx", string(b)) 611 } 612 613 if tx.ChainId().Cmp(s.chainId) != 0 { 614 return nil, ErrInvalidChainId 615 } 616 return tx.data.RecoverPubkey(s.Hash(tx), true, func(v *big.Int) *big.Int { 617 V := new(big.Int).Sub(v, s.chainIdMul) 618 return V.Sub(V, big8) 619 }) 620 } 621 622 func (s EIP155Signer) SenderFeePayer(tx *Transaction) ([]*ecdsa.PublicKey, error) { 623 if tx.IsEthTypedTransaction() { 624 return nil, ErrTxTypeNotSupported 625 } 626 627 if tx.IsLegacyTransaction() { 628 b, _ := json.Marshal(tx) 629 logger.Warn("No need to execute SenderFeePayer!", "tx", string(b)) 630 } 631 632 if tx.ChainId().Cmp(s.chainId) != 0 { 633 return nil, ErrInvalidChainId 634 } 635 636 tf, ok := tx.data.(TxInternalDataFeePayer) 637 if !ok { 638 return nil, errNotFeeDelegationTransaction 639 } 640 641 hash, err := s.HashFeePayer(tx) 642 if err != nil { 643 return nil, err 644 } 645 646 return tf.RecoverFeePayerPubkey(hash, true, func(v *big.Int) *big.Int { 647 V := new(big.Int).Sub(v, s.chainIdMul) 648 return V.Sub(V, big8) 649 }) 650 } 651 652 // SignatureValues returns a new transaction with the given signature. This signature 653 // needs to be in the [R || S || V] format where V is 0 or 1. 654 func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) { 655 if tx.Type().IsEthTypedTransaction() { 656 return nil, nil, nil, ErrTxTypeNotSupported 657 } 658 659 R, S, _ = decodeSignature(sig) 660 V = big.NewInt(int64(sig[crypto.RecoveryIDOffset] + 35)) 661 V.Add(V, s.chainIdMul) 662 663 return R, S, V, nil 664 } 665 666 // Hash returns the hash to be signed by the sender. 667 // It does not uniquely identify the transaction. 668 func (s EIP155Signer) Hash(tx *Transaction) common.Hash { 669 // If the data object implements SerializeForSignToByte(), use it. 670 if ser, ok := tx.data.(TxInternalDataSerializeForSignToByte); ok { 671 return rlpHash(struct { 672 Byte []byte 673 ChainId *big.Int 674 R uint 675 S uint 676 }{ 677 ser.SerializeForSignToBytes(), 678 s.chainId, 679 uint(0), 680 uint(0), 681 }) 682 } 683 684 infs := append(tx.data.SerializeForSign(), 685 s.chainId, uint(0), uint(0)) 686 return rlpHash(infs) 687 } 688 689 // HashFeePayer returns the hash with a fee payer's address to be signed by a fee payer. 690 // It does not uniquely identify the transaction. 691 func (s EIP155Signer) HashFeePayer(tx *Transaction) (common.Hash, error) { 692 tf, ok := tx.data.(TxInternalDataFeePayer) 693 if !ok { 694 return common.Hash{}, errNotFeeDelegationTransaction 695 } 696 697 // If the data object implements SerializeForSignToByte(), use it. 698 if ser, ok := tx.data.(TxInternalDataSerializeForSignToByte); ok { 699 return rlpHash(struct { 700 Byte []byte 701 FeePayer common.Address 702 ChainId *big.Int 703 R uint 704 S uint 705 }{ 706 ser.SerializeForSignToBytes(), 707 tf.GetFeePayer(), 708 s.chainId, 709 uint(0), 710 uint(0), 711 }), nil 712 } 713 714 infs := append(tx.data.SerializeForSign(), 715 tf.GetFeePayer(), 716 s.chainId, uint(0), uint(0)) 717 return rlpHash(infs), nil 718 } 719 720 func recoverPlainCommon(sighash common.Hash, R, S, Vb *big.Int, homestead bool) ([]byte, error) { 721 if Vb.BitLen() > 8 { 722 return []byte{}, ErrInvalidSig 723 } 724 V := byte(Vb.Uint64() - 27) 725 if !crypto.ValidateSignatureValues(V, R, S, homestead) { 726 return []byte{}, ErrInvalidSig 727 } 728 // encode the snature in uncompressed format 729 r, s := R.Bytes(), S.Bytes() 730 sig := make([]byte, crypto.SignatureLength) 731 copy(sig[32-len(r):32], r) 732 copy(sig[64-len(s):64], s) 733 sig[crypto.RecoveryIDOffset] = V 734 // recover the public key from the snature 735 pub, err := crypto.Ecrecover(sighash[:], sig) 736 if err != nil { 737 return []byte{}, err 738 } 739 if len(pub) == 0 || pub[0] != 4 { 740 return []byte{}, errors.New("invalid public key") 741 } 742 return pub, nil 743 } 744 745 func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) { 746 pub, err := recoverPlainCommon(sighash, R, S, Vb, homestead) 747 if err != nil { 748 return common.Address{}, err 749 } 750 751 var addr common.Address 752 copy(addr[:], crypto.Keccak256(pub[1:])[12:]) 753 return addr, nil 754 } 755 756 func recoverPlainPubkey(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (*ecdsa.PublicKey, error) { 757 pub, err := recoverPlainCommon(sighash, R, S, Vb, homestead) 758 if err != nil { 759 return nil, err 760 } 761 762 pubkey, err := crypto.UnmarshalPubkey(pub) 763 if err != nil { 764 return nil, err 765 } 766 767 return pubkey, nil 768 } 769 770 // deriveChainId derives the chain id from the given v parameter 771 func deriveChainId(v *big.Int) *big.Int { 772 if v.BitLen() <= 64 { 773 v := v.Uint64() 774 if v == 27 || v == 28 { 775 return new(big.Int) 776 } 777 return new(big.Int).SetUint64((v - 35) / 2) 778 } 779 v = new(big.Int).Sub(v, big.NewInt(35)) 780 return v.Div(v, common.Big2) 781 } 782 783 func decodeSignature(sig []byte) (r, s, v *big.Int) { 784 if len(sig) != crypto.SignatureLength { 785 panic(fmt.Sprintf("wrong size for signature: got %d, want %d", len(sig), crypto.SignatureLength)) 786 } 787 r = new(big.Int).SetBytes(sig[:32]) 788 s = new(big.Int).SetBytes(sig[32:64]) 789 v = new(big.Int).SetBytes([]byte{sig[64] + 27}) 790 return r, s, v 791 }