github.com/baptiste-b-pegasys/quorum/v22@v22.4.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  	"fmt"
    22  	"math"
    23  	"math/big"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/core/state"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/core/vm"
    29  	"github.com/ethereum/go-ethereum/log"
    30  	"github.com/ethereum/go-ethereum/multitenancy"
    31  	"github.com/ethereum/go-ethereum/params"
    32  	"github.com/ethereum/go-ethereum/private"
    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 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      vm.StateDB
    61  	evm        *vm.EVM
    62  }
    63  
    64  // Message represents a message sent to a contract.
    65  type Message interface {
    66  	From() common.Address
    67  	To() *common.Address
    68  
    69  	GasPrice() *big.Int
    70  	Gas() uint64
    71  	Value() *big.Int
    72  
    73  	Nonce() uint64
    74  	CheckNonce() bool
    75  	Data() []byte
    76  	AccessList() types.AccessList
    77  }
    78  
    79  // ExecutionResult includes all output after executing given evm
    80  // message no matter the execution itself is successful or not.
    81  type ExecutionResult struct {
    82  	UsedGas    uint64 // Total used gas but include the refunded gas
    83  	Err        error  // Any error encountered during the execution(listed in core/vm/errors.go)
    84  	ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
    85  }
    86  
    87  // Unwrap returns the internal evm error which allows us for further
    88  // analysis outside.
    89  func (result *ExecutionResult) Unwrap() error {
    90  	return result.Err
    91  }
    92  
    93  // Failed returns the indicator whether the execution is successful or not
    94  func (result *ExecutionResult) Failed() bool { return result.Err != nil }
    95  
    96  // Return is a helper function to help caller distinguish between revert reason
    97  // and function return. Return returns the data after execution if no error occurs.
    98  func (result *ExecutionResult) Return() []byte {
    99  	if result.Err != nil {
   100  		return nil
   101  	}
   102  	return common.CopyBytes(result.ReturnData)
   103  }
   104  
   105  // Revert returns the concrete revert reason if the execution is aborted by `REVERT`
   106  // opcode. Note the reason can be nil if no data supplied with revert opcode.
   107  func (result *ExecutionResult) Revert() []byte {
   108  	if result.Err != vm.ErrExecutionReverted {
   109  		return nil
   110  	}
   111  	return common.CopyBytes(result.ReturnData)
   112  }
   113  
   114  // PrivateMessage implements a private message
   115  type PrivateMessage interface {
   116  	Message
   117  	IsPrivate() bool
   118  }
   119  
   120  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
   121  func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool) (uint64, error) {
   122  	// Set the starting gas for the raw transaction
   123  	var gas uint64
   124  	if isContractCreation && isHomestead {
   125  		gas = params.TxGasContractCreation
   126  	} else {
   127  		gas = params.TxGas
   128  	}
   129  	// Bump the required gas by the amount of transactional data
   130  	if len(data) > 0 {
   131  		// Zero and non-zero bytes are priced differently
   132  		var nz uint64
   133  		for _, byt := range data {
   134  			if byt != 0 {
   135  				nz++
   136  			}
   137  		}
   138  		// Make sure we don't exceed uint64 for all data combinations
   139  		nonZeroGas := params.TxDataNonZeroGasFrontier
   140  		if isEIP2028 {
   141  			nonZeroGas = params.TxDataNonZeroGasEIP2028
   142  		}
   143  		if (math.MaxUint64-gas)/nonZeroGas < nz {
   144  			return 0, ErrGasUintOverflow
   145  		}
   146  		gas += nz * nonZeroGas
   147  
   148  		z := uint64(len(data)) - nz
   149  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   150  			return 0, ErrGasUintOverflow
   151  		}
   152  		gas += z * params.TxDataZeroGas
   153  	}
   154  	if accessList != nil {
   155  		gas += uint64(len(accessList)) * params.TxAccessListAddressGas
   156  		gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
   157  	}
   158  	return gas, nil
   159  }
   160  
   161  // NewStateTransition initialises and returns a new state transition object.
   162  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   163  	return &StateTransition{
   164  		gp:       gp,
   165  		evm:      evm,
   166  		msg:      msg,
   167  		gasPrice: msg.GasPrice(),
   168  		value:    msg.Value(),
   169  		data:     msg.Data(),
   170  		state:    evm.PublicState(),
   171  	}
   172  }
   173  
   174  // ApplyMessage computes the new state by applying the given message
   175  // against the old state within the environment.
   176  //
   177  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   178  // the gas used (which includes gas refunds) and an error if it failed. An error always
   179  // indicates a core error meaning that the message would always fail for that particular
   180  // state and would never be accepted within a block.
   181  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
   182  	return NewStateTransition(evm, msg, gp).TransitionDb()
   183  }
   184  
   185  // to returns the recipient of the message.
   186  func (st *StateTransition) to() common.Address {
   187  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   188  		return common.Address{}
   189  	}
   190  	return *st.msg.To()
   191  }
   192  
   193  func (st *StateTransition) buyGas() error {
   194  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   195  	if have, want := st.state.GetBalance(st.msg.From()), mgval; have.Cmp(want) < 0 {
   196  		return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want)
   197  	}
   198  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   199  		return err
   200  	}
   201  	st.gas += st.msg.Gas()
   202  
   203  	st.initialGas = st.msg.Gas()
   204  	st.state.SubBalance(st.msg.From(), mgval)
   205  	return nil
   206  }
   207  
   208  func (st *StateTransition) preCheck() error {
   209  	// Make sure this transaction's nonce is correct.
   210  	if st.msg.CheckNonce() {
   211  		stNonce := st.state.GetNonce(st.msg.From())
   212  		if msgNonce := st.msg.Nonce(); stNonce < msgNonce {
   213  			return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh,
   214  				st.msg.From().Hex(), msgNonce, stNonce)
   215  		} else if stNonce > msgNonce {
   216  			return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow,
   217  				st.msg.From().Hex(), msgNonce, stNonce)
   218  		}
   219  	}
   220  	return st.buyGas()
   221  }
   222  
   223  // TransitionDb will transition the state by applying the current message and
   224  // returning the evm execution result with following fields.
   225  //
   226  // - used gas:
   227  //      total gas used (including gas being refunded)
   228  // - returndata:
   229  //      the returned data from evm
   230  // - concrete execution error:
   231  //      various **EVM** error which aborts the execution,
   232  //      e.g. ErrOutOfGas, ErrExecutionReverted
   233  //
   234  // However if any consensus issue encountered, return the error directly with
   235  // nil evm execution result.
   236  //
   237  // Quorum:
   238  // 1. Intrinsic gas is calculated based on the encrypted payload hash
   239  //    and NOT the actual private payload.
   240  // 2. For private transactions, we only deduct intrinsic gas from the gas pool
   241  //    regardless the current node is party to the transaction or not.
   242  // 3. For privacy marker transactions, we only deduct the PMT gas from the gas pool. No gas is deducted
   243  //    for the internal private transaction, regardless of whether the current node is a party.
   244  // 4. With multitenancy support, we enforce the party set in the contract index must contain all
   245  //    parties from the transaction. This is to detect unauthorized access from a legit proxy contract
   246  //    to an unauthorized contract.
   247  func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
   248  	// First check this message satisfies all consensus rules before
   249  	// applying the message. The rules include these clauses
   250  	//
   251  	// 1. the nonce of the message caller is correct
   252  	// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
   253  	// 3. the amount of gas required is available in the block
   254  	// 4. the purchased gas is enough to cover intrinsic usage
   255  	// 5. there is no overflow when calculating intrinsic gas
   256  	// 6. caller has enough balance to cover asset transfer for **topmost** call
   257  
   258  	// Check clauses 1-3, buy gas if everything is correct
   259  	var err error
   260  	if err = st.preCheck(); err != nil {
   261  		return nil, err
   262  	}
   263  	msg := st.msg
   264  	sender := vm.AccountRef(msg.From())
   265  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
   266  	istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
   267  	contractCreation := msg.To() == nil
   268  	isQuorum := st.evm.ChainConfig().IsQuorum
   269  	snapshot := st.evm.StateDB.Snapshot()
   270  
   271  	var data []byte
   272  	isPrivate := false
   273  	publicState := st.state
   274  	pmh := newPMH(st)
   275  	if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() {
   276  		isPrivate = true
   277  		pmh.snapshot = snapshot
   278  		pmh.eph = common.BytesToEncryptedPayloadHash(st.data)
   279  		_, _, data, pmh.receivedPrivacyMetadata, err = private.P.Receive(pmh.eph)
   280  		// Increment the public account nonce if:
   281  		// 1. Tx is private and *not* a participant of the group and either call or create
   282  		// 2. Tx is private we are part of the group and is a call
   283  		if err != nil || !contractCreation {
   284  			publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1)
   285  		}
   286  		if err != nil {
   287  			return &ExecutionResult{
   288  				UsedGas:    0,
   289  				Err:        nil,
   290  				ReturnData: nil,
   291  			}, nil
   292  		}
   293  
   294  		pmh.hasPrivatePayload = data != nil
   295  
   296  		vmErr, consensusErr := pmh.prepare()
   297  		if consensusErr != nil || vmErr != nil {
   298  			return &ExecutionResult{
   299  				UsedGas:    0,
   300  				Err:        vmErr,
   301  				ReturnData: nil,
   302  			}, consensusErr
   303  		}
   304  	} else {
   305  		data = st.data
   306  	}
   307  
   308  	// Pay intrinsic gas. For a private contract this is done using the public hash passed in,
   309  	// not the private data retrieved above. This is because we need any (participant) validator
   310  	// node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues.
   311  	// Check clauses 4-5, subtract intrinsic gas if everything is correct
   312  	gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul)
   313  	if err != nil {
   314  		return nil, err
   315  	}
   316  	if st.gas < gas {
   317  		return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
   318  	}
   319  	st.gas -= gas
   320  
   321  	// Check clause 6
   322  	if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
   323  		return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
   324  	}
   325  
   326  	// Set up the initial access list.
   327  	if st.evm.ChainConfig().IsBerlin(st.evm.Context.BlockNumber) {
   328  		st.state.PrepareAccessList(msg.From(), msg.To(), st.evm.ActivePrecompiles(), msg.AccessList())
   329  	}
   330  
   331  	var (
   332  		leftoverGas uint64
   333  		evm         = st.evm
   334  		ret         []byte
   335  		// vm errors do not effect consensus and are therefor
   336  		// not assigned to err, except for insufficient balance
   337  		// error.
   338  		vmerr error
   339  	)
   340  	if contractCreation {
   341  		ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value)
   342  	} else {
   343  		// Increment the account nonce only if the transaction isn't private.
   344  		// If the transaction is private it has already been incremented on
   345  		// the public state.
   346  		if !isPrivate {
   347  			publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1)
   348  		}
   349  		var to common.Address
   350  		if isQuorum {
   351  			to = *st.msg.To()
   352  		} else {
   353  			to = st.to()
   354  		}
   355  		//if input is empty for the smart contract call, return
   356  		if len(data) == 0 && isPrivate {
   357  			st.refundGas()
   358  			st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   359  			return &ExecutionResult{
   360  				UsedGas:    0,
   361  				Err:        nil,
   362  				ReturnData: nil,
   363  			}, nil
   364  		}
   365  
   366  		ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value)
   367  	}
   368  	if vmerr != nil {
   369  		log.Info("VM returned with error", "err", vmerr)
   370  		// The only possible consensus-error would be if there wasn't
   371  		// sufficient balance to make the transfer happen. The first
   372  		// balance transfer may never fail.
   373  		if vmerr == vm.ErrInsufficientBalance {
   374  			return nil, vmerr
   375  		}
   376  		if errors.Is(vmerr, multitenancy.ErrNotAuthorized) {
   377  			return nil, vmerr
   378  		}
   379  	}
   380  
   381  	// Quorum - Privacy Enhancements
   382  	// perform privacy enhancements checks
   383  	if pmh.mustVerify() {
   384  		var exitEarly bool
   385  		exitEarly, err = pmh.verify(vmerr)
   386  		if exitEarly {
   387  			return &ExecutionResult{
   388  				UsedGas:    0,
   389  				Err:        ErrPrivateContractInteractionVerificationFailed,
   390  				ReturnData: nil,
   391  			}, err
   392  		}
   393  	}
   394  	// End Quorum - Privacy Enhancements
   395  
   396  	// Pay gas used during contract creation or execution (st.gas tracks remaining gas)
   397  	// However, if private contract then we don't want to do this else we can get
   398  	// a mismatch between a (non-participant) minter and (participant) validator,
   399  	// which can cause a 'BAD BLOCK' crash.
   400  	if !isPrivate {
   401  		st.gas = leftoverGas
   402  	}
   403  	// End Quorum
   404  
   405  	st.refundGas()
   406  	st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   407  
   408  	if isPrivate {
   409  		return &ExecutionResult{
   410  			UsedGas:    0,
   411  			Err:        vmerr,
   412  			ReturnData: ret,
   413  		}, err
   414  	}
   415  	// End Quorum
   416  
   417  	return &ExecutionResult{
   418  		UsedGas:    st.gasUsed(),
   419  		Err:        vmerr,
   420  		ReturnData: ret,
   421  	}, nil
   422  }
   423  
   424  func (st *StateTransition) refundGas() {
   425  	// Apply refund counter, capped to half of the used gas.
   426  	refund := st.gasUsed() / 2
   427  	if refund > st.state.GetRefund() {
   428  		refund = st.state.GetRefund()
   429  	}
   430  	st.gas += refund
   431  
   432  	// Return ETH for remaining gas, exchanged at the original rate.
   433  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   434  	st.state.AddBalance(st.msg.From(), remaining)
   435  
   436  	// Also return remaining gas to the block gas counter so it is
   437  	// available for the next transaction.
   438  	st.gp.AddGas(st.gas)
   439  }
   440  
   441  // gasUsed returns the amount of gas used up by the state transition.
   442  func (st *StateTransition) gasUsed() uint64 {
   443  	return st.initialGas - st.gas
   444  }
   445  
   446  // Quorum - Privacy Enhancements - implement the pmcStateTransitionAPI interface
   447  func (st *StateTransition) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
   448  	st.evm.SetTxPrivacyMetadata(pm)
   449  }
   450  func (st *StateTransition) IsPrivacyEnhancementsEnabled() bool {
   451  	return st.evm.ChainConfig().IsPrivacyEnhancementsEnabled(st.evm.Context.BlockNumber)
   452  }
   453  func (st *StateTransition) RevertToSnapshot(snapshot int) {
   454  	st.evm.StateDB.RevertToSnapshot(snapshot)
   455  }
   456  func (st *StateTransition) GetStatePrivacyMetadata(addr common.Address) (*state.PrivacyMetadata, error) {
   457  	return st.evm.StateDB.GetPrivacyMetadata(addr)
   458  }
   459  func (st *StateTransition) CalculateMerkleRoot() (common.Hash, error) {
   460  	return st.evm.CalculateMerkleRoot()
   461  }
   462  func (st *StateTransition) AffectedContracts() []common.Address {
   463  	return st.evm.AffectedContracts()
   464  }
   465  
   466  // End Quorum - Privacy Enhancements