github.com/matthieu/go-ethereum@v1.13.2/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  	"math"
    21  	"math/big"
    22  
    23  	"github.com/matthieu/go-ethereum/common"
    24  	"github.com/matthieu/go-ethereum/core/vm"
    25  	"github.com/matthieu/go-ethereum/params"
    26  )
    27  
    28  /*
    29  The State Transitioning Model
    30  
    31  A state transition is a change made when a transaction is applied to the current world state
    32  The state transitioning model does all the necessary work to work out a valid new state root.
    33  
    34  1) Nonce handling
    35  2) Pre pay gas
    36  3) Create a new state object if the recipient is \0*32
    37  4) Value transfer
    38  == If contract creation ==
    39    4a) Attempt to run transaction data
    40    4b) If valid, use result as code for the new state object
    41  == end ==
    42  5) Run Script section
    43  6) Derive new state root
    44  */
    45  type StateTransition struct {
    46  	gp         *GasPool
    47  	msg        Message
    48  	gas        uint64
    49  	gasPrice   *big.Int
    50  	initialGas uint64
    51  	value      *big.Int
    52  	data       []byte
    53  	state      vm.StateDB
    54  	evm        *vm.EVM
    55  }
    56  
    57  // Message represents a message sent to a contract.
    58  type Message interface {
    59  	From() common.Address
    60  	To() *common.Address
    61  
    62  	GasPrice() *big.Int
    63  	Gas() uint64
    64  	Value() *big.Int
    65  
    66  	Nonce() uint64
    67  	CheckNonce() bool
    68  	Data() []byte
    69  }
    70  
    71  // ExecutionResult includes all output after executing given evm
    72  // message no matter the execution itself is successful or not.
    73  type ExecutionResult struct {
    74  	UsedGas    uint64 // Total used gas but include the refunded gas
    75  	Err        error  // Any error encountered during the execution(listed in core/vm/errors.go)
    76  	ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
    77  }
    78  
    79  // Unwrap returns the internal evm error which allows us for further
    80  // analysis outside.
    81  func (result *ExecutionResult) Unwrap() error {
    82  	return result.Err
    83  }
    84  
    85  // Failed returns the indicator whether the execution is successful or not
    86  func (result *ExecutionResult) Failed() bool { return result.Err != nil }
    87  
    88  // Return is a helper function to help caller distinguish between revert reason
    89  // and function return. Return returns the data after execution if no error occurs.
    90  func (result *ExecutionResult) Return() []byte {
    91  	if result.Err != nil {
    92  		return nil
    93  	}
    94  	return common.CopyBytes(result.ReturnData)
    95  }
    96  
    97  // Revert returns the concrete revert reason if the execution is aborted by `REVERT`
    98  // opcode. Note the reason can be nil if no data supplied with revert opcode.
    99  func (result *ExecutionResult) Revert() []byte {
   100  	if result.Err != vm.ErrExecutionReverted {
   101  		return nil
   102  	}
   103  	return common.CopyBytes(result.ReturnData)
   104  }
   105  
   106  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
   107  func IntrinsicGas(data []byte, contractCreation, isHomestead bool, isEIP2028 bool) (uint64, error) {
   108  	// Set the starting gas for the raw transaction
   109  	var gas uint64
   110  	if contractCreation && isHomestead {
   111  		gas = params.TxGasContractCreation
   112  	} else {
   113  		gas = params.TxGas
   114  	}
   115  	// Bump the required gas by the amount of transactional data
   116  	if len(data) > 0 {
   117  		// Zero and non-zero bytes are priced differently
   118  		var nz uint64
   119  		for _, byt := range data {
   120  			if byt != 0 {
   121  				nz++
   122  			}
   123  		}
   124  		// Make sure we don't exceed uint64 for all data combinations
   125  		nonZeroGas := params.TxDataNonZeroGasFrontier
   126  		if isEIP2028 {
   127  			nonZeroGas = params.TxDataNonZeroGasEIP2028
   128  		}
   129  		if (math.MaxUint64-gas)/nonZeroGas < nz {
   130  			return 0, ErrGasUintOverflow
   131  		}
   132  		gas += nz * nonZeroGas
   133  
   134  		z := uint64(len(data)) - nz
   135  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   136  			return 0, ErrGasUintOverflow
   137  		}
   138  		gas += z * params.TxDataZeroGas
   139  	}
   140  	return gas, nil
   141  }
   142  
   143  // NewStateTransition initialises and returns a new state transition object.
   144  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   145  	return &StateTransition{
   146  		gp:       gp,
   147  		evm:      evm,
   148  		msg:      msg,
   149  		gasPrice: msg.GasPrice(),
   150  		value:    msg.Value(),
   151  		data:     msg.Data(),
   152  		state:    evm.StateDB,
   153  	}
   154  }
   155  
   156  // ApplyMessage computes the new state by applying the given message
   157  // against the old state within the environment.
   158  //
   159  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   160  // the gas used (which includes gas refunds) and an error if it failed. An error always
   161  // indicates a core error meaning that the message would always fail for that particular
   162  // state and would never be accepted within a block.
   163  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
   164  	return NewStateTransition(evm, msg, gp).TransitionDb()
   165  }
   166  
   167  // to returns the recipient of the message.
   168  func (st *StateTransition) to() common.Address {
   169  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   170  		return common.Address{}
   171  	}
   172  	return *st.msg.To()
   173  }
   174  
   175  func (st *StateTransition) buyGas() error {
   176  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   177  	if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
   178  		return ErrInsufficientFunds
   179  	}
   180  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   181  		return err
   182  	}
   183  	st.gas += st.msg.Gas()
   184  
   185  	st.initialGas = st.msg.Gas()
   186  	st.state.SubBalance(st.msg.From(), mgval)
   187  	return nil
   188  }
   189  
   190  func (st *StateTransition) preCheck() error {
   191  	// Make sure this transaction's nonce is correct.
   192  	if st.msg.CheckNonce() {
   193  		nonce := st.state.GetNonce(st.msg.From())
   194  		if nonce < st.msg.Nonce() {
   195  			return ErrNonceTooHigh
   196  		} else if nonce > st.msg.Nonce() {
   197  			return ErrNonceTooLow
   198  		}
   199  	}
   200  	return st.buyGas()
   201  }
   202  
   203  // TransitionDb will transition the state by applying the current message and
   204  // returning the evm execution result with following fields.
   205  //
   206  // - used gas:
   207  //      total gas used (including gas being refunded)
   208  // - returndata:
   209  //      the returned data from evm
   210  // - concrete execution error:
   211  //      various **EVM** error which aborts the execution,
   212  //      e.g. ErrOutOfGas, ErrExecutionReverted
   213  //
   214  // However if any consensus issue encountered, return the error directly with
   215  // nil evm execution result.
   216  func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
   217  	// First check this message satisfies all consensus rules before
   218  	// applying the message. The rules include these clauses
   219  	//
   220  	// 1. the nonce of the message caller is correct
   221  	// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
   222  	// 3. the amount of gas required is available in the block
   223  	// 4. the purchased gas is enough to cover intrinsic usage
   224  	// 5. there is no overflow when calculating intrinsic gas
   225  	// 6. caller has enough balance to cover asset transfer for **topmost** call
   226  
   227  	// Check clauses 1-3, buy gas if everything is correct
   228  	if err := st.preCheck(); err != nil {
   229  		return nil, err
   230  	}
   231  	msg := st.msg
   232  	sender := vm.AccountRef(msg.From())
   233  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
   234  	istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber)
   235  	contractCreation := msg.To() == nil
   236  
   237  	// Check clauses 4-5, subtract intrinsic gas if everything is correct
   238  	gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul)
   239  	if err != nil {
   240  		return nil, err
   241  	}
   242  	if st.gas < gas {
   243  		return nil, ErrIntrinsicGas
   244  	}
   245  	st.gas -= gas
   246  
   247  	// Check clause 6
   248  	if msg.Value().Sign() > 0 && !st.evm.CanTransfer(st.state, msg.From(), msg.Value()) {
   249  		return nil, ErrInsufficientFundsForTransfer
   250  	}
   251  	var (
   252  		ret   []byte
   253  		vmerr error // vm errors do not effect consensus and are therefore not assigned to err
   254  	)
   255  	if contractCreation {
   256  		ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value)
   257  	} else {
   258  		// Increment the nonce for the next transaction
   259  		st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
   260  		ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
   261  	}
   262  	st.refundGas()
   263  	st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   264  
   265  	return &ExecutionResult{
   266  		UsedGas:    st.gasUsed(),
   267  		Err:        vmerr,
   268  		ReturnData: ret,
   269  	}, nil
   270  }
   271  
   272  func (st *StateTransition) refundGas() {
   273  	// Apply refund counter, capped to half of the used gas.
   274  	refund := st.gasUsed() / 2
   275  	if refund > st.state.GetRefund() {
   276  		refund = st.state.GetRefund()
   277  	}
   278  	st.gas += refund
   279  
   280  	// Return ETH for remaining gas, exchanged at the original rate.
   281  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   282  	st.state.AddBalance(st.msg.From(), remaining)
   283  
   284  	// Also return remaining gas to the block gas counter so it is
   285  	// available for the next transaction.
   286  	st.gp.AddGas(st.gas)
   287  }
   288  
   289  // gasUsed returns the amount of gas used up by the state transition.
   290  func (st *StateTransition) gasUsed() uint64 {
   291  	return st.initialGas - st.gas
   292  }