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