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