github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/core/vm/evm.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 vm
    18  
    19  import (
    20  	"math/big"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/params"
    27  )
    28  
    29  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    30  // deployed contract addresses (relevant after the account abstraction).
    31  var emptyCodeHash = crypto.Keccak256Hash(nil)
    32  
    33  type (
    34  	// CanTransferFunc is the signature of a transfer guard function
    35  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    36  	// TransferFunc is the signature of a transfer function
    37  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    38  	// GetHashFunc returns the nth block hash in the blockchain
    39  	// and is used by the BLOCKHASH EVM op code.
    40  	GetHashFunc func(uint64) common.Hash
    41  )
    42  
    43  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    44  func run(evm *EVM, contract *Contract, input []byte) ([]byte, error) {
    45  	if contract.CodeAddr != nil {
    46  		precompiles := PrecompiledContractsHomestead
    47  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
    48  			precompiles = PrecompiledContractsByzantium
    49  		}
    50  		if p := precompiles[*contract.CodeAddr]; p != nil {
    51  			// 运行预编译合约
    52  			return RunPrecompiledContract(p, input, contract)
    53  		}
    54  	}
    55  	// 解释器执行合约代码
    56  	return evm.interpreter.Run(contract, input)
    57  }
    58  
    59  // Context provides the EVM with auxiliary information. Once provided
    60  // it shouldn't be modified.
    61  // Context为EVM提供辅助信息。提供后,不应被修改
    62  type Context struct {
    63  	// CanTransfer returns whether the account contains
    64  	// sufficient ether to transfer the value
    65  	// 返回账户是否包含足够的用来传输的以太币
    66  	CanTransfer CanTransferFunc
    67  	// Transfer transfers ether from one account to the other
    68  	// 完成转账的函数 将以太从一个帐户转移到另一个帐户
    69  	Transfer TransferFunc
    70  	// GetHash returns the hash corresponding to n
    71  	GetHash GetHashFunc
    72  
    73  	// Message information
    74  	// 消息相关信息
    75  	Origin   common.Address // Provides information for ORIGIN
    76  	GasPrice *big.Int       // Provides information for GASPRICE
    77  
    78  	// Block information
    79  	// 区块相关信息
    80  	Coinbase    common.Address // Provides information for COINBASE
    81  	GasLimit    uint64         // Provides information for GASLIMIT
    82  	BlockNumber *big.Int       // Provides information for NUMBER
    83  	Time        *big.Int       // Provides information for TIME
    84  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    85  }
    86  
    87  // EVM is the Ethereum Virtual Machine base object and provides
    88  // the necessary tools to run a contract on the given state with
    89  // the provided context. It should be noted that any error
    90  // generated through any of the calls should be considered a
    91  // revert-state-and-consume-all-gas operation, no checks on
    92  // specific errors should ever be performed. The interpreter makes
    93  // sure that any errors generated are to be considered faulty code.
    94  //
    95  // The EVM should never be reused and is not thread safe.
    96  // // EVM是以太坊虚拟机基础对象,并提供必要的工具,以使用提供的上下文运行给定状态的合约。
    97  // 应该指出的是,任何调用产生的任何错误都应该被认为是一种回滚修改状态和消耗所有GAS操作,
    98  // 不应该执行对具体错误的检查。 解释器确保生成的任何错误都被认为是错误的代码。
    99  type EVM struct {
   100  	// Context provides auxiliary blockchain related information
   101  	// 辅助信息对象(包括GasPrice,GasLimit,BlockNumber等信息)
   102  	Context
   103  	// StateDB gives access to the underlying state
   104  	// 为EVM提供StateDB相关操作
   105  	StateDB StateDB
   106  	// Depth is the current call stack
   107  	// 当前调用的栈深度
   108  	depth int
   109  
   110  	// chainConfig contains information about the current chain
   111  	// 链配置信息
   112  	chainConfig *params.ChainConfig
   113  	// chain rules contains the chain rules for the current epoch
   114  	// 链规则
   115  	chainRules params.Rules
   116  	// virtual machine configuration options used to initialise the
   117  	// evm.
   118  	// 虚拟机配置
   119  	vmConfig Config
   120  	// global (to this context) ethereum virtual machine
   121  	// used throughout the execution of the tx.
   122  	// 解释器
   123  	interpreter *Interpreter
   124  	// abort is used to abort the EVM calling operations
   125  	// NOTE: must be set atomically
   126  	// 用于中止EVM调用操作
   127  	abort int32
   128  	// callGasTemp holds the gas available for the current call. This is needed because the
   129  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   130  	// applied in opCall*.
   131  	// 当前call可用的gas
   132  	callGasTemp uint64
   133  }
   134  
   135  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   136  // only ever be used *once*.
   137  // 2.创建EVM对象
   138  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   139  	evm := &EVM{
   140  		Context:     ctx,
   141  		StateDB:     statedb,
   142  		vmConfig:    vmConfig,
   143  		chainConfig: chainConfig,
   144  		chainRules:  chainConfig.Rules(ctx.BlockNumber),
   145  	}
   146  
   147  	// 3.创建EVM解释器
   148  	evm.interpreter = NewInterpreter(evm, vmConfig)
   149  	return evm
   150  }
   151  
   152  // Cancel cancels any running EVM operation. This may be called concurrently and
   153  // it's safe to be called multiple times.
   154  func (evm *EVM) Cancel() {
   155  	atomic.StoreInt32(&evm.abort, 1)
   156  }
   157  
   158  // Call executes the contract associated with the addr with the given input as
   159  // parameters. It also handles any necessary value transfer required and takes
   160  // the necessary steps to create accounts and reverses the state in case of an
   161  // execution error or failed value transfer.
   162  // 使用给定输入作为参数执行与addr关联的合约
   163  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   164  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   165  		return nil, gas, nil
   166  	}
   167  
   168  	// Fail if we're trying to execute above the call depth limit
   169  	if evm.depth > int(params.CallCreateDepth) {
   170  		return nil, gas, ErrDepth
   171  	}
   172  	// Fail if we're trying to transfer more than the available balance
   173  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   174  		return nil, gas, ErrInsufficientBalance
   175  	}
   176  
   177  	var (
   178  		to       = AccountRef(addr)
   179  		snapshot = evm.StateDB.Snapshot()
   180  	)
   181  	if !evm.StateDB.Exist(addr) {
   182  		precompiles := PrecompiledContractsHomestead
   183  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   184  			precompiles = PrecompiledContractsByzantium
   185  		}
   186  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   187  			// Calling a non existing account, don't do antything, but ping the tracer
   188  			if evm.vmConfig.Debug && evm.depth == 0 {
   189  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   190  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   191  			}
   192  			return nil, gas, nil
   193  		}
   194  		evm.StateDB.CreateAccount(addr)
   195  	}
   196  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   197  
   198  	// Initialise a new contract and set the code that is to be used by the EVM.
   199  	// The contract is a scoped environment for this execution context only.
   200  	contract := NewContract(caller, to, value, gas)
   201  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   202  
   203  	start := time.Now()
   204  
   205  	// Capture the tracer start/end events in debug mode
   206  	if evm.vmConfig.Debug && evm.depth == 0 {
   207  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   208  
   209  		defer func() { // Lazy evaluation of the parameters
   210  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   211  		}()
   212  	}
   213  	ret, err = run(evm, contract, input)
   214  
   215  	// When an error was returned by the EVM or when setting the creation code
   216  	// above we revert to the snapshot and consume any gas remaining. Additionally
   217  	// when we're in homestead this also counts for code storage gas errors.
   218  	if err != nil {
   219  		evm.StateDB.RevertToSnapshot(snapshot)
   220  		if err != errExecutionReverted {
   221  			contract.UseGas(contract.Gas)
   222  		}
   223  	}
   224  	return ret, contract.Gas, err
   225  }
   226  
   227  // CallCode executes the contract associated with the addr with the given input
   228  // as parameters. It also handles any necessary value transfer required and takes
   229  // the necessary steps to create accounts and reverses the state in case of an
   230  // execution error or failed value transfer.
   231  //
   232  // CallCode differs from Call in the sense that it executes the given address'
   233  // code with the caller as context.
   234  //
   235  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   236  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   237  		return nil, gas, nil
   238  	}
   239  
   240  	// Fail if we're trying to execute above the call depth limit
   241  	if evm.depth > int(params.CallCreateDepth) {
   242  		return nil, gas, ErrDepth
   243  	}
   244  	// Fail if we're trying to transfer more than the available balance
   245  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   246  		return nil, gas, ErrInsufficientBalance
   247  	}
   248  
   249  	var (
   250  		snapshot = evm.StateDB.Snapshot()
   251  		to       = AccountRef(caller.Address())
   252  	)
   253  	// initialise a new contract and set the code that is to be used by the
   254  	// EVM. The contract is a scoped environment for this execution context
   255  	// only.
   256  	contract := NewContract(caller, to, value, gas)
   257  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   258  
   259  	ret, err = run(evm, contract, input)
   260  	if err != nil {
   261  		evm.StateDB.RevertToSnapshot(snapshot)
   262  		if err != errExecutionReverted {
   263  			contract.UseGas(contract.Gas)
   264  		}
   265  	}
   266  	return ret, contract.Gas, err
   267  }
   268  
   269  // DelegateCall executes the contract associated with the addr with the given input
   270  // as parameters. It reverses the state in case of an execution error.
   271  //
   272  // DelegateCall differs from CallCode in the sense that it executes the given address'
   273  // code with the caller as context and the caller is set to the caller of the caller.
   274  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   275  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   276  		return nil, gas, nil
   277  	}
   278  	// Fail if we're trying to execute above the call depth limit
   279  	if evm.depth > int(params.CallCreateDepth) {
   280  		return nil, gas, ErrDepth
   281  	}
   282  
   283  	var (
   284  		snapshot = evm.StateDB.Snapshot()
   285  		to       = AccountRef(caller.Address())
   286  	)
   287  
   288  	// Initialise a new contract and make initialise the delegate values
   289  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   290  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   291  
   292  	ret, err = run(evm, contract, input)
   293  	if err != nil {
   294  		evm.StateDB.RevertToSnapshot(snapshot)
   295  		if err != errExecutionReverted {
   296  			contract.UseGas(contract.Gas)
   297  		}
   298  	}
   299  	return ret, contract.Gas, err
   300  }
   301  
   302  // StaticCall executes the contract associated with the addr with the given input
   303  // as parameters while disallowing any modifications to the state during the call.
   304  // Opcodes that attempt to perform such modifications will result in exceptions
   305  // instead of performing the modifications.
   306  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   307  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   308  		return nil, gas, nil
   309  	}
   310  	// Fail if we're trying to execute above the call depth limit
   311  	if evm.depth > int(params.CallCreateDepth) {
   312  		return nil, gas, ErrDepth
   313  	}
   314  	// Make sure the readonly is only set if we aren't in readonly yet
   315  	// this makes also sure that the readonly flag isn't removed for
   316  	// child calls.
   317  	if !evm.interpreter.readOnly {
   318  		evm.interpreter.readOnly = true
   319  		defer func() { evm.interpreter.readOnly = false }()
   320  	}
   321  
   322  	var (
   323  		to       = AccountRef(addr)
   324  		snapshot = evm.StateDB.Snapshot()
   325  	)
   326  	// Initialise a new contract and set the code that is to be used by the
   327  	// EVM. The contract is a scoped environment for this execution context
   328  	// only.
   329  	contract := NewContract(caller, to, new(big.Int), gas)
   330  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   331  
   332  	// When an error was returned by the EVM or when setting the creation code
   333  	// above we revert to the snapshot and consume any gas remaining. Additionally
   334  	// when we're in Homestead this also counts for code storage gas errors.
   335  	ret, err = run(evm, contract, input)
   336  	if err != nil {
   337  		evm.StateDB.RevertToSnapshot(snapshot)
   338  		if err != errExecutionReverted {
   339  			contract.UseGas(contract.Gas)
   340  		}
   341  	}
   342  	return ret, contract.Gas, err
   343  }
   344  
   345  // Create creates a new contract using code as deployment code.
   346  // 创建合约
   347  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   348  
   349  	// Depth check execution. Fail if we're trying to execute above the
   350  	// limit.
   351  	// 执行深度检查,如果超出设定的深度限制  创建失败
   352  	if evm.depth > int(params.CallCreateDepth) {
   353  		return nil, common.Address{}, gas, ErrDepth
   354  	}
   355  	// 账户余额不足,创建失败
   356  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   357  		return nil, common.Address{}, gas, ErrInsufficientBalance
   358  	}
   359  	// Ensure there's no existing contract already at the designated address
   360  	// 确保指定地址没有已存在的相同合约
   361  	nonce := evm.StateDB.GetNonce(caller.Address())
   362  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   363  
   364  	// 创建合约地址
   365  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   366  	contractHash := evm.StateDB.GetCodeHash(contractAddr)
   367  	if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   368  		return nil, common.Address{}, 0, ErrContractAddressCollision
   369  	}
   370  	// Create a new account on the state
   371  	// 创建数据库快照,为了迅速回滚
   372  	snapshot := evm.StateDB.Snapshot()
   373  	// 在当前状态新建合约账户
   374  	evm.StateDB.CreateAccount(contractAddr)
   375  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   376  		evm.StateDB.SetNonce(contractAddr, 1)
   377  	}
   378  	// 转账操作
   379  	evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
   380  
   381  	// initialise a new contract and set the code that is to be used by the
   382  	// EVM. The contract is a scoped environment for this execution context
   383  	// only.
   384  	// 创建合约
   385  	contract := NewContract(caller, AccountRef(contractAddr), value, gas)
   386  	// 设置合约代码
   387  	contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code)
   388  
   389  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   390  		return nil, contractAddr, gas, nil
   391  	}
   392  
   393  	if evm.vmConfig.Debug && evm.depth == 0 {
   394  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), contractAddr, true, code, gas, value)
   395  	}
   396  	start := time.Now()
   397  
   398  	// 执行合约的初始化
   399  	ret, err = run(evm, contract, nil)
   400  
   401  	// check whether the max code size has been exceeded
   402  	// 检查初始化生成的代码长度是否超过限制
   403  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   404  	// if the contract creation ran successfully and no errors were returned
   405  	// calculate the gas required to store the code. If the code could not
   406  	// be stored due to not enough gas set an error and let it be handled
   407  	// by the error checking condition below.
   408  	// 合约创建成功
   409  	if err == nil && !maxCodeSizeExceeded {
   410  		// 计算存储代码所需要的Gas
   411  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   412  		if contract.UseGas(createDataGas) {
   413  			evm.StateDB.SetCode(contractAddr, ret)
   414  		} else {
   415  			// 当前拥有的Gas不足以存储代码
   416  			err = ErrCodeStoreOutOfGas
   417  		}
   418  	}
   419  
   420  	// When an error was returned by the EVM or when setting the creation code
   421  	// above we revert to the snapshot and consume any gas remaining. Additionally
   422  	// when we're in homestead this also counts for code storage gas errors.
   423  	// 合约创建失败,借助上面创建的快照快速回滚
   424  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   425  		evm.StateDB.RevertToSnapshot(snapshot)
   426  		if err != errExecutionReverted {
   427  			contract.UseGas(contract.Gas)
   428  		}
   429  	}
   430  	// Assign err if contract code size exceeds the max while the err is still empty.
   431  	if maxCodeSizeExceeded && err == nil {
   432  		err = errMaxCodeSizeExceeded
   433  	}
   434  	if evm.vmConfig.Debug && evm.depth == 0 {
   435  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   436  	}
   437  	return ret, contractAddr, contract.Gas, err
   438  }
   439  
   440  // ChainConfig returns the environment's chain configuration
   441  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   442  
   443  // Interpreter returns the EVM interpreter
   444  func (evm *EVM) Interpreter() *Interpreter { return evm.interpreter }