evm

package module
v0.0.0-...-328c054 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2023 License: GPL-3.0 Imports: 21 Imported by: 0

README

EVM

A reusable Ethereum Virtual Machine implementation in Go.

forkgo-ethereum Mawinor (v1.12.2).

Introduction

EVM is a Go package that provides a modular implementation of the Ethereum Virtual Machine, by abstracting dependencies and making it easy to integrate into any Ethereum-compatible blockchain.

It is based on the core EVM code from go-ethereum, but designed to be decoupled from other Ethereum specifics like State and BlockChain interfaces.

Features
  • Modular design, minimal dependencies
  • Compatible with Ethereum EVM specifications
  • Implements opcodes, gas costs, stack, memory, etc.
  • Easy integration with custom State implementations

Contributing

Contributions are welcome! Open an issue or PR.

License

EVM is released under the GNU GENERAL PUBLIC LICENSE.

Documentation

Index

Constants

View Source
const (
	GasQuickStep   uint64 = 2  // 快速操作的gas价格等级,包括对256位值的算数、位操作、SHA3等
	GasFastestStep uint64 = 3  // 最快操作的gas价格,包括访问stack的操作
	GasFastStep    uint64 = 5  // 快速操作,主要是访问内存的操作
	GasMidStep     uint64 = 8  // 中等速度操作,包括访问存储的操作
	GasSlowStep    uint64 = 10 // 慢速操作,主要包括日志相关操作
	GasExtStep     uint64 = 20 // 更慢的操作,包括外部调用等
)
View Source
const (
	DUP1 = 0x80 + iota
	DUP2
	DUP3
	DUP4
	DUP5
	DUP6
	DUP7
	DUP8
	DUP9
	DUP10
	DUP11
	DUP12
	DUP13
	DUP14
	DUP15
	DUP16 //0x8f
)

0x80 Stack 复制数据操作

View Source
const (
	SWAP1 = 0x90 + iota
	SWAP2
	SWAP3
	SWAP4
	SWAP5
	SWAP6
	SWAP7
	SWAP8
	SWAP9
	SWAP10
	SWAP11
	SWAP12
	SWAP13
	SWAP14
	SWAP15
	SWAP16 //0x9f
)

0x90 Stack 交换数据操作

View Source
const AddressLength int = 32
View Source
const HashLength int = 32

Variables

View Source
var (
	ErrOutOfGas                 = errors.New("out of gas")
	ErrCodeStoreOutOfGas        = errors.New("contract creation code storage out of gas")
	ErrDepth                    = errors.New("max call depth exceeded")
	ErrInsufficientBalance      = errors.New("insufficient balance for transfer")
	ErrContractAddressCollision = errors.New("contract common.Address collision")
	ErrExecutionReverted        = errors.New("execution reverted")
	ErrMaxInitCodeSizeExceeded  = errors.New("max initcode size exceeded")
	ErrMaxCodeSizeExceeded      = errors.New("max code size exceeded")
	ErrInvalidJump              = errors.New("invalid jump destination")
	ErrWriteProtection          = errors.New("write protection")
	ErrReturnDataOutOfBounds    = errors.New("return data out of bounds")
	ErrGasUintOverflow          = errors.New("gas uint64 overflow")
	ErrInvalidCode              = errors.New("invalid code: must not begin with 0xef")
	ErrNonceUintOverflow        = errors.New("nonce uint64 overflow")
)

List evm execution errors

View Source
var (
	PrecompiledAddressesCancun    []Address
	PrecompiledAddressesBerlin    []Address
	PrecompiledAddressesIstanbul  []Address
	PrecompiledAddressesByzantium []Address
	PrecompiledAddressesHomestead []Address
)
View Source
var PrecompiledContractsBLS = map[Address]PrecompiledContract{
	BytesToAddr([]byte{10}): &bls12381G1Add{},
	BytesToAddr([]byte{11}): &bls12381G1Mul{},
	BytesToAddr([]byte{12}): &bls12381G1MultiExp{},
	BytesToAddr([]byte{13}): &bls12381G2Add{},
	BytesToAddr([]byte{14}): &bls12381G2Mul{},
	BytesToAddr([]byte{15}): &bls12381G2MultiExp{},
	BytesToAddr([]byte{16}): &bls12381Pairing{},
	BytesToAddr([]byte{17}): &bls12381MapG1{},
	BytesToAddr([]byte{18}): &bls12381MapG2{},
}

PrecompiledContractsBLS contains the set of pre-compiled Ethereum contracts specified in EIP-2537. These are exported for testing purposes.

View Source
var PrecompiledContractsBerlin = map[Address]PrecompiledContract{
	BytesToAddr([]byte{1}): &ecrecover{},
	BytesToAddr([]byte{2}): &sha256hash{},
	BytesToAddr([]byte{3}): &ripemd160hash{},
	BytesToAddr([]byte{4}): &dataCopy{},
	BytesToAddr([]byte{5}): &bigModExp{eip2565: true},
	BytesToAddr([]byte{6}): &bn256AddIstanbul{},
	BytesToAddr([]byte{7}): &bn256ScalarMulIstanbul{},
	BytesToAddr([]byte{8}): &bn256PairingIstanbul{},
	BytesToAddr([]byte{9}): &blake2F{},
}

PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum contracts used in the Berlin release.

View Source
var PrecompiledContractsByzantium = map[Address]PrecompiledContract{
	BytesToAddr([]byte{1}): &ecrecover{},
	BytesToAddr([]byte{2}): &sha256hash{},
	BytesToAddr([]byte{3}): &ripemd160hash{},
	BytesToAddr([]byte{4}): &dataCopy{},
	BytesToAddr([]byte{5}): &bigModExp{eip2565: false},
	BytesToAddr([]byte{6}): &bn256AddByzantium{},
	BytesToAddr([]byte{7}): &bn256ScalarMulByzantium{},
	BytesToAddr([]byte{8}): &bn256PairingByzantium{},
}

PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum contracts used in the Byzantium release.

View Source
var PrecompiledContractsCancun = map[Address]PrecompiledContract{
	BytesToAddr([]byte{1}):    &ecrecover{},
	BytesToAddr([]byte{2}):    &sha256hash{},
	BytesToAddr([]byte{3}):    &ripemd160hash{},
	BytesToAddr([]byte{4}):    &dataCopy{},
	BytesToAddr([]byte{5}):    &bigModExp{eip2565: true},
	BytesToAddr([]byte{6}):    &bn256AddIstanbul{},
	BytesToAddr([]byte{7}):    &bn256ScalarMulIstanbul{},
	BytesToAddr([]byte{8}):    &bn256PairingIstanbul{},
	BytesToAddr([]byte{9}):    &blake2F{},
	BytesToAddr([]byte{0x0a}): &kzgPointEvaluation{},
}

PrecompiledContractsCancun contains the default set of pre-compiled Ethereum contracts used in the Cancun release.

View Source
var PrecompiledContractsHomestead = map[Address]PrecompiledContract{
	BytesToAddr([]byte{1}): &ecrecover{},
	BytesToAddr([]byte{2}): &sha256hash{},
	BytesToAddr([]byte{3}): &ripemd160hash{},
	BytesToAddr([]byte{4}): &dataCopy{},
}

PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum contracts used in the Frontier and Homestead releases.

View Source
var PrecompiledContractsIstanbul = map[Address]PrecompiledContract{
	BytesToAddr([]byte{1}): &ecrecover{},
	BytesToAddr([]byte{2}): &sha256hash{},
	BytesToAddr([]byte{3}): &ripemd160hash{},
	BytesToAddr([]byte{4}): &dataCopy{},
	BytesToAddr([]byte{5}): &bigModExp{eip2565: false},
	BytesToAddr([]byte{6}): &bn256AddIstanbul{},
	BytesToAddr([]byte{7}): &bn256ScalarMulIstanbul{},
	BytesToAddr([]byte{8}): &bn256PairingIstanbul{},
	BytesToAddr([]byte{9}): &blake2F{},
}

PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum contracts used in the Istanbul release.

Functions

func ActivateableEips

func ActivateableEips() []string

func AddrToBytes

func AddrToBytes(a Address) []byte

func Bytes2Hex

func Bytes2Hex(d []byte) string

func EnableEIP

func EnableEIP(eipNum int, jt *JumpTable) error

EnableEIP enables the given EIP on the config. This operation writes in-place, and callers need to ensure that the globally defined jump tables are not polluted.

func FromHex

func FromHex(s string) []byte

func HashToBytes

func HashToBytes(h Hash) []byte

func Hex2Bytes

func Hex2Bytes(str string) []byte

Hex2Bytes returns the bytes represented by the hexadecimal string str.

func Keccak256

func Keccak256(data ...[]byte) []byte

func LeftPadBytes

func LeftPadBytes(slice []byte, l int) []byte

func RightPadBytes

func RightPadBytes(slice []byte, l int) []byte

func RunPrecompiledContract

func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error)

func ValidEip

func ValidEip(eipNum int) bool

Types

type AccountRef

type AccountRef Address

func (AccountRef) Address

func (ar AccountRef) Address() Address

type Address

type Address [AddressLength]byte
var NilAddr Address = Address{}

func ActivePrecompiles

func ActivePrecompiles(rules params.Rules) []Address

ActivePrecompiles returns the precompiles enabled with the current configuration.

func BytesToAddr

func BytesToAddr(b []byte) Address

func CreateAddress

func CreateAddress(a []byte, nonce uint64) Address

func CreateAddress2

func CreateAddress2(a []byte, salt [32]byte, inithash []byte) Address

func HexToAddress

func HexToAddress(s string) Address

func (Address) Bytes

func (a Address) Bytes() []byte

func (Address) Hex

func (a Address) Hex() string

func (*Address) SetBytes

func (a *Address) SetBytes(b []byte)

type BlockContext

type BlockContext struct {
	// CanTransfer returns whether the account contains
	// sufficient ether to transfer the value
	CanTransfer CanTransferFunc
	// Transfer transfers ether from one account to the other
	Transfer TransferFunc
	// GetHash returns the hash corresponding to n
	GetHash GetHashFunc

	// Block information
	Coinbase      Address  // Provides information for COINBASE
	GasLimit      uint64   // Provides information for GASLIMIT
	BlockNumber   *big.Int // Provides information for NUMBER
	Time          uint64   // Provides information for TIME
	Difficulty    *big.Int // Provides information for DIFFICULTY
	BaseFee       *big.Int // Provides information for BASEFEE
	Random        *Hash    // Provides information for PREVRANDAO
	ExcessBlobGas *uint64  // ExcessBlobGas field in the header, needed to compute the data
}

type CallContext

type CallContext interface {
	// Call calls another contract.
	Call(env *EVM, me ContractRef, addr Address, data []byte, gas, value *big.Int) ([]byte, error)
	// CallCode takes another contracts code and execute within our own context
	CallCode(env *EVM, me ContractRef, addr Address, data []byte, gas, value *big.Int) ([]byte, error)
	// DelegateCall is same as CallCode except sender and value is propagated from parent to child scope
	DelegateCall(env *EVM, me ContractRef, addr Address, data []byte, gas *big.Int) ([]byte, error)
	// Create creates a new contract
	Create(env *EVM, me ContractRef, data []byte, gas, value *big.Int) ([]byte, Address, error)
}

CallContext provides a basic interface for the EVM calling conventions. The EVM depends on this context being implemented for doing subcalls and initialising new EVM contracts.

type CanTransferFunc

type CanTransferFunc func(StateDB, Address, *big.Int) bool

type Config

type Config struct {
	Tracer                  EVMLogger // Opcode logger
	NoBaseFee               bool      // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
	EnablePreimageRecording bool      // Enables recording of SHA3/keccak preimages
	ExtraEips               []int     // Additional EIPS that are to be enabled
}

Config are the configuration options for the Interpreter

type Contract

type Contract struct {
	// Callercommon.Address is the result of the caller which initialised this
	// contract. However when the "call method" is delegated this value
	// needs to be initialised to that of the caller's caller.
	CallerAddress Address

	Code     []byte
	CodeHash Hash
	CodeAddr *Address
	Input    []byte

	Gas uint64
	// contains filtered or unexported fields
}

func NewContract

func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uint64) *Contract

NewContract returns a new contract environment for the execution of EVM.

func (*Contract) Address

func (c *Contract) Address() Address

返回合约地址

func (*Contract) AsDelegate

func (c *Contract) AsDelegate() *Contract

将合约设置为委托调用并返回当前合约(用于链式调用)

func (*Contract) Caller

func (c *Contract) Caller() Address

返回合约调用者的地址 委托调用(DelegateCall)时,调用方将递归地调用调用方,返回调用方(合约)的调用方(合约/用户)地址

func (*Contract) GetOp

func (c *Contract) GetOp(n uint64) OpCode

GetOp returns the n'th element in the contract's byte array

func (*Contract) SetCallCode

func (c *Contract) SetCallCode(addr *Address, hash Hash, code []byte)

SetCallCode sets the code of the contract and define.Address of the backing data object

func (*Contract) SetCodeOptionalHash

func (c *Contract) SetCodeOptionalHash(addr *Address, codeAndHash *codeAndHash)

SetCodeOptionalHash can be used to provide code, but it's optional to provide hash. In case hash is not provided, the jumpdest analysis will not be saved to the parent context

func (*Contract) UseGas

func (c *Contract) UseGas(gas uint64) (ok bool)

尝试扣减gas,成功时返回true

func (*Contract) Value

func (c *Contract) Value() *big.Int

返回合约的value(从它的调用者发送给它的)

type ContractRef

type ContractRef interface {
	Address() Address
}

type EVM

type EVM struct {
	// Context provides auxiliary blockchain related information
	Context BlockContext
	TxContext
	// StateDB gives access to the underlying state
	StateDB StateDB

	// virtual machine configuration options used to initialise the
	// evm.
	Config Config
	// contains filtered or unexported fields
}

func NewEVM

func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM

func (*EVM) Call

func (evm *EVM) Call(caller ContractRef, addr Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

调用其他合约

func (*EVM) CallCode

func (evm *EVM) CallCode(caller ContractRef, addr Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

func (*EVM) Cancel

func (evm *EVM) Cancel()

Cancel cancels any running EVM operation. This may be called concurrently and it's safe to be called multiple times.

func (*EVM) Cancelled

func (evm *EVM) Cancelled() bool

Cancelled returns true if Cancel has been called

func (*EVM) Create

func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr Address, leftOverGas uint64, err error)

func (*EVM) Create2

func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr Address, leftOverGas uint64, err error)

func (*EVM) DelegateCall

func (evm *EVM) DelegateCall(caller ContractRef, addr Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

func (*EVM) Interpreter

func (evm *EVM) Interpreter() *EVMInterpreter

Interpreter returns the current interpreter

func (*EVM) Reset

func (evm *EVM) Reset(txCtx TxContext, statedb StateDB)

Reset resets the EVM with a new transaction context.Reset This is not threadsafe and should only be done very cautiously.

func (*EVM) SetBlockContext

func (evm *EVM) SetBlockContext(blockCtx BlockContext)

SetBlockContext updates the block context of the EVM.

func (*EVM) StaticCall

func (evm *EVM) StaticCall(caller ContractRef, addr Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

以给定的输入作为参数执行与addr相关联的合约, 但是不允许在调用期间对状态进行任何修改 如果试图执行修改状态的操作码将导致异常

type EVMInterpreter

type EVMInterpreter struct {
	// contains filtered or unexported fields
}

EVMInterpreter represents an EVM interpreter

func NewEVMInterpreter

func NewEVMInterpreter(evm *EVM) *EVMInterpreter

NewEVMInterpreter returns a new instance of the Interpreter.

func (*EVMInterpreter) Run

func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error)

type EVMLogger

type EVMLogger interface {
	CaptureTxStart(gasLimit uint64)
	CaptureTxEnd(restGas uint64)

	CaptureStart(env *EVM, from Address, to Address, create bool, input []byte, gas uint64, value *big.Int)
	CaptureEnd(output []byte, gasUsed uint64, err error)

	CaptureEnter(typ OpCode, from Address, to Address, input []byte, gas uint64, value *big.Int)
	CaptureExit(output []byte, gasUsed uint64, err error)

	CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error)
	CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error)
}

type ErrInvalidOpCode

type ErrInvalidOpCode struct {
	// contains filtered or unexported fields
}

ErrInvalidOpCode wraps an evm error when an invalid opcode is encountered.

func (*ErrInvalidOpCode) Error

func (e *ErrInvalidOpCode) Error() string

type ErrStackOverflow

type ErrStackOverflow struct {
	// contains filtered or unexported fields
}

ErrStackOverflow wraps an evm error when the items on the stack exceeds the maximum allowance.

func (*ErrStackOverflow) Error

func (e *ErrStackOverflow) Error() string

type ErrStackUnderflow

type ErrStackUnderflow struct {
	// contains filtered or unexported fields
}

ErrStackUnderflow wraps an evm error when the items on the stack less than the minimal requirement.

func (*ErrStackUnderflow) Error

func (e *ErrStackUnderflow) Error() string

type GetHashFunc

type GetHashFunc func(uint64) Hash

type Hash

type Hash [HashLength]byte
var (
	NilHash       Hash = Hash{}
	EmptyCodeHash Hash = Keccak256Hash(nil)
)

func BytesToHash

func BytesToHash(b []byte) Hash

func Keccak256Hash

func Keccak256Hash(data ...[]byte) (h Hash)

func (Hash) Bytes

func (h Hash) Bytes() []byte

func (*Hash) SetBytes

func (h *Hash) SetBytes(b []byte)

type JumpTable

type JumpTable [256]*operation

func LookupInstructionSet

func LookupInstructionSet(rules params.Rules) (JumpTable, error)

LookupInstructionSet returns the instructionset for the fork configured by the rules.

type KeccakState

type KeccakState interface {
	hash.Hash
	Read([]byte) (int, error)
}

func NewKeccakState

func NewKeccakState() KeccakState

type Log

type Log struct {
	// Consensus fields:
	// address of the contract that generated the event
	Address Address `json:"address"`
	// list of topics provided by the contract.
	Topics []Hash `json:"topics"`
	// supplied by the contract, usually ABI-encoded
	Data []byte `json:"data"`

	// Derived fields. These fields are filled in by the node
	// but not secured by consensus.
	// block in which the transaction was included
	BlockNumber uint64 `json:"blockNumber"`
	// hash of the transaction
	TxHash Hash `json:"transactionHash"`
	// index of the transaction in the block
	TxIndex uint `json:"transactionIndex"`
	// hash of the block in which the transaction was included
	BlockHash Hash `json:"blockHash"`
	// index of the log in the block
	Index uint `json:"logIndex"`

	// The Removed field is true if this log was reverted due to a chain reorganisation.
	// You must pay attention to this field if you receive logs through a filter query.
	Removed bool `json:"removed"`
}

func NewLog

func NewLog(addr Address, topics []Hash, data []byte, blockNumber uint64) Log

type Memory

type Memory struct {
	// contains filtered or unexported fields
}

evm的简单内存模型

func NewMemory

func NewMemory() *Memory

func (*Memory) Copy

func (m *Memory) Copy(dst, src, len uint64)

复制src位置的数据到dst位置,数据可能会覆盖 默认slice容量足够大, 否则会panic

func (*Memory) Data

func (m *Memory) Data() []byte

func (*Memory) GetCopy

func (m *Memory) GetCopy(offset, size int64) (cpy []byte)

复制Memory中指定位置的数据到新的Slice中,并返回

func (*Memory) GetPtr

func (m *Memory) GetPtr(offset, size int64) []byte

返回Memory指定位置数据的指针

func (*Memory) Len

func (m *Memory) Len() int

func (*Memory) Resize

func (m *Memory) Resize(size uint64)

func (*Memory) Set

func (m *Memory) Set(offset, size uint64, val []byte)

func (*Memory) Set32

func (m *Memory) Set32(offset uint64, val *uint256.Int)

solidity的int/int256/uint/uint256数值类型

type OpCode

type OpCode byte
const (
	STOP       OpCode = 0x0
	ADD        OpCode = 0x1
	MUL        OpCode = 0x2
	SUB        OpCode = 0x3
	DIV        OpCode = 0x4
	SDIV       OpCode = 0x5
	MOD        OpCode = 0x6
	SMOD       OpCode = 0x7
	ADDMOD     OpCode = 0x8
	MULMOD     OpCode = 0x9
	EXP        OpCode = 0xa
	SIGNEXTEND OpCode = 0xb
)

0x0 算术操作

const (
	LT     OpCode = 0x10
	GT     OpCode = 0x11
	SLT    OpCode = 0x12
	SGT    OpCode = 0x13
	EQ     OpCode = 0x14
	ISZERO OpCode = 0x15
	// 位运算
	AND  OpCode = 0x16
	OR   OpCode = 0x17
	XOR  OpCode = 0x18
	NOT  OpCode = 0x19
	BYTE OpCode = 0x1a
	SHL  OpCode = 0x1b
	SHR  OpCode = 0x1c
	SAR  OpCode = 0x1d
)

0x10 比较操作

const (
	ADDRESS        OpCode = 0x30
	BALANCE        OpCode = 0x31
	ORIGIN         OpCode = 0x32
	CALLER         OpCode = 0x33
	CALLVALUE      OpCode = 0x34
	CALLDATALOAD   OpCode = 0x35
	CALLDATASIZE   OpCode = 0x36
	CALLDATACOPY   OpCode = 0x37
	CODESIZE       OpCode = 0x38
	CODECOPY       OpCode = 0x39
	GASPRICE       OpCode = 0x3a
	EXTCODESIZE    OpCode = 0x3b
	EXTCODECOPY    OpCode = 0x3c
	RETURNDATASIZE OpCode = 0x3d
	RETURNDATACOPY OpCode = 0x3e
	EXTCODEHASH    OpCode = 0x3f
)

0x30 关闭状态

const (
	BLOCKHASH   OpCode = 0x40
	COINBASE    OpCode = 0x41
	TIMESTAMP   OpCode = 0x42
	NUMBER      OpCode = 0x43
	DIFFICULTY  OpCode = 0x44
	RANDOM      OpCode = 0x44
	PREVRANDAO  OpCode = 0x44
	GASLIMIT    OpCode = 0x45
	CHAINID     OpCode = 0x46
	SELFBALANCE OpCode = 0x47
	BASEFEE     OpCode = 0x48
	BLOBHASH    OpCode = 0x49
)

0x40 区块操作

const (
	POP      OpCode = 0x50
	MLOAD    OpCode = 0x51
	MSTORE   OpCode = 0x52
	MSTORE8  OpCode = 0x53
	SLOAD    OpCode = 0x54
	SSTORE   OpCode = 0x55
	JUMP     OpCode = 0x56
	JUMPI    OpCode = 0x57
	PC       OpCode = 0x58
	MSIZE    OpCode = 0x59
	GAS      OpCode = 0x5a
	JUMPDEST OpCode = 0x5b
	TLOAD    OpCode = 0x5c
	TSTORE   OpCode = 0x5d
	MCOPY    OpCode = 0x5e
	PUSH0    OpCode = 0x5f
)

0x50 storage和执行 操作

const (
	PUSH1 OpCode = 0x60 + iota
	PUSH2
	PUSH3
	PUSH4
	PUSH5
	PUSH6
	PUSH7
	PUSH8
	PUSH9
	PUSH10
	PUSH11
	PUSH12
	PUSH13
	PUSH14
	PUSH15
	PUSH16
	PUSH17
	PUSH18
	PUSH19
	PUSH20
	PUSH21
	PUSH22
	PUSH23
	PUSH24
	PUSH25
	PUSH26
	PUSH27
	PUSH28
	PUSH29
	PUSH30
	PUSH31
	PUSH32 //0x7f
)

0x60 Stack push数据操作

const (
	LOG0 OpCode = 0xa0 + iota
	LOG1
	LOG2
	LOG3
	LOG4
)

0xa0 日志操作

const (
	CREATE       OpCode = 0xf0
	CALL         OpCode = 0xf1
	CALLCODE     OpCode = 0xf2
	RETURN       OpCode = 0xf3
	DELEGATECALL OpCode = 0xf4
	CREATE2      OpCode = 0xf5

	STATICCALL   OpCode = 0xfa
	REVERT       OpCode = 0xfd
	INVALID      OpCode = 0xfe
	SELFDESTRUCT OpCode = 0xff
)

0xf0 关闭

const (
	KECCAK256 OpCode = 0x20
)

0x20 加密操作

func StringToOp

func StringToOp(str string) OpCode

StringToOp finds the opcode whose name is stored in `str`.

func (OpCode) String

func (op OpCode) String() string

type PrecompiledContract

type PrecompiledContract interface {
	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
}

type ScopeContext

type ScopeContext struct {
	Memory   *Memory
	Stack    *Stack
	Contract *Contract
}

ScopeContext contains the things that are per-call, such as stack and memory, but not transients like pc and gas

type Stack

type Stack struct {
	// contains filtered or unexported fields
}

stack本身只是个FILO模型的Slice

func (*Stack) Back

func (s *Stack) Back(n int) *uint256.Int

返回但不删除指定位置的值

func (*Stack) Data

func (s *Stack) Data() []uint256.Int

type StateDB

type StateDB interface {
	CreateAccount(Address)

	SubBalance(Address, *big.Int)
	AddBalance(Address, *big.Int)
	GetBalance(Address) *big.Int

	GetNonce(Address) uint64
	SetNonce(Address, uint64)

	GetCodeHash(Address) Hash
	GetCode(Address) []byte
	SetCode(Address, []byte)
	GetCodeSize(Address) int

	// 添加退款金额
	AddRefund(uint64)
	// 减去退款金额
	SubRefund(uint64)
	GetRefund() uint64

	// 返回的是当前执行context提交到数据库的已提交状态(committed state)
	// 也就是上次日志记录点(journal checkpoint)时的状态
	GetCommittedState(Address, Hash) Hash
	// 返回的是当前VM执行过程中的当前状态(current state),包含未提交的变更
	// 反映了所有最近的写入,但未提交至底层数据库
	GetState(Address, Hash) Hash
	SetState(Address, Hash, Hash)

	GetTransientState(addr Address, key Hash) Hash
	SetTransientState(addr Address, key, val Hash)

	SelfDestruct(Address)
	HasSelfDestructed(Address) bool

	Selfdestruct6780(Address)

	// Exist reports whether the given account exists in state.
	// Notably this should also return true for self-destructed accounts.
	Exist(Address) bool
	// Empty returns whether the given account is empty. Empty
	// is defined according to EIP161 (balance = nonce = code = 0).
	Empty(Address) bool

	AddressInAccessList(addr Address) bool
	SlotInAccessList(addr Address, slot Hash) (addressOk bool, slotOk bool)
	// Addcommon.AddressToAccessList adds the given define.Address to the access list. This operation is safe to perform
	// even if the feature/fork is not active yet
	AddAddressToAccessList(addr Address)
	// AddSlotToAccessList adds the given (define.Address,slot) to the access list. This operation is safe to perform
	// even if the feature/fork is not active yet
	AddSlotToAccessList(addr Address, slot Hash)

	RevertToSnapshot(int)
	Snapshot() int

	AddLog(Log)
	AddPreimage(Hash, []byte)
}

type TransferFunc

type TransferFunc func(StateDB, Address, Address, *big.Int)

type TxContext

type TxContext struct {
	// Message information
	Origin     Address  // Provides information for ORIGIN
	GasPrice   *big.Int // Provides information for GASPRICE
	BlobHashes []Hash   // Provides information for BLOBHASH
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL