github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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  	Gas   uint64
    61  	value *uint256.Int
    62  }
    63  
    64  // NewContract returns a new contract environment for the execution of EVM.
    65  func NewContract(caller ContractRef, object ContractRef, value *uint256.Int, gas uint64) *Contract {
    66  	c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object}
    67  
    68  	if parent, ok := caller.(*Contract); ok {
    69  		// Reuse JUMPDEST analysis from parent context if available.
    70  		c.jumpdests = parent.jumpdests
    71  	} else {
    72  		c.jumpdests = make(map[common.Hash]bitvec)
    73  	}
    74  
    75  	// Gas should be a pointer so it can safely be reduced through the run
    76  	// This pointer will be off the state transition
    77  	c.Gas = gas
    78  	// ensures a value is set
    79  	c.value = value
    80  
    81  	return c
    82  }
    83  
    84  func (c *Contract) validJumpdest(dest *uint256.Int) bool {
    85  	udest, overflow := dest.Uint64WithOverflow()
    86  	// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
    87  	// Don't bother checking for JUMPDEST in that case.
    88  	if overflow || udest >= uint64(len(c.Code)) {
    89  		return false
    90  	}
    91  	// Only JUMPDESTs allowed for destinations
    92  	if OpCode(c.Code[udest]) != JUMPDEST {
    93  		return false
    94  	}
    95  	return c.isCode(udest)
    96  }
    97  
    98  // isCode returns true if the provided PC location is an actual opcode, as
    99  // opposed to a data-segment following a PUSHN operation.
   100  func (c *Contract) isCode(udest uint64) bool {
   101  	// Do we already have an analysis laying around?
   102  	if c.analysis != nil {
   103  		return c.analysis.codeSegment(udest)
   104  	}
   105  	// Do we have a contract hash already?
   106  	// If we do have a hash, that means it's a 'regular' contract. For regular
   107  	// contracts ( not temporary initcode), we store the analysis in a map
   108  	if c.CodeHash != (common.Hash{}) {
   109  		// Does parent context have the analysis?
   110  		analysis, exist := c.jumpdests[c.CodeHash]
   111  		if !exist {
   112  			// Do the analysis and save in parent context
   113  			// We do not need to store it in c.analysis
   114  			analysis = codeBitmap(c.Code)
   115  			c.jumpdests[c.CodeHash] = analysis
   116  		}
   117  		// Also stash it in current contract for faster access
   118  		c.analysis = analysis
   119  		return analysis.codeSegment(udest)
   120  	}
   121  	// We don't have the code hash, most likely a piece of initcode not already
   122  	// in state trie. In that case, we do an analysis, and save it locally, so
   123  	// we don't have to recalculate it for every JUMP instruction in the execution
   124  	// However, we don't save it within the parent context
   125  	if c.analysis == nil {
   126  		c.analysis = codeBitmap(c.Code)
   127  	}
   128  	return c.analysis.codeSegment(udest)
   129  }
   130  
   131  // AsDelegate sets the contract to be a delegate call and returns the current
   132  // contract (for chaining calls)
   133  func (c *Contract) AsDelegate() *Contract {
   134  	// NOTE: caller must, at all times be a contract. It should never happen
   135  	// that caller is something other than a Contract.
   136  	parent := c.caller.(*Contract)
   137  	c.CallerAddress = parent.CallerAddress
   138  	c.value = parent.value
   139  
   140  	return c
   141  }
   142  
   143  // GetOp returns the n'th element in the contract's byte array
   144  func (c *Contract) GetOp(n uint64) OpCode {
   145  	if n < uint64(len(c.Code)) {
   146  		return OpCode(c.Code[n])
   147  	}
   148  
   149  	return STOP
   150  }
   151  
   152  // Caller returns the caller of the contract.
   153  //
   154  // Caller will recursively call caller when the contract is a delegate
   155  // call, including that of caller's caller.
   156  func (c *Contract) Caller() common.Address {
   157  	return c.CallerAddress
   158  }
   159  
   160  // UseGas attempts the use gas and subtracts it and returns true on success
   161  func (c *Contract) UseGas(gas uint64, logger *tracing.Hooks, reason tracing.GasChangeReason) (ok bool) {
   162  	if c.Gas < gas {
   163  		return false
   164  	}
   165  	if logger != nil && logger.OnGasChange != nil && reason != tracing.GasChangeIgnored {
   166  		logger.OnGasChange(c.Gas, c.Gas-gas, reason)
   167  	}
   168  	c.Gas -= gas
   169  	return true
   170  }
   171  
   172  // RefundGas refunds gas to the contract
   173  func (c *Contract) RefundGas(gas uint64, logger *tracing.Hooks, reason tracing.GasChangeReason) {
   174  	if gas == 0 {
   175  		return
   176  	}
   177  	if logger != nil && logger.OnGasChange != nil && reason != tracing.GasChangeIgnored {
   178  		logger.OnGasChange(c.Gas, c.Gas+gas, reason)
   179  	}
   180  	c.Gas += gas
   181  }
   182  
   183  // Address returns the contracts address
   184  func (c *Contract) Address() common.Address {
   185  	return c.self.Address()
   186  }
   187  
   188  // Value returns the contract's value (sent to it from it's caller)
   189  func (c *Contract) Value() *uint256.Int {
   190  	return c.value
   191  }
   192  
   193  // SetCallCode sets the code of the contract and address of the backing data
   194  // object
   195  func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) {
   196  	c.Code = code
   197  	c.CodeHash = hash
   198  	c.CodeAddr = addr
   199  }
   200  
   201  // SetCodeOptionalHash can be used to provide code, but it's optional to provide hash.
   202  // In case hash is not provided, the jumpdest analysis will not be saved to the parent context
   203  func (c *Contract) SetCodeOptionalHash(addr *common.Address, codeAndHash *codeAndHash) {
   204  	c.Code = codeAndHash.code
   205  	c.CodeHash = codeAndHash.hash
   206  	c.CodeAddr = addr
   207  }