github.com/VietJr/bor@v1.0.3/core/state_transition.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"fmt"
    21  	"math"
    22  	"math/big"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	cmath "github.com/ethereum/go-ethereum/common/math"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/core/vm"
    28  	"github.com/ethereum/go-ethereum/crypto"
    29  	"github.com/ethereum/go-ethereum/params"
    30  )
    31  
    32  var emptyCodeHash = crypto.Keccak256Hash(nil)
    33  
    34  /*
    35  The State Transitioning Model
    36  
    37  A state transition is a change made when a transaction is applied to the current world state
    38  The state transitioning model does all the necessary work to work out a valid new state root.
    39  
    40  1) Nonce handling
    41  2) Pre pay gas
    42  3) Create a new state object if the recipient is \0*32
    43  4) Value transfer
    44  == If contract creation ==
    45  
    46  	4a) Attempt to run transaction data
    47  	4b) If valid, use result as code for the new state object
    48  
    49  == end ==
    50  5) Run Script section
    51  6) Derive new state root
    52  */
    53  type StateTransition struct {
    54  	gp         *GasPool
    55  	msg        Message
    56  	gas        uint64
    57  	gasPrice   *big.Int
    58  	gasFeeCap  *big.Int
    59  	gasTipCap  *big.Int
    60  	initialGas uint64
    61  	value      *big.Int
    62  	data       []byte
    63  	state      vm.StateDB
    64  	evm        *vm.EVM
    65  }
    66  
    67  // Message represents a message sent to a contract.
    68  type Message interface {
    69  	From() common.Address
    70  	To() *common.Address
    71  
    72  	GasPrice() *big.Int
    73  	GasFeeCap() *big.Int
    74  	GasTipCap() *big.Int
    75  	Gas() uint64
    76  	Value() *big.Int
    77  
    78  	Nonce() uint64
    79  	IsFake() bool
    80  	Data() []byte
    81  	AccessList() types.AccessList
    82  }
    83  
    84  // ExecutionResult includes all output after executing given evm
    85  // message no matter the execution itself is successful or not.
    86  type ExecutionResult struct {
    87  	UsedGas    uint64 // Total used gas but include the refunded gas
    88  	Err        error  // Any error encountered during the execution(listed in core/vm/errors.go)
    89  	ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
    90  }
    91  
    92  // Unwrap returns the internal evm error which allows us for further
    93  // analysis outside.
    94  func (result *ExecutionResult) Unwrap() error {
    95  	return result.Err
    96  }
    97  
    98  // Failed returns the indicator whether the execution is successful or not
    99  func (result *ExecutionResult) Failed() bool { return result.Err != nil }
   100  
   101  // Return is a helper function to help caller distinguish between revert reason
   102  // and function return. Return returns the data after execution if no error occurs.
   103  func (result *ExecutionResult) Return() []byte {
   104  	if result.Err != nil {
   105  		return nil
   106  	}
   107  	return common.CopyBytes(result.ReturnData)
   108  }
   109  
   110  // Revert returns the concrete revert reason if the execution is aborted by `REVERT`
   111  // opcode. Note the reason can be nil if no data supplied with revert opcode.
   112  func (result *ExecutionResult) Revert() []byte {
   113  	if result.Err != vm.ErrExecutionReverted {
   114  		return nil
   115  	}
   116  	return common.CopyBytes(result.ReturnData)
   117  }
   118  
   119  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
   120  func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool) (uint64, error) {
   121  	// Set the starting gas for the raw transaction
   122  	var gas uint64
   123  	if isContractCreation && isHomestead {
   124  		gas = params.TxGasContractCreation
   125  	} else {
   126  		gas = params.TxGas
   127  	}
   128  	// Bump the required gas by the amount of transactional data
   129  	if len(data) > 0 {
   130  		// Zero and non-zero bytes are priced differently
   131  		var nz uint64
   132  		for _, byt := range data {
   133  			if byt != 0 {
   134  				nz++
   135  			}
   136  		}
   137  		// Make sure we don't exceed uint64 for all data combinations
   138  		nonZeroGas := params.TxDataNonZeroGasFrontier
   139  		if isEIP2028 {
   140  			nonZeroGas = params.TxDataNonZeroGasEIP2028
   141  		}
   142  		if (math.MaxUint64-gas)/nonZeroGas < nz {
   143  			return 0, ErrGasUintOverflow
   144  		}
   145  		gas += nz * nonZeroGas
   146  
   147  		z := uint64(len(data)) - nz
   148  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   149  			return 0, ErrGasUintOverflow
   150  		}
   151  		gas += z * params.TxDataZeroGas
   152  	}
   153  	if accessList != nil {
   154  		gas += uint64(len(accessList)) * params.TxAccessListAddressGas
   155  		gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
   156  	}
   157  	return gas, nil
   158  }
   159  
   160  // NewStateTransition initialises and returns a new state transition object.
   161  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   162  	return &StateTransition{
   163  		gp:        gp,
   164  		evm:       evm,
   165  		msg:       msg,
   166  		gasPrice:  msg.GasPrice(),
   167  		gasFeeCap: msg.GasFeeCap(),
   168  		gasTipCap: msg.GasTipCap(),
   169  		value:     msg.Value(),
   170  		data:      msg.Data(),
   171  		state:     evm.StateDB,
   172  	}
   173  }
   174  
   175  // ApplyMessage computes the new state by applying the given message
   176  // against the old state within the environment.
   177  //
   178  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   179  // the gas used (which includes gas refunds) and an error if it failed. An error always
   180  // indicates a core error meaning that the message would always fail for that particular
   181  // state and would never be accepted within a block.
   182  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
   183  	return NewStateTransition(evm, msg, gp).TransitionDb()
   184  }
   185  
   186  // to returns the recipient of the message.
   187  func (st *StateTransition) to() common.Address {
   188  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   189  		return common.Address{}
   190  	}
   191  	return *st.msg.To()
   192  }
   193  
   194  func (st *StateTransition) buyGas() error {
   195  	mgval := new(big.Int).SetUint64(st.msg.Gas())
   196  	mgval = mgval.Mul(mgval, st.gasPrice)
   197  	balanceCheck := mgval
   198  	if st.gasFeeCap != nil {
   199  		balanceCheck = new(big.Int).SetUint64(st.msg.Gas())
   200  		balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap)
   201  		balanceCheck.Add(balanceCheck, st.value)
   202  	}
   203  	if have, want := st.state.GetBalance(st.msg.From()), balanceCheck; have.Cmp(want) < 0 {
   204  		return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want)
   205  	}
   206  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   207  		return err
   208  	}
   209  	st.gas += st.msg.Gas()
   210  
   211  	st.initialGas = st.msg.Gas()
   212  	st.state.SubBalance(st.msg.From(), mgval)
   213  	return nil
   214  }
   215  
   216  func (st *StateTransition) preCheck() error {
   217  	// Only check transactions that are not fake
   218  	if !st.msg.IsFake() {
   219  		// Make sure this transaction's nonce is correct.
   220  		stNonce := st.state.GetNonce(st.msg.From())
   221  		if msgNonce := st.msg.Nonce(); stNonce < msgNonce {
   222  			return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh,
   223  				st.msg.From().Hex(), msgNonce, stNonce)
   224  		} else if stNonce > msgNonce {
   225  			return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow,
   226  				st.msg.From().Hex(), msgNonce, stNonce)
   227  		} else if stNonce+1 < stNonce {
   228  			return fmt.Errorf("%w: address %v, nonce: %d", ErrNonceMax,
   229  				st.msg.From().Hex(), stNonce)
   230  		}
   231  		// Make sure the sender is an EOA
   232  		if codeHash := st.state.GetCodeHash(st.msg.From()); codeHash != emptyCodeHash && codeHash != (common.Hash{}) {
   233  			return fmt.Errorf("%w: address %v, codehash: %s", ErrSenderNoEOA,
   234  				st.msg.From().Hex(), codeHash)
   235  		}
   236  	}
   237  	// Make sure that transaction gasFeeCap is greater than the baseFee (post london)
   238  	if st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber) {
   239  		// Skip the checks if gas fields are zero and baseFee was explicitly disabled (eth_call)
   240  		if !st.evm.Config.NoBaseFee || st.gasFeeCap.BitLen() > 0 || st.gasTipCap.BitLen() > 0 {
   241  			if l := st.gasFeeCap.BitLen(); l > 256 {
   242  				return fmt.Errorf("%w: address %v, maxFeePerGas bit length: %d", ErrFeeCapVeryHigh,
   243  					st.msg.From().Hex(), l)
   244  			}
   245  			if l := st.gasTipCap.BitLen(); l > 256 {
   246  				return fmt.Errorf("%w: address %v, maxPriorityFeePerGas bit length: %d", ErrTipVeryHigh,
   247  					st.msg.From().Hex(), l)
   248  			}
   249  			if st.gasFeeCap.Cmp(st.gasTipCap) < 0 {
   250  				return fmt.Errorf("%w: address %v, maxPriorityFeePerGas: %s, maxFeePerGas: %s", ErrTipAboveFeeCap,
   251  					st.msg.From().Hex(), st.gasTipCap, st.gasFeeCap)
   252  			}
   253  			// This will panic if baseFee is nil, but basefee presence is verified
   254  			// as part of header validation.
   255  			if st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 {
   256  				return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow,
   257  					st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee)
   258  			}
   259  		}
   260  	}
   261  	return st.buyGas()
   262  }
   263  
   264  // TransitionDb will transition the state by applying the current message and
   265  // returning the evm execution result with following fields.
   266  //
   267  //   - used gas:
   268  //     total gas used (including gas being refunded)
   269  //   - returndata:
   270  //     the returned data from evm
   271  //   - concrete execution error:
   272  //     various **EVM** error which aborts the execution,
   273  //     e.g. ErrOutOfGas, ErrExecutionReverted
   274  //
   275  // However if any consensus issue encountered, return the error directly with
   276  // nil evm execution result.
   277  func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
   278  	input1 := st.state.GetBalance(st.msg.From())
   279  	input2 := st.state.GetBalance(st.evm.Context.Coinbase)
   280  
   281  	// First check this message satisfies all consensus rules before
   282  	// applying the message. The rules include these clauses
   283  	//
   284  	// 1. the nonce of the message caller is correct
   285  	// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
   286  	// 3. the amount of gas required is available in the block
   287  	// 4. the purchased gas is enough to cover intrinsic usage
   288  	// 5. there is no overflow when calculating intrinsic gas
   289  	// 6. caller has enough balance to cover asset transfer for **topmost** call
   290  
   291  	// Check clauses 1-3, buy gas if everything is correct
   292  	if err := st.preCheck(); err != nil {
   293  		return nil, err
   294  	}
   295  	msg := st.msg
   296  	sender := vm.AccountRef(msg.From())
   297  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
   298  	istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
   299  	london := st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber)
   300  	contractCreation := msg.To() == nil
   301  
   302  	// Check clauses 4-5, subtract intrinsic gas if everything is correct
   303  	gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul)
   304  	if err != nil {
   305  		return nil, err
   306  	}
   307  	if st.gas < gas {
   308  		return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
   309  	}
   310  	st.gas -= gas
   311  
   312  	// Check clause 6
   313  	if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
   314  		return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
   315  	}
   316  
   317  	// Set up the initial access list.
   318  	if rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber, st.evm.Context.Random != nil); rules.IsBerlin {
   319  		st.state.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList())
   320  	}
   321  	var (
   322  		ret   []byte
   323  		vmerr error // vm errors do not effect consensus and are therefore not assigned to err
   324  	)
   325  	if contractCreation {
   326  		ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value)
   327  	} else {
   328  		// Increment the nonce for the next transaction
   329  		st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
   330  		ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
   331  	}
   332  
   333  	if !london {
   334  		// Before EIP-3529: refunds were capped to gasUsed / 2
   335  		st.refundGas(params.RefundQuotient)
   336  	} else {
   337  		// After EIP-3529: refunds are capped to gasUsed / 5
   338  		st.refundGas(params.RefundQuotientEIP3529)
   339  	}
   340  	effectiveTip := st.gasPrice
   341  	if london {
   342  		effectiveTip = cmath.BigMin(st.gasTipCap, new(big.Int).Sub(st.gasFeeCap, st.evm.Context.BaseFee))
   343  	}
   344  	amount := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip)
   345  	if london {
   346  		burntContractAddress := common.HexToAddress(st.evm.ChainConfig().Bor.CalculateBurntContract(st.evm.Context.BlockNumber.Uint64()))
   347  		burnAmount := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.evm.Context.BaseFee)
   348  		st.state.AddBalance(burntContractAddress, burnAmount)
   349  	}
   350  	st.state.AddBalance(st.evm.Context.Coinbase, amount)
   351  	output1 := new(big.Int).SetBytes(input1.Bytes())
   352  	output2 := new(big.Int).SetBytes(input2.Bytes())
   353  
   354  	// Deprecating transfer log and will be removed in future fork. PLEASE DO NOT USE this transfer log going forward. Parameters won't get updated as expected going forward with EIP1559
   355  	// add transfer log
   356  	AddFeeTransferLog(
   357  		st.state,
   358  
   359  		msg.From(),
   360  		st.evm.Context.Coinbase,
   361  
   362  		amount,
   363  		input1,
   364  		input2,
   365  		output1.Sub(output1, amount),
   366  		output2.Add(output2, amount),
   367  	)
   368  
   369  	return &ExecutionResult{
   370  		UsedGas:    st.gasUsed(),
   371  		Err:        vmerr,
   372  		ReturnData: ret,
   373  	}, nil
   374  }
   375  
   376  func (st *StateTransition) refundGas(refundQuotient uint64) {
   377  	// Apply refund counter, capped to a refund quotient
   378  	refund := st.gasUsed() / refundQuotient
   379  	if refund > st.state.GetRefund() {
   380  		refund = st.state.GetRefund()
   381  	}
   382  	st.gas += refund
   383  
   384  	// Return ETH for remaining gas, exchanged at the original rate.
   385  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   386  	st.state.AddBalance(st.msg.From(), remaining)
   387  
   388  	// Also return remaining gas to the block gas counter so it is
   389  	// available for the next transaction.
   390  	st.gp.AddGas(st.gas)
   391  }
   392  
   393  // gasUsed returns the amount of gas used up by the state transition.
   394  func (st *StateTransition) gasUsed() uint64 {
   395  	return st.initialGas - st.gas
   396  }