github.com/klaytn/klaytn@v1.12.1/blockchain/types/tx_internal_data.go (about)

     1  // Copyright 2019 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package types
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/ecdsa"
    22  	"errors"
    23  	"math"
    24  	"math/big"
    25  
    26  	"github.com/klaytn/klaytn/blockchain/types/accountkey"
    27  	"github.com/klaytn/klaytn/common"
    28  	"github.com/klaytn/klaytn/params"
    29  	"github.com/klaytn/klaytn/rlp"
    30  )
    31  
    32  // MaxFeeRatio is the maximum value of feeRatio. Since it is represented in percentage,
    33  // the maximum value is 100.
    34  const MaxFeeRatio FeeRatio = 100
    35  
    36  const SubTxTypeBits uint = 3
    37  
    38  type TxType uint16
    39  
    40  const (
    41  	// TxType declarations
    42  	// There are three type declarations at each line:
    43  	//   <base type>, <fee-delegated type>, and <fee-delegated type with a fee ratio>
    44  	// If types other than <base type> are not useful, they are declared with underscore(_).
    45  	// Each base type is self-descriptive.
    46  	TxTypeLegacyTransaction, _, _ TxType = iota << SubTxTypeBits, iota<<SubTxTypeBits + 1, iota<<SubTxTypeBits + 2
    47  	TxTypeValueTransfer, TxTypeFeeDelegatedValueTransfer, TxTypeFeeDelegatedValueTransferWithRatio
    48  	TxTypeValueTransferMemo, TxTypeFeeDelegatedValueTransferMemo, TxTypeFeeDelegatedValueTransferMemoWithRatio
    49  	TxTypeAccountCreation, _, _
    50  	TxTypeAccountUpdate, TxTypeFeeDelegatedAccountUpdate, TxTypeFeeDelegatedAccountUpdateWithRatio
    51  	TxTypeSmartContractDeploy, TxTypeFeeDelegatedSmartContractDeploy, TxTypeFeeDelegatedSmartContractDeployWithRatio
    52  	TxTypeSmartContractExecution, TxTypeFeeDelegatedSmartContractExecution, TxTypeFeeDelegatedSmartContractExecutionWithRatio
    53  	TxTypeCancel, TxTypeFeeDelegatedCancel, TxTypeFeeDelegatedCancelWithRatio
    54  	TxTypeBatch, _, _
    55  	TxTypeChainDataAnchoring, TxTypeFeeDelegatedChainDataAnchoring, TxTypeFeeDelegatedChainDataAnchoringWithRatio
    56  	TxTypeKlaytnLast, _, _
    57  	TxTypeEthereumAccessList = TxType(0x7801)
    58  	TxTypeEthereumDynamicFee = TxType(0x7802)
    59  	TxTypeEthereumLast       = TxType(0x7803)
    60  )
    61  
    62  type TxValueKeyType uint
    63  
    64  const EthereumTxTypeEnvelope = TxType(0x78)
    65  
    66  const (
    67  	TxValueKeyNonce TxValueKeyType = iota
    68  	TxValueKeyTo
    69  	TxValueKeyAmount
    70  	TxValueKeyGasLimit
    71  	TxValueKeyGasPrice
    72  	TxValueKeyData
    73  	TxValueKeyFrom
    74  	TxValueKeyAnchoredData
    75  	TxValueKeyHumanReadable
    76  	TxValueKeyAccountKey
    77  	TxValueKeyFeePayer
    78  	TxValueKeyFeeRatioOfFeePayer
    79  	TxValueKeyCodeFormat
    80  	TxValueKeyAccessList
    81  	TxValueKeyChainID
    82  	TxValueKeyGasTipCap
    83  	TxValueKeyGasFeeCap
    84  )
    85  
    86  type TxTypeMask uint8
    87  
    88  const (
    89  	TxFeeDelegationBitMask          TxTypeMask = 1
    90  	TxFeeDelegationWithRatioBitMask TxTypeMask = 2
    91  )
    92  
    93  var (
    94  	errNotTxTypeValueTransfer                 = errors.New("not value transfer transaction type")
    95  	errNotTxTypeValueTransferWithFeeDelegator = errors.New("not a fee-delegated value transfer transaction")
    96  	errNotTxTypeAccountCreation               = errors.New("not account creation transaction type")
    97  	errUndefinedTxType                        = errors.New("undefined tx type")
    98  	errCannotBeSignedByFeeDelegator           = errors.New("this transaction type cannot be signed by a fee delegator")
    99  	errUndefinedKeyRemains                    = errors.New("undefined key remains")
   100  
   101  	errValueKeyHumanReadableMustBool     = errors.New("HumanReadable must be a type of bool")
   102  	errValueKeyAccountKeyMustAccountKey  = errors.New("AccountKey must be a type of AccountKey")
   103  	errValueKeyAnchoredDataMustByteSlice = errors.New("AnchoredData must be a slice of bytes")
   104  	errValueKeyNonceMustUint64           = errors.New("Nonce must be a type of uint64")
   105  	errValueKeyToMustAddress             = errors.New("To must be a type of common.Address")
   106  	errValueKeyToMustAddressPointer      = errors.New("To must be a type of *common.Address")
   107  	errValueKeyAmountMustBigInt          = errors.New("Amount must be a type of *big.Int")
   108  	errValueKeyGasLimitMustUint64        = errors.New("GasLimit must be a type of uint64")
   109  	errValueKeyGasPriceMustBigInt        = errors.New("GasPrice must be a type of *big.Int")
   110  	errValueKeyFromMustAddress           = errors.New("From must be a type of common.Address")
   111  	errValueKeyFeePayerMustAddress       = errors.New("FeePayer must be a type of common.Address")
   112  	errValueKeyDataMustByteSlice         = errors.New("Data must be a slice of bytes")
   113  	errValueKeyFeeRatioMustUint8         = errors.New("FeeRatio must be a type of uint8")
   114  	errValueKeyCodeFormatInvalid         = errors.New("The smart contract code format is invalid")
   115  	errValueKeyAccessListInvalid         = errors.New("AccessList must be a type of AccessList")
   116  	errValueKeyChainIDInvalid            = errors.New("ChainID must be a type of ChainID")
   117  	errValueKeyGasTipCapMustBigInt       = errors.New("GasTipCap must be a type of *big.Int")
   118  	errValueKeyGasFeeCapMustBigInt       = errors.New("GasFeeCap must be a type of *big.Int")
   119  
   120  	ErrTxTypeNotSupported         = errors.New("transaction type not supported")
   121  	ErrSenderPubkeyNotSupported   = errors.New("SenderPubkey is not supported for this signer")
   122  	ErrSenderFeePayerNotSupported = errors.New("SenderFeePayer is not supported for this signer")
   123  	ErrHashFeePayerNotSupported   = errors.New("HashFeePayer is not supported for this signer")
   124  
   125  	// ErrGasUintOverflow is returned when calculating gas usage.
   126  	ErrGasUintOverflow = errors.New("gas uint64 overflow")
   127  )
   128  
   129  func (t TxValueKeyType) String() string {
   130  	switch t {
   131  	case TxValueKeyNonce:
   132  		return "TxValueKeyNonce"
   133  	case TxValueKeyTo:
   134  		return "TxValueKeyTo"
   135  	case TxValueKeyAmount:
   136  		return "TxValueKeyAmount"
   137  	case TxValueKeyGasLimit:
   138  		return "TxValueKeyGasLimit"
   139  	case TxValueKeyGasPrice:
   140  		return "TxValueKeyGasPrice"
   141  	case TxValueKeyData:
   142  		return "TxValueKeyData"
   143  	case TxValueKeyFrom:
   144  		return "TxValueKeyFrom"
   145  	case TxValueKeyAnchoredData:
   146  		return "TxValueKeyAnchoredData"
   147  	case TxValueKeyHumanReadable:
   148  		return "TxValueKeyHumanReadable"
   149  	case TxValueKeyAccountKey:
   150  		return "TxValueKeyAccountKey"
   151  	case TxValueKeyFeePayer:
   152  		return "TxValueKeyFeePayer"
   153  	case TxValueKeyFeeRatioOfFeePayer:
   154  		return "TxValueKeyFeeRatioOfFeePayer"
   155  	case TxValueKeyCodeFormat:
   156  		return "TxValueKeyCodeFormat"
   157  	case TxValueKeyChainID:
   158  		return "TxValueKeyChainID"
   159  	case TxValueKeyAccessList:
   160  		return "TxValueKeyAccessList"
   161  	case TxValueKeyGasTipCap:
   162  		return "TxValueKeyGasTipCap"
   163  	case TxValueKeyGasFeeCap:
   164  		return "TxValueKeyGasFeeCap"
   165  	}
   166  
   167  	return "UndefinedTxValueKeyType"
   168  }
   169  
   170  func (t TxType) String() string {
   171  	switch t {
   172  	case TxTypeLegacyTransaction:
   173  		return "TxTypeLegacyTransaction"
   174  	case TxTypeValueTransfer:
   175  		return "TxTypeValueTransfer"
   176  	case TxTypeFeeDelegatedValueTransfer:
   177  		return "TxTypeFeeDelegatedValueTransfer"
   178  	case TxTypeFeeDelegatedValueTransferWithRatio:
   179  		return "TxTypeFeeDelegatedValueTransferWithRatio"
   180  	case TxTypeValueTransferMemo:
   181  		return "TxTypeValueTransferMemo"
   182  	case TxTypeFeeDelegatedValueTransferMemo:
   183  		return "TxTypeFeeDelegatedValueTransferMemo"
   184  	case TxTypeFeeDelegatedValueTransferMemoWithRatio:
   185  		return "TxTypeFeeDelegatedValueTransferMemoWithRatio"
   186  	case TxTypeAccountCreation:
   187  		return "TxTypeAccountCreation"
   188  	case TxTypeAccountUpdate:
   189  		return "TxTypeAccountUpdate"
   190  	case TxTypeFeeDelegatedAccountUpdate:
   191  		return "TxTypeFeeDelegatedAccountUpdate"
   192  	case TxTypeFeeDelegatedAccountUpdateWithRatio:
   193  		return "TxTypeFeeDelegatedAccountUpdateWithRatio"
   194  	case TxTypeSmartContractDeploy:
   195  		return "TxTypeSmartContractDeploy"
   196  	case TxTypeFeeDelegatedSmartContractDeploy:
   197  		return "TxTypeFeeDelegatedSmartContractDeploy"
   198  	case TxTypeFeeDelegatedSmartContractDeployWithRatio:
   199  		return "TxTypeFeeDelegatedSmartContractDeployWithRatio"
   200  	case TxTypeSmartContractExecution:
   201  		return "TxTypeSmartContractExecution"
   202  	case TxTypeFeeDelegatedSmartContractExecution:
   203  		return "TxTypeFeeDelegatedSmartContractExecution"
   204  	case TxTypeFeeDelegatedSmartContractExecutionWithRatio:
   205  		return "TxTypeFeeDelegatedSmartContractExecutionWithRatio"
   206  	case TxTypeCancel:
   207  		return "TxTypeCancel"
   208  	case TxTypeFeeDelegatedCancel:
   209  		return "TxTypeFeeDelegatedCancel"
   210  	case TxTypeFeeDelegatedCancelWithRatio:
   211  		return "TxTypeFeeDelegatedCancelWithRatio"
   212  	case TxTypeBatch:
   213  		return "TxTypeBatch"
   214  	case TxTypeChainDataAnchoring:
   215  		return "TxTypeChainDataAnchoring"
   216  	case TxTypeFeeDelegatedChainDataAnchoring:
   217  		return "TxTypeFeeDelegatedChainDataAnchoring"
   218  	case TxTypeFeeDelegatedChainDataAnchoringWithRatio:
   219  		return "TxTypeFeeDelegatedChainDataAnchoringWithRatio"
   220  	case TxTypeEthereumAccessList:
   221  		return "TxTypeEthereumAccessList"
   222  	case TxTypeEthereumDynamicFee:
   223  		return "TxTypeEthereumDynamicFee"
   224  	}
   225  
   226  	return "UndefinedTxType"
   227  }
   228  
   229  func (t TxType) IsAccountCreation() bool {
   230  	return t == TxTypeAccountCreation
   231  }
   232  
   233  func (t TxType) IsAccountUpdate() bool {
   234  	return (t &^ ((1 << SubTxTypeBits) - 1)) == TxTypeAccountUpdate
   235  }
   236  
   237  func (t TxType) IsContractDeploy() bool {
   238  	return (t &^ ((1 << SubTxTypeBits) - 1)) == TxTypeSmartContractDeploy
   239  }
   240  
   241  func (t TxType) IsCancelTransaction() bool {
   242  	return (t &^ ((1 << SubTxTypeBits) - 1)) == TxTypeCancel
   243  }
   244  
   245  func (t TxType) IsLegacyTransaction() bool {
   246  	return t == TxTypeLegacyTransaction
   247  }
   248  
   249  func (t TxType) IsFeeDelegatedTransaction() bool {
   250  	return (TxTypeMask(t)&(TxFeeDelegationBitMask|TxFeeDelegationWithRatioBitMask)) != 0x0 && !t.IsEthereumTransaction()
   251  }
   252  
   253  func (t TxType) IsFeeDelegatedWithRatioTransaction() bool {
   254  	return (TxTypeMask(t)&TxFeeDelegationWithRatioBitMask) != 0x0 && !t.IsEthereumTransaction()
   255  }
   256  
   257  func (t TxType) IsEthTypedTransaction() bool {
   258  	return (t & 0xff00) == (EthereumTxTypeEnvelope << 8)
   259  }
   260  
   261  func (t TxType) IsEthereumTransaction() bool {
   262  	return t.IsLegacyTransaction() || t.IsEthTypedTransaction()
   263  }
   264  
   265  func (t TxType) IsChainDataAnchoring() bool {
   266  	return (t &^ ((1 << SubTxTypeBits) - 1)) == TxTypeChainDataAnchoring
   267  }
   268  
   269  type FeeRatio uint8
   270  
   271  // FeeRatio is valid where it is [1,99].
   272  func (f FeeRatio) IsValid() bool {
   273  	return 1 <= f && f <= 99
   274  }
   275  
   276  // TxInternalData is an interface for an internal data structure of a Transaction
   277  type TxInternalData interface {
   278  	Type() TxType
   279  
   280  	GetAccountNonce() uint64
   281  	GetPrice() *big.Int
   282  	GetGasLimit() uint64
   283  	GetRecipient() *common.Address
   284  	GetAmount() *big.Int
   285  	GetHash() *common.Hash
   286  
   287  	SetHash(*common.Hash)
   288  	SetSignature(TxSignatures)
   289  
   290  	// RawSignatureValues returns signatures as a slice of `*big.Int`.
   291  	// Due to multi signatures, it is not good to return three values of `*big.Int`.
   292  	// The format would be something like [["V":v, "R":r, "S":s}, {"V":v, "R":r, "S":s}].
   293  	RawSignatureValues() TxSignatures
   294  
   295  	// ValidateSignature returns true if the signature is valid.
   296  	ValidateSignature() bool
   297  
   298  	// RecoverAddress returns address derived from txhash and signatures(r, s, v).
   299  	// Since EIP155Signer modifies V value during recovering while other signers don't, it requires vfunc for the treatment.
   300  	RecoverAddress(txhash common.Hash, homestead bool, vfunc func(*big.Int) *big.Int) (common.Address, error)
   301  
   302  	// RecoverPubkey returns a public key derived from txhash and signatures(r, s, v).
   303  	// Since EIP155Signer modifies V value during recovering while other signers don't, it requires vfunc for the treatment.
   304  	RecoverPubkey(txhash common.Hash, homestead bool, vfunc func(*big.Int) *big.Int) ([]*ecdsa.PublicKey, error)
   305  
   306  	// ChainId returns which chain id this transaction was signed for (if at all)
   307  	ChainId() *big.Int
   308  
   309  	// Equal returns true if all attributes are the same.
   310  	Equal(t TxInternalData) bool
   311  
   312  	// IntrinsicGas computes additional 'intrinsic gas' based on tx types.
   313  	IntrinsicGas(currentBlockNumber uint64) (uint64, error)
   314  
   315  	// SerializeForSign returns a slice containing attributes to make its tx signature.
   316  	SerializeForSign() []interface{}
   317  
   318  	// SenderTxHash returns a hash of the tx without the fee payer's address and signature.
   319  	SenderTxHash() common.Hash
   320  
   321  	// Validate returns nil if tx is validated with the given stateDB and currentBlockNumber.
   322  	// Otherwise, it returns an error.
   323  	// This function is called in TxPool.validateTx() and TxInternalData.Execute().
   324  	Validate(stateDB StateDB, currentBlockNumber uint64) error
   325  
   326  	// ValidateMutableValue returns nil if tx is validated. Otherwise, it returns an error.
   327  	// The function validates tx values associated with mutable values in the state.
   328  	// MutableValues: accountKey, the existence of creating address, feePayer's balance, etc.
   329  	ValidateMutableValue(stateDB StateDB, currentBlockNumber uint64) error
   330  
   331  	// IsLegacyTransaction returns true if the tx type is a legacy transaction (TxInternalDataLegacy) object.
   332  	IsLegacyTransaction() bool
   333  
   334  	// GetRoleTypeForValidation returns RoleType to validate this transaction.
   335  	GetRoleTypeForValidation() accountkey.RoleType
   336  
   337  	// String returns a string containing information about the fields of the object.
   338  	String() string
   339  
   340  	// Execute performs execution of the transaction according to the transaction type.
   341  	Execute(sender ContractRef, vm VM, stateDB StateDB, currentBlockNumber uint64, gas uint64, value *big.Int) (ret []byte, usedGas uint64, err error)
   342  
   343  	MakeRPCOutput() map[string]interface{}
   344  }
   345  
   346  type TxInternalDataContractAddressFiller interface {
   347  	// FillContractAddress fills contract address to receipt. This only works for types deploying a smart contract.
   348  	FillContractAddress(from common.Address, r *Receipt)
   349  }
   350  
   351  type TxInternalDataSerializeForSignToByte interface {
   352  	SerializeForSignToBytes() []byte
   353  }
   354  
   355  // TxInternalDataFeePayer has functions related to fee delegated transactions.
   356  type TxInternalDataFeePayer interface {
   357  	GetFeePayer() common.Address
   358  
   359  	// GetFeePayerRawSignatureValues returns fee payer's signatures as a slice of `*big.Int`.
   360  	// Due to multi signatures, it is not good to return three values of `*big.Int`.
   361  	// The format would be something like [["V":v, "R":r, "S":s}, {"V":v, "R":r, "S":s}].
   362  	GetFeePayerRawSignatureValues() TxSignatures
   363  
   364  	// RecoverFeePayerPubkey returns the fee payer's public key derived from txhash and signatures(r, s, v).
   365  	RecoverFeePayerPubkey(txhash common.Hash, homestead bool, vfunc func(*big.Int) *big.Int) ([]*ecdsa.PublicKey, error)
   366  
   367  	SetFeePayerSignatures(s TxSignatures)
   368  }
   369  
   370  // TxInternalDataFeeRatio has a function `GetFeeRatio`.
   371  type TxInternalDataFeeRatio interface {
   372  	// GetFeeRatio returns a ratio of tx fee paid by the fee payer in percentage.
   373  	// For example, if it is 30, 30% of tx fee will be paid by the fee payer.
   374  	// 70% will be paid by the sender.
   375  	GetFeeRatio() FeeRatio
   376  }
   377  
   378  // TxInternalDataFrom has a function `GetFrom()`.
   379  // All other transactions to be implemented will have `from` field, but
   380  // `TxInternalDataLegacy` (a legacy transaction type) does not have the field.
   381  // Hence, this function is defined in another interface TxInternalDataFrom.
   382  type TxInternalDataFrom interface {
   383  	GetFrom() common.Address
   384  }
   385  
   386  // TxInternalDataPayload has a function `GetPayload()`.
   387  // Since the payload field is not a common field for all tx types, we provide
   388  // an interface `TxInternalDataPayload` to obtain the payload.
   389  type TxInternalDataPayload interface {
   390  	GetPayload() []byte
   391  }
   392  
   393  // TxInternalDataEthTyped has a function related to EIP-2718 Ethereum typed transaction.
   394  // For supporting new typed transaction defined EIP-2718, We provide an interface `TxInternalDataEthTyped `
   395  type TxInternalDataEthTyped interface {
   396  	setSignatureValues(chainID, v, r, s *big.Int)
   397  	GetAccessList() AccessList
   398  	TxHash() common.Hash
   399  }
   400  
   401  // TxInternalDataBaseFee has a function related to EIP-1559 Ethereum typed transaction.
   402  type TxInternalDataBaseFee interface {
   403  	GetGasTipCap() *big.Int
   404  	GetGasFeeCap() *big.Int
   405  }
   406  
   407  // Since we cannot access the package `blockchain/vm` directly, an interface `VM` is introduced.
   408  // TODO-Klaytn-Refactoring: Transaction and related data structures should be a new package.
   409  type VM interface {
   410  	Create(caller ContractRef, code []byte, gas uint64, value *big.Int, codeFormat params.CodeFormat) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error)
   411  	CreateWithAddress(caller ContractRef, code []byte, gas uint64, value *big.Int, contractAddr common.Address, humanReadable bool, codeFormat params.CodeFormat) ([]byte, common.Address, uint64, error)
   412  	Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)
   413  }
   414  
   415  // Since we cannot access the package `blockchain/state` directly, an interface `StateDB` is introduced.
   416  // TODO-Klaytn-Refactoring: Transaction and related data structures should be a new package.
   417  type StateDB interface {
   418  	IncNonce(common.Address)
   419  	Exist(common.Address) bool
   420  	UpdateKey(addr common.Address, key accountkey.AccountKey, currentBlockNumber uint64) error
   421  	CreateEOA(addr common.Address, humanReadable bool, key accountkey.AccountKey)
   422  	CreateSmartContractAccount(addr common.Address, format params.CodeFormat, r params.Rules)
   423  	CreateSmartContractAccountWithKey(addr common.Address, humanReadable bool, key accountkey.AccountKey, format params.CodeFormat, r params.Rules)
   424  	IsProgramAccount(addr common.Address) bool
   425  	IsContractAvailable(addr common.Address) bool
   426  	IsValidCodeFormat(addr common.Address) bool
   427  	GetKey(addr common.Address) accountkey.AccountKey
   428  }
   429  
   430  func NewTxInternalData(t TxType) (TxInternalData, error) {
   431  	switch t {
   432  	case TxTypeLegacyTransaction:
   433  		return newTxInternalDataLegacy(), nil
   434  	case TxTypeValueTransfer:
   435  		return newTxInternalDataValueTransfer(), nil
   436  	case TxTypeFeeDelegatedValueTransfer:
   437  		return newTxInternalDataFeeDelegatedValueTransfer(), nil
   438  	case TxTypeFeeDelegatedValueTransferWithRatio:
   439  		return NewTxInternalDataFeeDelegatedValueTransferWithRatio(), nil
   440  	case TxTypeValueTransferMemo:
   441  		return newTxInternalDataValueTransferMemo(), nil
   442  	case TxTypeFeeDelegatedValueTransferMemo:
   443  		return newTxInternalDataFeeDelegatedValueTransferMemo(), nil
   444  	case TxTypeFeeDelegatedValueTransferMemoWithRatio:
   445  		return newTxInternalDataFeeDelegatedValueTransferMemoWithRatio(), nil
   446  	// case TxTypeAccountCreation:
   447  	//	return newTxInternalDataAccountCreation(), nil
   448  	case TxTypeAccountUpdate:
   449  		return newTxInternalDataAccountUpdate(), nil
   450  	case TxTypeFeeDelegatedAccountUpdate:
   451  		return newTxInternalDataFeeDelegatedAccountUpdate(), nil
   452  	case TxTypeFeeDelegatedAccountUpdateWithRatio:
   453  		return newTxInternalDataFeeDelegatedAccountUpdateWithRatio(), nil
   454  	case TxTypeSmartContractDeploy:
   455  		return newTxInternalDataSmartContractDeploy(), nil
   456  	case TxTypeFeeDelegatedSmartContractDeploy:
   457  		return newTxInternalDataFeeDelegatedSmartContractDeploy(), nil
   458  	case TxTypeFeeDelegatedSmartContractDeployWithRatio:
   459  		return newTxInternalDataFeeDelegatedSmartContractDeployWithRatio(), nil
   460  	case TxTypeSmartContractExecution:
   461  		return newTxInternalDataSmartContractExecution(), nil
   462  	case TxTypeFeeDelegatedSmartContractExecution:
   463  		return newTxInternalDataFeeDelegatedSmartContractExecution(), nil
   464  	case TxTypeFeeDelegatedSmartContractExecutionWithRatio:
   465  		return newTxInternalDataFeeDelegatedSmartContractExecutionWithRatio(), nil
   466  	case TxTypeCancel:
   467  		return newTxInternalDataCancel(), nil
   468  	case TxTypeFeeDelegatedCancel:
   469  		return newTxInternalDataFeeDelegatedCancel(), nil
   470  	case TxTypeFeeDelegatedCancelWithRatio:
   471  		return newTxInternalDataFeeDelegatedCancelWithRatio(), nil
   472  	case TxTypeChainDataAnchoring:
   473  		return newTxInternalDataChainDataAnchoring(), nil
   474  	case TxTypeFeeDelegatedChainDataAnchoring:
   475  		return newTxInternalDataFeeDelegatedChainDataAnchoring(), nil
   476  	case TxTypeFeeDelegatedChainDataAnchoringWithRatio:
   477  		return newTxInternalDataFeeDelegatedChainDataAnchoringWithRatio(), nil
   478  	case TxTypeEthereumAccessList:
   479  		return newTxInternalDataEthereumAccessList(), nil
   480  	case TxTypeEthereumDynamicFee:
   481  		return newTxInternalDataEthereumDynamicFee(), nil
   482  	}
   483  
   484  	return nil, errUndefinedTxType
   485  }
   486  
   487  func NewTxInternalDataWithMap(t TxType, values map[TxValueKeyType]interface{}) (TxInternalData, error) {
   488  	switch t {
   489  	case TxTypeLegacyTransaction:
   490  		return newTxInternalDataLegacyWithMap(values)
   491  	case TxTypeValueTransfer:
   492  		return newTxInternalDataValueTransferWithMap(values)
   493  	case TxTypeFeeDelegatedValueTransfer:
   494  		return newTxInternalDataFeeDelegatedValueTransferWithMap(values)
   495  	case TxTypeFeeDelegatedValueTransferWithRatio:
   496  		return newTxInternalDataFeeDelegatedValueTransferWithRatioWithMap(values)
   497  	case TxTypeValueTransferMemo:
   498  		return newTxInternalDataValueTransferMemoWithMap(values)
   499  	case TxTypeFeeDelegatedValueTransferMemo:
   500  		return newTxInternalDataFeeDelegatedValueTransferMemoWithMap(values)
   501  	case TxTypeFeeDelegatedValueTransferMemoWithRatio:
   502  		return newTxInternalDataFeeDelegatedValueTransferMemoWithRatioWithMap(values)
   503  	// case TxTypeAccountCreation:
   504  	//	return newTxInternalDataAccountCreationWithMap(values)
   505  	case TxTypeAccountUpdate:
   506  		return newTxInternalDataAccountUpdateWithMap(values)
   507  	case TxTypeFeeDelegatedAccountUpdate:
   508  		return newTxInternalDataFeeDelegatedAccountUpdateWithMap(values)
   509  	case TxTypeFeeDelegatedAccountUpdateWithRatio:
   510  		return newTxInternalDataFeeDelegatedAccountUpdateWithRatioWithMap(values)
   511  	case TxTypeSmartContractDeploy:
   512  		return newTxInternalDataSmartContractDeployWithMap(values)
   513  	case TxTypeFeeDelegatedSmartContractDeploy:
   514  		return newTxInternalDataFeeDelegatedSmartContractDeployWithMap(values)
   515  	case TxTypeFeeDelegatedSmartContractDeployWithRatio:
   516  		return newTxInternalDataFeeDelegatedSmartContractDeployWithRatioWithMap(values)
   517  	case TxTypeSmartContractExecution:
   518  		return newTxInternalDataSmartContractExecutionWithMap(values)
   519  	case TxTypeFeeDelegatedSmartContractExecution:
   520  		return newTxInternalDataFeeDelegatedSmartContractExecutionWithMap(values)
   521  	case TxTypeFeeDelegatedSmartContractExecutionWithRatio:
   522  		return newTxInternalDataFeeDelegatedSmartContractExecutionWithRatioWithMap(values)
   523  	case TxTypeCancel:
   524  		return newTxInternalDataCancelWithMap(values)
   525  	case TxTypeFeeDelegatedCancel:
   526  		return newTxInternalDataFeeDelegatedCancelWithMap(values)
   527  	case TxTypeFeeDelegatedCancelWithRatio:
   528  		return newTxInternalDataFeeDelegatedCancelWithRatioWithMap(values)
   529  	case TxTypeChainDataAnchoring:
   530  		return newTxInternalDataChainDataAnchoringWithMap(values)
   531  	case TxTypeFeeDelegatedChainDataAnchoring:
   532  		return newTxInternalDataFeeDelegatedChainDataAnchoringWithMap(values)
   533  	case TxTypeFeeDelegatedChainDataAnchoringWithRatio:
   534  		return newTxInternalDataFeeDelegatedChainDataAnchoringWithRatioWithMap(values)
   535  	case TxTypeEthereumAccessList:
   536  		return newTxInternalDataEthereumAccessListWithMap(values)
   537  	case TxTypeEthereumDynamicFee:
   538  		return newTxInternalDataEthereumDynamicFeeWithMap(values)
   539  	}
   540  
   541  	return nil, errUndefinedTxType
   542  }
   543  
   544  // toWordSize returns the ceiled word size required for init code payment calculation.
   545  func toWordSize(size uint64) uint64 {
   546  	if size > math.MaxUint64-31 {
   547  		return math.MaxUint64/32 + 1
   548  	}
   549  
   550  	return (size + 31) / 32
   551  }
   552  
   553  func IntrinsicGasPayload(gas uint64, data []byte, isContractCreation bool, rules params.Rules) (uint64, error) {
   554  	// Bump the required gas by the amount of transactional data
   555  	length := uint64(len(data))
   556  	if length == 0 {
   557  		return gas, nil
   558  	}
   559  	// Make sure we don't exceed uint64 for all data combinations
   560  	if (math.MaxUint64-gas)/params.TxDataGas < length {
   561  		return 0, ErrGasUintOverflow
   562  	}
   563  	gas += length * params.TxDataGas
   564  
   565  	if isContractCreation && rules.IsShanghai {
   566  		lenWords := toWordSize(length)
   567  		if (math.MaxUint64-gas)/params.InitCodeWordGas < lenWords {
   568  			return 0, ErrGasUintOverflow
   569  		}
   570  		gas += lenWords * params.InitCodeWordGas
   571  	}
   572  	return gas, nil
   573  }
   574  
   575  func IntrinsicGasPayloadLegacy(gas uint64, data []byte) (uint64, error) {
   576  	length := uint64(len(data))
   577  	if length > 0 {
   578  		// Zero and non-zero bytes are priced differently
   579  		var nz uint64
   580  		for _, byt := range data {
   581  			if byt != 0 {
   582  				nz++
   583  			}
   584  		}
   585  		// Make sure we don't exceed uint64 for all data combinations
   586  		if (math.MaxUint64-gas)/params.TxDataNonZeroGas < nz {
   587  			return 0, ErrGasUintOverflow
   588  		}
   589  		gas += nz * params.TxDataNonZeroGas
   590  
   591  		z := uint64(len(data)) - nz
   592  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   593  			return 0, ErrGasUintOverflow
   594  		}
   595  		gas += z * params.TxDataZeroGas
   596  	}
   597  
   598  	return gas, nil
   599  }
   600  
   601  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
   602  func IntrinsicGas(data []byte, accessList AccessList, contractCreation bool, r params.Rules) (uint64, error) {
   603  	// Set the starting gas for the raw transaction
   604  	var gas uint64
   605  	if contractCreation {
   606  		gas = params.TxGasContractCreation
   607  	} else {
   608  		gas = params.TxGas
   609  	}
   610  
   611  	var gasPayloadWithGas uint64
   612  	var err error
   613  	if r.IsIstanbul {
   614  		gasPayloadWithGas, err = IntrinsicGasPayload(gas, data, contractCreation, r)
   615  	} else {
   616  		gasPayloadWithGas, err = IntrinsicGasPayloadLegacy(gas, data)
   617  	}
   618  
   619  	if err != nil {
   620  		return 0, err
   621  	}
   622  
   623  	// We charge additional gas for the accessList:
   624  	// ACCESS_LIST_ADDRESS_COST : gas per address in AccessList
   625  	// ACCESS_LIST_STORAGE_KEY_COST : gas per storage key in AccessList
   626  	if accessList != nil {
   627  		gasPayloadWithGas += uint64(len(accessList)) * params.TxAccessListAddressGas
   628  		gasPayloadWithGas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
   629  	}
   630  
   631  	return gasPayloadWithGas, nil
   632  }
   633  
   634  // CalcFeeWithRatio returns feePayer's fee and sender's fee based on feeRatio.
   635  // For example, if fee = 100 and feeRatio = 30, feePayer = 30 and feeSender = 70.
   636  func CalcFeeWithRatio(feeRatio FeeRatio, fee *big.Int) (*big.Int, *big.Int) {
   637  	// feePayer = fee * ratio / 100
   638  	feePayer := new(big.Int).Div(new(big.Int).Mul(fee, new(big.Int).SetUint64(uint64(feeRatio))), common.Big100)
   639  	// feeSender = fee - feePayer
   640  	feeSender := new(big.Int).Sub(fee, feePayer)
   641  
   642  	return feePayer, feeSender
   643  }
   644  
   645  func equalRecipient(a, b *common.Address) bool {
   646  	if a == nil && b == nil {
   647  		return true
   648  	}
   649  
   650  	if a != nil && b != nil && bytes.Equal(a.Bytes(), b.Bytes()) {
   651  		return true
   652  	}
   653  
   654  	return false
   655  }
   656  
   657  // NewAccountCreationTransactionWithMap is a test only function since the accountCreation tx is disabled.
   658  // The function generates an accountCreation function like 'NewTxInternalDataWithMap()'.
   659  func NewAccountCreationTransactionWithMap(values map[TxValueKeyType]interface{}) (*Transaction, error) {
   660  	txData, err := newTxInternalDataAccountCreationWithMap(values)
   661  	if err != nil {
   662  		return nil, err
   663  	}
   664  
   665  	return NewTx(txData), nil
   666  }
   667  
   668  func calculateTxSize(data TxInternalData) common.StorageSize {
   669  	c := writeCounter(0)
   670  	rlp.Encode(&c, data)
   671  	return common.StorageSize(c)
   672  }