github.com/bcnmy/go-ethereum@v1.10.27/core/types/transaction.go (about) 1 // Copyright 2014 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 "bytes" 21 "container/heap" 22 "errors" 23 "io" 24 "math/big" 25 "sync/atomic" 26 "time" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/common/math" 30 "github.com/ethereum/go-ethereum/crypto" 31 "github.com/ethereum/go-ethereum/rlp" 32 ) 33 34 var ( 35 ErrInvalidSig = errors.New("invalid transaction v, r, s values") 36 ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures") 37 ErrInvalidTxType = errors.New("transaction type not valid in this context") 38 ErrTxTypeNotSupported = errors.New("transaction type not supported") 39 ErrGasFeeCapTooLow = errors.New("fee cap less than base fee") 40 errShortTypedTx = errors.New("typed transaction too short") 41 ) 42 43 // Transaction types. 44 const ( 45 LegacyTxType = iota 46 AccessListTxType 47 DynamicFeeTxType 48 ) 49 50 // Transaction is an Ethereum transaction. 51 type Transaction struct { 52 inner TxData // Consensus contents of a transaction 53 time time.Time // Time first seen locally (spam avoidance) 54 55 // caches 56 hash atomic.Value 57 size atomic.Value 58 from atomic.Value 59 } 60 61 // NewTx creates a new transaction. 62 func NewTx(inner TxData) *Transaction { 63 tx := new(Transaction) 64 tx.setDecoded(inner.copy(), 0) 65 return tx 66 } 67 68 // TxData is the underlying data of a transaction. 69 // 70 // This is implemented by DynamicFeeTx, LegacyTx and AccessListTx. 71 type TxData interface { 72 txType() byte // returns the type ID 73 copy() TxData // creates a deep copy and initializes all fields 74 75 chainID() *big.Int 76 accessList() AccessList 77 data() []byte 78 gas() uint64 79 gasPrice() *big.Int 80 gasTipCap() *big.Int 81 gasFeeCap() *big.Int 82 value() *big.Int 83 nonce() uint64 84 to() *common.Address 85 86 rawSignatureValues() (v, r, s *big.Int) 87 setSignatureValues(chainID, v, r, s *big.Int) 88 } 89 90 // EncodeRLP implements rlp.Encoder 91 func (tx *Transaction) EncodeRLP(w io.Writer) error { 92 if tx.Type() == LegacyTxType { 93 return rlp.Encode(w, tx.inner) 94 } 95 // It's an EIP-2718 typed TX envelope. 96 buf := encodeBufferPool.Get().(*bytes.Buffer) 97 defer encodeBufferPool.Put(buf) 98 buf.Reset() 99 if err := tx.encodeTyped(buf); err != nil { 100 return err 101 } 102 return rlp.Encode(w, buf.Bytes()) 103 } 104 105 // encodeTyped writes the canonical encoding of a typed transaction to w. 106 func (tx *Transaction) encodeTyped(w *bytes.Buffer) error { 107 w.WriteByte(tx.Type()) 108 return rlp.Encode(w, tx.inner) 109 } 110 111 // MarshalBinary returns the canonical encoding of the transaction. 112 // For legacy transactions, it returns the RLP encoding. For EIP-2718 typed 113 // transactions, it returns the type and payload. 114 func (tx *Transaction) MarshalBinary() ([]byte, error) { 115 if tx.Type() == LegacyTxType { 116 return rlp.EncodeToBytes(tx.inner) 117 } 118 var buf bytes.Buffer 119 err := tx.encodeTyped(&buf) 120 return buf.Bytes(), err 121 } 122 123 // DecodeRLP implements rlp.Decoder 124 func (tx *Transaction) DecodeRLP(s *rlp.Stream) error { 125 kind, size, err := s.Kind() 126 switch { 127 case err != nil: 128 return err 129 case kind == rlp.List: 130 // It's a legacy transaction. 131 var inner LegacyTx 132 err := s.Decode(&inner) 133 if err == nil { 134 tx.setDecoded(&inner, int(rlp.ListSize(size))) 135 } 136 return err 137 default: 138 // It's an EIP-2718 typed TX envelope. 139 var b []byte 140 if b, err = s.Bytes(); err != nil { 141 return err 142 } 143 inner, err := tx.decodeTyped(b) 144 if err == nil { 145 tx.setDecoded(inner, len(b)) 146 } 147 return err 148 } 149 } 150 151 // UnmarshalBinary decodes the canonical encoding of transactions. 152 // It supports legacy RLP transactions and EIP2718 typed transactions. 153 func (tx *Transaction) UnmarshalBinary(b []byte) error { 154 if len(b) > 0 && b[0] > 0x7f { 155 // It's a legacy transaction. 156 var data LegacyTx 157 err := rlp.DecodeBytes(b, &data) 158 if err != nil { 159 return err 160 } 161 tx.setDecoded(&data, len(b)) 162 return nil 163 } 164 // It's an EIP2718 typed transaction envelope. 165 inner, err := tx.decodeTyped(b) 166 if err != nil { 167 return err 168 } 169 tx.setDecoded(inner, len(b)) 170 return nil 171 } 172 173 // decodeTyped decodes a typed transaction from the canonical format. 174 func (tx *Transaction) decodeTyped(b []byte) (TxData, error) { 175 if len(b) <= 1 { 176 return nil, errShortTypedTx 177 } 178 switch b[0] { 179 case AccessListTxType: 180 var inner AccessListTx 181 err := rlp.DecodeBytes(b[1:], &inner) 182 return &inner, err 183 case DynamicFeeTxType: 184 var inner DynamicFeeTx 185 err := rlp.DecodeBytes(b[1:], &inner) 186 return &inner, err 187 default: 188 return nil, ErrTxTypeNotSupported 189 } 190 } 191 192 // setDecoded sets the inner transaction and size after decoding. 193 func (tx *Transaction) setDecoded(inner TxData, size int) { 194 tx.inner = inner 195 tx.time = time.Now() 196 if size > 0 { 197 tx.size.Store(common.StorageSize(size)) 198 } 199 } 200 201 func sanityCheckSignature(v *big.Int, r *big.Int, s *big.Int, maybeProtected bool) error { 202 if isProtectedV(v) && !maybeProtected { 203 return ErrUnexpectedProtection 204 } 205 206 var plainV byte 207 if isProtectedV(v) { 208 chainID := deriveChainId(v).Uint64() 209 plainV = byte(v.Uint64() - 35 - 2*chainID) 210 } else if maybeProtected { 211 // Only EIP-155 signatures can be optionally protected. Since 212 // we determined this v value is not protected, it must be a 213 // raw 27 or 28. 214 plainV = byte(v.Uint64() - 27) 215 } else { 216 // If the signature is not optionally protected, we assume it 217 // must already be equal to the recovery id. 218 plainV = byte(v.Uint64()) 219 } 220 if !crypto.ValidateSignatureValues(plainV, r, s, false) { 221 return ErrInvalidSig 222 } 223 224 return nil 225 } 226 227 func isProtectedV(V *big.Int) bool { 228 if V.BitLen() <= 8 { 229 v := V.Uint64() 230 return v != 27 && v != 28 && v != 1 && v != 0 231 } 232 // anything not 27 or 28 is considered protected 233 return true 234 } 235 236 // Protected says whether the transaction is replay-protected. 237 func (tx *Transaction) Protected() bool { 238 switch tx := tx.inner.(type) { 239 case *LegacyTx: 240 return tx.V != nil && isProtectedV(tx.V) 241 default: 242 return true 243 } 244 } 245 246 // Type returns the transaction type. 247 func (tx *Transaction) Type() uint8 { 248 return tx.inner.txType() 249 } 250 251 // ChainId returns the EIP155 chain ID of the transaction. The return value will always be 252 // non-nil. For legacy transactions which are not replay-protected, the return value is 253 // zero. 254 func (tx *Transaction) ChainId() *big.Int { 255 return tx.inner.chainID() 256 } 257 258 // Data returns the input data of the transaction. 259 func (tx *Transaction) Data() []byte { return tx.inner.data() } 260 261 // AccessList returns the access list of the transaction. 262 func (tx *Transaction) AccessList() AccessList { return tx.inner.accessList() } 263 264 // Gas returns the gas limit of the transaction. 265 func (tx *Transaction) Gas() uint64 { return tx.inner.gas() } 266 267 // GasPrice returns the gas price of the transaction. 268 func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.inner.gasPrice()) } 269 270 // GasTipCap returns the gasTipCap per gas of the transaction. 271 func (tx *Transaction) GasTipCap() *big.Int { return new(big.Int).Set(tx.inner.gasTipCap()) } 272 273 // GasFeeCap returns the fee cap per gas of the transaction. 274 func (tx *Transaction) GasFeeCap() *big.Int { return new(big.Int).Set(tx.inner.gasFeeCap()) } 275 276 // Value returns the ether amount of the transaction. 277 func (tx *Transaction) Value() *big.Int { return new(big.Int).Set(tx.inner.value()) } 278 279 // Nonce returns the sender account nonce of the transaction. 280 func (tx *Transaction) Nonce() uint64 { return tx.inner.nonce() } 281 282 // To returns the recipient address of the transaction. 283 // For contract-creation transactions, To returns nil. 284 func (tx *Transaction) To() *common.Address { 285 return copyAddressPtr(tx.inner.to()) 286 } 287 288 // Cost returns gas * gasPrice + value. 289 func (tx *Transaction) Cost() *big.Int { 290 total := new(big.Int).Mul(tx.GasPrice(), new(big.Int).SetUint64(tx.Gas())) 291 total.Add(total, tx.Value()) 292 return total 293 } 294 295 // RawSignatureValues returns the V, R, S signature values of the transaction. 296 // The return values should not be modified by the caller. 297 func (tx *Transaction) RawSignatureValues() (v, r, s *big.Int) { 298 return tx.inner.rawSignatureValues() 299 } 300 301 // GasFeeCapCmp compares the fee cap of two transactions. 302 func (tx *Transaction) GasFeeCapCmp(other *Transaction) int { 303 return tx.inner.gasFeeCap().Cmp(other.inner.gasFeeCap()) 304 } 305 306 // GasFeeCapIntCmp compares the fee cap of the transaction against the given fee cap. 307 func (tx *Transaction) GasFeeCapIntCmp(other *big.Int) int { 308 return tx.inner.gasFeeCap().Cmp(other) 309 } 310 311 // GasTipCapCmp compares the gasTipCap of two transactions. 312 func (tx *Transaction) GasTipCapCmp(other *Transaction) int { 313 return tx.inner.gasTipCap().Cmp(other.inner.gasTipCap()) 314 } 315 316 // GasTipCapIntCmp compares the gasTipCap of the transaction against the given gasTipCap. 317 func (tx *Transaction) GasTipCapIntCmp(other *big.Int) int { 318 return tx.inner.gasTipCap().Cmp(other) 319 } 320 321 // EffectiveGasTip returns the effective miner gasTipCap for the given base fee. 322 // Note: if the effective gasTipCap is negative, this method returns both error 323 // the actual negative value, _and_ ErrGasFeeCapTooLow 324 func (tx *Transaction) EffectiveGasTip(baseFee *big.Int) (*big.Int, error) { 325 if baseFee == nil { 326 return tx.GasTipCap(), nil 327 } 328 var err error 329 gasFeeCap := tx.GasFeeCap() 330 if gasFeeCap.Cmp(baseFee) == -1 { 331 err = ErrGasFeeCapTooLow 332 } 333 return math.BigMin(tx.GasTipCap(), gasFeeCap.Sub(gasFeeCap, baseFee)), err 334 } 335 336 // EffectiveGasTipValue is identical to EffectiveGasTip, but does not return an 337 // error in case the effective gasTipCap is negative 338 func (tx *Transaction) EffectiveGasTipValue(baseFee *big.Int) *big.Int { 339 effectiveTip, _ := tx.EffectiveGasTip(baseFee) 340 return effectiveTip 341 } 342 343 // EffectiveGasTipCmp compares the effective gasTipCap of two transactions assuming the given base fee. 344 func (tx *Transaction) EffectiveGasTipCmp(other *Transaction, baseFee *big.Int) int { 345 if baseFee == nil { 346 return tx.GasTipCapCmp(other) 347 } 348 return tx.EffectiveGasTipValue(baseFee).Cmp(other.EffectiveGasTipValue(baseFee)) 349 } 350 351 // EffectiveGasTipIntCmp compares the effective gasTipCap of a transaction to the given gasTipCap. 352 func (tx *Transaction) EffectiveGasTipIntCmp(other *big.Int, baseFee *big.Int) int { 353 if baseFee == nil { 354 return tx.GasTipCapIntCmp(other) 355 } 356 return tx.EffectiveGasTipValue(baseFee).Cmp(other) 357 } 358 359 // Hash returns the transaction hash. 360 func (tx *Transaction) Hash() common.Hash { 361 if hash := tx.hash.Load(); hash != nil { 362 return hash.(common.Hash) 363 } 364 365 var h common.Hash 366 if tx.Type() == LegacyTxType { 367 h = rlpHash(tx.inner) 368 } else { 369 h = prefixedRlpHash(tx.Type(), tx.inner) 370 } 371 tx.hash.Store(h) 372 return h 373 } 374 375 // Size returns the true RLP encoded storage size of the transaction, either by 376 // encoding and returning it, or returning a previously cached value. 377 func (tx *Transaction) Size() common.StorageSize { 378 if size := tx.size.Load(); size != nil { 379 return size.(common.StorageSize) 380 } 381 c := writeCounter(0) 382 rlp.Encode(&c, &tx.inner) 383 tx.size.Store(common.StorageSize(c)) 384 return common.StorageSize(c) 385 } 386 387 // WithSignature returns a new transaction with the given signature. 388 // This signature needs to be in the [R || S || V] format where V is 0 or 1. 389 func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) { 390 r, s, v, err := signer.SignatureValues(tx, sig) 391 if err != nil { 392 return nil, err 393 } 394 cpy := tx.inner.copy() 395 cpy.setSignatureValues(signer.ChainID(), v, r, s) 396 return &Transaction{inner: cpy, time: tx.time}, nil 397 } 398 399 // Transactions implements DerivableList for transactions. 400 type Transactions []*Transaction 401 402 // Len returns the length of s. 403 func (s Transactions) Len() int { return len(s) } 404 405 // EncodeIndex encodes the i'th transaction to w. Note that this does not check for errors 406 // because we assume that *Transaction will only ever contain valid txs that were either 407 // constructed by decoding or via public API in this package. 408 func (s Transactions) EncodeIndex(i int, w *bytes.Buffer) { 409 tx := s[i] 410 if tx.Type() == LegacyTxType { 411 rlp.Encode(w, tx.inner) 412 } else { 413 tx.encodeTyped(w) 414 } 415 } 416 417 // TxDifference returns a new set which is the difference between a and b. 418 func TxDifference(a, b Transactions) Transactions { 419 keep := make(Transactions, 0, len(a)) 420 421 remove := make(map[common.Hash]struct{}) 422 for _, tx := range b { 423 remove[tx.Hash()] = struct{}{} 424 } 425 426 for _, tx := range a { 427 if _, ok := remove[tx.Hash()]; !ok { 428 keep = append(keep, tx) 429 } 430 } 431 432 return keep 433 } 434 435 // HashDifference returns a new set which is the difference between a and b. 436 func HashDifference(a, b []common.Hash) []common.Hash { 437 keep := make([]common.Hash, 0, len(a)) 438 439 remove := make(map[common.Hash]struct{}) 440 for _, hash := range b { 441 remove[hash] = struct{}{} 442 } 443 444 for _, hash := range a { 445 if _, ok := remove[hash]; !ok { 446 keep = append(keep, hash) 447 } 448 } 449 450 return keep 451 } 452 453 // TxByNonce implements the sort interface to allow sorting a list of transactions 454 // by their nonces. This is usually only useful for sorting transactions from a 455 // single account, otherwise a nonce comparison doesn't make much sense. 456 type TxByNonce Transactions 457 458 func (s TxByNonce) Len() int { return len(s) } 459 func (s TxByNonce) Less(i, j int) bool { return s[i].Nonce() < s[j].Nonce() } 460 func (s TxByNonce) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 461 462 // TxWithMinerFee wraps a transaction with its gas price or effective miner gasTipCap 463 type TxWithMinerFee struct { 464 tx *Transaction 465 minerFee *big.Int 466 } 467 468 // NewTxWithMinerFee creates a wrapped transaction, calculating the effective 469 // miner gasTipCap if a base fee is provided. 470 // Returns error in case of a negative effective miner gasTipCap. 471 func NewTxWithMinerFee(tx *Transaction, baseFee *big.Int) (*TxWithMinerFee, error) { 472 minerFee, err := tx.EffectiveGasTip(baseFee) 473 if err != nil { 474 return nil, err 475 } 476 return &TxWithMinerFee{ 477 tx: tx, 478 minerFee: minerFee, 479 }, nil 480 } 481 482 // TxByPriceAndTime implements both the sort and the heap interface, making it useful 483 // for all at once sorting as well as individually adding and removing elements. 484 type TxByPriceAndTime []*TxWithMinerFee 485 486 func (s TxByPriceAndTime) Len() int { return len(s) } 487 func (s TxByPriceAndTime) Less(i, j int) bool { 488 // If the prices are equal, use the time the transaction was first seen for 489 // deterministic sorting 490 cmp := s[i].minerFee.Cmp(s[j].minerFee) 491 if cmp == 0 { 492 return s[i].tx.time.Before(s[j].tx.time) 493 } 494 return cmp > 0 495 } 496 func (s TxByPriceAndTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 497 498 func (s *TxByPriceAndTime) Push(x interface{}) { 499 *s = append(*s, x.(*TxWithMinerFee)) 500 } 501 502 func (s *TxByPriceAndTime) Pop() interface{} { 503 old := *s 504 n := len(old) 505 x := old[n-1] 506 *s = old[0 : n-1] 507 return x 508 } 509 510 // TransactionsByPriceAndNonce represents a set of transactions that can return 511 // transactions in a profit-maximizing sorted order, while supporting removing 512 // entire batches of transactions for non-executable accounts. 513 type TransactionsByPriceAndNonce struct { 514 txs map[common.Address]Transactions // Per account nonce-sorted list of transactions 515 heads TxByPriceAndTime // Next transaction for each unique account (price heap) 516 signer Signer // Signer for the set of transactions 517 baseFee *big.Int // Current base fee 518 } 519 520 // NewTransactionsByPriceAndNonce creates a transaction set that can retrieve 521 // price sorted transactions in a nonce-honouring way. 522 // 523 // Note, the input map is reowned so the caller should not interact any more with 524 // if after providing it to the constructor. 525 func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions, baseFee *big.Int) *TransactionsByPriceAndNonce { 526 // Initialize a price and received time based heap with the head transactions 527 heads := make(TxByPriceAndTime, 0, len(txs)) 528 for from, accTxs := range txs { 529 acc, _ := Sender(signer, accTxs[0]) 530 wrapped, err := NewTxWithMinerFee(accTxs[0], baseFee) 531 // Remove transaction if sender doesn't match from, or if wrapping fails. 532 if acc != from || err != nil { 533 delete(txs, from) 534 continue 535 } 536 heads = append(heads, wrapped) 537 txs[from] = accTxs[1:] 538 } 539 heap.Init(&heads) 540 541 // Assemble and return the transaction set 542 return &TransactionsByPriceAndNonce{ 543 txs: txs, 544 heads: heads, 545 signer: signer, 546 baseFee: baseFee, 547 } 548 } 549 550 // Peek returns the next transaction by price. 551 func (t *TransactionsByPriceAndNonce) Peek() *Transaction { 552 if len(t.heads) == 0 { 553 return nil 554 } 555 return t.heads[0].tx 556 } 557 558 // Shift replaces the current best head with the next one from the same account. 559 func (t *TransactionsByPriceAndNonce) Shift() { 560 acc, _ := Sender(t.signer, t.heads[0].tx) 561 if txs, ok := t.txs[acc]; ok && len(txs) > 0 { 562 if wrapped, err := NewTxWithMinerFee(txs[0], t.baseFee); err == nil { 563 t.heads[0], t.txs[acc] = wrapped, txs[1:] 564 heap.Fix(&t.heads, 0) 565 return 566 } 567 } 568 heap.Pop(&t.heads) 569 } 570 571 // Pop removes the best transaction, *not* replacing it with the next one from 572 // the same account. This should be used when a transaction cannot be executed 573 // and hence all subsequent ones should be discarded from the same account. 574 func (t *TransactionsByPriceAndNonce) Pop() { 575 heap.Pop(&t.heads) 576 } 577 578 // Message is a fully derived transaction and implements core.Message 579 // 580 // NOTE: In a future PR this will be removed. 581 type Message struct { 582 to *common.Address 583 from common.Address 584 nonce uint64 585 amount *big.Int 586 gasLimit uint64 587 gasPrice *big.Int 588 gasFeeCap *big.Int 589 gasTipCap *big.Int 590 data []byte 591 accessList AccessList 592 isFake bool 593 } 594 595 func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice, gasFeeCap, gasTipCap *big.Int, data []byte, accessList AccessList, isFake bool) Message { 596 return Message{ 597 from: from, 598 to: to, 599 nonce: nonce, 600 amount: amount, 601 gasLimit: gasLimit, 602 gasPrice: gasPrice, 603 gasFeeCap: gasFeeCap, 604 gasTipCap: gasTipCap, 605 data: data, 606 accessList: accessList, 607 isFake: isFake, 608 } 609 } 610 611 // AsMessage returns the transaction as a core.Message. 612 func (tx *Transaction) AsMessage(s Signer, baseFee *big.Int) (Message, error) { 613 msg := Message{ 614 nonce: tx.Nonce(), 615 gasLimit: tx.Gas(), 616 gasPrice: new(big.Int).Set(tx.GasPrice()), 617 gasFeeCap: new(big.Int).Set(tx.GasFeeCap()), 618 gasTipCap: new(big.Int).Set(tx.GasTipCap()), 619 to: tx.To(), 620 amount: tx.Value(), 621 data: tx.Data(), 622 accessList: tx.AccessList(), 623 isFake: false, 624 } 625 // If baseFee provided, set gasPrice to effectiveGasPrice. 626 if baseFee != nil { 627 msg.gasPrice = math.BigMin(msg.gasPrice.Add(msg.gasTipCap, baseFee), msg.gasFeeCap) 628 } 629 var err error 630 msg.from, err = Sender(s, tx) 631 return msg, err 632 } 633 634 func (m Message) From() common.Address { return m.from } 635 func (m Message) To() *common.Address { return m.to } 636 func (m Message) GasPrice() *big.Int { return m.gasPrice } 637 func (m Message) GasFeeCap() *big.Int { return m.gasFeeCap } 638 func (m Message) GasTipCap() *big.Int { return m.gasTipCap } 639 func (m Message) Value() *big.Int { return m.amount } 640 func (m Message) Gas() uint64 { return m.gasLimit } 641 func (m Message) Nonce() uint64 { return m.nonce } 642 func (m Message) Data() []byte { return m.data } 643 func (m Message) AccessList() AccessList { return m.accessList } 644 func (m Message) IsFake() bool { return m.isFake } 645 646 // copyAddressPtr copies an address. 647 func copyAddressPtr(a *common.Address) *common.Address { 648 if a == nil { 649 return nil 650 } 651 cpy := *a 652 return &cpy 653 }