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