github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/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/crypto"
    30  	"github.com/ethereum/go-ethereum/rlp"
    31  )
    32  
    33  var (
    34  	ErrInvalidSig           = errors.New("invalid transaction v, r, s values")
    35  	ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures")
    36  	ErrInvalidTxType        = errors.New("transaction type not valid in this context")
    37  	ErrTxTypeNotSupported   = errors.New("transaction type not supported")
    38  	errEmptyTypedTx         = errors.New("empty typed transaction bytes")
    39  )
    40  
    41  // Transaction types.
    42  const (
    43  	LegacyTxType = iota
    44  	AccessListTxType
    45  )
    46  
    47  // Transaction is an Ethereum transaction.
    48  type Transaction struct {
    49  	inner TxData    // Consensus contents of a transaction
    50  	time  time.Time // Time first seen locally (spam avoidance)
    51  
    52  	// caches
    53  	hash atomic.Value
    54  	size atomic.Value
    55  	from atomic.Value
    56  }
    57  
    58  // NewTx creates a new transaction.
    59  func NewTx(inner TxData) *Transaction {
    60  	tx := new(Transaction)
    61  	tx.setDecoded(inner.copy(), 0)
    62  	return tx
    63  }
    64  
    65  // TxData is the underlying data of a transaction.
    66  //
    67  // This is implemented by LegacyTx and AccessListTx.
    68  type TxData interface {
    69  	txType() byte // returns the type ID
    70  	copy() TxData // creates a deep copy and initializes all fields
    71  
    72  	chainID() *big.Int
    73  	accessList() AccessList
    74  	data() []byte
    75  	gas() uint64
    76  	gasPrice() *big.Int
    77  	value() *big.Int
    78  	nonce() uint64
    79  	to() *common.Address
    80  
    81  	rawSignatureValues() (v, r, s *big.Int)
    82  	setSignatureValues(chainID, v, r, s *big.Int)
    83  }
    84  
    85  // Time returns transaction's time
    86  func (tx *Transaction) Time() time.Time {
    87  	return tx.time
    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  	default:
   186  		return nil, ErrTxTypeNotSupported
   187  	}
   188  }
   189  
   190  // setDecoded sets the inner transaction and size after decoding.
   191  func (tx *Transaction) setDecoded(inner TxData, size int) {
   192  	tx.inner = inner
   193  	tx.time = time.Now()
   194  	if size > 0 {
   195  		tx.size.Store(common.StorageSize(size))
   196  	}
   197  }
   198  
   199  func sanityCheckSignature(v *big.Int, r *big.Int, s *big.Int, maybeProtected bool) error {
   200  	if isProtectedV(v) && !maybeProtected {
   201  		return ErrUnexpectedProtection
   202  	}
   203  
   204  	var plainV byte
   205  	if isProtectedV(v) {
   206  		chainID := deriveChainId(v).Uint64()
   207  		plainV = byte(v.Uint64() - 35 - 2*chainID)
   208  	} else if maybeProtected {
   209  		// Only EIP-155 signatures can be optionally protected. Since
   210  		// we determined this v value is not protected, it must be a
   211  		// raw 27 or 28.
   212  		plainV = byte(v.Uint64() - 27)
   213  	} else {
   214  		// If the signature is not optionally protected, we assume it
   215  		// must already be equal to the recovery id.
   216  		plainV = byte(v.Uint64())
   217  	}
   218  	if !crypto.ValidateSignatureValues(plainV, r, s, false) {
   219  		return ErrInvalidSig
   220  	}
   221  
   222  	return nil
   223  }
   224  
   225  func isProtectedV(V *big.Int) bool {
   226  	if V.BitLen() <= 8 {
   227  		v := V.Uint64()
   228  		return v != 27 && v != 28 && v != 1 && v != 0
   229  	}
   230  	// anything not 27 or 28 is considered protected
   231  	return true
   232  }
   233  
   234  // Protected says whether the transaction is replay-protected.
   235  func (tx *Transaction) Protected() bool {
   236  	switch tx := tx.inner.(type) {
   237  	case *LegacyTx:
   238  		return tx.V != nil && isProtectedV(tx.V)
   239  	default:
   240  		return true
   241  	}
   242  }
   243  
   244  // Type returns the transaction type.
   245  func (tx *Transaction) Type() uint8 {
   246  	return tx.inner.txType()
   247  }
   248  
   249  // ChainId returns the EIP155 chain ID of the transaction. The return value will always be
   250  // non-nil. For legacy transactions which are not replay-protected, the return value is
   251  // zero.
   252  func (tx *Transaction) ChainId() *big.Int {
   253  	return tx.inner.chainID()
   254  }
   255  
   256  // Data returns the input data of the transaction.
   257  func (tx *Transaction) Data() []byte { return tx.inner.data() }
   258  
   259  // AccessList returns the access list of the transaction.
   260  func (tx *Transaction) AccessList() AccessList { return tx.inner.accessList() }
   261  
   262  // Gas returns the gas limit of the transaction.
   263  func (tx *Transaction) Gas() uint64 { return tx.inner.gas() }
   264  
   265  // GasPrice returns the gas price of the transaction.
   266  func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.inner.gasPrice()) }
   267  
   268  // The return value of ImmutableGasPrice can not been modified.
   269  func (tx *Transaction) ImmutableGasPrice() *big.Int { return tx.inner.gasPrice() }
   270  
   271  // Value returns the ether amount of the transaction.
   272  func (tx *Transaction) Value() *big.Int { return new(big.Int).Set(tx.inner.value()) }
   273  
   274  // Nonce returns the sender account nonce of the transaction.
   275  func (tx *Transaction) Nonce() uint64 { return tx.inner.nonce() }
   276  
   277  // To returns the recipient address of the transaction.
   278  // For contract-creation transactions, To returns nil.
   279  func (tx *Transaction) To() *common.Address {
   280  	// Copy the pointed-to address.
   281  	ito := tx.inner.to()
   282  	if ito == nil {
   283  		return nil
   284  	}
   285  	cpy := *ito
   286  	return &cpy
   287  }
   288  
   289  // Cost returns gas * gasPrice + value.
   290  func (tx *Transaction) Cost() *big.Int {
   291  	total := new(big.Int).Mul(tx.GasPrice(), new(big.Int).SetUint64(tx.Gas()))
   292  	total.Add(total, tx.Value())
   293  	return total
   294  }
   295  
   296  // RawSignatureValues returns the V, R, S signature values of the transaction.
   297  // The return values should not be modified by the caller.
   298  func (tx *Transaction) RawSignatureValues() (v, r, s *big.Int) {
   299  	return tx.inner.rawSignatureValues()
   300  }
   301  
   302  // GasPriceCmp compares the gas prices of two transactions.
   303  func (tx *Transaction) GasPriceCmp(other *Transaction) int {
   304  	return tx.inner.gasPrice().Cmp(other.inner.gasPrice())
   305  }
   306  
   307  // GasPriceIntCmp compares the gas price of the transaction against the given price.
   308  func (tx *Transaction) GasPriceIntCmp(other *big.Int) int {
   309  	return tx.inner.gasPrice().Cmp(other)
   310  }
   311  
   312  // Hash returns the transaction hash.
   313  func (tx *Transaction) Hash() common.Hash {
   314  	if hash := tx.hash.Load(); hash != nil {
   315  		return hash.(common.Hash)
   316  	}
   317  
   318  	var h common.Hash
   319  	if tx.Type() == LegacyTxType {
   320  		h = rlpHash(tx.inner)
   321  	} else {
   322  		h = prefixedRlpHash(tx.Type(), tx.inner)
   323  	}
   324  	tx.hash.Store(h)
   325  	return h
   326  }
   327  
   328  // Size returns the true RLP encoded storage size of the transaction, either by
   329  // encoding and returning it, or returning a previously cached value.
   330  func (tx *Transaction) Size() common.StorageSize {
   331  	if size := tx.size.Load(); size != nil {
   332  		return size.(common.StorageSize)
   333  	}
   334  	c := writeCounter(0)
   335  	rlp.Encode(&c, &tx.inner)
   336  	tx.size.Store(common.StorageSize(c))
   337  	return common.StorageSize(c)
   338  }
   339  
   340  // WithSignature returns a new transaction with the given signature.
   341  // This signature needs to be in the [R || S || V] format where V is 0 or 1.
   342  func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) {
   343  	r, s, v, err := signer.SignatureValues(tx, sig)
   344  	if err != nil {
   345  		return nil, err
   346  	}
   347  	cpy := tx.inner.copy()
   348  	cpy.setSignatureValues(signer.ChainID(), v, r, s)
   349  	return &Transaction{inner: cpy, time: tx.time}, nil
   350  }
   351  
   352  // Transactions implements DerivableList for transactions.
   353  type Transactions []*Transaction
   354  
   355  // Len returns the length of s.
   356  func (s Transactions) Len() int { return len(s) }
   357  
   358  // EncodeIndex encodes the i'th transaction to w. Note that this does not check for errors
   359  // because we assume that *Transaction will only ever contain valid txs that were either
   360  // constructed by decoding or via public API in this package.
   361  func (s Transactions) EncodeIndex(i int, w *bytes.Buffer) {
   362  	tx := s[i]
   363  	if tx.Type() == LegacyTxType {
   364  		rlp.Encode(w, tx.inner)
   365  	} else {
   366  		tx.encodeTyped(w)
   367  	}
   368  }
   369  
   370  // TxDifference returns a new set which is the difference between a and b.
   371  func TxDifference(a, b Transactions) Transactions {
   372  	keep := make(Transactions, 0, len(a))
   373  
   374  	remove := make(map[common.Hash]struct{})
   375  	for _, tx := range b {
   376  		remove[tx.Hash()] = struct{}{}
   377  	}
   378  
   379  	for _, tx := range a {
   380  		if _, ok := remove[tx.Hash()]; !ok {
   381  			keep = append(keep, tx)
   382  		}
   383  	}
   384  
   385  	return keep
   386  }
   387  
   388  // TxByNonce implements the sort interface to allow sorting a list of transactions
   389  // by their nonces. This is usually only useful for sorting transactions from a
   390  // single account, otherwise a nonce comparison doesn't make much sense.
   391  type TxByNonce Transactions
   392  
   393  func (s TxByNonce) Len() int           { return len(s) }
   394  func (s TxByNonce) Less(i, j int) bool { return s[i].Nonce() < s[j].Nonce() }
   395  func (s TxByNonce) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   396  
   397  // TxByPriceAndTime implements both the sort and the heap interface, making it useful
   398  // for all at once sorting as well as individually adding and removing elements.
   399  type TxByPriceAndTime Transactions
   400  
   401  func (s TxByPriceAndTime) Len() int { return len(s) }
   402  func (s TxByPriceAndTime) Less(i, j int) bool {
   403  	// If the prices are equal, use the time the transaction was first seen for
   404  	// deterministic sorting
   405  	cmp := s[i].ImmutableGasPrice().Cmp(s[j].ImmutableGasPrice())
   406  	if cmp == 0 {
   407  		return s[i].time.Before(s[j].time)
   408  	}
   409  	return cmp > 0
   410  }
   411  func (s TxByPriceAndTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   412  
   413  func (s *TxByPriceAndTime) Push(x interface{}) {
   414  	*s = append(*s, x.(*Transaction))
   415  }
   416  
   417  func (s *TxByPriceAndTime) Pop() interface{} {
   418  	old := *s
   419  	n := len(old)
   420  	x := old[n-1]
   421  	*s = old[0 : n-1]
   422  	return x
   423  }
   424  
   425  // TransactionsByPriceAndNonce represents a set of transactions that can return
   426  // transactions in a profit-maximizing sorted order, while supporting removing
   427  // entire batches of transactions for non-executable accounts.
   428  type TransactionsByPriceAndNonce struct {
   429  	txs    map[common.Address]Transactions // Per account nonce-sorted list of transactions
   430  	heads  TxByPriceAndTime                // Next transaction for each unique account (price heap)
   431  	signer Signer                          // Signer for the set of transactions
   432  }
   433  
   434  // NewTransactionsByPriceAndNonce creates a transaction set that can retrieve
   435  // price sorted transactions in a nonce-honouring way.
   436  //
   437  // Note, the input map is reowned so the caller should not interact any more with
   438  // if after providing it to the constructor.
   439  func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByPriceAndNonce {
   440  	// Initialize a price and received time based heap with the head transactions
   441  	heads := make(TxByPriceAndTime, 0, len(txs))
   442  	for from, accTxs := range txs {
   443  		// Ensure the sender address is from the signer
   444  		if acc, _ := Sender(signer, accTxs[0]); acc != from {
   445  			delete(txs, from)
   446  			continue
   447  		}
   448  		heads = append(heads, accTxs[0])
   449  		txs[from] = accTxs[1:]
   450  	}
   451  	heap.Init(&heads)
   452  
   453  	// Assemble and return the transaction set
   454  	return &TransactionsByPriceAndNonce{
   455  		txs:    txs,
   456  		heads:  heads,
   457  		signer: signer,
   458  	}
   459  }
   460  
   461  // Copy copys a new TransactionsPriceAndNonce with the same *transaction
   462  func (t *TransactionsByPriceAndNonce) Copy() *TransactionsByPriceAndNonce {
   463  	heads := make([]*Transaction, len(t.heads))
   464  	copy(heads, t.heads)
   465  	txs := make(map[common.Address]Transactions, len(t.txs))
   466  	for acc, txsTmp := range t.txs {
   467  		txs[acc] = txsTmp
   468  	}
   469  	return &TransactionsByPriceAndNonce{
   470  		heads:  heads,
   471  		txs:    txs,
   472  		signer: t.signer,
   473  	}
   474  }
   475  
   476  // Peek returns the next transaction by price.
   477  func (t *TransactionsByPriceAndNonce) Peek() *Transaction {
   478  	if len(t.heads) == 0 {
   479  		return nil
   480  	}
   481  	return t.heads[0]
   482  }
   483  
   484  // Shift replaces the current best head with the next one from the same account.
   485  func (t *TransactionsByPriceAndNonce) Shift() {
   486  	acc, _ := Sender(t.signer, t.heads[0])
   487  	if txs, ok := t.txs[acc]; ok && len(txs) > 0 {
   488  		t.heads[0], t.txs[acc] = txs[0], txs[1:]
   489  		heap.Fix(&t.heads, 0)
   490  	} else {
   491  		heap.Pop(&t.heads)
   492  	}
   493  }
   494  
   495  // Pop removes the best transaction, *not* replacing it with the next one from
   496  // the same account. This should be used when a transaction cannot be executed
   497  // and hence all subsequent ones should be discarded from the same account.
   498  func (t *TransactionsByPriceAndNonce) Pop() {
   499  	heap.Pop(&t.heads)
   500  }
   501  
   502  func (t *TransactionsByPriceAndNonce) CurrentSize() int {
   503  	return len(t.heads)
   504  }
   505  
   506  //Forward moves current transaction to be the one which is one index after tx
   507  func (t *TransactionsByPriceAndNonce) Forward(tx *Transaction) {
   508  	if tx == nil {
   509  		if len(t.heads) > 0 {
   510  			t.heads = t.heads[0:0]
   511  		}
   512  		return
   513  	}
   514  	//check whether target tx exists in t.heads
   515  	for _, head := range t.heads {
   516  		if tx == head {
   517  			//shift t to the position one after tx
   518  			txTmp := t.Peek()
   519  			for txTmp != tx {
   520  				t.Shift()
   521  				txTmp = t.Peek()
   522  			}
   523  			t.Shift()
   524  			return
   525  		}
   526  	}
   527  	//get the sender address of tx
   528  	acc, _ := Sender(t.signer, tx)
   529  	//check whether target tx exists in t.txs
   530  	if txs, ok := t.txs[acc]; ok {
   531  		for _, txTmp := range txs {
   532  			//found the same pointer in t.txs as tx and then shift t to the position one after tx
   533  			if txTmp == tx {
   534  				txTmp = t.Peek()
   535  				for txTmp != tx {
   536  					t.Shift()
   537  					txTmp = t.Peek()
   538  				}
   539  				t.Shift()
   540  				return
   541  			}
   542  		}
   543  	}
   544  }
   545  
   546  // Message is a fully derived transaction and implements core.Message
   547  //
   548  // NOTE: In a future PR this will be removed.
   549  type Message struct {
   550  	to         *common.Address
   551  	from       common.Address
   552  	nonce      uint64
   553  	amount     *big.Int
   554  	gasLimit   uint64
   555  	gasPrice   *big.Int
   556  	data       []byte
   557  	accessList AccessList
   558  	checkNonce bool
   559  }
   560  
   561  func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, accessList AccessList, checkNonce bool) Message {
   562  	return Message{
   563  		from:       from,
   564  		to:         to,
   565  		nonce:      nonce,
   566  		amount:     amount,
   567  		gasLimit:   gasLimit,
   568  		gasPrice:   gasPrice,
   569  		data:       data,
   570  		accessList: accessList,
   571  		checkNonce: checkNonce,
   572  	}
   573  }
   574  
   575  // AsMessage returns the transaction as a core.Message.
   576  func (tx *Transaction) AsMessage(s Signer) (Message, error) {
   577  	msg := Message{
   578  		nonce:      tx.Nonce(),
   579  		gasLimit:   tx.Gas(),
   580  		gasPrice:   new(big.Int).Set(tx.GasPrice()),
   581  		to:         tx.To(),
   582  		amount:     tx.Value(),
   583  		data:       tx.Data(),
   584  		accessList: tx.AccessList(),
   585  		checkNonce: true,
   586  	}
   587  
   588  	var err error
   589  	msg.from, err = Sender(s, tx)
   590  	return msg, err
   591  }
   592  
   593  // AsMessageNoNonceCheck returns the transaction with checkNonce field set to be false.
   594  func (tx *Transaction) AsMessageNoNonceCheck(s Signer) (Message, error) {
   595  	msg, err := tx.AsMessage(s)
   596  	if err == nil {
   597  		msg.checkNonce = false
   598  	}
   599  	return msg, err
   600  }
   601  
   602  func (m Message) From() common.Address   { return m.from }
   603  func (m Message) To() *common.Address    { return m.to }
   604  func (m Message) GasPrice() *big.Int     { return m.gasPrice }
   605  func (m Message) Value() *big.Int        { return m.amount }
   606  func (m Message) Gas() uint64            { return m.gasLimit }
   607  func (m Message) Nonce() uint64          { return m.nonce }
   608  func (m Message) Data() []byte           { return m.data }
   609  func (m Message) AccessList() AccessList { return m.accessList }
   610  func (m Message) CheckNonce() bool       { return m.checkNonce }