github.com/klaytn/klaytn@v1.10.2/blockchain/types/transaction.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.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package types
    22  
    23  import (
    24  	"bytes"
    25  	"container/heap"
    26  	"crypto/ecdsa"
    27  	"encoding/json"
    28  	"errors"
    29  	"io"
    30  	"math/big"
    31  	"sync"
    32  	"sync/atomic"
    33  	"time"
    34  
    35  	"github.com/klaytn/klaytn/blockchain/types/accountkey"
    36  	"github.com/klaytn/klaytn/common"
    37  	"github.com/klaytn/klaytn/common/math"
    38  	"github.com/klaytn/klaytn/crypto"
    39  	"github.com/klaytn/klaytn/kerrors"
    40  	"github.com/klaytn/klaytn/rlp"
    41  )
    42  
    43  var (
    44  	ErrInvalidSig                     = errors.New("invalid transaction v, r, s values")
    45  	ErrInvalidSigSender               = errors.New("invalid transaction v, r, s values of the sender")
    46  	ErrInvalidSigFeePayer             = errors.New("invalid transaction v, r, s values of the fee payer")
    47  	errNoSigner                       = errors.New("missing signing methods")
    48  	ErrInvalidTxTypeForAnchoredData   = errors.New("invalid transaction type for anchored data")
    49  	errLegacyTransaction              = errors.New("should not be called by a legacy transaction")
    50  	errNotImplementTxInternalDataFrom = errors.New("not implement TxInternalDataFrom")
    51  	errNotFeeDelegationTransaction    = errors.New("not a fee delegation type transaction")
    52  	errInvalidValueMap                = errors.New("tx fields should be filled with valid values")
    53  	errNotImplementTxInternalEthTyped = errors.New("not implement TxInternalDataEthTyped")
    54  )
    55  
    56  // deriveSigner makes a *best* guess about which signer to use.
    57  func deriveSigner(V *big.Int) Signer {
    58  	return LatestSignerForChainID(deriveChainId(V))
    59  }
    60  
    61  type Transaction struct {
    62  	data TxInternalData
    63  	time time.Time
    64  	// caches
    65  	hash         atomic.Value
    66  	size         atomic.Value
    67  	from         atomic.Value
    68  	feePayer     atomic.Value
    69  	senderTxHash atomic.Value
    70  
    71  	// validatedSender represents the sender of the transaction to be used for ApplyTransaction().
    72  	// This value is set in AsMessageWithAccountKeyPicker().
    73  	validatedSender common.Address
    74  	// validatedFeePayer represents the fee payer of the transaction to be used for ApplyTransaction().
    75  	// This value is set in AsMessageWithAccountKeyPicker().
    76  	validatedFeePayer common.Address
    77  	// validatedIntrinsicGas represents intrinsic gas of the transaction to be used for ApplyTransaction().
    78  	// This value is set in AsMessageWithAccountKeyPicker().
    79  	validatedIntrinsicGas uint64
    80  	// The account's nonce is checked only if `checkNonce` is true.
    81  	checkNonce bool
    82  	// This value is set when the tx is invalidated in block tx validation, and is used to remove pending tx in txPool.
    83  	markedUnexecutable int32
    84  
    85  	// lock for protecting fields in Transaction struct
    86  	mu sync.RWMutex
    87  }
    88  
    89  // NewTransactionWithMap generates a tx from tx field values.
    90  // One of the return value, retErr, is lastly updated when panic is occurred.
    91  func NewTransactionWithMap(t TxType, values map[TxValueKeyType]interface{}) (tx *Transaction, retErr error) {
    92  	defer func() {
    93  		if err := recover(); err != nil {
    94  			logger.Warn("Got panic and recovered", "panicErr", err)
    95  			retErr = errInvalidValueMap
    96  		}
    97  	}()
    98  	txData, err := NewTxInternalDataWithMap(t, values)
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  	tx = NewTx(txData)
   103  	return tx, retErr
   104  }
   105  
   106  // NewTx creates a new transaction.
   107  func NewTx(data TxInternalData) *Transaction {
   108  	tx := new(Transaction)
   109  	tx.setDecoded(data, 0)
   110  
   111  	return tx
   112  }
   113  
   114  func NewTransaction(nonce uint64, to common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
   115  	return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data)
   116  }
   117  
   118  func NewContractCreation(nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
   119  	return newTransaction(nonce, nil, amount, gasLimit, gasPrice, data)
   120  }
   121  
   122  func newTransaction(nonce uint64, to *common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
   123  	if len(data) > 0 {
   124  		data = common.CopyBytes(data)
   125  	}
   126  	d := TxInternalDataLegacy{
   127  		AccountNonce: nonce,
   128  		Recipient:    to,
   129  		Payload:      data,
   130  		Amount:       new(big.Int),
   131  		GasLimit:     gasLimit,
   132  		Price:        new(big.Int),
   133  		V:            new(big.Int),
   134  		R:            new(big.Int),
   135  		S:            new(big.Int),
   136  	}
   137  	if amount != nil {
   138  		d.Amount.Set(amount)
   139  	}
   140  	if gasPrice != nil {
   141  		d.Price.Set(gasPrice)
   142  	}
   143  
   144  	return NewTx(&d)
   145  }
   146  
   147  // ChainId returns which chain id this transaction was signed for (if at all)
   148  func (tx *Transaction) ChainId() *big.Int {
   149  	return tx.data.ChainId()
   150  }
   151  
   152  // SenderTxHash returns (SenderTxHash, true) if the tx is a fee-delegated transaction.
   153  // Otherwise, it returns (nil hash, false).
   154  func (tx *Transaction) SenderTxHash() (common.Hash, bool) {
   155  	if tx.Type().IsFeeDelegatedTransaction() == false {
   156  		// Do not compute SenderTxHash for non-fee-delegated txs
   157  		return common.Hash{}, false
   158  	}
   159  	if senderTxHash := tx.senderTxHash.Load(); senderTxHash != nil {
   160  		return senderTxHash.(common.Hash), tx.Type().IsFeeDelegatedTransaction()
   161  	}
   162  	v := tx.data.SenderTxHash()
   163  	tx.senderTxHash.Store(v)
   164  	return v, tx.Type().IsFeeDelegatedTransaction()
   165  }
   166  
   167  // SenderTxHashAll returns SenderTxHash for all tx types.
   168  // If it is not a fee-delegated tx, SenderTxHash and TxHash are the same.
   169  func (tx *Transaction) SenderTxHashAll() common.Hash {
   170  	if senderTxHash := tx.senderTxHash.Load(); senderTxHash != nil {
   171  		return senderTxHash.(common.Hash)
   172  	}
   173  	v := tx.data.SenderTxHash()
   174  	tx.senderTxHash.Store(v)
   175  	return v
   176  }
   177  
   178  func validateSignature(v, r, s *big.Int) bool {
   179  	// TODO-Klaytn: Need to consider the case v.BitLen() > 64.
   180  	// Since ValidateSignatureValues receives v as type of byte, leave it as a future work.
   181  	if v != nil && !isProtectedV(v) {
   182  		return crypto.ValidateSignatureValues(byte(v.Uint64()-27), r, s, true)
   183  	}
   184  
   185  	chainID := deriveChainId(v).Uint64()
   186  	V := byte(v.Uint64() - 35 - 2*chainID)
   187  
   188  	return crypto.ValidateSignatureValues(V, r, s, false)
   189  }
   190  
   191  func (tx *Transaction) Equal(tb *Transaction) bool {
   192  	return tx.data.Equal(tb.data)
   193  }
   194  
   195  // EncodeRLP implements rlp.Encoder
   196  func (tx *Transaction) EncodeRLP(w io.Writer) error {
   197  	serializer := newTxInternalDataSerializerWithValues(tx.data)
   198  	return rlp.Encode(w, serializer)
   199  }
   200  
   201  // MarshalBinary returns the canonical encoding of the transaction.
   202  // For legacy transactions, it returns the RLP encoding. For typed
   203  // transactions, it returns the type and payload.
   204  func (tx *Transaction) MarshalBinary() ([]byte, error) {
   205  	var buf bytes.Buffer
   206  	err := tx.EncodeRLP(&buf)
   207  	return buf.Bytes(), err
   208  }
   209  
   210  // DecodeRLP implements rlp.Decoder
   211  func (tx *Transaction) DecodeRLP(s *rlp.Stream) error {
   212  	serializer := newTxInternalDataSerializer()
   213  	if err := s.Decode(serializer); err != nil {
   214  		return err
   215  	}
   216  
   217  	if !serializer.tx.ValidateSignature() {
   218  		return ErrInvalidSig
   219  	}
   220  
   221  	size := calculateTxSize(serializer.tx)
   222  	tx.setDecoded(serializer.tx, int(size))
   223  
   224  	return nil
   225  }
   226  
   227  // UnmarshalBinary decodes the canonical encoding of transactions.
   228  // It supports legacy RLP transactions and EIP2718 typed transactions.
   229  func (tx *Transaction) UnmarshalBinary(b []byte) error {
   230  	newTx := &Transaction{}
   231  	if err := rlp.DecodeBytes(b, newTx); err != nil {
   232  		return err
   233  	}
   234  
   235  	tx.setDecoded(newTx.data, len(b))
   236  	return nil
   237  }
   238  
   239  // MarshalJSON encodes the web3 RPC transaction format.
   240  func (tx *Transaction) MarshalJSON() ([]byte, error) {
   241  	hash := tx.Hash()
   242  	data := tx.data
   243  	data.SetHash(&hash)
   244  	serializer := newTxInternalDataSerializerWithValues(tx.data)
   245  	return json.Marshal(serializer)
   246  }
   247  
   248  // UnmarshalJSON decodes the web3 RPC transaction format.
   249  func (tx *Transaction) UnmarshalJSON(input []byte) error {
   250  	serializer := newTxInternalDataSerializer()
   251  	if err := json.Unmarshal(input, serializer); err != nil {
   252  		return err
   253  	}
   254  	if !serializer.tx.ValidateSignature() {
   255  		return ErrInvalidSig
   256  	}
   257  
   258  	tx.setDecoded(serializer.tx, 0)
   259  	return nil
   260  }
   261  
   262  func (tx *Transaction) setDecoded(inner TxInternalData, size int) {
   263  	tx.data = inner
   264  	tx.time = time.Now()
   265  
   266  	if size > 0 {
   267  		tx.size.Store(common.StorageSize(size))
   268  	}
   269  }
   270  
   271  func (tx *Transaction) Gas() uint64        { return tx.data.GetGasLimit() }
   272  func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.data.GetPrice()) }
   273  func (tx *Transaction) GasTipCap() *big.Int {
   274  	if tx.Type() == TxTypeEthereumDynamicFee {
   275  		te := tx.GetTxInternalData().(TxInternalDataBaseFee)
   276  		return te.GetGasTipCap()
   277  	}
   278  
   279  	return tx.data.GetPrice()
   280  }
   281  
   282  func (tx *Transaction) GasFeeCap() *big.Int {
   283  	if tx.Type() == TxTypeEthereumDynamicFee {
   284  		te := tx.GetTxInternalData().(TxInternalDataBaseFee)
   285  		return te.GetGasFeeCap()
   286  	}
   287  
   288  	return tx.data.GetPrice()
   289  }
   290  
   291  // This function is disabled because klaytn has no gas tip
   292  func (tx *Transaction) EffectiveGasTip(baseFee *big.Int) *big.Int {
   293  	if tx.Type() == TxTypeEthereumDynamicFee {
   294  		te := tx.GetTxInternalData().(TxInternalDataBaseFee)
   295  		return math.BigMin(te.GetGasTipCap(), new(big.Int).Sub(te.GetGasFeeCap(), baseFee))
   296  	}
   297  	return tx.GasPrice()
   298  }
   299  
   300  func (tx *Transaction) EffectiveGasPrice(header *Header) *big.Int {
   301  	if header != nil && header.BaseFee != nil {
   302  		return header.BaseFee
   303  	}
   304  	// Only enters if Magma is not enabled. If Magma is enabled, it will return BaseFee in the above if statement.
   305  	if tx.Type() == TxTypeEthereumDynamicFee {
   306  		te := tx.GetTxInternalData().(TxInternalDataBaseFee)
   307  		return te.GetGasFeeCap()
   308  	}
   309  	return tx.GasPrice()
   310  }
   311  
   312  func (tx *Transaction) AccessList() AccessList {
   313  	if tx.IsEthTypedTransaction() {
   314  		te := tx.GetTxInternalData().(TxInternalDataEthTyped)
   315  		return te.GetAccessList()
   316  	}
   317  	return nil
   318  }
   319  
   320  func (tx *Transaction) Value() *big.Int { return new(big.Int).Set(tx.data.GetAmount()) }
   321  func (tx *Transaction) Nonce() uint64   { return tx.data.GetAccountNonce() }
   322  func (tx *Transaction) CheckNonce() bool {
   323  	tx.mu.RLock()
   324  	defer tx.mu.RUnlock()
   325  	return tx.checkNonce
   326  }
   327  func (tx *Transaction) Type() TxType                { return tx.data.Type() }
   328  func (tx *Transaction) IsLegacyTransaction() bool   { return tx.Type().IsLegacyTransaction() }
   329  func (tx *Transaction) IsEthTypedTransaction() bool { return tx.Type().IsEthTypedTransaction() }
   330  func (tx *Transaction) IsEthereumTransaction() bool {
   331  	return tx.Type().IsEthereumTransaction()
   332  }
   333  
   334  func isProtectedV(V *big.Int) bool {
   335  	if V.BitLen() <= 8 {
   336  		v := V.Uint64()
   337  		return v != 27 && v != 28 && v != 1 && v != 0
   338  	}
   339  	// anything not 27 or 28 is considered protected
   340  	return true
   341  }
   342  
   343  // Protected says whether the transaction is replay-protected.
   344  func (tx *Transaction) Protected() bool {
   345  	if tx.IsLegacyTransaction() {
   346  		v := tx.RawSignatureValues()[0].V
   347  		return v != nil && isProtectedV(v)
   348  	}
   349  	return true
   350  }
   351  
   352  func (tx *Transaction) ValidatedSender() common.Address {
   353  	tx.mu.RLock()
   354  	defer tx.mu.RUnlock()
   355  	return tx.validatedSender
   356  }
   357  
   358  func (tx *Transaction) ValidatedFeePayer() common.Address {
   359  	tx.mu.RLock()
   360  	defer tx.mu.RUnlock()
   361  	return tx.validatedFeePayer
   362  }
   363  
   364  func (tx *Transaction) ValidatedIntrinsicGas() uint64 {
   365  	tx.mu.RLock()
   366  	defer tx.mu.RUnlock()
   367  	return tx.validatedIntrinsicGas
   368  }
   369  func (tx *Transaction) MakeRPCOutput() map[string]interface{} { return tx.data.MakeRPCOutput() }
   370  func (tx *Transaction) GetTxInternalData() TxInternalData     { return tx.data }
   371  
   372  func (tx *Transaction) IntrinsicGas(currentBlockNumber uint64) (uint64, error) {
   373  	return tx.data.IntrinsicGas(currentBlockNumber)
   374  }
   375  
   376  func (tx *Transaction) Validate(db StateDB, blockNumber uint64) error {
   377  	return tx.data.Validate(db, blockNumber)
   378  }
   379  
   380  // ValidateMutableValue conducts validation of the sender's account key and additional validation for each transaction type.
   381  func (tx *Transaction) ValidateMutableValue(db StateDB, signer Signer, currentBlockNumber uint64) error {
   382  	// validate the sender's account key
   383  	accKey := db.GetKey(tx.ValidatedSender())
   384  	if tx.IsEthereumTransaction() {
   385  		if !accKey.Type().IsLegacyAccountKey() {
   386  			return ErrInvalidSigSender
   387  		}
   388  	} else {
   389  		pubkey, err := SenderPubkey(signer, tx)
   390  		if err != nil || accountkey.ValidateAccountKey(currentBlockNumber, tx.ValidatedSender(), accKey, pubkey, tx.GetRoleTypeForValidation()) != nil {
   391  			return ErrInvalidSigSender
   392  		}
   393  	}
   394  
   395  	// validate the fee payer's account key
   396  	if tx.IsFeeDelegatedTransaction() {
   397  		feePayerAccKey := db.GetKey(tx.ValidatedFeePayer())
   398  		feePayerPubkey, err := SenderFeePayerPubkey(signer, tx)
   399  		if err != nil || accountkey.ValidateAccountKey(currentBlockNumber, tx.ValidatedFeePayer(), feePayerAccKey, feePayerPubkey, accountkey.RoleFeePayer) != nil {
   400  			return ErrInvalidSigFeePayer
   401  		}
   402  	}
   403  
   404  	return tx.data.ValidateMutableValue(db, currentBlockNumber)
   405  }
   406  
   407  func (tx *Transaction) GetRoleTypeForValidation() accountkey.RoleType {
   408  	return tx.data.GetRoleTypeForValidation()
   409  }
   410  
   411  func (tx *Transaction) Data() []byte {
   412  	tp, ok := tx.data.(TxInternalDataPayload)
   413  	if !ok {
   414  		return []byte{}
   415  	}
   416  
   417  	return common.CopyBytes(tp.GetPayload())
   418  }
   419  
   420  // IsFeeDelegatedTransaction returns true if the transaction is a fee-delegated transaction.
   421  // A fee-delegated transaction has an address of the fee payer which can be different from `from` of the tx.
   422  func (tx *Transaction) IsFeeDelegatedTransaction() bool {
   423  	_, ok := tx.data.(TxInternalDataFeePayer)
   424  
   425  	return ok
   426  }
   427  
   428  // AnchoredData returns the anchored data of the chain data anchoring transaction.
   429  // if the tx is not chain data anchoring transaction, it will return error.
   430  func (tx *Transaction) AnchoredData() ([]byte, error) {
   431  	switch tx.Type() {
   432  	case TxTypeChainDataAnchoring:
   433  		txData, ok := tx.data.(*TxInternalDataChainDataAnchoring)
   434  		if ok {
   435  			return txData.Payload, nil
   436  		}
   437  	case TxTypeFeeDelegatedChainDataAnchoring:
   438  		txData, ok := tx.data.(*TxInternalDataFeeDelegatedChainDataAnchoring)
   439  		if ok {
   440  			return txData.Payload, nil
   441  		}
   442  	case TxTypeFeeDelegatedChainDataAnchoringWithRatio:
   443  		txData, ok := tx.data.(*TxInternalDataFeeDelegatedChainDataAnchoringWithRatio)
   444  		if ok {
   445  			return txData.Payload, nil
   446  		}
   447  	}
   448  	return []byte{}, ErrInvalidTxTypeForAnchoredData
   449  }
   450  
   451  // To returns the recipient address of the transaction.
   452  // It returns nil if the transaction is a contract creation.
   453  func (tx *Transaction) To() *common.Address {
   454  	if tx.data.GetRecipient() == nil {
   455  		return nil
   456  	}
   457  	to := *tx.data.GetRecipient()
   458  	return &to
   459  }
   460  
   461  // From returns the from address of the transaction.
   462  // Since a legacy transaction (TxInternalDataLegacy) does not have the field `from`,
   463  // calling From() is failed for `TxInternalDataLegacy`.
   464  func (tx *Transaction) From() (common.Address, error) {
   465  	if tx.IsEthereumTransaction() {
   466  		return common.Address{}, errLegacyTransaction
   467  	}
   468  
   469  	tf, ok := tx.data.(TxInternalDataFrom)
   470  	if !ok {
   471  		return common.Address{}, errNotImplementTxInternalDataFrom
   472  	}
   473  
   474  	return tf.GetFrom(), nil
   475  }
   476  
   477  // FeePayer returns the fee payer address.
   478  // If the tx is a fee-delegated transaction, it returns the specified fee payer.
   479  // Otherwise, it returns `from` of the tx.
   480  func (tx *Transaction) FeePayer() (common.Address, error) {
   481  	tf, ok := tx.data.(TxInternalDataFeePayer)
   482  	if !ok {
   483  		// if the tx is not a fee-delegated transaction, the fee payer is `from` of the tx.
   484  		return tx.From()
   485  	}
   486  
   487  	return tf.GetFeePayer(), nil
   488  }
   489  
   490  // FeeRatio returns the fee ratio of a transaction and a boolean value indicating TxInternalDataFeeRatio implementation.
   491  // If the transaction does not implement TxInternalDataFeeRatio,
   492  // it returns MaxFeeRatio which means the fee payer will be paid all tx fee by default.
   493  func (tx *Transaction) FeeRatio() (FeeRatio, bool) {
   494  	tf, ok := tx.data.(TxInternalDataFeeRatio)
   495  	if !ok {
   496  		// default fee ratio is MaxFeeRatio.
   497  		return MaxFeeRatio, ok
   498  	}
   499  
   500  	return tf.GetFeeRatio(), ok
   501  }
   502  
   503  // Hash hashes the RLP encoding of tx.
   504  // It uniquely identifies the transaction.
   505  func (tx *Transaction) Hash() common.Hash {
   506  	if hash := tx.hash.Load(); hash != nil {
   507  		return hash.(common.Hash)
   508  	}
   509  
   510  	var v common.Hash
   511  	if tx.IsEthTypedTransaction() {
   512  		te := tx.data.(TxInternalDataEthTyped)
   513  		v = te.TxHash()
   514  	} else {
   515  		v = rlpHash(tx)
   516  	}
   517  
   518  	tx.hash.Store(v)
   519  	return v
   520  }
   521  
   522  // Size returns the true RLP encoded storage size of the transaction, either by
   523  // encoding and returning it, or returning a previsouly cached value.
   524  func (tx *Transaction) Size() common.StorageSize {
   525  	if size := tx.size.Load(); size != nil {
   526  		return size.(common.StorageSize)
   527  	}
   528  
   529  	size := calculateTxSize(tx.data)
   530  	tx.size.Store(size)
   531  
   532  	return size
   533  }
   534  
   535  // Time returns the time that transaction was created.
   536  func (tx *Transaction) Time() time.Time {
   537  	return tx.time
   538  }
   539  
   540  // FillContractAddress fills contract address to receipt. This only works for types deploying a smart contract.
   541  func (tx *Transaction) FillContractAddress(from common.Address, r *Receipt) {
   542  	if filler, ok := tx.data.(TxInternalDataContractAddressFiller); ok {
   543  		filler.FillContractAddress(from, r)
   544  	}
   545  }
   546  
   547  // Execute performs execution of the transaction. This function will be called from StateTransition.TransitionDb().
   548  // Since each transaction type performs different execution, this function calls TxInternalData.TransitionDb().
   549  func (tx *Transaction) Execute(vm VM, stateDB StateDB, currentBlockNumber uint64, gas uint64, value *big.Int) ([]byte, uint64, error) {
   550  	sender := NewAccountRefWithFeePayer(tx.ValidatedSender(), tx.ValidatedFeePayer())
   551  	return tx.data.Execute(sender, vm, stateDB, currentBlockNumber, gas, value)
   552  }
   553  
   554  // AsMessageWithAccountKeyPicker returns the transaction as a blockchain.Message.
   555  //
   556  // AsMessageWithAccountKeyPicker requires a signer to derive the sender and AccountKeyPicker.
   557  //
   558  // XXX Rename message to something less arbitrary?
   559  // TODO-Klaytn: Message is removed and this function will return *Transaction.
   560  func (tx *Transaction) AsMessageWithAccountKeyPicker(s Signer, picker AccountKeyPicker, currentBlockNumber uint64) (*Transaction, error) {
   561  	intrinsicGas, err := tx.IntrinsicGas(currentBlockNumber)
   562  	if err != nil {
   563  		return nil, err
   564  	}
   565  
   566  	gasFrom, err := tx.ValidateSender(s, picker, currentBlockNumber)
   567  	if err != nil {
   568  		return nil, err
   569  	}
   570  
   571  	tx.mu.Lock()
   572  	tx.checkNonce = true
   573  	tx.mu.Unlock()
   574  
   575  	gasFeePayer := uint64(0)
   576  	if tx.IsFeeDelegatedTransaction() {
   577  		gasFeePayer, err = tx.ValidateFeePayer(s, picker, currentBlockNumber)
   578  		if err != nil {
   579  			return nil, err
   580  		}
   581  	}
   582  
   583  	tx.mu.Lock()
   584  	tx.validatedIntrinsicGas = intrinsicGas + gasFrom + gasFeePayer
   585  	tx.mu.Unlock()
   586  
   587  	return tx, err
   588  }
   589  
   590  // WithSignature returns a new transaction with the given signature.
   591  // This signature needs to be formatted as described in the yellow paper (v+27).
   592  func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) {
   593  	r, s, v, err := signer.SignatureValues(tx, sig)
   594  	if err != nil {
   595  		return nil, err
   596  	}
   597  
   598  	cpy := &Transaction{data: tx.data, time: tx.time}
   599  	if tx.Type().IsEthTypedTransaction() {
   600  		te, ok := cpy.data.(TxInternalDataEthTyped)
   601  		if ok {
   602  			te.setSignatureValues(signer.ChainID(), v, r, s)
   603  		} else {
   604  			return nil, errNotImplementTxInternalEthTyped
   605  		}
   606  	}
   607  
   608  	cpy.data.SetSignature(TxSignatures{&TxSignature{v, r, s}})
   609  	return cpy, nil
   610  }
   611  
   612  // WithFeePayerSignature returns a new transaction with the given fee payer signature.
   613  func (tx *Transaction) WithFeePayerSignature(signer Signer, sig []byte) (*Transaction, error) {
   614  	r, s, v, err := signer.SignatureValues(tx, sig)
   615  	if err != nil {
   616  		return nil, err
   617  	}
   618  
   619  	cpy := &Transaction{data: tx.data, time: tx.time}
   620  
   621  	feePayerSig := TxSignatures{&TxSignature{v, r, s}}
   622  	if err := cpy.SetFeePayerSignatures(feePayerSig); err != nil {
   623  		return nil, err
   624  	}
   625  	return cpy, nil
   626  }
   627  
   628  // Cost returns amount + gasprice * gaslimit.
   629  func (tx *Transaction) Cost() *big.Int {
   630  	total := tx.Fee()
   631  	total.Add(total, tx.data.GetAmount())
   632  	return total
   633  }
   634  
   635  func (tx *Transaction) Fee() *big.Int {
   636  	return new(big.Int).Mul(tx.data.GetPrice(), new(big.Int).SetUint64(tx.data.GetGasLimit()))
   637  }
   638  
   639  // Sign signs the tx with the given signer and private key.
   640  func (tx *Transaction) Sign(s Signer, prv *ecdsa.PrivateKey) error {
   641  	h := s.Hash(tx)
   642  	sig, err := NewTxSignatureWithValues(s, tx, h, prv)
   643  	if err != nil {
   644  		return err
   645  	}
   646  
   647  	tx.SetSignature(TxSignatures{sig})
   648  	return nil
   649  }
   650  
   651  // SignWithKeys signs the tx with the given signer and a slice of private keys.
   652  func (tx *Transaction) SignWithKeys(s Signer, prv []*ecdsa.PrivateKey) error {
   653  	h := s.Hash(tx)
   654  	sig, err := NewTxSignaturesWithValues(s, tx, h, prv)
   655  	if err != nil {
   656  		return err
   657  	}
   658  
   659  	tx.SetSignature(sig)
   660  	return nil
   661  }
   662  
   663  // SignFeePayer signs the tx with the given signer and private key as a fee payer.
   664  func (tx *Transaction) SignFeePayer(s Signer, prv *ecdsa.PrivateKey) error {
   665  	h, err := s.HashFeePayer(tx)
   666  	if err != nil {
   667  		return err
   668  	}
   669  	sig, err := NewTxSignatureWithValues(s, tx, h, prv)
   670  	if err != nil {
   671  		return err
   672  	}
   673  
   674  	if err := tx.SetFeePayerSignatures(TxSignatures{sig}); err != nil {
   675  		return err
   676  	}
   677  
   678  	return nil
   679  }
   680  
   681  // SignFeePayerWithKeys signs the tx with the given signer and a slice of private keys as a fee payer.
   682  func (tx *Transaction) SignFeePayerWithKeys(s Signer, prv []*ecdsa.PrivateKey) error {
   683  	h, err := s.HashFeePayer(tx)
   684  	if err != nil {
   685  		return err
   686  	}
   687  	sig, err := NewTxSignaturesWithValues(s, tx, h, prv)
   688  	if err != nil {
   689  		return err
   690  	}
   691  
   692  	if err := tx.SetFeePayerSignatures(sig); err != nil {
   693  		return err
   694  	}
   695  
   696  	return nil
   697  }
   698  
   699  func (tx *Transaction) SetFeePayerSignatures(s TxSignatures) error {
   700  	tf, ok := tx.data.(TxInternalDataFeePayer)
   701  	if !ok {
   702  		return errNotFeeDelegationTransaction
   703  	}
   704  
   705  	tf.SetFeePayerSignatures(s)
   706  
   707  	return nil
   708  }
   709  
   710  // GetFeePayerSignatures returns fee payer signatures of the transaction.
   711  func (tx *Transaction) GetFeePayerSignatures() (TxSignatures, error) {
   712  	tf, ok := tx.data.(TxInternalDataFeePayer)
   713  	if !ok {
   714  		return nil, errNotFeeDelegationTransaction
   715  	}
   716  	return tf.GetFeePayerRawSignatureValues(), nil
   717  }
   718  
   719  func (tx *Transaction) SetSignature(signature TxSignatures) {
   720  	tx.data.SetSignature(signature)
   721  }
   722  
   723  func (tx *Transaction) MarkUnexecutable(b bool) {
   724  	v := int32(0)
   725  	if b {
   726  		v = 1
   727  	}
   728  	atomic.StoreInt32(&tx.markedUnexecutable, v)
   729  }
   730  
   731  func (tx *Transaction) IsMarkedUnexecutable() bool {
   732  	return atomic.LoadInt32(&tx.markedUnexecutable) == 1
   733  }
   734  
   735  func (tx *Transaction) RawSignatureValues() TxSignatures {
   736  	return tx.data.RawSignatureValues()
   737  }
   738  
   739  func (tx *Transaction) String() string {
   740  	return tx.data.String()
   741  }
   742  
   743  // ValidateSender finds a sender from both legacy and new types of transactions.
   744  // It returns the senders address and gas used for the tx validation.
   745  func (tx *Transaction) ValidateSender(signer Signer, p AccountKeyPicker, currentBlockNumber uint64) (uint64, error) {
   746  	if tx.IsEthereumTransaction() {
   747  		addr, err := Sender(signer, tx)
   748  		// Legacy transaction cannot be executed unless the account has a legacy key.
   749  		if p.GetKey(addr).Type().IsLegacyAccountKey() == false {
   750  			return 0, kerrors.ErrLegacyTransactionMustBeWithLegacyKey
   751  		}
   752  		tx.mu.Lock()
   753  		if tx.validatedSender == (common.Address{}) {
   754  			tx.validatedSender = addr
   755  			tx.validatedFeePayer = addr
   756  		}
   757  		tx.mu.Unlock()
   758  		return 0, err
   759  	}
   760  
   761  	pubkey, err := SenderPubkey(signer, tx)
   762  	if err != nil {
   763  		return 0, err
   764  	}
   765  	txfrom, ok := tx.data.(TxInternalDataFrom)
   766  	if !ok {
   767  		return 0, errNotTxInternalDataFrom
   768  	}
   769  	from := txfrom.GetFrom()
   770  	accKey := p.GetKey(from)
   771  
   772  	gasKey, err := accKey.SigValidationGas(currentBlockNumber, tx.GetRoleTypeForValidation(), len(pubkey))
   773  	if err != nil {
   774  		return 0, err
   775  	}
   776  
   777  	if err := accountkey.ValidateAccountKey(currentBlockNumber, from, accKey, pubkey, tx.GetRoleTypeForValidation()); err != nil {
   778  		return 0, ErrInvalidSigSender
   779  	}
   780  
   781  	tx.mu.Lock()
   782  	if tx.validatedSender == (common.Address{}) {
   783  		tx.validatedSender = from
   784  		tx.validatedFeePayer = from
   785  	}
   786  	tx.mu.Unlock()
   787  
   788  	return gasKey, nil
   789  }
   790  
   791  // ValidateFeePayer finds a fee payer from a transaction.
   792  // If the transaction is not a fee-delegated transaction, it returns an error.
   793  func (tx *Transaction) ValidateFeePayer(signer Signer, p AccountKeyPicker, currentBlockNumber uint64) (uint64, error) {
   794  	tf, ok := tx.data.(TxInternalDataFeePayer)
   795  	if !ok {
   796  		return 0, errUndefinedTxType
   797  	}
   798  
   799  	pubkey, err := SenderFeePayerPubkey(signer, tx)
   800  	if err != nil {
   801  		return 0, err
   802  	}
   803  
   804  	feePayer := tf.GetFeePayer()
   805  	accKey := p.GetKey(feePayer)
   806  
   807  	gasKey, err := accKey.SigValidationGas(currentBlockNumber, accountkey.RoleFeePayer, len(pubkey))
   808  	if err != nil {
   809  		return 0, err
   810  	}
   811  
   812  	if err := accountkey.ValidateAccountKey(currentBlockNumber, feePayer, accKey, pubkey, accountkey.RoleFeePayer); err != nil {
   813  		return 0, ErrInvalidSigFeePayer
   814  	}
   815  
   816  	tx.mu.Lock()
   817  	if tx.validatedFeePayer == tx.validatedSender {
   818  		tx.validatedFeePayer = feePayer
   819  	}
   820  	tx.mu.Unlock()
   821  
   822  	return gasKey, nil
   823  }
   824  
   825  // Transactions is a Transaction slice type for basic sorting.
   826  type Transactions []*Transaction
   827  
   828  // Len returns the length of s.
   829  func (s Transactions) Len() int { return len(s) }
   830  
   831  // Swap swaps the i'th and the j'th element in s.
   832  func (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   833  
   834  // GetRlp implements Rlpable and returns the i'th element of s in rlp.
   835  func (s Transactions) GetRlp(i int) []byte {
   836  	enc, _ := rlp.EncodeToBytes(s[i])
   837  	return enc
   838  }
   839  
   840  // TxDifference returns a new set t which is the difference between a to b.
   841  func TxDifference(a, b Transactions) (keep Transactions) {
   842  	keep = make(Transactions, 0, len(a))
   843  
   844  	remove := make(map[common.Hash]struct{})
   845  	for _, tx := range b {
   846  		remove[tx.Hash()] = struct{}{}
   847  	}
   848  
   849  	for _, tx := range a {
   850  		if _, ok := remove[tx.Hash()]; !ok {
   851  			keep = append(keep, tx)
   852  		}
   853  	}
   854  
   855  	return keep
   856  }
   857  
   858  // FilterTransactionWithBaseFee returns a list of transactions for each account that filters transactions
   859  // that are greater than or equal to baseFee.
   860  func FilterTransactionWithBaseFee(pending map[common.Address]Transactions, baseFee *big.Int) map[common.Address]Transactions {
   861  	txMap := make(map[common.Address]Transactions)
   862  	for addr, list := range pending {
   863  		txs := list
   864  		for i, tx := range list {
   865  			if tx.GasPrice().Cmp(baseFee) < 0 {
   866  				txs = list[:i]
   867  				break
   868  			}
   869  		}
   870  
   871  		if len(txs) > 0 {
   872  			txMap[addr] = txs
   873  		}
   874  	}
   875  	return txMap
   876  }
   877  
   878  // TxByNonce implements the sort interface to allow sorting a list of transactions
   879  // by their nonces. This is usually only useful for sorting transactions from a
   880  // single account, otherwise a nonce comparison doesn't make much sense.
   881  type TxByNonce Transactions
   882  
   883  func (s TxByNonce) Len() int { return len(s) }
   884  func (s TxByNonce) Less(i, j int) bool {
   885  	return s[i].data.GetAccountNonce() < s[j].data.GetAccountNonce()
   886  }
   887  func (s TxByNonce) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   888  
   889  type TxByTime Transactions
   890  
   891  func (s TxByTime) Len() int { return len(s) }
   892  func (s TxByTime) Less(i, j int) bool {
   893  	// Use the time the transaction was first seen for deterministic sorting
   894  	return s[i].time.Before(s[j].time)
   895  }
   896  func (s TxByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   897  
   898  func (s *TxByTime) Push(x interface{}) {
   899  	*s = append(*s, x.(*Transaction))
   900  }
   901  
   902  func (s *TxByTime) Pop() interface{} {
   903  	old := *s
   904  	n := len(old)
   905  	x := old[n-1]
   906  	*s = old[0 : n-1]
   907  	return x
   908  }
   909  
   910  // TxByPriceAndTime implements both the sort and the heap interface, making it useful
   911  // for all at once sorting as well as individually adding and removing elements.
   912  type TxByPriceAndTime Transactions
   913  
   914  func (s TxByPriceAndTime) Len() int { return len(s) }
   915  func (s TxByPriceAndTime) Less(i, j int) bool {
   916  	// Use the time the transaction was first seen for deterministic sorting
   917  	cmp := s[i].GasPrice().Cmp(s[j].GasPrice())
   918  	if cmp == 0 {
   919  		return s[i].time.Before(s[j].time)
   920  	}
   921  	return cmp > 0
   922  }
   923  func (s TxByPriceAndTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   924  
   925  func (s *TxByPriceAndTime) Push(x interface{}) {
   926  	*s = append(*s, x.(*Transaction))
   927  }
   928  
   929  func (s *TxByPriceAndTime) Pop() interface{} {
   930  	old := *s
   931  	n := len(old)
   932  	x := old[n-1]
   933  	*s = old[0 : n-1]
   934  	return x
   935  }
   936  
   937  // TransactionsByTimeAndNonce represents a set of transactions that can return
   938  // transactions in a profit-maximizing sorted order, while supporting removing
   939  // entire batches of transactions for non-executable accounts.
   940  type TransactionsByTimeAndNonce struct {
   941  	txs    map[common.Address]Transactions // Per account nonce-sorted list of transactions
   942  	heads  TxByTime                        // Next transaction for each unique account (transaction's time heap)
   943  	signer Signer                          // Signer for the set of transactions
   944  }
   945  
   946  // ############ method for debug
   947  func (t *TransactionsByTimeAndNonce) Count() (int, int) {
   948  	var count int
   949  
   950  	for _, tx := range t.txs {
   951  		count += tx.Len()
   952  	}
   953  
   954  	return len(t.txs), count
   955  }
   956  
   957  func (t *TransactionsByTimeAndNonce) Txs() map[common.Address]Transactions {
   958  	return t.txs
   959  }
   960  
   961  // NewTransactionsByTimeAndNonce creates a transaction set that can retrieve
   962  // time sorted transactions in a nonce-honouring way.
   963  //
   964  // Note, the input map is reowned so the caller should not interact any more with
   965  // if after providing it to the constructor.
   966  func NewTransactionsByTimeAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByTimeAndNonce {
   967  	// Initialize received time based heap with the head transactions
   968  	heads := make(TxByTime, 0, len(txs))
   969  	for _, accTxs := range txs {
   970  		heads = append(heads, accTxs[0])
   971  		// Ensure the sender address is from the signer
   972  		acc, _ := Sender(signer, accTxs[0])
   973  		txs[acc] = accTxs[1:]
   974  	}
   975  	heap.Init(&heads)
   976  
   977  	// Assemble and return the transaction set
   978  	return &TransactionsByTimeAndNonce{
   979  		txs:    txs,
   980  		heads:  heads,
   981  		signer: signer,
   982  	}
   983  }
   984  
   985  // Peek returns the next transaction by time.
   986  func (t *TransactionsByTimeAndNonce) Peek() *Transaction {
   987  	if len(t.heads) == 0 {
   988  		return nil
   989  	}
   990  	return t.heads[0]
   991  }
   992  
   993  // Shift replaces the current best head with the next one from the same account.
   994  func (t *TransactionsByTimeAndNonce) Shift() {
   995  	if len(t.heads) == 0 {
   996  		return
   997  	}
   998  	acc, _ := Sender(t.signer, t.heads[0])
   999  	if txs, ok := t.txs[acc]; ok && len(txs) > 0 {
  1000  		t.heads[0], t.txs[acc] = txs[0], txs[1:]
  1001  		heap.Fix(&t.heads, 0)
  1002  	} else {
  1003  		heap.Pop(&t.heads)
  1004  	}
  1005  }
  1006  
  1007  // Pop removes the best transaction, *not* replacing it with the next one from
  1008  // the same account. This should be used when a transaction cannot be executed
  1009  // and hence all subsequent ones should be discarded from the same account.
  1010  func (t *TransactionsByTimeAndNonce) Pop() {
  1011  	heap.Pop(&t.heads)
  1012  }
  1013  
  1014  // NewMessage returns a `*Transaction` object with the given arguments.
  1015  func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, checkNonce bool, intrinsicGas uint64) *Transaction {
  1016  	transaction := &Transaction{
  1017  		validatedIntrinsicGas: intrinsicGas,
  1018  		validatedFeePayer:     from,
  1019  		validatedSender:       from,
  1020  		checkNonce:            checkNonce,
  1021  	}
  1022  
  1023  	internalData := newTxInternalDataLegacyWithValues(nonce, to, amount, gasLimit, gasPrice, data)
  1024  	transaction.setDecoded(internalData, 0)
  1025  
  1026  	return transaction
  1027  }