github.com/luckypickle/go-ethereum-vet@v1.14.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  	"errors"
    21  	"math"
    22  	"math/big"
    23  
    24  	"github.com/luckypickle/go-ethereum-vet/common"
    25  	"github.com/luckypickle/go-ethereum-vet/core/vm"
    26  	"github.com/luckypickle/go-ethereum-vet/log"
    27  	"github.com/luckypickle/go-ethereum-vet/params"
    28  )
    29  
    30  var (
    31  	errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
    32  )
    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  	initialGas uint64
    59  	value      *big.Int
    60  	data       []byte
    61  	state      vm.StateDB
    62  	evm        *vm.EVM
    63  }
    64  
    65  // Message represents a message sent to a contract.
    66  type Message interface {
    67  	From() common.Address
    68  	//FromFrontier() (common.Address, error)
    69  	To() *common.Address
    70  
    71  	GasPrice() *big.Int
    72  	Gas() uint64
    73  	Value() *big.Int
    74  
    75  	Nonce() uint64
    76  	CheckNonce() bool
    77  	Data() []byte
    78  }
    79  
    80  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
    81  func IntrinsicGas(data []byte, contractCreation, homestead bool) (uint64, error) {
    82  	// Set the starting gas for the raw transaction
    83  	var gas uint64
    84  	if contractCreation && homestead {
    85  		gas = params.TxGasContractCreation
    86  	} else {
    87  		gas = params.TxGas
    88  	}
    89  	// Bump the required gas by the amount of transactional data
    90  	if len(data) > 0 {
    91  		// Zero and non-zero bytes are priced differently
    92  		var nz uint64
    93  		for _, byt := range data {
    94  			if byt != 0 {
    95  				nz++
    96  			}
    97  		}
    98  		// Make sure we don't exceed uint64 for all data combinations
    99  		if (math.MaxUint64-gas)/params.TxDataNonZeroGas < nz {
   100  			return 0, vm.ErrOutOfGas
   101  		}
   102  		gas += nz * params.TxDataNonZeroGas
   103  
   104  		z := uint64(len(data)) - nz
   105  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   106  			return 0, vm.ErrOutOfGas
   107  		}
   108  		gas += z * params.TxDataZeroGas
   109  	}
   110  	return gas, nil
   111  }
   112  
   113  // NewStateTransition initialises and returns a new state transition object.
   114  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   115  	return &StateTransition{
   116  		gp:       gp,
   117  		evm:      evm,
   118  		msg:      msg,
   119  		gasPrice: msg.GasPrice(),
   120  		value:    msg.Value(),
   121  		data:     msg.Data(),
   122  		state:    evm.StateDB,
   123  	}
   124  }
   125  
   126  // ApplyMessage computes the new state by applying the given message
   127  // against the old state within the environment.
   128  //
   129  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   130  // the gas used (which includes gas refunds) and an error if it failed. An error always
   131  // indicates a core error meaning that the message would always fail for that particular
   132  // state and would never be accepted within a block.
   133  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) {
   134  	return NewStateTransition(evm, msg, gp).TransitionDb()
   135  }
   136  
   137  // to returns the recipient of the message.
   138  func (st *StateTransition) to() common.Address {
   139  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   140  		return common.Address{}
   141  	}
   142  	return *st.msg.To()
   143  }
   144  
   145  func (st *StateTransition) useGas(amount uint64) error {
   146  	if st.gas < amount {
   147  		return vm.ErrOutOfGas
   148  	}
   149  	st.gas -= amount
   150  
   151  	return nil
   152  }
   153  
   154  func (st *StateTransition) buyGas() error {
   155  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   156  	if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
   157  		return errInsufficientBalanceForGas
   158  	}
   159  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   160  		return err
   161  	}
   162  	st.gas += st.msg.Gas()
   163  
   164  	st.initialGas = st.msg.Gas()
   165  	st.state.SubBalance(st.msg.From(), mgval)
   166  	return nil
   167  }
   168  
   169  func (st *StateTransition) preCheck() error {
   170  	// Make sure this transaction's nonce is correct.
   171  	if st.msg.CheckNonce() {
   172  		nonce := st.state.GetNonce(st.msg.From())
   173  		if nonce < st.msg.Nonce() {
   174  			return ErrNonceTooHigh
   175  		} else if nonce > st.msg.Nonce() {
   176  			return ErrNonceTooLow
   177  		}
   178  	}
   179  	return st.buyGas()
   180  }
   181  
   182  // TransitionDb will transition the state by applying the current message and
   183  // returning the result including the used gas. It returns an error if failed.
   184  // An error indicates a consensus issue.
   185  func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
   186  	if err = st.preCheck(); err != nil {
   187  		return
   188  	}
   189  	msg := st.msg
   190  	sender := vm.AccountRef(msg.From())
   191  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
   192  	contractCreation := msg.To() == nil
   193  
   194  	// Pay intrinsic gas
   195  	gas, err := IntrinsicGas(st.data, contractCreation, homestead)
   196  	if err != nil {
   197  		return nil, 0, false, err
   198  	}
   199  	if err = st.useGas(gas); err != nil {
   200  		return nil, 0, false, err
   201  	}
   202  
   203  	var (
   204  		evm = st.evm
   205  		// vm errors do not effect consensus and are therefor
   206  		// not assigned to err, except for insufficient balance
   207  		// error.
   208  		vmerr error
   209  	)
   210  	if contractCreation {
   211  		ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
   212  	} else {
   213  		// Increment the nonce for the next transaction
   214  		st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
   215  		ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value)
   216  	}
   217  	if vmerr != nil {
   218  		log.Debug("VM returned with error", "err", vmerr)
   219  		// The only possible consensus-error would be if there wasn't
   220  		// sufficient balance to make the transfer happen. The first
   221  		// balance transfer may never fail.
   222  		if vmerr == vm.ErrInsufficientBalance {
   223  			return nil, 0, false, vmerr
   224  		}
   225  	}
   226  	st.refundGas()
   227  	st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   228  
   229  	return ret, st.gasUsed(), vmerr != nil, err
   230  }
   231  
   232  func (st *StateTransition) refundGas() {
   233  	// Apply refund counter, capped to half of the used gas.
   234  	refund := st.gasUsed() / 2
   235  	if refund > st.state.GetRefund() {
   236  		refund = st.state.GetRefund()
   237  	}
   238  	st.gas += refund
   239  
   240  	// Return ETH for remaining gas, exchanged at the original rate.
   241  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   242  	st.state.AddBalance(st.msg.From(), remaining)
   243  
   244  	// Also return remaining gas to the block gas counter so it is
   245  	// available for the next transaction.
   246  	st.gp.AddGas(st.gas)
   247  }
   248  
   249  // gasUsed returns the amount of gas used up by the state transition.
   250  func (st *StateTransition) gasUsed() uint64 {
   251  	return st.initialGas - st.gas
   252  }