kernel

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: LGPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

*

  • @Author: yzy
  • @Description:
  • @Version: 1.0.0
  • @Date: 2021/8/19 15:26
  • @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室

Package math provides integer math utilities.

*

  • @Author: yzy
  • @Description:
  • @Version: 1.0.0
  • @Date: 2021/8/19 15:32
  • @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室

*

  • @Author: yzy
  • @Description:
  • @Version: 1.0.0
  • @Date: 2021/9/24 16:58
  • @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室

Index

Constants

View Source
const (
	GasLimitBoundDivisor uint64 = 1024    // The bound divisor of the gas limit, used in update calculations.
	MinGasLimit          uint64 = 5000    // Minimum the gas limit may ever be.
	GenesisGasLimit      uint64 = 4712388 // Gas limit of the Genesis block.

	MaximumExtraDataSize  uint64 = 32    // Maximum size extra data may be after Genesis.
	ExpByteGas            uint64 = 10    // Times ceil(log256(exponent)) for the EXP instruction.
	SloadGas              uint64 = 50    // Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added.
	CallValueTransferGas  uint64 = 9000  // Paid for CALL when the value transfer is non-zero.
	CallNewAccountGas     uint64 = 25000 // Paid for CALL when the destination address didn't exist prior.
	TxGas                 uint64 = 21000 // Per transaction not creating a contract. NOTE: Not payable on data of calls between transactions.
	TxGasContractCreation uint64 = 53000 // Per transaction that creates a contract. NOTE: Not payable on data of calls between transactions.
	TxDataZeroGas         uint64 = 4     // Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions.
	QuadCoeffDiv          uint64 = 512   // Divisor for the quadratic particle of the memory cost equation.
	SstoreSetGas          uint64 = 20000 // Once per SLOAD operation.
	LogDataGas            uint64 = 8     // Per byte in a LOG* operation's data.
	CallStipend           uint64 = 2300  // Free gas given at beginning of call.

	Sha3Gas          uint64 = 30    // Once per SHA3 operation.
	Sha3WordGas      uint64 = 6     // Once per word of the SHA3 operation's data.
	SstoreResetGas   uint64 = 5000  // Once per SSTORE operation if the zeroness changes from zero.
	SstoreClearGas   uint64 = 5000  // Once per SSTORE operation if the zeroness doesn't change.
	SstoreRefundGas  uint64 = 15000 // Once per SSTORE operation if the zeroness changes to zero.
	JumpdestGas      uint64 = 1     // Refunded gas, once per SSTORE operation if the zeroness changes to zero.
	EpochDuration    uint64 = 30000 // Duration between proof-of-work epochs.
	CallGas          uint64 = 40    // Once per CALL operation & message call transaction.
	CreateDataGas    uint64 = 200   //
	CallCreateDepth  uint64 = 1024  // Maximum depth of call/create stack.
	ExpGas           uint64 = 10    // Once per EXP instruction
	LogGas           uint64 = 375   // Per LOG* operation.
	CopyGas          uint64 = 3     //
	StackLimit       uint64 = 1024  // Maximum size of VM stack allowed.
	TierStepGas      uint64 = 0     // Once per operation, for a selection of them.
	LogTopicGas      uint64 = 375   // Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas.
	CreateGas        uint64 = 32000 // Once per CREATE operation & contract-creation transaction.
	SuicideRefundGas uint64 = 24000 // Refunded following a suicide operation.
	MemoryGas        uint64 = 3     // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL.
	TxDataNonZeroGas uint64 = 68    // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.

	MaxCodeSize = 24576 // Maximum bytecode to permit for a contract

	EcrecoverGas        uint64 = 3000 // Elliptic curve sender recovery gas price
	Sha256BaseGas       uint64 = 60   // Base price for a SHA256 operation
	Sha256PerWordGas    uint64 = 12   // Per-word price for a SHA256 operation
	Ripemd160BaseGas    uint64 = 600  // Base price for a RIPEMD160 operation
	Ripemd160PerWordGas uint64 = 120  // Per-word price for a RIPEMD160 operation
	IdentityBaseGas     uint64 = 15   // Base price for a data copy operation
	IdentityPerWordGas  uint64 = 3    // Per-work price for a data copy operation
	ModExpQuadCoeffDiv  uint64 = 20   // Divisor for the quadratic particle of the big int modular exponentiation

	Bn256AddGas             uint64 = 500    // Gas needed for an elliptic curve addition
	Bn256ScalarMulGas       uint64 = 40000  // Gas needed for an elliptic curve scalar multiplication
	Bn256PairingBaseGas     uint64 = 100000 // Base price for an elliptic curve pairing check
	Bn256PairingPerPointGas uint64 = 80000  // Per-point price for an elliptic curve pairing check

)
View Source
const (
	GasQuickStep   uint64 = 2
	GasFastestStep uint64 = 3
	GasFastStep    uint64 = 5
	GasMidStep     uint64 = 8
	GasSlowStep    uint64 = 10
	GasExtStep     uint64 = 20

	GasReturn       uint64 = 0
	GasStop         uint64 = 0
	GasContractByte uint64 = 200
)

Gas costs

View Source
const (
	MaxInt8   = 1<<7 - 1
	MinInt8   = -1 << 7
	MaxInt16  = 1<<15 - 1
	MinInt16  = -1 << 15
	MaxInt32  = 1<<31 - 1
	MinInt32  = -1 << 31
	MaxInt64  = 1<<63 - 1
	MinInt64  = -1 << 63
	MaxUint8  = 1<<8 - 1
	MaxUint16 = 1<<16 - 1
	MaxUint32 = 1<<32 - 1
	MaxUint64 = 1<<64 - 1
)

Integer limit values.

View Source
const (
	CREATE OpCode = 0xf0 + iota
	CALL
	CALLCODE
	RETURN
	DELEGATECALL
	STATICCALL = 0xfa

	REVERT       = 0xfd
	SELFDESTRUCT = 0xff
)

0xf0 range - closures.

Variables

View Source
var (
	Big1    = big.NewInt(1)
	Big2    = big.NewInt(2)
	Big3    = big.NewInt(3)
	Big0    = big.NewInt(0)
	Big32   = big.NewInt(32)
	Big256  = big.NewInt(256)
	Big257  = big.NewInt(257)
	BigZero = new(big.Int)
)
View Source
var (
	MaxBig256 = new(big.Int).Set(tt256m1)
	MaxBig63  = new(big.Int).Sub(tt63, big.NewInt(1))
)

Various big integer limit values.

View Source
var (
	MainnetGenesisHash = common.HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3")
	TestnetGenesisHash = common.HexToHash("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d")
)

Genesis hashes to enforce below configs on.

View Source
var (
	// MainnetChainConfig is the chain parameters to run a node on the main network.
	MainnetChainConfig = &ChainConfig{
		ChainID:             big.NewInt(1),
		HomesteadBlock:      big.NewInt(1150000),
		DAOForkBlock:        big.NewInt(1920000),
		DAOForkSupport:      true,
		EIP150Block:         big.NewInt(2463000),
		EIP150Hash:          common.HexToHash("0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"),
		EIP155Block:         big.NewInt(2675000),
		EIP158Block:         big.NewInt(2675000),
		ByzantiumBlock:      big.NewInt(4370000),
		ConstantinopleBlock: nil,
		Ethash:              new(EthashConfig),
	}

	// TestnetChainConfig contains the chain parameters to run a node on the Ropsten test network.
	TestnetChainConfig = &ChainConfig{
		ChainID:             big.NewInt(3),
		HomesteadBlock:      big.NewInt(0),
		DAOForkBlock:        nil,
		DAOForkSupport:      true,
		EIP150Block:         big.NewInt(0),
		EIP150Hash:          common.HexToHash("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"),
		EIP155Block:         big.NewInt(10),
		EIP158Block:         big.NewInt(10),
		ByzantiumBlock:      big.NewInt(1700000),
		ConstantinopleBlock: nil,
		Ethash:              new(EthashConfig),
	}

	// RinkebyChainConfig contains the chain parameters to run a node on the Rinkeby test network.
	RinkebyChainConfig = &ChainConfig{
		ChainID:             big.NewInt(4),
		HomesteadBlock:      big.NewInt(1),
		DAOForkBlock:        nil,
		DAOForkSupport:      true,
		EIP150Block:         big.NewInt(2),
		EIP150Hash:          common.HexToHash("0x9b095b36c15eaf13044373aef8ee0bd3a382a5abb92e402afa44b8249c3a90e9"),
		EIP155Block:         big.NewInt(3),
		EIP158Block:         big.NewInt(3),
		ByzantiumBlock:      big.NewInt(1035301),
		ConstantinopleBlock: nil,
		Clique: &CliqueConfig{
			Period: 15,
			Epoch:  30000,
		},
	}

	// AllEthashProtocolChanges contains every protocol change (EIPs) introduced
	// and accepted by the Ethereum core developers into the Ethash consensus.
	//
	// This configuration is intentionally not using keyed fields to force anyone
	// adding flags to the config to also have to set these fields.
	AllEthashProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, new(EthashConfig), nil}

	// AllCliqueProtocolChanges contains every protocol change (EIPs) introduced
	// and accepted by the Ethereum core developers into the Clique consensus.
	//
	// This configuration is intentionally not using keyed fields to force anyone
	// adding flags to the config to also have to set these fields.
	AllCliqueProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, &CliqueConfig{Period: 0, Epoch: 30000}}

	TestChainConfig = &ChainConfig{big.NewInt(1), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, new(EthashConfig), nil}
	TestRules       = TestChainConfig.Rules(new(big.Int))
)
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")
	ErrTraceLimitReached        = errors.New("the number of logs reached the specified limit")
	ErrInsufficientBalance      = errors.New("insufficient balance for transfer")
	ErrContractAddressCollision = errors.New("contract address collision")
)

List execution errors

View Source
var (
	// GasTableHomestead contain the gas prices for
	// the homestead phase.
	GasTableHomestead = GasTable{
		ExtcodeSize: 20,
		ExtcodeCopy: 20,
		Balance:     20,
		SLoad:       50,
		Calls:       40,
		Suicide:     0,
		ExpByte:     10,
	}

	// GasTableEIP150 contain the gas re-prices for
	// the EIP150 phase.
	GasTableEIP150 = GasTable{
		ExtcodeSize: 700,
		ExtcodeCopy: 700,
		Balance:     400,
		SLoad:       200,
		Calls:       700,
		Suicide:     5000,
		ExpByte:     10,

		CreateBySuicide: 25000,
	}
	// GasTableEIP158 contain the gas re-prices for
	// the EIP15* phase.
	GasTableEIP158 = GasTable{
		ExtcodeSize: 700,
		ExtcodeCopy: 700,
		Balance:     400,
		SLoad:       200,
		Calls:       700,
		Suicide:     5000,
		ExpByte:     50,

		CreateBySuicide: 25000,
	}
)

Variables containing gas prices for different ethereum phases.

View Source
var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
	common.BytesToAddress([]byte{1}): &ecrecover{},
	common.BytesToAddress([]byte{2}): &sha256hash{},
	common.BytesToAddress([]byte{3}): &ripemd160hash{},
	common.BytesToAddress([]byte{4}): &dataCopy{},
	common.BytesToAddress([]byte{5}): &bigModExp{},
	common.BytesToAddress([]byte{6}): &bn256Add{},
	common.BytesToAddress([]byte{7}): &bn256ScalarMul{},
	common.BytesToAddress([]byte{8}): &bn256Pairing{},
}

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

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

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

View Source
var (
	StateObjectNotFoundErr = errors.New("stateObject not exist")
)

Functions

func BigMax

func BigMax(x, y *big.Int) *big.Int

BigMax returns the larger of x or y.

func BigMin

func BigMin(x, y *big.Int) *big.Int

BigMin returns the smaller of x or y.

func BigPow

func BigPow(a, b int64) *big.Int

BigPow returns a ** b as a big integer.

func Byte

func Byte(bigint *big.Int, padlength, n int) byte

Byte returns the byte at position n, with the supplied padlength in Little-Endian encoding. n==0 returns the MSB Example: bigint '5', padlength 32, n=31 => 5

func Exp

func Exp(base, exponent *big.Int) *big.Int

Exp implements exponentiation by squaring. Exp returns a newly-allocated big integer and does not change base or exponent. The result is truncated to 256 bits.

Courtesy @karalabe and @chfast

func FirstBitSet

func FirstBitSet(v *big.Int) int

FirstBitSet returns the index of the first 1 bit in v, counting from LSB.

func FromECDSA

func FromECDSA(priv *ecdsa.PrivateKey) []byte

FromECDSA exports a private key into a binary dump.

func FromECDSAPub

func FromECDSAPub(pub *ecdsa.PublicKey) []byte

func GenerateKey

func GenerateKey() (*ecdsa.PrivateKey, error)

func HexToECDSA

func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error)

HexToECDSA parses a secp256k1 private key.

func Keccak256

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

Keccak256 calculates and returns the Keccak256 hash of the input data.

func Keccak256Hash

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

Keccak256Hash calculates and returns the Keccak256 hash of the input data, converting it to an internal Hash data structure.

func Keccak512

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

Keccak512 calculates and returns the Keccak512 hash of the input data.

func LoadECDSA

func LoadECDSA(file string) (*ecdsa.PrivateKey, error)

LoadECDSA loads a secp256k1 private key from the given file.

func MustParseBig256

func MustParseBig256(s string) *big.Int

MustParseBig256 parses s as a 256 bit big integer and panics if the string is invalid.

func MustParseUint64

func MustParseUint64(s string) uint64

MustParseUint64 parses s as an integer and panics if the string is invalid.

func PaddedBigBytes

func PaddedBigBytes(bigint *big.Int, n int) []byte

PaddedBigBytes encodes a big integer as a big-endian byte slice. The length of the slice is at least n bytes.

func ParseBig256

func ParseBig256(s string) (*big.Int, bool)

ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax. Leading zeros are accepted. The empty string parses as zero.

func ParseUint64

func ParseUint64(s string) (uint64, bool)

ParseUint64 parses s as an integer in decimal or hexadecimal syntax. Leading zeros are accepted. The empty string parses as zero.

func PubkeyToAddress

func PubkeyToAddress(p ecdsa.PublicKey) common.Address

func ReadBits

func ReadBits(bigint *big.Int, buf []byte)

ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure that buf has enough space. If buf is too short the result will be incomplete.

func RunPrecompiledContract

func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error)

RunPrecompiledContract runs and evaluates the output of a precompiled contract.

func S256

func S256(x *big.Int) *big.Int

S256 interprets x as a two's complement number. x must not exceed 256 bits (the result is undefined if it does) and is not modified.

S256(0)        = 0
S256(1)        = 1
S256(2**255)   = -2**255
S256(2**256-1) = -1

func SafeAdd

func SafeAdd(x, y uint64) (uint64, bool)

SafeAdd returns the result and whether overflow occurred.

func SafeMul

func SafeMul(x, y uint64) (uint64, bool)

SafeMul returns multiplication result and whether overflow occurred.

func SafeSub

func SafeSub(x, y uint64) (uint64, bool)

SafeSub returns subtraction result and whether overflow occurred.

func SaveECDSA

func SaveECDSA(file string, key *ecdsa.PrivateKey) error

SaveECDSA saves a secp256k1 private key to the given file with restrictive permissions. The key data is saved hex-encoded.

func ToECDSA

func ToECDSA(d []byte) (*ecdsa.PrivateKey, error)

ToECDSA creates a private key with the given D value.

func ToECDSAUnsafe

func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey

ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost never be used unless you are sure the input is valid and want to avoid hitting errors due to bad origin encoding (0 prefixes cut off).

func U256

func U256(x *big.Int) *big.Int

U256 encodes as a 256 bit two's complement number. This operation is destructive.

func UnmarshalPubkey

func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error)

UnmarshalPubkey converts bytes to a secp256k1 public key.

func ValidateSignatureValues

func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool

ValidateSignatureValues verifies whether the signature values are valid with the given chain rules. The v value is assumed to be either 0 or 1.

func WriteLogs

func WriteLogs(writer io.Writer, logs []*Log)

WriteLogs writes vm logs in a readable format to the given writer

func WriteTrace

func WriteTrace(writer io.Writer, logs []StructLog)

WriteTrace writes a formatted trace to the given writer

Types

type Account

type Account struct {
	Nonce    uint64   // 账户产生交易次数
	Balance  *big.Int // 账户余额
	CodeHash []byte   // 智能合约代码哈希数组
}

func NewEmptyAccount

func NewEmptyAccount() Account

func (*Account) DeepCopy

func (act *Account) DeepCopy() Account

func (*Account) GetBalance

func (act *Account) GetBalance() *big.Int

func (*Account) SetBalance

func (act *Account) SetBalance(amount *big.Int)

type AccountRef

type AccountRef common.Address

AccountRef implements ContractRef.

Account references are used during EVM initialisation and it's primary use is to fetch addresses. Removing this object proves difficult because of the cached jump destinations which are fetched from the parent contract (i.e. the caller), which is a ContractRef.

func (AccountRef) Address

func (ar AccountRef) Address() common.Address

Address casts AccountRef to a Address

func (AccountRef) CreateContractAddress

func (ar AccountRef) CreateContractAddress(b common.Address, nonce uint64) common.Address

type AddressHandler

type AddressHandler interface {
	CreateAddress(b common.Address, nonce uint64) common.Address
}

type ChainConfig

type ChainConfig struct {
	ChainID *big.Int `json:"chainId"` // chainId identifies the current chain and is used for replay protection

	HomesteadBlock *big.Int `json:"homesteadBlock,omitempty"` // Homestead switch block (nil = no fork, 0 = already homestead)

	DAOForkBlock   *big.Int `json:"daoForkBlock,omitempty"`   // TheDAO hard-fork switch block (nil = no fork)
	DAOForkSupport bool     `json:"daoForkSupport,omitempty"` // Whether the nodes supports or opposes the DAO hard-fork

	// EIP150 implements the Gas price changes (https://github.com/ethereum/EIPs/issues/150)
	EIP150Block *big.Int    `json:"eip150Block,omitempty"` // EIP150 HF block (nil = no fork)
	EIP150Hash  common.Hash `json:"eip150Hash,omitempty"`  // EIP150 HF hash (needed for header only clients as only gas pricing changed)

	EIP155Block *big.Int `json:"eip155Block,omitempty"` // EIP155 HF block
	EIP158Block *big.Int `json:"eip158Block,omitempty"` // EIP158 HF block

	ByzantiumBlock      *big.Int `json:"byzantiumBlock,omitempty"`      // Byzantium switch block (nil = no fork, 0 = already on byzantium)
	ConstantinopleBlock *big.Int `json:"constantinopleBlock,omitempty"` // Constantinople switch block (nil = no fork, 0 = already activated)

	// Various consensus engines
	Ethash *EthashConfig `json:"ethash,omitempty"`
	Clique *CliqueConfig `json:"clique,omitempty"`
}

ChainConfig is the core config which determines the blockchain settings.

ChainConfig is stored in the database on a per block basis. This means that any network, identified by its genesis block, can have its own set of configuration options.

func (*ChainConfig) CheckCompatible

func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64) *ConfigCompatError

CheckCompatible checks whether scheduled fork transitions have been imported with a mismatching chain configuration.

func (*ChainConfig) GasTable

func (c *ChainConfig) GasTable(num *big.Int) GasTable

GasTable returns the gas table corresponding to the current phase (homestead or homestead reprice).

The returned GasTable's fields shouldn't, under any circumstances, be changed.

func (*ChainConfig) IsByzantium

func (c *ChainConfig) IsByzantium(num *big.Int) bool

IsByzantium returns whether num is either equal to the Byzantium fork block or greater.

func (*ChainConfig) IsConstantinople

func (c *ChainConfig) IsConstantinople(num *big.Int) bool

IsConstantinople returns whether num is either equal to the Constantinople fork block or greater.

func (*ChainConfig) IsDAOFork

func (c *ChainConfig) IsDAOFork(num *big.Int) bool

IsDAOFork returns whether num is either equal to the DAO fork block or greater.

func (*ChainConfig) IsEIP150

func (c *ChainConfig) IsEIP150(num *big.Int) bool

IsEIP150 returns whether num is either equal to the EIP150 fork block or greater.

func (*ChainConfig) IsEIP155

func (c *ChainConfig) IsEIP155(num *big.Int) bool

IsEIP155 returns whether num is either equal to the EIP155 fork block or greater.

func (*ChainConfig) IsEIP158

func (c *ChainConfig) IsEIP158(num *big.Int) bool

IsEIP158 returns whether num is either equal to the EIP158 fork block or greater.

func (*ChainConfig) IsHomestead

func (c *ChainConfig) IsHomestead(num *big.Int) bool

IsHomestead returns whether num is either equal to the homestead block or greater.

func (*ChainConfig) Rules

func (c *ChainConfig) Rules(num *big.Int) Rules

Rules ensures c's ChainID is not nil.

func (*ChainConfig) String

func (c *ChainConfig) String() string

String implements the fmt.Stringer interface.

type ChainHandler

type ChainHandler interface {
	GetBlockHeaderHash(uint64) common.Hash
}

type CliqueConfig

type CliqueConfig struct {
	Period uint64 `json:"period"` // Number of seconds between blocks to enforce
	Epoch  uint64 `json:"epoch"`  // Epoch length to reset votes and checkpoint
}

CliqueConfig is the consensus engine configs for proof-of-authority based sealing.

func (*CliqueConfig) String

func (c *CliqueConfig) String() string

String implements the stringer interface, returning the consensus engine details.

type Config

type Config struct {
	// Debug enabled debugging Interpreter options
	Debug bool
	// Tracer is the op code logger
	Tracer Tracer
	// NoRecursion disabled Interpreter call, callcode,
	// delegate call and create.
	NoRecursion bool
	// Enable recording of SHA3/keccak preimages
	EnablePreimageRecording bool
	// JumpTable contains the EVM instruction table. This
	// may be left uninitialised and will be set to the default
	// table.
	JumpTable [256]operation
}

Config are the configuration options for the Interpreter

type ConfigCompatError

type ConfigCompatError struct {
	What string
	// block numbers of the stored and new configurations
	StoredConfig, NewConfig *big.Int
	// the block number to which the local chain must be rewound to correct the error
	RewindTo uint64
}

ConfigCompatError is raised if the locally-stored blockchain is initialised with a ChainConfig that would alter the past.

func (*ConfigCompatError) Error

func (err *ConfigCompatError) Error() string

type Context

type Context struct {
	// Message information
	Origin   common.Address // Provides information for ORIGIN
	GasPrice *big.Int       // Provides information for GASPRICE

	// Block information
	Coinbase    common.Address // Provides information for COINBASE
	GasLimit    uint64         // Provides information for GASLIMIT
	BlockNumber *big.Int       // Provides information for NUMBER
	Time        *big.Int       // Provides information for TIME
	Difficulty  *big.Int       // Provides information for DIFFICULTY
}

Context provides the EVM with auxiliary information. Once provided it shouldn't be modified.

type Contract

type Contract struct {
	// CallerAddress 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 common.Address

	Code     []byte
	CodeHash common.Hash
	CodeAddr *common.Address
	Input    []byte
	Gas      uint64

	Args         []byte
	DelegateCall bool
	// contains filtered or unexported fields
}

Contract represents an ethereum contract in the state database. It contains the the contract code, calling arguments. Contract implements ContractRef

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() common.Address

Address returns the contracts address

func (*Contract) AsDelegate

func (c *Contract) AsDelegate() *Contract

AsDelegate sets the contract to be a delegate call and returns the current contract (for chaining calls)

func (*Contract) Caller

func (c *Contract) Caller() common.Address

Caller returns the caller of the contract.

Caller will recursively call caller when the contract is a delegate call, including that of caller's caller.

func (*Contract) CreateContractAddress

func (c *Contract) CreateContractAddress(b common.Address, nonce uint64) common.Address

func (*Contract) GetByte

func (c *Contract) GetByte(n uint64) byte

GetByte returns the n'th byte in the contract's byte array

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 *common.Address, hash common.Hash, code []byte)

SetCallCode sets the code of the contract and address of the backing data object

func (*Contract) SetCode

func (c *Contract) SetCode(hash common.Hash, code []byte)

SetCode sets the code to the contract

func (*Contract) UseGas

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

UseGas attempts the use gas and subtracts it and returns true on success

func (*Contract) Value

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

Value returns the contracts value (sent to it from it's caller)

type ContractRef

type ContractRef interface {
	Address() common.Address
	CreateContractAddress(b common.Address, nonce uint64) common.Address
}

ContractRef is a reference to the contract's backing object

type DB

type DB interface {
	// 根据传入的hash 从数据库中取出rlp编码的stateObject 并进行解码
	OpenAccount(addr common.Address) []byte
	// 传入stateObject 对其进行rlp编码 然后插入数据库中去
	SaveToDB(common.Address, []byte) error
	// 数据库是否存在账户
	ExistAccount(common.Address) bool
	// 更新账户数据
	UpdateAccount(common.Address, []byte) error
}

type ETHChainHandler

type ETHChainHandler struct{}

func (*ETHChainHandler) GetBlockHeaderHash

func (ethChainHandler *ETHChainHandler) GetBlockHeaderHash(uint64) common.Hash

type EVM

type EVM struct {
	// Context provides auxiliary blockchain related information
	Context

	// StateDB gives access to the underlying state
	StateDBHandler StateDB
	// contains filtered or unexported fields
}

EVM is the Ethereum Virtual Machine base object and provides the necessary tools to run a contract on the given state with the provided context. It should be noted that any error generated through any of the calls should be considered a revert-state-and-consume-all-gas operation, no checks on specific errors should ever be performed. The interpreter makes sure that any errors generated are to be considered faulty code.

The EVM should never be reused and is not thread safe.

func NewEVM

func NewEVM(ctx Context, statedb StateDB, chainhandler ChainHandler, chainConfig *ChainConfig, vmConfig Config) *EVM

NewEVM returns a new EVM. The returned EVM is not thread safe and should only ever be used *once*.

func (*EVM) Call

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

Call executes the contract associated with the addr with the given input as parameters. It also handles any necessary value transfer required and takes the necessary steps to create accounts and reverses the state in case of an execution error or failed value transfer.

func (*EVM) CallCode

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

CallCode executes the contract associated with the addr with the given input as parameters. It also handles any necessary value transfer required and takes the necessary steps to create accounts and reverses the state in case of an execution error or failed value transfer.

CallCode differs from Call in the sense that it executes the given address' code with the caller as context.

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) ChainConfig

func (evm *EVM) ChainConfig() *ChainConfig

ChainConfig returns the environment's chain configuration

func (*EVM) Create

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

Create creates a new contract using code as deployment code.

func (*EVM) DelegateCall

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

DelegateCall executes the contract associated with the addr with the given input as parameters. It reverses the state in case of an execution error.

DelegateCall differs from CallCode in the sense that it executes the given address' code with the caller as context and the caller is set to the caller of the caller.

func (*EVM) Interpreter

func (evm *EVM) Interpreter() *Interpreter

Interpreter returns the EVM interpreter

func (*EVM) StaticCall

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

StaticCall executes the contract associated with the addr with the given input as parameters while disallowing any modifications to the state during the call. Opcodes that attempt to perform such modifications will result in exceptions instead of performing the modifications.

type EthashConfig

type EthashConfig struct{}

EthashConfig is the consensus engine configs for proof-of-work based sealing.

func (*EthashConfig) String

func (c *EthashConfig) String() string

String implements the stringer interface, returning the consensus engine details.

type GasTable

type GasTable struct {
	ExtcodeSize uint64
	ExtcodeCopy uint64
	Balance     uint64
	SLoad       uint64
	Calls       uint64
	Suicide     uint64

	ExpByte uint64

	// CreateBySuicide occurs when the
	// refunded account is one that does
	// not exist. This logic is similar
	// to call. May be left nil. Nil means
	// not charged.
	CreateBySuicide uint64
}

GasTable organizes gas prices for different ethereum phases.

type HexOrDecimal256

type HexOrDecimal256 big.Int

HexOrDecimal256 marshals big.Int as hex or decimal.

func (*HexOrDecimal256) MarshalText

func (i *HexOrDecimal256) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*HexOrDecimal256) UnmarshalText

func (i *HexOrDecimal256) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type HexOrDecimal64

type HexOrDecimal64 uint64

HexOrDecimal64 marshals uint64 as hex or decimal.

func (HexOrDecimal64) MarshalText

func (i HexOrDecimal64) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*HexOrDecimal64) UnmarshalText

func (i *HexOrDecimal64) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Interpreter

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

Interpreter is used to run Ethereum based contracts and will utilise the passed environment to query external sources for state information. The Interpreter will run the byte code VM based on the passed configuration.

func NewInterpreter

func NewInterpreter(evm *EVM, cfg Config) *Interpreter

NewInterpreter returns a new instance of the Interpreter.

func (*Interpreter) Run

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

Run loops and evaluates the contract's code with the given input data and returns the return byte-slice and an error if one occurred.

It's important to note that any errors returned by the interpreter should be considered a revert-and-consume-all-gas operation except for errExecutionReverted which means revert-and-keep-gas-left.

type Log

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

	// 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 common.Hash `json:"transactionHash" gencodec:"required"`
	// index of the transaction in the block
	TxIndex uint `json:"transactionIndex" gencodec:"required"`
	// hash of the block in which the transaction was included
	BlockHash common.Hash `json:"blockHash"`
	// index of the log in the receipt
	Index uint `json:"logIndex" gencodec:"required"`

	// 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"`
}

Log represents a contract log event. These events are generated by the LOG opcode and stored/indexed by the node.

type LogConfig

type LogConfig struct {
	DisableMemory  bool // disable memory capture
	DisableStack   bool // disable stack capture
	DisableStorage bool // disable storage capture
	Debug          bool // print output during capture end
	Limit          int  // maximum length of output, but zero means unlimited
}

LogConfig are the configuration options for structured logger the EVM

type MStateDB

type MStateDB struct {
	DB DB // 落库的数据库引用
	// contains filtered or unexported fields
}

func MakeNewStateDB

func MakeNewStateDB(db DB) *MStateDB

func (*MStateDB) AddBalance

func (s *MStateDB) AddBalance(addr common.Address, amount *big.Int)

func (*MStateDB) AddLog

func (s *MStateDB) AddLog(*Log)

func (*MStateDB) AddPreimage

func (s *MStateDB) AddPreimage(common.Hash, []byte)

func (*MStateDB) AddRefund

func (s *MStateDB) AddRefund(uint64)

AddRefund 没有用到 暂不实现

func (*MStateDB) CreateAccount

func (s *MStateDB) CreateAccount(addr common.Address)

func (*MStateDB) Empty

func (s *MStateDB) Empty(addr common.Address) bool

func (*MStateDB) Exist

func (s *MStateDB) Exist(addr common.Address) bool

func (*MStateDB) ForEachStorage

func (s *MStateDB) ForEachStorage(common.Address, func(common.Hash, common.Hash) bool)

func (*MStateDB) GetABI

func (s *MStateDB) GetABI(addr common.Address) *abi.ABI

func (*MStateDB) GetBalance

func (s *MStateDB) GetBalance(addr common.Address) *big.Int

func (*MStateDB) GetCode

func (s *MStateDB) GetCode(addr common.Address) []byte

func (*MStateDB) GetCodeHash

func (s *MStateDB) GetCodeHash(addr common.Address) common.Hash

func (*MStateDB) GetCodeSize

func (s *MStateDB) GetCodeSize(addr common.Address) int

func (*MStateDB) GetNonce

func (s *MStateDB) GetNonce(addr common.Address) uint64

func (*MStateDB) GetRefund

func (s *MStateDB) GetRefund() uint64

func (*MStateDB) GetState

func (s *MStateDB) GetState(addr common.Address, key common.Hash) common.Hash

func (*MStateDB) GetStateObject added in v1.1.2

func (s *MStateDB) GetStateObject(addr common.Address) *stateObject

func (*MStateDB) HasSuicided

func (s *MStateDB) HasSuicided(common.Address) bool

func (*MStateDB) HaveSufficientBalance

func (s *MStateDB) HaveSufficientBalance(common.Address, *big.Int) bool

func (*MStateDB) ResetStateObject added in v1.1.2

func (s *MStateDB) ResetStateObject(addr common.Address)

func (*MStateDB) RevertToSnapshot

func (s *MStateDB) RevertToSnapshot(pre int)

func (*MStateDB) SetABI

func (s *MStateDB) SetABI(addr common.Address, abi *abi.ABI, bytes []byte)

func (*MStateDB) SetCode

func (s *MStateDB) SetCode(addr common.Address, data []byte)

func (*MStateDB) SetNonce

func (s *MStateDB) SetNonce(addr common.Address, nonce uint64)

func (*MStateDB) SetState

func (s *MStateDB) SetState(addr common.Address, key common.Hash, value common.Hash)

func (*MStateDB) Snapshot

func (s *MStateDB) Snapshot() int

func (*MStateDB) SubBalance

func (s *MStateDB) SubBalance(addr common.Address, amount *big.Int)

func (*MStateDB) Suicide

func (s *MStateDB) Suicide(common.Address) bool

Suicide 没有用到 暂不实现

func (*MStateDB) TransferBalance

func (s *MStateDB) TransferBalance(common.Address, common.Address, *big.Int)

type Memory

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

Memory implements a simple memory model for the ethereum virtual machine.

func NewMemory

func NewMemory() *Memory

NewMemory returns a new memory memory model.

func (*Memory) Data

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

Data returns the backing slice

func (*Memory) Get

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

Get returns offset + size as a new slice

func (*Memory) GetPtr

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

GetPtr returns the offset + size

func (*Memory) Len

func (m *Memory) Len() int

Len returns the length of the backing slice

func (*Memory) Print

func (m *Memory) Print()

Print dumps the content of the memory.

func (*Memory) Resize

func (m *Memory) Resize(size uint64)

Resize resizes the memory to size

func (*Memory) Set

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

Set sets offset + size to value

func (*Memory) Set32

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

Set32 sets the 32 bytes starting at offset to the value of val, left-padded with zeroes to 32 bytes.

type MockDB

type MockDB struct{}

func (*MockDB) ExistAccount

func (*MockDB) ExistAccount(common.Address) bool

func (*MockDB) OpenAccount

func (*MockDB) OpenAccount(addr common.Address) []byte

func (*MockDB) SaveToDB

func (*MockDB) SaveToDB(common.Address, []byte) error

func (MockDB) UpdateAccount

func (MockDB) UpdateAccount(common.Address, []byte) error

type OpCode

type OpCode byte

OpCode is an EVM opcode

const (
	STOP OpCode = iota
	ADD
	MUL
	SUB
	DIV
	SDIV
	MOD
	SMOD
	ADDMOD
	MULMOD
	EXP
	SIGNEXTEND
)

0x0 range - arithmetic ops.

const (
	LT OpCode = iota + 0x10
	GT
	SLT
	SGT
	EQ
	ISZERO
	AND
	OR
	XOR
	NOT
	BYTE
	SHL
	SHR
	SAR

	SHA3 = 0x20
)

0x10 range - comparison ops.

const (
	ADDRESS OpCode = 0x30 + iota
	BALANCE
	ORIGIN
	CALLER
	CALLVALUE
	CALLDATALOAD
	CALLDATASIZE
	CALLDATACOPY
	CODESIZE
	CODECOPY
	GASPRICE
	EXTCODESIZE
	EXTCODECOPY
	RETURNDATASIZE
	RETURNDATACOPY
)

0x30 range - closure state.

const (
	BLOCKHASH OpCode = 0x40 + iota
	COINBASE
	TIMESTAMP
	NUMBER
	DIFFICULTY
	GASLIMIT
)

0x40 range - block operations.

const (
	POP OpCode = 0x50 + iota
	MLOAD
	MSTORE
	MSTORE8
	SLOAD
	SSTORE
	JUMP
	JUMPI
	PC
	MSIZE
	GAS
	JUMPDEST
)

0x50 range - 'storage' and execution.

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
	DUP1
	DUP2
	DUP3
	DUP4
	DUP5
	DUP6
	DUP7
	DUP8
	DUP9
	DUP10
	DUP11
	DUP12
	DUP13
	DUP14
	DUP15
	DUP16
	SWAP1
	SWAP2
	SWAP3
	SWAP4
	SWAP5
	SWAP6
	SWAP7
	SWAP8
	SWAP9
	SWAP10
	SWAP11
	SWAP12
	SWAP13
	SWAP14
	SWAP15
	SWAP16
)

0x60 range.

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

0xa0 range - logging ops.

const (
	PUSH OpCode = 0xb0 + iota
	DUP
	SWAP
)

unofficial opcodes used for parsing.

func StringToOp

func StringToOp(str string) OpCode

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

func (OpCode) IsPush

func (op OpCode) IsPush() bool

IsPush specifies if an opcode is a PUSH opcode.

func (OpCode) IsStaticJump

func (op OpCode) IsStaticJump() bool

IsStaticJump specifies if an opcode is JUMP.

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
}

PrecompiledContract is the basic interface for native Go contracts. The implementation requires a deterministic gas count based on the input size of the Run method of the contract.

type Rules

type Rules struct {
	ChainID                                   *big.Int
	IsHomestead, IsEIP150, IsEIP155, IsEIP158 bool
	IsByzantium                               bool
}

Rules wraps ChainConfig and is merely syntatic sugar or can be used for functions that do not have or require information about the block.

Rules is a one time interface meaning that it shouldn't be used in between transition phases.

type Stack

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

Stack is an object for basic stack operations. Items popped to the stack are expected to be changed and modified. stack does not take care of adding newly initialised objects.

func (*Stack) Back

func (st *Stack) Back(n int) *big.Int

Back returns the n'th item in stack

func (*Stack) Data

func (st *Stack) Data() []*big.Int

Data returns the underlying big.Int array.

func (*Stack) Print

func (st *Stack) Print()

Print dumps the content of the stack

type StateDB

type StateDB interface {
	CreateAccount(common.Address)
	GetStateObject(common.Address) *stateObject
	ResetStateObject(common.Address)

	SetABI(common.Address, *abi.ABI, []byte)
	GetABI(common.Address) *abi.ABI

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

	GetNonce(common.Address) uint64
	SetNonce(common.Address, uint64)

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

	AddRefund(uint64)
	GetRefund() uint64

	GetState(common.Address, common.Hash) common.Hash
	SetState(common.Address, common.Hash, common.Hash)

	Suicide(common.Address) bool
	HasSuicided(common.Address) bool

	Exist(common.Address) bool
	Empty(common.Address) bool

	RevertToSnapshot(int)
	Snapshot() int

	HaveSufficientBalance(common.Address, *big.Int) bool
	TransferBalance(common.Address, common.Address, *big.Int)

	AddLog(*Log)
	AddPreimage(common.Hash, []byte)
	ForEachStorage(common.Address, func(common.Hash, common.Hash) bool)
}

StateDB is an EVM database for full state querying.

type StateObject

type StateObject interface {
	GetState(key common.Hash) common.Hash
	SetState(key, value common.Hash)
	AddBalance(amount *big.Int)
	SubBalance(amount *big.Int)
	SetBalance(amount *big.Int)
	Address() common.Address
	Nonce() uint64
	SetNonce(nonce uint64)
	CodeHash() common.Hash
	SnapShot()
	RevertToSnap(pre int)
	RevertToInit()
}

type StateObjectJson added in v1.1.4

type StateObjectJson struct {
	ABI      []byte `msg:"abi"`
	Address  []byte `msg:"address"`
	AddrHash []byte `msg:"addrhash"`
	Data     []byte `msg:"data"`
	Code     []byte `msg:"code"`
	Origin   []byte `msg:"origin"`
}

func (*StateObjectJson) DecodeMsg added in v1.1.4

func (z *StateObjectJson) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*StateObjectJson) EncodeMsg added in v1.1.4

func (z *StateObjectJson) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*StateObjectJson) FromByteArray added in v1.1.4

func (s *StateObjectJson) FromByteArray(data []byte) error

func (*StateObjectJson) MarshalMsg added in v1.1.4

func (z *StateObjectJson) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*StateObjectJson) Msgsize added in v1.1.4

func (z *StateObjectJson) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*StateObjectJson) ToByteArray added in v1.1.4

func (s *StateObjectJson) ToByteArray() ([]byte, error)

func (*StateObjectJson) UnmarshalMsg added in v1.1.4

func (z *StateObjectJson) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type Storage

type Storage map[common.Hash]common.Hash

Storage represents a contract's storage.

func (Storage) Copy

func (s Storage) Copy() Storage

Copy duplicates the current storage.

type StructLog

type StructLog struct {
	Pc         uint64                      `json:"pc"`
	Op         OpCode                      `json:"op"`
	Gas        uint64                      `json:"gas"`
	GasCost    uint64                      `json:"gasCost"`
	Memory     []byte                      `json:"memory"`
	MemorySize int                         `json:"memSize"`
	Stack      []*big.Int                  `json:"stack"`
	Storage    map[common.Hash]common.Hash `json:"-"`
	Depth      int                         `json:"depth"`
	Err        error                       `json:"-"`
}

StructLog is emitted to the EVM each cycle and lists information about the current internal state prior to the execution of the statement.

func (*StructLog) ErrorString

func (s *StructLog) ErrorString() string

ErrorString formats the log's error as a string.

func (*StructLog) OpName

func (s *StructLog) OpName() string

OpName formats the operand name in a human-readable format.

type StructLogger

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

StructLogger is an EVM state logger and implements Tracer.

StructLogger can capture state based on the given Log configuration and also keeps a track record of modified storage which is used in reporting snapshots of the contract their storage.

func NewStructLogger

func NewStructLogger(cfg *LogConfig) *StructLogger

NewStructLogger returns a new logger

func (*StructLogger) CaptureEnd

func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error

CaptureEnd is called after the call finishes to finalize the tracing.

func (*StructLogger) CaptureFault

func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error

CaptureFault implements the Tracer interface to trace an execution fault while running an opcode.

func (*StructLogger) CaptureStart

func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error

CaptureStart implements the Tracer interface to initialize the tracing operation.

func (*StructLogger) CaptureState

func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error

CaptureState logs a new structured log message and pushes it out to the environment

CaptureState also tracks SSTORE ops to track dirty values.

func (*StructLogger) Error

func (l *StructLogger) Error() error

Error returns the VM error captured by the trace.

func (*StructLogger) Output

func (l *StructLogger) Output() []byte

Output returns the VM return value captured by the trace.

func (*StructLogger) StructLogs

func (l *StructLogger) StructLogs() []StructLog

StructLogs returns the captured log entries.

type Tracer

type Tracer interface {
	CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error
	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
}

Tracer is used to collect execution traces from an EVM transaction execution. CaptureState is called for each step of the VM with the current VM state. Note that reference types are actual VM data structures; make copies if you need to retain them beyond the current call.

Jump to

Keyboard shortcuts

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