github.com/bhs-gq/quorum-hotstuff@v21.1.0+incompatible/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  	"strings"
    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  var (
    36  	errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas")
    37  )
    38  
    39  /*
    40  The State Transitioning Model
    41  
    42  A state transition is a change made when a transaction is applied to the current world state
    43  The state transitioning model does all the necessary work to work out a valid new state root.
    44  
    45  1) Nonce handling
    46  2) Pre pay gas
    47  3) Create a new state object if the recipient is \0*32
    48  4) Value transfer
    49  == If contract creation ==
    50    4a) Attempt to run transaction data
    51    4b) If valid, use result as code for the new state object
    52  == end ==
    53  5) Run Script section
    54  6) Derive new state root
    55  */
    56  type StateTransition struct {
    57  	gp         *GasPool
    58  	msg        Message
    59  	gas        uint64
    60  	gasPrice   *big.Int
    61  	initialGas uint64
    62  	value      *big.Int
    63  	data       []byte
    64  	state      vm.StateDB
    65  	evm        *vm.EVM
    66  }
    67  
    68  // Message represents a message sent to a contract.
    69  type Message interface {
    70  	From() common.Address
    71  	//FromFrontier() (common.Address, error)
    72  	To() *common.Address
    73  
    74  	GasPrice() *big.Int
    75  	Gas() uint64
    76  	Value() *big.Int
    77  
    78  	Nonce() uint64
    79  	CheckNonce() bool
    80  	Data() []byte
    81  }
    82  
    83  // PrivateMessage implements a private message
    84  type PrivateMessage interface {
    85  	Message
    86  	IsPrivate() bool
    87  }
    88  
    89  // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
    90  func IntrinsicGas(data []byte, contractCreation, isEIP155 bool, isEIP2028 bool) (uint64, error) {
    91  	// Set the starting gas for the raw transaction
    92  	var gas uint64
    93  	if contractCreation && isEIP155 {
    94  		gas = params.TxGasContractCreation
    95  	} else {
    96  		gas = params.TxGas
    97  	}
    98  	// Bump the required gas by the amount of transactional data
    99  	if len(data) > 0 {
   100  		// Zero and non-zero bytes are priced differently
   101  		var nz uint64
   102  		for _, byt := range data {
   103  			if byt != 0 {
   104  				nz++
   105  			}
   106  		}
   107  		// Make sure we don't exceed uint64 for all data combinations
   108  		nonZeroGas := params.TxDataNonZeroGasFrontier
   109  		if isEIP2028 {
   110  			nonZeroGas = params.TxDataNonZeroGasEIP2028
   111  		}
   112  		if (math.MaxUint64-gas)/nonZeroGas < nz {
   113  			return 0, vm.ErrOutOfGas
   114  		}
   115  		gas += nz * nonZeroGas
   116  
   117  		z := uint64(len(data)) - nz
   118  		if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
   119  			return 0, vm.ErrOutOfGas
   120  		}
   121  		gas += z * params.TxDataZeroGas
   122  	}
   123  	return gas, nil
   124  }
   125  
   126  // NewStateTransition initialises and returns a new state transition object.
   127  func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
   128  	return &StateTransition{
   129  		gp:       gp,
   130  		evm:      evm,
   131  		msg:      msg,
   132  		gasPrice: msg.GasPrice(),
   133  		value:    msg.Value(),
   134  		data:     msg.Data(),
   135  		state:    evm.PublicState(),
   136  	}
   137  }
   138  
   139  // ApplyMessage computes the new state by applying the given message
   140  // against the old state within the environment.
   141  //
   142  // ApplyMessage returns the bytes returned by any EVM execution (if it took place),
   143  // the gas used (which includes gas refunds) and an error if it failed. An error always
   144  // indicates a core error meaning that the message would always fail for that particular
   145  // state and would never be accepted within a block.
   146  
   147  func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, uint64, bool, error) {
   148  	return NewStateTransition(evm, msg, gp).TransitionDb()
   149  }
   150  
   151  // to returns the recipient of the message.
   152  func (st *StateTransition) to() common.Address {
   153  	if st.msg == nil || st.msg.To() == nil /* contract creation */ {
   154  		return common.Address{}
   155  	}
   156  	return *st.msg.To()
   157  }
   158  
   159  func (st *StateTransition) useGas(amount uint64) error {
   160  	if st.gas < amount {
   161  		return vm.ErrOutOfGas
   162  	}
   163  	st.gas -= amount
   164  
   165  	return nil
   166  }
   167  
   168  func (st *StateTransition) buyGas() error {
   169  	mgval := new(big.Int).Mul(new(big.Int).SetUint64(st.msg.Gas()), st.gasPrice)
   170  	if st.state.GetBalance(st.msg.From()).Cmp(mgval) < 0 {
   171  		return errInsufficientBalanceForGas
   172  	}
   173  	if err := st.gp.SubGas(st.msg.Gas()); err != nil {
   174  		return err
   175  	}
   176  	st.gas += st.msg.Gas()
   177  
   178  	st.initialGas = st.msg.Gas()
   179  	st.state.SubBalance(st.msg.From(), mgval)
   180  	return nil
   181  }
   182  
   183  func (st *StateTransition) preCheck() error {
   184  	// Make sure this transaction's nonce is correct.
   185  	if st.msg.CheckNonce() {
   186  		nonce := st.state.GetNonce(st.msg.From())
   187  		if nonce < st.msg.Nonce() {
   188  			return ErrNonceTooHigh
   189  		} else if nonce > st.msg.Nonce() {
   190  			return ErrNonceTooLow
   191  		}
   192  	}
   193  	return st.buyGas()
   194  }
   195  
   196  // TransitionDb will transition the state by applying the current message and
   197  // returning the result including the used gas. It returns an error if failed.
   198  // An error indicates a consensus issue.
   199  //
   200  // Quorum:
   201  // 1. Intrinsic gas is calculated based on the encrypted payload hash
   202  //    and NOT the actual private payload
   203  // 2. For private transactions, we only deduct intrinsic gas from the gas pool
   204  //    regardless the current node is party to the transaction or not
   205  // 3. With multitenancy support, we enforce the party set in the contract index must contain all
   206  //    parties from the transaction. This is to detect unauthorized access from a legit proxy contract
   207  //    to an unauthorized contract.
   208  func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
   209  	if err = st.preCheck(); err != nil {
   210  		return
   211  	}
   212  	msg := st.msg
   213  	sender := vm.AccountRef(msg.From())
   214  	homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
   215  	istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber)
   216  	contractCreation := msg.To() == nil
   217  	isQuorum := st.evm.ChainConfig().IsQuorum
   218  	snapshot := st.evm.StateDB.Snapshot()
   219  
   220  	var data []byte
   221  	var managedPartiesInTx []string
   222  	isPrivate := false
   223  	publicState := st.state
   224  	pmh := newPMH(st)
   225  	if msg, ok := msg.(PrivateMessage); ok && isQuorum && msg.IsPrivate() {
   226  		isPrivate = true
   227  		pmh.snapshot = snapshot
   228  		pmh.eph = common.BytesToEncryptedPayloadHash(st.data)
   229  		_, managedPartiesInTx, data, pmh.receivedPrivacyMetadata, err = private.P.Receive(pmh.eph)
   230  		// Increment the public account nonce if:
   231  		// 1. Tx is private and *not* a participant of the group and either call or create
   232  		// 2. Tx is private we are part of the group and is a call
   233  		if err != nil || !contractCreation {
   234  			publicState.SetNonce(sender.Address(), publicState.GetNonce(sender.Address())+1)
   235  		}
   236  
   237  		if err != nil {
   238  			return nil, 0, false, nil
   239  		}
   240  
   241  		pmh.hasPrivatePayload = data != nil
   242  
   243  		if ok, err := pmh.prepare(); !ok {
   244  			return nil, 0, true, err
   245  		}
   246  	} else {
   247  		data = st.data
   248  	}
   249  
   250  	// Pay intrinsic gas. For a private contract this is done using the public hash passed in,
   251  	// not the private data retrieved above. This is because we need any (participant) validator
   252  	// node to get the same result as a (non-participant) minter node, to avoid out-of-gas issues.
   253  	gas, err := IntrinsicGas(st.data, contractCreation, homestead, istanbul)
   254  	if err != nil {
   255  		return nil, 0, false, err
   256  	}
   257  	if err = st.useGas(gas); err != nil {
   258  		return nil, 0, false, err
   259  	}
   260  
   261  	var (
   262  		leftoverGas uint64
   263  		evm         = st.evm
   264  		// vm errors do not effect consensus and are therefor
   265  		// not assigned to err, except for insufficient balance
   266  		// error.
   267  		vmerr error
   268  	)
   269  	if contractCreation {
   270  		ret, _, leftoverGas, vmerr = evm.Create(sender, data, st.gas, st.value)
   271  	} else {
   272  		// Increment the account nonce only if the transaction isn't private.
   273  		// If the transaction is private it has already been incremented on
   274  		// the public state.
   275  		if !isPrivate {
   276  			publicState.SetNonce(msg.From(), publicState.GetNonce(sender.Address())+1)
   277  		}
   278  		var to common.Address
   279  		if isQuorum {
   280  			to = *st.msg.To()
   281  		} else {
   282  			to = st.to()
   283  		}
   284  		//if input is empty for the smart contract call, return
   285  		if len(data) == 0 && isPrivate {
   286  			st.refundGas()
   287  			st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   288  			return nil, 0, false, nil
   289  		}
   290  
   291  		ret, leftoverGas, vmerr = evm.Call(sender, to, data, st.gas, st.value)
   292  	}
   293  	if vmerr != nil {
   294  		log.Info("VM returned with error", "err", vmerr)
   295  		// The only possible consensus-error would be if there wasn't
   296  		// sufficient balance to make the transfer happen. The first
   297  		// balance transfer may never fail.
   298  		if vmerr == vm.ErrInsufficientBalance {
   299  			return nil, 0, false, vmerr
   300  		}
   301  		if errors.Is(vmerr, multitenancy.ErrNotAuthorized) {
   302  			return nil, 0, false, vmerr
   303  		}
   304  	}
   305  
   306  	// Quorum - Privacy Enhancements
   307  	// perform privacy enhancements checks
   308  	if pmh.mustVerify() {
   309  		var exitEarly = false
   310  		exitEarly, err = pmh.verify(vmerr)
   311  		if exitEarly {
   312  			return nil, 0, true, err
   313  		}
   314  	}
   315  	// End Quorum - Privacy Enhancements
   316  
   317  	// do the affected contract managed party checks
   318  	if msg, ok := msg.(PrivateMessage); ok && isQuorum && st.evm.SupportsMultitenancy && msg.IsPrivate() {
   319  		if len(managedPartiesInTx) > 0 {
   320  			for _, address := range evm.AffectedContracts() {
   321  				managedPartiesInContract, err := st.evm.StateDB.GetManagedParties(address)
   322  				if err != nil {
   323  					return nil, 0, true, err
   324  				}
   325  				// managed parties for public transactions is empty so nothing to check there
   326  				if len(managedPartiesInContract) > 0 {
   327  					if common.NotContainsAll(managedPartiesInContract, managedPartiesInTx) {
   328  						log.Debug("Managed parties check has failed for contract", "addr", address, "EPH",
   329  							pmh.eph.TerminalString(), "contractMP", managedPartiesInContract, "txMP", managedPartiesInTx)
   330  						st.evm.RevertToSnapshot(snapshot)
   331  						// TODO - see whether we can find a way to store this error and make it available via customizations to getTransactionReceipt
   332  						return nil, 0, true, nil
   333  					}
   334  				}
   335  			}
   336  		}
   337  	}
   338  
   339  	// Pay gas used during contract creation or execution (st.gas tracks remaining gas)
   340  	// However, if private contract then we don't want to do this else we can get
   341  	// a mismatch between a (non-participant) minter and (participant) validator,
   342  	// which can cause a 'BAD BLOCK' crash.
   343  	if !isPrivate {
   344  		st.gas = leftoverGas
   345  	}
   346  
   347  	st.refundGas()
   348  	st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
   349  
   350  	// for all contracts being created as the result of the transaction execution
   351  	// we build the index for them if multitenancy is enabled
   352  	if st.evm.SupportsMultitenancy {
   353  		addresses := evm.CreatedContracts()
   354  		for _, address := range addresses {
   355  			log.Debug("Save to extra data",
   356  				"address", strings.ToLower(address.Hex()),
   357  				"isPrivate", isPrivate,
   358  				"parties", managedPartiesInTx)
   359  			st.evm.StateDB.SetManagedParties(address, managedPartiesInTx)
   360  		}
   361  	}
   362  
   363  	if isPrivate {
   364  		return ret, 0, vmerr != nil, err
   365  	}
   366  	return ret, st.gasUsed(), vmerr != nil, err
   367  }
   368  
   369  func (st *StateTransition) refundGas() {
   370  	// Apply refund counter, capped to half of the used gas.
   371  	refund := st.gasUsed() / 2
   372  	if refund > st.state.GetRefund() {
   373  		refund = st.state.GetRefund()
   374  	}
   375  	st.gas += refund
   376  
   377  	// Return ETH for remaining gas, exchanged at the original rate.
   378  	remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
   379  	st.state.AddBalance(st.msg.From(), remaining)
   380  
   381  	// Also return remaining gas to the block gas counter so it is
   382  	// available for the next transaction.
   383  	st.gp.AddGas(st.gas)
   384  }
   385  
   386  // gasUsed returns the amount of gas used up by the state transition.
   387  func (st *StateTransition) gasUsed() uint64 {
   388  	return st.initialGas - st.gas
   389  }
   390  
   391  // Quorum - Privacy Enhancements - implement the pmcStateTransitionAPI interface
   392  func (st *StateTransition) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
   393  	st.evm.SetTxPrivacyMetadata(pm)
   394  }
   395  func (st *StateTransition) IsPrivacyEnhancementsEnabled() bool {
   396  	return st.evm.ChainConfig().IsPrivacyEnhancementsEnabled(st.evm.BlockNumber)
   397  }
   398  func (st *StateTransition) RevertToSnapshot(snapshot int) {
   399  	st.evm.StateDB.RevertToSnapshot(snapshot)
   400  }
   401  func (st *StateTransition) GetStatePrivacyMetadata(addr common.Address) (*state.PrivacyMetadata, error) {
   402  	return st.evm.StateDB.GetPrivacyMetadata(addr)
   403  }
   404  func (st *StateTransition) CalculateMerkleRoot() (common.Hash, error) {
   405  	return st.evm.CalculateMerkleRoot()
   406  }
   407  func (st *StateTransition) AffectedContracts() []common.Address {
   408  	return st.evm.AffectedContracts()
   409  }
   410  
   411  // End Quorum - Privacy Enhancements