github.com/ccm-chain/ccmchain@v1.0.0/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/ccm-chain/ccmchain/common"
    24  	"github.com/ccm-chain/ccmchain/core/vm"
    25  	"github.com/ccm-chain/ccmchain/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) (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 (math.MaxUint64-gas)/nonZeroGas < nz {
   127  			return 0, ErrGasUintOverflow
   128  		}
   129  		gas += nz * nonZeroGas
   130  
   131  		z := uint64(len(data)) - nz
   132  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   133  			return 0, ErrGasUintOverflow
   134  		}
   135  		gas += z * params.TxDataZeroGas
   136  	}
   137  	return gas, nil
   138  }
   139  
   140  // NewStateTransition initialises and returns a new state transition object.
   141  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   142  	return &StateTransition{
   143  		gp:       gp,
   144  		evm:      evm,
   145  		msg:      msg,
   146  		gasPrice: msg.GasPrice(),
   147  		value:    msg.Value(),
   148  		data:     msg.Data(),
   149  		state:    evm.StateDB,
   150  	}
   151  }
   152  
   153  // ApplyMessage computes the new state by applying the given message
   154  // against the old state within the environment.
   155  //
   156  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   157  // the gas used (which includes gas refunds) and an error if it failed. An error always
   158  // indicates a core error meaning that the message would always fail for that particular
   159  // state and would never be accepted within a block.
   160  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
   161  	return NewStateTransition(evm, msg, gp).TransitionDb()
   162  }
   163  
   164  // to returns the recipient of the message.
   165  func (st *StateTransition) to() common.Address {
   166  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   167  		return common.Address{}
   168  	}
   169  	return *st.msg.To()
   170  }
   171  
   172  func (st *StateTransition) buyGas() error {
   173  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   174  	if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
   175  		return ErrInsufficientFunds
   176  	}
   177  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   178  		return err
   179  	}
   180  	st.gas += st.msg.Gas()
   181  
   182  	st.initialGas = st.msg.Gas()
   183  	st.state.SubBalance(st.msg.From(), mgval)
   184  	return nil
   185  }
   186  
   187  func (st *StateTransition) preCheck() error {
   188  	// Make sure this transaction's nonce is correct.
   189  	if st.msg.CheckNonce() {
   190  		nonce := st.state.GetNonce(st.msg.From())
   191  		if nonce < st.msg.Nonce() {
   192  			return ErrNonceTooHigh
   193  		} else if nonce > st.msg.Nonce() {
   194  			return ErrNonceTooLow
   195  		}
   196  	}
   197  	return st.buyGas()
   198  }
   199  
   200  // TransitionDb will transition the state by applying the current message and
   201  // returning the evm execution result with following fields.
   202  //
   203  // - used gas:
   204  //      total gas used (including gas being refunded)
   205  // - returndata:
   206  //      the returned data from evm
   207  // - concrete execution error:
   208  //      various **EVM** error which aborts the execution,
   209  //      e.g. ErrOutOfGas, ErrExecutionReverted
   210  //
   211  // However if any consensus issue encountered, return the error directly with
   212  // nil evm execution result.
   213  func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
   214  	// First check this message satisfies all consensus rules before
   215  	// applying the message. The rules include these clauses
   216  	//
   217  	// 1. the nonce of the message caller is correct
   218  	// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
   219  	// 3. the amount of gas required is available in the block
   220  	// 4. the purchased gas is enough to cover intrinsic usage
   221  	// 5. there is no overflow when calculating intrinsic gas
   222  	// 6. caller has enough balance to cover asset transfer for **topmost** call
   223  
   224  	// Check clauses 1-3, buy gas if everything is correct
   225  	if err := st.preCheck(); err != nil {
   226  		return nil, err
   227  	}
   228  	msg := st.msg
   229  	sender := vm.AccountRef(msg.From())
   230  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
   231  	contractCreation := msg.To() == nil
   232  
   233  	// Check clauses 4-5, subtract intrinsic gas if everything is correct
   234  	gas, err := IntrinsicGas(st.data, contractCreation, homestead)
   235  	if err != nil {
   236  		return nil, err
   237  	}
   238  	if st.gas < gas {
   239  		return nil, ErrIntrinsicGas
   240  	}
   241  	st.gas -= gas
   242  
   243  	// Check clause 6
   244  	if msg.Value().Sign() > 0 && !st.evm.CanTransfer(st.state, msg.From(), msg.Value()) {
   245  		return nil, ErrInsufficientFundsForTransfer
   246  	}
   247  	var (
   248  		ret   []byte
   249  		vmerr error // vm errors do not effect consensus and are therefore not assigned to err
   250  	)
   251  	if contractCreation {
   252  		ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value)
   253  	} else {
   254  		// Increment the nonce for the next transaction
   255  		st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
   256  		ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
   257  	}
   258  	st.refundGas()
   259  	st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   260  
   261  	return &ExecutionResult{
   262  		UsedGas:    st.gasUsed(),
   263  		Err:        vmerr,
   264  		ReturnData: ret,
   265  	}, nil
   266  }
   267  
   268  func (st *StateTransition) refundGas() {
   269  	// Apply refund counter, capped to half of the used gas.
   270  	refund := st.gasUsed() / 2
   271  	if refund > st.state.GetRefund() {
   272  		refund = st.state.GetRefund()
   273  	}
   274  	st.gas += refund
   275  
   276  	// Return ETH for remaining gas, exchanged at the original rate.
   277  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   278  	st.state.AddBalance(st.msg.From(), remaining)
   279  
   280  	// Also return remaining gas to the block gas counter so it is
   281  	// available for the next transaction.
   282  	st.gp.AddGas(st.gas)
   283  }
   284  
   285  // gasUsed returns the amount of gas used up by the state transition.
   286  func (st *StateTransition) gasUsed() uint64 {
   287  	return st.initialGas - st.gas
   288  }