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