kernal

package
v0.0.0-...-1cbaea7 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2020 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package math provides integer math utilities.

Package common contains various helper functions.

Package hexutil implements hex encoding with 0x prefix. This encoding is used by the Ethereum RPC API to transport binary data in JSON payloads.

Encoding Rules

All hex data must have prefix "0x".

For byte slices, the hex data must be of even length. An empty byte slice encodes as "0x".

Integers are encoded using the least amount of digits (no leading zero digits). Their encoding may be of uneven length. The number zero encodes as "0x0".

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.

View Source
const (
	HashLength    = 32
	AddressLength = 20
)

Lengths of hashes and addresses in bytes.

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 = HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3")
	TestnetGenesisHash = 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:          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:          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:          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), 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), 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), 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 (
	ErrEmptyString   = &decError{"empty hex string"}
	ErrSyntax        = &decError{"invalid hex string"}
	ErrMissingPrefix = &decError{"hex string without 0x prefix"}
	ErrOddLength     = &decError{"hex string of odd length"}
	ErrEmptyNumber   = &decError{"hex string \"0x\""}
	ErrLeadingZero   = &decError{"hex number with leading zero digits"}
	ErrUint64Range   = &decError{"hex number > 64 bits"}
	ErrUintRange     = &decError{fmt.Sprintf("hex number > %d bits", uintBits)}
	ErrBig256Range   = &decError{"hex number > 256 bits"}
)

Errors

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

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

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

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

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 Bytes2Hex

func Bytes2Hex(d []byte) string

Bytes2Hex returns the hexadecimal encoding of d.

func CopyBytes

func CopyBytes(b []byte) (copiedBytes []byte)

CopyBytes returns an exact copy of the provided bytes.

func Decode

func Decode(input string) ([]byte, error)

Decode decodes a hex string with 0x prefix.

func DecodeBig

func DecodeBig(input string) (*big.Int, error)

DecodeBig decodes a hex string with 0x prefix as a quantity. Numbers larger than 256 bits are not accepted.

func DecodeUint64

func DecodeUint64(input string) (uint64, error)

DecodeUint64 decodes a hex string with 0x prefix as a quantity.

func Encode

func Encode(b []byte) string

Encode encodes b as a hex string with 0x prefix.

func EncodeBig

func EncodeBig(bigint *big.Int) string

EncodeBig encodes bigint as a hex string with 0x prefix. The sign of the integer is ignored.

func EncodeUint64

func EncodeUint64(i uint64) string

EncodeUint64 encodes i as a hex string with 0x prefix.

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 FromHex

func FromHex(s string) []byte

FromHex returns the bytes represented by the hexadecimal string s. s may be prefixed with "0x".

func GenerateKey

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

func Hex2Bytes

func Hex2Bytes(str string) []byte

Hex2Bytes returns the bytes represented by the hexadecimal string str.

func Hex2BytesFixed

func Hex2BytesFixed(str string, flen int) []byte

Hex2BytesFixed returns bytes of a specified fixed length flen.

func HexToECDSA

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

HexToECDSA parses a secp256k1 private key.

func IsHexAddress

func IsHexAddress(s string) bool

IsHexAddress verifies whether a string can represent a valid hex-encoded Ethereum address or not.

func Keccak256

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

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

func Keccak512

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

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

func LeftPadBytes

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

LeftPadBytes zero-pads slice to the left up to length l.

func LoadECDSA

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

LoadECDSA loads a secp256k1 private key from the given file.

func MustDecode

func MustDecode(input string) []byte

MustDecode decodes a hex string with 0x prefix. It panics for invalid input.

func MustDecodeBig

func MustDecodeBig(input string) *big.Int

MustDecodeBig decodes a hex string with 0x prefix as a quantity. It panics for invalid input.

func MustDecodeUint64

func MustDecodeUint64(input string) uint64

MustDecodeUint64 decodes a hex string with 0x prefix as a quantity. It panics for invalid input.

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 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 RightPadBytes

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

RightPadBytes zero-pads slice to the right up to length l.

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 ToHex deprecated

func ToHex(b []byte) string

ToHex returns the hex representation of b, prefixed with '0x'. For empty slices, the return value is "0x0".

Deprecated: use hexutil.Encode instead.

func U256

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

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

func UnmarshalFixedJSON

func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error

UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out determines the required input length. This function is commonly used to implement the UnmarshalJSON method for fixed-size types.

func UnmarshalFixedText

func UnmarshalFixedText(typname string, input, out []byte) error

UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out determines the required input length. This function is commonly used to implement the UnmarshalText method for fixed-size types.

func UnmarshalFixedUnprefixedText

func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error

UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The length of out determines the required input length. This function is commonly used to implement the UnmarshalText method for fixed-size types.

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 AccountRef

type AccountRef 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() Address

Address casts AccountRef to a Address

func (AccountRef) CreateContractAddress

func (ar AccountRef) CreateContractAddress(Address, uint64) Address

type Address

type Address [AddressLength]byte

Address represents the 20 byte address of an Ethereum account.

func BigToAddress

func BigToAddress(b *big.Int) Address

BigToAddress returns Address with byte values of b. If b is larger than len(h), b will be cropped from the left.

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress returns Address with value b. If b is larger than len(h), b will be cropped from the left.

func HexToAddress

func HexToAddress(s string) Address

HexToAddress returns Address with byte values of s. If s is larger than len(h), s will be cropped from the left.

func PubkeyToAddress

func PubkeyToAddress(p ecdsa.PublicKey) Address

func (Address) Big

func (a Address) Big() *big.Int

Big converts an address to a big integer.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes gets the string representation of the underlying address.

func (Address) Format

func (a Address) Format(s fmt.State, c rune)

Format implements fmt.Formatter, forcing the byte slice to be formatted as is, without going through the stringer interface used for logging.

func (Address) Hash

func (a Address) Hash() Hash

Hash converts an address to a hash by left-padding it with zeros.

func (Address) Hex

func (a Address) Hex() string

Hex returns an EIP55-compliant hex string representation of the address.

func (Address) MarshalText

func (a Address) MarshalText() ([]byte, error)

MarshalText returns the hex representation of a.

func (*Address) SetBytes

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

SetBytes sets the address to the value of b. If b is larger than len(a) it will panic.

func (Address) String

func (a Address) String() string

String implements fmt.Stringer.

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash in hex syntax.

func (*Address) UnmarshalText

func (a *Address) UnmarshalText(input []byte) error

UnmarshalText parses a hash in hex syntax.

type AddressHandler

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

type Big

type Big big.Int

Big marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".

Negative integers are not supported at this time. Attempting to marshal them will return an error. Values larger than 256bits are rejected by Unmarshal but will be marshaled without error.

func (Big) MarshalText

func (b Big) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler

func (*Big) String

func (b *Big) String() string

String returns the hex encoding of b.

func (*Big) ToInt

func (b *Big) ToInt() *big.Int

ToInt converts b to a big.Int.

func (*Big) UnmarshalJSON

func (b *Big) UnmarshalJSON(input []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Big) UnmarshalText

func (b *Big) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler

type Bytes

type Bytes []byte

Bytes marshals/unmarshals as a JSON string with 0x prefix. The empty slice marshals as "0x".

func (Bytes) MarshalText

func (b Bytes) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler

func (Bytes) String

func (b Bytes) String() string

String returns the hex encoding of b.

func (*Bytes) UnmarshalJSON

func (b *Bytes) UnmarshalJSON(input []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Bytes) UnmarshalText

func (b *Bytes) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

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  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) 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   Address  // Provides information for ORIGIN
	GasPrice *big.Int // Provides information for GASPRICE

	// Block information
	Coinbase    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 Address

	Code     []byte
	CodeHash Hash
	CodeAddr *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() 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() 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 Address, nonce uint64) 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 *Address, hash 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 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() Address
	CreateContractAddress(b Address, nonce uint64) Address
}

ContractRef is a reference to the contract's backing object

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 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 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 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 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 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 Hash

type Hash [HashLength]byte

Hash represents the 32 byte Keccak256 hash of arbitrary data.

func BigToHash

func BigToHash(b *big.Int) Hash

BigToHash sets byte representation of b to hash. If b is larger than len(h), b will be cropped from the left.

func BytesToHash

func BytesToHash(b []byte) Hash

BytesToHash sets b to hash. If b is larger than len(h), b will be cropped from the left.

func HexToHash

func HexToHash(s string) Hash

HexToHash sets byte representation of s to hash. If b is larger than len(h), b will be cropped from the left.

func Keccak256Hash

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

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

func (Hash) Big

func (h Hash) Big() *big.Int

Big converts a hash to a big integer.

func (Hash) Bytes

func (h Hash) Bytes() []byte

Bytes gets the byte representation of the underlying hash.

func (Hash) Format

func (h Hash) Format(s fmt.State, c rune)

Format implements fmt.Formatter, forcing the byte slice to be formatted as is, without going through the stringer interface used for logging.

func (Hash) Generate

func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value

Generate implements testing/quick.Generator.

func (Hash) Hex

func (h Hash) Hex() string

Hex converts a hash to a hex string.

func (Hash) MarshalText

func (h Hash) MarshalText() ([]byte, error)

MarshalText returns the hex representation of h.

func (*Hash) SetBytes

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

SetBytes sets the hash to the value of b. If b is larger than len(h), b will be cropped from the left.

func (Hash) String

func (h Hash) String() string

String implements the stringer interface and is used also by the logger when doing full logging into a file.

func (Hash) TerminalString

func (h Hash) TerminalString() string

TerminalString implements log.TerminalStringer, formatting a string for console output during logging.

func (*Hash) UnmarshalJSON

func (h *Hash) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash in hex syntax.

func (*Hash) UnmarshalText

func (h *Hash) UnmarshalText(input []byte) error

UnmarshalText parses a hash in hex syntax.

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 Address `json:"address" gencodec:"required"`
	// list of topics provided by the contract.
	Topics []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 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 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 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 MixedcaseAddress

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

MixedcaseAddress retains the original string, which may or may not be correctly checksummed

func NewMixedcaseAddress

func NewMixedcaseAddress(addr Address) MixedcaseAddress

NewMixedcaseAddress constructor (mainly for testing)

func NewMixedcaseAddressFromString

func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error)

NewMixedcaseAddressFromString is mainly meant for unit-testing

func (*MixedcaseAddress) Address

func (ma *MixedcaseAddress) Address() Address

Address returns the address

func (*MixedcaseAddress) MarshalJSON

func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error)

MarshalJSON marshals the original value

func (*MixedcaseAddress) Original

func (ma *MixedcaseAddress) Original() string

Original returns the mixed-case input string

func (*MixedcaseAddress) String

func (ma *MixedcaseAddress) String() string

String implements fmt.Stringer

func (*MixedcaseAddress) UnmarshalJSON

func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error

UnmarshalJSON parses MixedcaseAddress

func (*MixedcaseAddress) ValidChecksum

func (ma *MixedcaseAddress) ValidChecksum() bool

ValidChecksum returns true if the address has valid checksum

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(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)
	GetRefund() uint64

	GetState(Address, Hash) Hash
	SetState(Address, Hash, Hash)

	Suicide(Address) bool
	HasSuicided(Address) bool

	// Exist reports whether the given account exists in state.
	// Notably this should also return true for suicided 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

	RevertToSnapshot(int)
	Snapshot() int
	//Define function aimed at replacement of CanTransfer and Transfer
	HaveSufficientBalance(Address, *big.Int) bool
	TransferBalance(Address, Address, *big.Int)

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

StateDB is an EVM database for full state querying.

type Storage

type Storage map[Hash]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[Hash]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 Address, to 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 Address, to 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.

type Uint

type Uint uint

Uint marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".

func (Uint) MarshalText

func (b Uint) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Uint) String

func (b Uint) String() string

String returns the hex encoding of b.

func (*Uint) UnmarshalJSON

func (b *Uint) UnmarshalJSON(input []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Uint) UnmarshalText

func (b *Uint) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Uint64

type Uint64 uint64

Uint64 marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".

func (Uint64) MarshalText

func (b Uint64) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Uint64) String

func (b Uint64) String() string

String returns the hex encoding of b.

func (*Uint64) UnmarshalJSON

func (b *Uint64) UnmarshalJSON(input []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Uint64) UnmarshalText

func (b *Uint64) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler

type UnprefixedAddress

type UnprefixedAddress Address

UnprefixedAddress allows marshaling an Address without 0x prefix.

func (UnprefixedAddress) MarshalText

func (a UnprefixedAddress) MarshalText() ([]byte, error)

MarshalText encodes the address as hex.

func (*UnprefixedAddress) UnmarshalText

func (a *UnprefixedAddress) UnmarshalText(input []byte) error

UnmarshalText decodes the address from hex. The 0x prefix is optional.

type UnprefixedHash

type UnprefixedHash Hash

UnprefixedHash allows marshaling a Hash without 0x prefix.

func (UnprefixedHash) MarshalText

func (h UnprefixedHash) MarshalText() ([]byte, error)

MarshalText encodes the hash as hex.

func (*UnprefixedHash) UnmarshalText

func (h *UnprefixedHash) UnmarshalText(input []byte) error

UnmarshalText decodes the hash from hex. The 0x prefix is optional.

Jump to

Keyboard shortcuts

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