github.com/ethereum/go-ethereum@v1.14.4-0.20240516095835-473ee8fc07a3/core/vm/contract.go (about)

     1  // Copyright 2015 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 vm
    18  
    19  import (
    20  	"github.com/ethereum/go-ethereum/common"
    21  	"github.com/ethereum/go-ethereum/core/tracing"
    22  	"github.com/holiman/uint256"
    23  )
    24  
    25  // ContractRef is a reference to the contract's backing object
    26  type ContractRef interface {
    27  	Address() common.Address
    28  }
    29  
    30  // AccountRef implements ContractRef.
    31  //
    32  // Account references are used during EVM initialisation and
    33  // its primary use is to fetch addresses. Removing this object
    34  // proves difficult because of the cached jump destinations which
    35  // are fetched from the parent contract (i.e. the caller), which
    36  // is a ContractRef.
    37  type AccountRef common.Address
    38  
    39  // Address casts AccountRef to an Address
    40  func (ar AccountRef) Address() common.Address { return (common.Address)(ar) }
    41  
    42  // Contract represents an ethereum contract in the state database. It contains
    43  // the contract code, calling arguments. Contract implements ContractRef
    44  type Contract struct {
    45  	// CallerAddress is the result of the caller which initialised this
    46  	// contract. However when the "call method" is delegated this value
    47  	// needs to be initialised to that of the caller's caller.
    48  	CallerAddress common.Address
    49  	caller        ContractRef
    50  	self          ContractRef
    51  
    52  	jumpdests map[common.Hash]bitvec // Aggregated result of JUMPDEST analysis.
    53  	analysis  bitvec                 // Locally cached result of JUMPDEST analysis
    54  
    55  	Code     []byte
    56  	CodeHash common.Hash
    57  	CodeAddr *common.Address
    58  	Input    []byte
    59  
    60  	// is the execution frame represented by this object a contract deployment
    61  	IsDeployment bool
    62  
    63  	Gas   uint64
    64  	value *uint256.Int
    65  }
    66  
    67  // NewContract returns a new contract environment for the execution of EVM.
    68  func NewContract(caller ContractRef, object ContractRef, value *uint256.Int, gas uint64) *Contract {
    69  	c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object}
    70  
    71  	if parent, ok := caller.(*Contract); ok {
    72  		// Reuse JUMPDEST analysis from parent context if available.
    73  		c.jumpdests = parent.jumpdests
    74  	} else {
    75  		c.jumpdests = make(map[common.Hash]bitvec)
    76  	}
    77  
    78  	// Gas should be a pointer so it can safely be reduced through the run
    79  	// This pointer will be off the state transition
    80  	c.Gas = gas
    81  	// ensures a value is set
    82  	c.value = value
    83  
    84  	return c
    85  }
    86  
    87  func (c *Contract) validJumpdest(dest *uint256.Int) bool {
    88  	udest, overflow := dest.Uint64WithOverflow()
    89  	// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
    90  	// Don't bother checking for JUMPDEST in that case.
    91  	if overflow || udest >= uint64(len(c.Code)) {
    92  		return false
    93  	}
    94  	// Only JUMPDESTs allowed for destinations
    95  	if OpCode(c.Code[udest]) != JUMPDEST {
    96  		return false
    97  	}
    98  	return c.isCode(udest)
    99  }
   100  
   101  // isCode returns true if the provided PC location is an actual opcode, as
   102  // opposed to a data-segment following a PUSHN operation.
   103  func (c *Contract) isCode(udest uint64) bool {
   104  	// Do we already have an analysis laying around?
   105  	if c.analysis != nil {
   106  		return c.analysis.codeSegment(udest)
   107  	}
   108  	// Do we have a contract hash already?
   109  	// If we do have a hash, that means it's a 'regular' contract. For regular
   110  	// contracts ( not temporary initcode), we store the analysis in a map
   111  	if c.CodeHash != (common.Hash{}) {
   112  		// Does parent context have the analysis?
   113  		analysis, exist := c.jumpdests[c.CodeHash]
   114  		if !exist {
   115  			// Do the analysis and save in parent context
   116  			// We do not need to store it in c.analysis
   117  			analysis = codeBitmap(c.Code)
   118  			c.jumpdests[c.CodeHash] = analysis
   119  		}
   120  		// Also stash it in current contract for faster access
   121  		c.analysis = analysis
   122  		return analysis.codeSegment(udest)
   123  	}
   124  	// We don't have the code hash, most likely a piece of initcode not already
   125  	// in state trie. In that case, we do an analysis, and save it locally, so
   126  	// we don't have to recalculate it for every JUMP instruction in the execution
   127  	// However, we don't save it within the parent context
   128  	if c.analysis == nil {
   129  		c.analysis = codeBitmap(c.Code)
   130  	}
   131  	return c.analysis.codeSegment(udest)
   132  }
   133  
   134  // AsDelegate sets the contract to be a delegate call and returns the current
   135  // contract (for chaining calls)
   136  func (c *Contract) AsDelegate() *Contract {
   137  	// NOTE: caller must, at all times be a contract. It should never happen
   138  	// that caller is something other than a Contract.
   139  	parent := c.caller.(*Contract)
   140  	c.CallerAddress = parent.CallerAddress
   141  	c.value = parent.value
   142  
   143  	return c
   144  }
   145  
   146  // GetOp returns the n'th element in the contract's byte array
   147  func (c *Contract) GetOp(n uint64) OpCode {
   148  	if n < uint64(len(c.Code)) {
   149  		return OpCode(c.Code[n])
   150  	}
   151  
   152  	return STOP
   153  }
   154  
   155  // Caller returns the caller of the contract.
   156  //
   157  // Caller will recursively call caller when the contract is a delegate
   158  // call, including that of caller's caller.
   159  func (c *Contract) Caller() common.Address {
   160  	return c.CallerAddress
   161  }
   162  
   163  // UseGas attempts the use gas and subtracts it and returns true on success
   164  func (c *Contract) UseGas(gas uint64, logger *tracing.Hooks, reason tracing.GasChangeReason) (ok bool) {
   165  	if c.Gas < gas {
   166  		return false
   167  	}
   168  	if logger != nil && logger.OnGasChange != nil && reason != tracing.GasChangeIgnored {
   169  		logger.OnGasChange(c.Gas, c.Gas-gas, reason)
   170  	}
   171  	c.Gas -= gas
   172  	return true
   173  }
   174  
   175  // RefundGas refunds gas to the contract
   176  func (c *Contract) RefundGas(gas uint64, logger *tracing.Hooks, reason tracing.GasChangeReason) {
   177  	if gas == 0 {
   178  		return
   179  	}
   180  	if logger != nil && logger.OnGasChange != nil && reason != tracing.GasChangeIgnored {
   181  		logger.OnGasChange(c.Gas, c.Gas+gas, reason)
   182  	}
   183  	c.Gas += gas
   184  }
   185  
   186  // Address returns the contracts address
   187  func (c *Contract) Address() common.Address {
   188  	return c.self.Address()
   189  }
   190  
   191  // Value returns the contract's value (sent to it from it's caller)
   192  func (c *Contract) Value() *uint256.Int {
   193  	return c.value
   194  }
   195  
   196  // SetCallCode sets the code of the contract and address of the backing data
   197  // object
   198  func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) {
   199  	c.Code = code
   200  	c.CodeHash = hash
   201  	c.CodeAddr = addr
   202  }
   203  
   204  // SetCodeOptionalHash can be used to provide code, but it's optional to provide hash.
   205  // In case hash is not provided, the jumpdest analysis will not be saved to the parent context
   206  func (c *Contract) SetCodeOptionalHash(addr *common.Address, codeAndHash *codeAndHash) {
   207  	c.Code = codeAndHash.code
   208  	c.CodeHash = codeAndHash.hash
   209  	c.CodeAddr = addr
   210  }