github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/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  	"errors"
    21  	"math"
    22  	"math/big"
    23  
    24  	"github.com/ethereum-optimism/optimism/l2geth/common"
    25  	"github.com/ethereum-optimism/optimism/l2geth/common/hexutil"
    26  	"github.com/ethereum-optimism/optimism/l2geth/core/types"
    27  	"github.com/ethereum-optimism/optimism/l2geth/core/vm"
    28  	"github.com/ethereum-optimism/optimism/l2geth/log"
    29  	"github.com/ethereum-optimism/optimism/l2geth/params"
    30  	"github.com/ethereum-optimism/optimism/l2geth/rollup/fees"
    31  	"github.com/ethereum-optimism/optimism/l2geth/rollup/rcfg"
    32  )
    33  
    34  var (
    35  	errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
    36  )
    37  
    38  /*
    39  The State Transitioning Model
    40  
    41  A state transition is a change made when a transaction is applied to the current world state
    42  The state transitioning model does all the necessary work to work out a valid new state root.
    43  
    44  1) Nonce handling
    45  2) Pre pay gas
    46  3) Create a new state object if the recipient is \0*32
    47  4) Value transfer
    48  == If contract creation ==
    49    4a) Attempt to run transaction data
    50    4b) If valid, use result as code for the new state object
    51  == end ==
    52  5) Run Script section
    53  6) Derive new state root
    54  */
    55  type StateTransition struct {
    56  	gp         *GasPool
    57  	msg        Message
    58  	gas        uint64
    59  	gasPrice   *big.Int
    60  	initialGas uint64
    61  	value      *big.Int
    62  	data       []byte
    63  	state      vm.StateDB
    64  	evm        *vm.EVM
    65  	// UsingOVM
    66  	l1Fee *big.Int
    67  }
    68  
    69  // Message represents a message sent to a contract.
    70  type Message interface {
    71  	From() common.Address
    72  	//FromFrontier() (common.Address, error)
    73  	To() *common.Address
    74  
    75  	GasPrice() *big.Int
    76  	Gas() uint64
    77  	Value() *big.Int
    78  
    79  	Nonce() uint64
    80  	CheckNonce() bool
    81  	Data() []byte
    82  	AccessList() types.AccessList
    83  
    84  	L1Timestamp() uint64
    85  	L1BlockNumber() *big.Int
    86  	QueueOrigin() types.QueueOrigin
    87  }
    88  
    89  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
    90  func IntrinsicGas(data []byte, contractCreation, isHomestead bool, isEIP2028 bool) (uint64, error) {
    91  	// Set the starting gas for the raw transaction
    92  	var gas uint64
    93  	if contractCreation && isHomestead {
    94  		gas = params.TxGasContractCreation
    95  	} else {
    96  		gas = params.TxGas
    97  	}
    98  	// Bump the required gas by the amount of transactional data
    99  	if len(data) > 0 {
   100  		// Zero and non-zero bytes are priced differently
   101  		var nz uint64
   102  		for _, byt := range data {
   103  			if byt != 0 {
   104  				nz++
   105  			}
   106  		}
   107  		// Make sure we don't exceed uint64 for all data combinations
   108  		nonZeroGas := params.TxDataNonZeroGasFrontier
   109  		if isEIP2028 {
   110  			nonZeroGas = params.TxDataNonZeroGasEIP2028
   111  		}
   112  		if (math.MaxUint64-gas)/nonZeroGas < nz {
   113  			return 0, vm.ErrOutOfGas
   114  		}
   115  		gas += nz * nonZeroGas
   116  
   117  		z := uint64(len(data)) - nz
   118  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   119  			return 0, vm.ErrOutOfGas
   120  		}
   121  		gas += z * params.TxDataZeroGas
   122  	}
   123  	return gas, nil
   124  }
   125  
   126  // NewStateTransition initialises and returns a new state transition object.
   127  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   128  	l1Fee := new(big.Int)
   129  	if rcfg.UsingOVM {
   130  		if msg.GasPrice().Cmp(common.Big0) != 0 {
   131  			// Compute the L1 fee before the state transition
   132  			// so it only has to be read from state one time.
   133  			l1Fee, _ = fees.CalculateL1MsgFee(msg, evm.StateDB, nil)
   134  		}
   135  	}
   136  
   137  	return &StateTransition{
   138  		gp:       gp,
   139  		evm:      evm,
   140  		msg:      msg,
   141  		gasPrice: msg.GasPrice(),
   142  		value:    msg.Value(),
   143  		data:     msg.Data(),
   144  		state:    evm.StateDB,
   145  		l1Fee:    l1Fee,
   146  	}
   147  }
   148  
   149  // ApplyMessage computes the new state by applying the given message
   150  // against the old state within the environment.
   151  //
   152  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   153  // the gas used (which includes gas refunds) and an error if it failed. An error always
   154  // indicates a core error meaning that the message would always fail for that particular
   155  // state and would never be accepted within a block.
   156  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) {
   157  	return NewStateTransition(evm, msg, gp).TransitionDb()
   158  }
   159  
   160  // to returns the recipient of the message.
   161  func (st *StateTransition) to() common.Address {
   162  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   163  		return common.Address{}
   164  	}
   165  	return *st.msg.To()
   166  }
   167  
   168  func (st *StateTransition) useGas(amount uint64) error {
   169  	if st.gas < amount {
   170  		return vm.ErrOutOfGas
   171  	}
   172  	st.gas -= amount
   173  
   174  	return nil
   175  }
   176  
   177  func (st *StateTransition) buyGas() error {
   178  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   179  	if rcfg.UsingOVM {
   180  		// Only charge the L1 fee for QueueOrigin sequencer transactions
   181  		if st.msg.QueueOrigin() == types.QueueOriginSequencer {
   182  			mgval = mgval.Add(mgval, st.l1Fee)
   183  			if st.msg.CheckNonce() {
   184  				log.Debug("Adding L1 fee", "l1-fee", st.l1Fee)
   185  			}
   186  		}
   187  	}
   188  	if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
   189  		return errInsufficientBalanceForGas
   190  	}
   191  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   192  		return err
   193  	}
   194  	st.gas += st.msg.Gas()
   195  
   196  	st.initialGas = st.msg.Gas()
   197  	st.state.SubBalance(st.msg.From(), mgval)
   198  	return nil
   199  }
   200  
   201  func (st *StateTransition) preCheck() error {
   202  	// Make sure this transaction's nonce is correct.
   203  	if st.msg.CheckNonce() {
   204  		if rcfg.UsingOVM {
   205  			if st.msg.QueueOrigin() == types.QueueOriginL1ToL2 {
   206  				return st.buyGas()
   207  			}
   208  		}
   209  		nonce := st.state.GetNonce(st.msg.From())
   210  		if nonce < st.msg.Nonce() {
   211  			return ErrNonceTooHigh
   212  		} else if nonce > st.msg.Nonce() {
   213  			return ErrNonceTooLow
   214  		}
   215  	}
   216  	return st.buyGas()
   217  }
   218  
   219  // TransitionDb will transition the state by applying the current message and
   220  // returning the result including the used gas. It returns an error if failed.
   221  // An error indicates a consensus issue.
   222  func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
   223  	if err = st.preCheck(); err != nil {
   224  		return
   225  	}
   226  	msg := st.msg
   227  	sender := vm.AccountRef(msg.From())
   228  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
   229  	istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber)
   230  	contractCreation := msg.To() == nil
   231  
   232  	// Pay intrinsic gas
   233  	gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul)
   234  	if err != nil {
   235  		return nil, 0, false, err
   236  	}
   237  	if err = st.useGas(gas); err != nil {
   238  		return nil, 0, false, err
   239  	}
   240  
   241  	var (
   242  		evm = st.evm
   243  		// vm errors do not effect consensus and are therefore
   244  		// not assigned to err, except for insufficient balance
   245  		// error.
   246  		vmerr error
   247  	)
   248  
   249  	// The access list gets created here
   250  	if rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber); rules.IsBerlin {
   251  		st.state.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList())
   252  	}
   253  
   254  	if contractCreation {
   255  		ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
   256  	} else {
   257  		// Increment the nonce for the next transaction
   258  		st.state.SetNonce(msg.From(), st.state.GetNonce(msg.From())+1)
   259  		ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value)
   260  	}
   261  
   262  	if vmerr != nil {
   263  		log.Debug("VM returned with error", "err", vmerr, "ret", hexutil.Encode(ret))
   264  		// The only possible consensus-error would be if there wasn't
   265  		// sufficient balance to make the transfer happen. The first
   266  		// balance transfer may never fail.
   267  		if vmerr == vm.ErrInsufficientBalance {
   268  			return nil, 0, false, vmerr
   269  		}
   270  	}
   271  	st.refundGas()
   272  	if rcfg.UsingOVM {
   273  		// The L2 Fee is the same as the fee that is charged in the normal geth
   274  		// codepath. Add the L1 fee to the L2 fee for the total fee that is sent
   275  		// to the sequencer.
   276  		l2Fee := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice)
   277  		fee := new(big.Int).Add(st.l1Fee, l2Fee)
   278  		st.state.AddBalance(evm.Coinbase, fee)
   279  	} else {
   280  		st.state.AddBalance(evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   281  	}
   282  
   283  	return ret, st.gasUsed(), vmerr != nil, err
   284  }
   285  
   286  func (st *StateTransition) refundGas() {
   287  	// Apply refund counter, capped to half of the used gas.
   288  	refund := st.gasUsed() / 2
   289  	if refund > st.state.GetRefund() {
   290  		refund = st.state.GetRefund()
   291  	}
   292  	st.gas += refund
   293  
   294  	// Return ETH for remaining gas, exchanged at the original rate.
   295  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   296  	st.state.AddBalance(st.msg.From(), remaining)
   297  
   298  	// Also return remaining gas to the block gas counter so it is
   299  	// available for the next transaction.
   300  	st.gp.AddGas(st.gas)
   301  }
   302  
   303  // gasUsed returns the amount of gas used up by the state transition.
   304  func (st *StateTransition) gasUsed() uint64 {
   305  	return st.initialGas - st.gas
   306  }