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