iface

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2025 License: GPL-3.0, LGPL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package iface provides neutral interfaces to break import cycles. This package should have minimal dependencies and serve as the contract between different layers of the system.

Index

Constants

View Source
const (
	// DefaultMinBlockGasCost is the default minimum block gas cost
	DefaultMinBlockGasCost = 0

	// DefaultMaxBlockGasCost is the default maximum block gas cost
	DefaultMaxBlockGasCost = 10_000_000

	// DefaultTargetBlockRate is the default target block rate (2 seconds)
	DefaultTargetBlockRate = 2

	// DefaultBlockGasCostStep is the default block gas cost step
	DefaultBlockGasCostStep = 200_000
)

ConsensusConstants for node consensus

View Source
const (
	KiB = 1024       // 1 kibibyte
	MiB = 1024 * KiB // 1 mebibyte
	GiB = 1024 * MiB // 1 gibibyte
)

Size constants

View Source
const MaxInt32 = math.MaxInt32

MaxInt32 is the maximum int32 value

View Source
const MaxUint64 = ^uint64(0)

MaxUint64 is the maximum uint64 value

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
	ErrClosed   = errors.New("database closed")
)

Database errors

View Source
var (
	ErrUnknownValidator = errors.New("unknown validator")
	ErrWeightOverflow   = errors.New("weight overflowed")
)
View Source
var (
	ErrInvalidAddressLength = errors.New("invalid address length")
)
View Source
var (
	ErrInvalidPublicKeyLength = errors.New("invalid public key length")
)

Functions

func Marshal

func Marshal(codec Codec, v interface{}) ([]byte, error)

Marshal is a helper function to marshal an object

func Parse

func Parse(bytes []byte) (interface{}, error)

Parse parses a warp payload

func RegisterPlugin

func RegisterPlugin(name string, factory VMFactory) error

RegisterPlugin registers a VM plugin

func SafeAdd

func SafeAdd(a, b uint64) (uint64, bool)

SafeAdd adds two uint64s and returns overflow flag

func SafeMul

func SafeMul(a, b uint64) (uint64, bool)

SafeMul multiplies two uint64s and returns overflow flag

func SetPrecompileRegistry

func SetPrecompileRegistry(registry PrecompileRegistry)

SetPrecompileRegistry sets the global precompile registry This should be called during application initialization

func SortValidators added in v0.8.1

func SortValidators(vdrs []*WarpValidator)

SortValidators sorts validators by their public key bytes

func Unmarshal

func Unmarshal(codec Codec, b []byte, v interface{}) error

Unmarshal is a helper function to unmarshal bytes

Types

type AcceptedContractCaller

type AcceptedContractCaller interface {
	AcceptedCallContract(ctx context.Context, call CallMsg) ([]byte, error)
}

AcceptedContractCaller can be used to perform calls against the accepted state.

type AcceptedStateReader

type AcceptedStateReader interface {
	AcceptedCodeAt(ctx context.Context, address common.Address) ([]byte, error)
	AcceptedNonceAt(ctx context.Context, address common.Address) (uint64, error)
}

AcceptedStateReader wraps access to the accepted state.

type AddressedCall

type AddressedCall struct {
	SourceAddress []byte
	Payload       []byte
}

AddressedCall represents a warp message payload for contract calls

func ParseAddressedCall

func ParseAddressedCall(bytes []byte) (*AddressedCall, error)

ParseAddressedCall parses an addressed call payload

func (*AddressedCall) Bytes added in v0.8.1

func (a *AddressedCall) Bytes() []byte

Bytes returns the byte representation of the addressed call

func (*AddressedCall) Unmarshal added in v0.8.1

func (a *AddressedCall) Unmarshal(data []byte) error

Unmarshal deserializes bytes into an AddressedCall

func (*AddressedCall) Verify added in v0.8.1

func (a *AddressedCall) Verify() error

Verify validates the addressed call

type AtomicMemory

type AtomicMemory interface {
	// NewSharedMemory creates a new shared memory instance for a chain
	NewSharedMemory(chainID ID) SharedMemory
}

AtomicMemory manages shared memory across chains

func NewMemory

func NewMemory(db Database) AtomicMemory

NewMemory creates a new atomic memory instance

type AtomicTx

type AtomicTx interface {
	// BlockNumber returns the block number
	BlockNumber() *big.Int

	// UTXOs returns the UTXOs
	UTXOs() [][]byte
}

AtomicTx represents an atomic transaction

type BLSPublicKey added in v0.8.1

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

BLSPublicKey represents a BLS public key

func NewBLSPublicKey added in v0.8.1

func NewBLSPublicKey(bytes []byte) (*BLSPublicKey, error)

NewBLSPublicKey creates a new BLS public key from bytes

func (*BLSPublicKey) String added in v0.8.1

func (pk *BLSPublicKey) String() string

String returns the hex representation of the public key

func (*BLSPublicKey) UncompressedBytes added in v0.8.1

func (pk *BLSPublicKey) UncompressedBytes() []byte

UncompressedBytes returns the uncompressed bytes of the public key

type BLSSignature added in v0.8.1

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

BLSSignature represents a BLS signature

func AggregateSignatures

func AggregateSignatures(sigs []*BLSSignature) (*BLSSignature, error)

AggregateSignatures aggregates multiple BLS signatures

func SignatureFromBytes

func SignatureFromBytes(bytes []byte) (*BLSSignature, error)

SignatureFromBytes creates a signature from bytes

func (*BLSSignature) NumSigners added in v0.8.1

func (sig *BLSSignature) NumSigners() (int, error)

NumSigners returns the number of signers in the signature

func (*BLSSignature) Verify added in v0.8.1

func (sig *BLSSignature) Verify(
	msg *UnsignedMessage,
	networkID uint32,
	validators *CanonicalValidatorSet,
	quorumNum uint64,
	quorumDen uint64,
) error

Verify verifies a BLS signature

type Batch

type Batch interface {
	ethdb.Batch
}

Batch represents a batch operation

type Batcher

type Batcher interface {
	// NewBatch creates a new batch
	NewBatch() ethdb.Batch
}

Batcher wraps batch operations

type Bits

type Bits interface {
	// Add adds a bit to the set
	Add(i int)

	// Contains checks if a bit is in the set
	Contains(i int) bool

	// Remove removes a bit from the set
	Remove(i int)

	// Clear clears all bits
	Clear()

	// Len returns the number of bits set
	Len() int

	// Bytes returns the byte representation
	Bytes() []byte
}

Bits provides a bit set interface

type Block

type Block interface {
	// ID returns the block's ID
	ID() ID

	// Accept marks the block as accepted
	Accept(context.Context) error

	// Reject marks the block as rejected
	Reject(context.Context) error

	// Status returns the block's status
	Status() Status

	// Parent returns the parent block ID
	Parent() ID

	// Height returns the block height
	Height() uint64

	// Timestamp returns the block timestamp
	Timestamp() Timestamp

	// Verify verifies the block
	Verify(context.Context) error

	// Bytes returns the block bytes
	Bytes() []byte
}

Block represents a block in the blockchain

type BlockContext

type BlockContext struct {
	CanTransfer func(StateDB, common.Address, *big.Int) bool
	Transfer    func(StateDB, common.Address, common.Address, *big.Int) error
	GetHash     func(uint64) common.Hash
	Coinbase    common.Address
	GasLimit    uint64
	BlockNumber *big.Int
	Time        uint64
	Difficulty  *big.Int
	BaseFee     *big.Int
}

BlockContext provides context about the block

type BlockID

type BlockID = ID

BlockID represents a block identifier

type BlockRequest

type BlockRequest struct {
	Hash    []byte
	Number  uint64
	Parents uint16
}

BlockRequest represents a request for blocks

type BlockSignatureRequest

type BlockSignatureRequest struct {
	BlockID []byte
}

BlockSignatureRequest represents a request for block signature

type Cacher

type Cacher[K comparable, V any] interface {
	Put(key K, value V)
	Get(key K) (V, bool)
	Evict(key K)
	Flush()
	Len() int
}

Cacher is a generic cache interface

type CallMsg

type CallMsg struct {
	From          common.Address  // the sender of the 'transaction'
	To            *common.Address // the destination contract (nil for contract creation)
	Gas           uint64          // if 0, the call executes with near-infinite gas
	GasPrice      *big.Int        // wei <-> gas exchange ratio
	GasFeeCap     *big.Int        // EIP-1559 fee cap per gas.
	GasTipCap     *big.Int        // EIP-1559 tip per gas.
	Value         *big.Int        // amount of wei sent along with the call
	Data          []byte          // input data, usually an ABI-encoded contract method invocation
	BlobGasFeeCap *big.Int        // EIP-4844 blob gas fee cap
	BlobHashes    []common.Hash   // EIP-4844 blob hashes

	AccessList types.AccessList // EIP-2930 access list.
}

CallMsg contains parameters for contract calls.

type CanonicalValidatorSet added in v0.8.1

type CanonicalValidatorSet struct {
	// Validators slice in canonical ordering of the validators that has public key
	Validators []*WarpValidator
	// The total weight of all the validators, including the ones that doesn't have a public key
	TotalWeight uint64
}

CanonicalValidatorSet represents the canonical set of validators

func FlattenValidatorSet added in v0.8.1

func FlattenValidatorSet(vdrSet map[common.Hash]*ValidatorOutput) (CanonicalValidatorSet, error)

FlattenValidatorSet converts the provided vdrSet into a canonical ordering.

func GetCanonicalValidatorSetFromChainID added in v0.8.1

func GetCanonicalValidatorSetFromChainID(
	ctx context.Context,
	pChainState ValidatorState,
	pChainHeight uint64,
	sourceChainID common.Hash,
) (CanonicalValidatorSet, error)

GetCanonicalValidatorSetFromChainID returns the canonical validator set given a ValidatorState, pChain height and a sourceChainID.

func GetCanonicalValidatorSetFromSubnetID added in v0.8.1

func GetCanonicalValidatorSetFromSubnetID(
	ctx context.Context,
	pChainState ValidatorState,
	pChainHeight uint64,
	subnetID common.Hash,
) (CanonicalValidatorSet, error)

GetCanonicalValidatorSetFromSubnetID returns the CanonicalValidatorSet of subnetID at pChainHeight.

type ChainConfig

type ChainConfig interface {
	// Chain identification
	GetChainID() *big.Int

	// Fork activation checks
	IsHomestead(num *big.Int) bool
	IsEIP150(num *big.Int) bool
	IsEIP155(num *big.Int) bool
	IsEIP158(num *big.Int) bool
	IsByzantium(num *big.Int) bool
	IsConstantinople(num *big.Int) bool
	IsPetersburg(num *big.Int) bool
	IsIstanbul(num *big.Int) bool
	IsBerlin(num *big.Int) bool
	IsLondon(num *big.Int) bool
	IsShanghai(num *big.Int, time uint64) bool
	IsCancun(time uint64) bool

	// Lux-specific methods
	// For v2.0.0, all upgrades are active at genesis
	IsGenesis(time uint64) bool
	AllowedFeeRecipients() bool
	GenesisRules(blockNum *big.Int, timestamp uint64) GenesisRules

	// AsGeth returns the underlying geth ChainConfig for compatibility
	AsGeth() interface{}
}

ChainConfig represents the chain configuration

type ChainContext

type ChainContext struct {
	NetworkID uint32
	SubnetID  SubnetID
	ChainID   ChainID
	NodeID    NodeID

	// Node version
	AppVersion uint32

	// Chain configuration
	ChainDataDir string

	// Validator state
	ValidatorState ValidatorState
}

ChainContext provides consensus context

type ChainHeaderReader

type ChainHeaderReader interface {
	// Config retrieves the blockchain's chain configuration.
	Config() ChainConfig

	// CurrentHeader retrieves the current header from the local chain.
	CurrentHeader() *types.Header

	// GetHeader retrieves a block header from the database by hash and number.
	GetHeader(hash common.Hash, number uint64) *types.Header

	// GetHeaderByNumber retrieves a block header from the database by number.
	GetHeaderByNumber(number uint64) *types.Header

	// GetHeaderByHash retrieves a block header from the database by its hash.
	GetHeaderByHash(hash common.Hash) *types.Header

	// GetTd retrieves the total difficulty from the database by hash and number.
	GetTd(hash common.Hash, number uint64) *big.Int

	// GetCoinbaseAt returns the configured coinbase address at the given timestamp
	GetCoinbaseAt(timestamp uint64) common.Address

	// GetFeeConfigAt returns the fee configuration at the given timestamp
	GetFeeConfigAt(timestamp uint64) (FeeConfig, error)
}

ChainHeaderReader defines methods needed to access the local blockchain during header verification.

type ChainID

type ChainID [32]byte

ChainID is a 32-byte chain identifier

func (ChainID) String

func (id ChainID) String() string

String returns the string representation of a ChainID

type ChainReader

type ChainReader interface {
	ChainHeaderReader

	// GetBlock retrieves a block from the database by hash and number.
	GetBlock(hash common.Hash, number uint64) *types.Block
}

ChainReader defines a small collection of methods needed to access the local blockchain during header and/or uncle verification.

type ChainStateReader

type ChainStateReader interface {
	BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
	StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error)
	CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
	NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
}

ChainStateReader wraps access to the state trie of the canonical blockchain. Note that implementations of the interface may be unable to return state values for old blocks. In many cases, using CallContract can be preferable to reading raw contract storage.

type ChainSyncReader

type ChainSyncReader interface {
	SyncProgress(ctx context.Context) (*SyncProgress, error)
}

ChainSyncReader wraps access to the node's current sync status. If there's no sync currently running, it returns nil.

type Choice

type Choice uint32

Choice represents the status of a decision

const (
	// Undecided means the decision hasn't been made yet
	Undecided Choice = iota
	// Processing means the decision is being processed
	Processing
	// Accepted means the decision was accepted
	Accepted
	// Rejected means the decision was rejected
	Rejected
)

func (Choice) String

func (c Choice) String() string

type CodeRequest

type CodeRequest struct {
	Hashes [][]byte
}

CodeRequest represents a request for code

type Codec

type Codec interface {
	// Marshal serializes an object into bytes
	Marshal(v interface{}) ([]byte, error)

	// Unmarshal deserializes bytes into an object
	Unmarshal(b []byte, v interface{}) error
}

Codec defines serialization operations

type CodecRegistry

type CodecRegistry interface {
	// RegisterCodec registers a codec for a type
	RegisterCodec(version uint16, codec Codec) error

	// GetCodec gets a codec for a version
	GetCodec(version uint16) (Codec, error)
}

CodecRegistry manages codecs

type Compacter

type Compacter interface {
	// Compact compacts the underlying DB
	Compact(start []byte, limit []byte) error
}

Compacter wraps compaction operations

type Context added in v0.8.1

type Context struct {
	// PChainHeight is the height that this block will use to verify it's state.
	PChainHeight uint64
}

Context defines the block context for warp validation

type ContractCaller

type ContractCaller interface {
	CallContract(ctx context.Context, call CallMsg, blockNumber *big.Int) ([]byte, error)
}

CallContract executes an Ethereum contract call with the specified data as the input.

type ContractRef

type ContractRef interface {
	Address() common.Address
}

ContractRef is the interface for a contract caller

type CrossChainRequestHandler

type CrossChainRequestHandler interface {
	// HandleEthCallRequest handles ethereum call requests
	HandleEthCallRequest(ctx context.Context, requestingChainID ChainID, requestID uint32, ethCallRequest EthCallRequest) ([]byte, error)
}

CrossChainRequestHandler handles cross-chain requests

type Database

Database wraps all database operations for node compatibility

func NewPrefixDB

func NewPrefixDB(prefix []byte, db Database) Database

NewPrefixDB creates a new prefix database

type Decidable

type Decidable interface {
	// ID returns the ID of this element
	ID() BlockID

	// Status returns the current status
	Status() Choice

	// Accept accepts this element
	Accept(context.Context) error

	// Reject rejects this element
	Reject(context.Context) error
}

Decidable represents an element that can be decided on

type EVM

type EVM interface {
	// Context returns the EVM context
	Context() VMContext

	// Call executes the contract with the given input
	Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

	// CallCode executes the contract with the caller's context
	CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

	// DelegateCall executes the contract with the caller's context and storage
	DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

	// StaticCall executes the contract with read-only access
	StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

	// Create creates a new contract
	Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error)

	// Create2 creates a new contract with deterministic address
	Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error)
}

EVM is the interface for the Ethereum Virtual Machine

type EVMChainReader

type EVMChainReader interface {
	BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
	BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
	HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
	HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
	TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error)
	TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error)

	// This method subscribes to notifications about changes of the head block of
	// the canonical chain.
	SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (Subscription, error)
}

ChainReader provides access to the blockchain. The methods in this interface access raw data from either the canonical chain (when requesting by block number) or any blockchain fork that was previously downloaded and processed by the node. The block number argument can be nil to select the latest canonical block. Reading block headers should be preferred over full blocks whenever possible.

The returned error is NotFound if the requested item does not exist.

type EndpointRequester

type EndpointRequester interface {
	// SendRequest sends an RPC request
	SendRequest(ctx context.Context, method string, params interface{}, reply interface{}, options ...RPCOption) error
}

EndpointRequester makes requests to RPC endpoints

func NewEndpointRequester

func NewEndpointRequester(uri, endpoint string) EndpointRequester

NewEndpointRequester creates a new endpoint requester

type Engine

type Engine interface {
	// Author retrieves the Ethereum address of the account that minted the given block.
	Author(header *types.Header) (common.Address, error)

	// VerifyHeader checks whether a header conforms to the consensus rules of a given engine.
	VerifyHeader(chain ChainHeaderReader, header *types.Header, seal bool) error

	// VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers concurrently.
	VerifyHeaders(chain ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

	// VerifyUncles verifies that the given block's uncles conform to the consensus rules.
	VerifyUncles(chain ChainReader, block *types.Block) error

	// Prepare initializes the consensus fields of a block header according to the rules.
	Prepare(chain ChainHeaderReader, header *types.Header) error

	// Finalize runs any post-transaction state modifications and assembles the final block.
	Finalize(chain ChainHeaderReader, header *types.Header, state StateDB, txs []*types.Transaction,
		uncles []*types.Header) (*types.Block, error)

	// FinalizeAndAssemble runs any post-transaction state modifications and assembles the final block.
	FinalizeAndAssemble(chain ChainHeaderReader, header *types.Header, state StateDB, txs []*types.Transaction,
		uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)

	// Seal generates a new sealing request for the given input block and pushes it to the sealer.
	Seal(chain ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

	// SealHash returns the hash of a block prior to it being sealed.
	SealHash(header *types.Header) common.Hash

	// CalcDifficulty is the difficulty adjustment algorithm.
	CalcDifficulty(chain ChainHeaderReader, time uint64, parent *types.Header) *big.Int

	// Close terminates any background threads maintained by the consensus engine.
	Close() error
}

Engine is an algorithm agnostic consensus engine.

type EthCallRequest

type EthCallRequest struct {
	RequestArgs []byte
}

EthCallRequest represents an ethereum call request

type FeeConfig

type FeeConfig interface {
	// Basic getters for fee configuration
	GetGasLimit() *big.Int
	GetTargetBlockRate() uint64
	GetMinBaseFee() *big.Int
	GetTargetGas() *big.Int
	GetBaseFeeChangeDenominator() *big.Int
	GetMinBlockGasCost() *big.Int
	GetMaxBlockGasCost() *big.Int
	GetBlockGasCostStep() *big.Int
}

FeeConfig represents the fee configuration

type FeeHistory

type FeeHistory struct {
	OldestBlock      *big.Int     // block corresponding to first response value
	Reward           [][]*big.Int // list every txs priority fee per block
	BaseFee          []*big.Int   // list of each block's base fee
	GasUsedRatio     []float64    // ratio of gas used out of the total available limit
	BlobBaseFee      []*big.Int   // list of each block's blob base fee
	BlobGasUsedRatio []float64    // ratio of blob gas used out of the total available limit
	NextBaseFee      *big.Int     // base fee for the next block
	NextBlobBaseFee  *big.Int     // blob base fee for the next block
}

FeeHistory provides recent fee market data that consumers can use to determine a reasonable maxPriorityFeePerGas value.

type FeeHistoryReader

type FeeHistoryReader interface {
	FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (*FeeHistory, error)
}

FeeHistoryReader provides access to the fee history oracle.

type FilterQuery

type FilterQuery struct {
	BlockHash *common.Hash     // used by eth_getLogs, return logs only from block with this hash
	FromBlock *big.Int         // beginning of the queried range, nil means genesis block
	ToBlock   *big.Int         // end of the range, nil means latest block
	Addresses []common.Address // restricts matches to events created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position AND B in second position
	// {{A}, {B}}         matches topic A in first position AND B in second position
	// {{A, B}, {C, D}}   matches topic (A OR B) in first position AND (C OR D) in second position
	Topics [][]common.Hash
}

FilterQuery contains options for contract log filtering.

type GasEstimator

type GasEstimator interface {
	EstimateGas(ctx context.Context, call CallMsg) (uint64, error)
}

GasEstimator wraps EstimateGas, which tries to estimate the gas needed to execute a specific transaction based on the pending state. There is no guarantee that this is the true gas limit requirement as other transactions may be added or removed by miners, but it should provide a basis for setting a reasonable default.

type GasPricer

type GasPricer interface {
	SuggestGasPrice(ctx context.Context) (*big.Int, error)
}

GasPricer wraps the gas price oracle, which monitors the blockchain to determine the optimal gas price given current fee market conditions.

type GasPricer1559

type GasPricer1559 interface {
	SuggestGasTipCap(ctx context.Context) (*big.Int, error)
}

GasPricer1559 provides access to the EIP-1559 gas price oracle.

type GenericSet

type GenericSet[T comparable] interface {
	Add(items ...T)
	Remove(item T)
	Contains(item T) bool
	Clear()
	Len() int
	List() []T
}

GenericSet is a generic set interface

type GenesisRules added in v0.8.1

type GenesisRules interface {
	IsGenesis() bool

	// Precompile access
	PredicatersExist() bool
	PredicaterExists(addr common.Address) bool
	GetActivePrecompiles() map[common.Address]interface{}
	GetPredicaters() map[common.Address]interface{}
	GetAccepterPrecompiles() map[common.Address]interface{}
}

GenesisRules defines the Genesis-specific fork rules

type GetValidatorOutput

type GetValidatorOutput struct {
	NodeID    NodeID
	PublicKey []byte
	Weight    uint64
}

GetValidatorOutput represents validator information

type GossipHandler

type GossipHandler interface {
	// HandleEthTxs handles ethereum transaction gossip
	HandleEthTxs(nodeID NodeID, msg GossipMessage) error
}

GossipHandler handles gossip messages

type GossipMessage

type GossipMessage interface {
	// Bytes returns the message bytes
	Bytes() []byte
}

GossipMessage represents a gossip message

type Hash

type Hash struct {
	Hash [32]byte
}

Hash represents a hash payload

func ParseHash

func ParseHash(bytes []byte) (*Hash, error)

ParseHash parses a hash payload

type HealthChecker

type HealthChecker interface {
	HealthCheck() (interface{}, error)
}

HealthChecker provides health check capability

type ID

type ID [32]byte

ID represents a generic identifier

func (ID) String

func (id ID) String() string

String returns the string representation of an ID

type Iteratee

type Iteratee interface {
	// NewIterator creates a new iterator
	NewIterator(prefix []byte, start []byte) ethdb.Iterator
}

Iteratee wraps iteration operations

type Iterator

type Iterator interface {
	ethdb.Iterator
}

Iterator represents an iterator

type KeyValueDeleter

type KeyValueDeleter interface {
	// Delete removes the key from the key-value data store.
	Delete(key []byte) error
}

KeyValueDeleter wraps the Delete method of a backing data store.

type KeyValueReader

type KeyValueReader interface {
	// Has retrieves if a key is present in the key-value data store.
	Has(key []byte) (bool, error)

	// Get retrieves the given key if it's present in the key-value data store.
	Get(key []byte) ([]byte, error)
}

KeyValueReader wraps the Has and Get method of a backing data store.

type KeyValueWriter

type KeyValueWriter interface {
	// Put inserts the given value into the key-value data store.
	Put(key []byte, value []byte) error
}

KeyValueWriter wraps the Put method of a backing data store.

type LeafsRequest

type LeafsRequest struct {
	Root     []byte
	Account  []byte
	Start    []byte
	End      []byte
	Limit    uint16
	NodeType uint
}

LeafsRequest represents a request for trie leafs

type LogFilterer

type LogFilterer interface {
	FilterLogs(ctx context.Context, q FilterQuery) ([]types.Log, error)
	SubscribeFilterLogs(ctx context.Context, q FilterQuery, ch chan<- types.Log) (Subscription, error)
}

FilterLogs executes a log filter operation, blocking during execution and returning all the results in one batch.

TODO(karalabe): Deprecate when the subscription one can return past data too.

type Message

type Message interface {
	From() common.Address
	To() *common.Address
	GasPrice() *big.Int
	GasFeeCap() *big.Int
	GasTipCap() *big.Int
	Gas() uint64
	Value() *big.Int
	Nonce() uint64
	IsFake() bool
	Data() []byte
	AccessList() types.AccessList
}

Message represents a transaction message

type MessageSignatureRequest

type MessageSignatureRequest struct {
	MessageID []byte
}

MessageSignatureRequest represents a request for message signature

type Metrics

type Metrics interface {
	// IncCounter increments a counter metric
	IncCounter(name string)

	// AddSample adds a sample to a metric
	AddSample(name string, value float64)

	// SetGauge sets a gauge metric
	SetGauge(name string, value float64)
}

Metrics provides metric collection

type MockableTimer

type MockableTimer interface {
	Time() time.Time
	Set(time time.Time)
	Advance(duration time.Duration)
}

MockableTimer is an interface for a mockable clock

type Network

type Network interface {
	// SendAppRequest sends an application request to specified nodes
	SendAppRequest(ctx context.Context, nodeIDs Set, requestID uint32, request []byte) error

	// SendAppResponse sends an application response to a specific node
	SendAppResponse(ctx context.Context, nodeID NodeID, requestID uint32, response []byte) error

	// SendAppGossip gossips application data to peers
	SendAppGossip(ctx context.Context, config SendConfig, appGossipBytes []byte) error

	// SendCrossChainAppRequest sends a cross-chain app request
	SendCrossChainAppRequest(ctx context.Context, chainID ChainID, requestID uint32, appRequestBytes []byte) error

	// SendCrossChainAppResponse sends a cross-chain app response
	SendCrossChainAppResponse(ctx context.Context, chainID ChainID, requestID uint32, appResponseBytes []byte) error
}

Network provides network operations

type NodeConsensus

type NodeConsensus interface {
	// GetConsensusParamsAt returns consensus parameters at a given block height
	GetConsensusParamsAt(ctx context.Context, blockHeight uint64) (*NodeConsensusParams, error)

	// IsUpgradeActive checks if an upgrade is active at a given timestamp
	IsUpgradeActive(upgradeID string, timestamp uint64) bool
}

NodeConsensus provides chain-specific consensus information for node integration

type NodeConsensusParams

type NodeConsensusParams struct {
	// BlockGasCost is the base gas cost for a block
	BlockGasCost uint64

	// BlockGasLimit is the maximum gas allowed in a block
	BlockGasLimit uint64

	// MinBaseFee is the minimum base fee
	MinBaseFee uint64

	// TargetBlockRate is the target rate for block production
	TargetBlockRate uint64

	// BaseFeeChangeDenominator controls base fee adjustment rate
	BaseFeeChangeDenominator uint64

	// MinBlockGasCost is the minimum gas cost for a block
	MinBlockGasCost uint64

	// MaxBlockGasCost is the maximum gas cost for a block
	MaxBlockGasCost uint64

	// BlockGasCostStep is the step size for block gas cost changes
	BlockGasCostStep uint64
}

NodeConsensusParams represents consensus parameters for node integration

type NodeID

type NodeID [32]byte

NodeID is a 32-byte identifier for nodes

func (NodeID) String

func (id NodeID) String() string

String returns the string representation of a NodeID

type P2PClient

type P2PClient interface {
	// SendRequest sends a request to a peer
	SendRequest(ctx context.Context, nodeID NodeID, request []byte, responseHandler func([]byte, error)) error

	// TrackBandwidth tracks bandwidth usage
	TrackBandwidth(nodeID NodeID, bandwidth float64)
}

P2PClient provides peer-to-peer communication

type PeerTracker

type PeerTracker interface {
	// Connected notifies that a peer connected
	Connected(nodeID NodeID, version *Version)

	// Disconnected notifies that a peer disconnected
	Disconnected(nodeID NodeID)

	// NumPeers returns the number of connected peers
	NumPeers() int

	// ConnectedPeers returns the set of connected peers
	ConnectedPeers() []NodeID
}

PeerTracker tracks peer information

type PendingContractCaller

type PendingContractCaller interface {
	PendingCallContract(ctx context.Context, call CallMsg) ([]byte, error)
}

PendingContractCaller can be used to perform calls against the pending state.

type PendingStateEventer

type PendingStateEventer interface {
	SubscribePendingTransactions(ctx context.Context, ch chan<- *types.Transaction) (Subscription, error)
}

A PendingStateEventer provides access to real time notifications about changes to the pending state.

type PendingStateReader

type PendingStateReader interface {
	PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error)
	PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error)
	PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
	PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
	PendingTransactionCount(ctx context.Context) (uint, error)
}

A PendingStateReader provides access to the pending state, which is the result of all known executable transactions which have not yet been included in the blockchain. It is commonly used to display the result of 'unconfirmed' actions (e.g. wallet value transfers) initiated by the user. The PendingNonceAt operation is a good way to retrieve the next available transaction nonce for a specific account.

type PluginRegistry

type PluginRegistry interface {
	// Register registers a VM factory with a name
	Register(name string, factory VMFactory) error

	// Get retrieves a VM factory by name
	Get(name string) (VMFactory, error)

	// List returns all registered VM names
	List() []string
}

PluginRegistry manages VM plugins

var GlobalRegistry PluginRegistry = &defaultRegistry{
	factories: make(map[string]VMFactory),
}

GlobalRegistry is the global plugin registry

type PrecompileConfig

type PrecompileConfig interface {
	Address() common.Address
	IsDisabled() bool
	Timestamp() *uint64
}

PrecompileConfig represents a precompile configuration

type PrecompileModule

type PrecompileModule interface {
	// Address returns the address of the precompile
	Address() common.Address

	// Contract returns the precompile contract
	Contract() interface{}

	// Configurator returns the configurator for this precompile
	Configurator() interface{}

	// DefaultConfig returns the default config for this precompile
	DefaultConfig() interface{}

	// MakeConfig creates a new config instance
	MakeConfig() interface{}

	// ConfigKey returns the configuration key for this module
	ConfigKey() string
}

PrecompileModule represents a precompile module

func GetPrecompileModule

func GetPrecompileModule(key string) (PrecompileModule, bool)

GetPrecompileModule is a convenience function that uses the global registry

func GetPrecompileModuleByAddress

func GetPrecompileModuleByAddress(address common.Address) (PrecompileModule, bool)

GetPrecompileModuleByAddress is a convenience function that uses the global registry

type PrecompileRegistry

type PrecompileRegistry interface {
	// GetPrecompileModule returns a precompile module by key
	GetPrecompileModule(key string) (PrecompileModule, bool)

	// GetPrecompileModuleByAddress returns a precompile module by address
	GetPrecompileModuleByAddress(address common.Address) (PrecompileModule, bool)

	// RegisteredModules returns all registered modules
	RegisteredModules() []PrecompileModule
}

PrecompileRegistry manages precompile modules

func GetPrecompileRegistry

func GetPrecompileRegistry() PrecompileRegistry

GetPrecompileRegistry returns the global precompile registry

type PrefixDB

type PrefixDB interface {
	Database
}

PrefixDB wraps a database with a key prefix

type RPCOption

type RPCOption func(*RPCOptions)

RPCOption configures an RPC request

type RPCOptions

type RPCOptions struct {
	Headers http.Header
}

RPCOptions holds RPC request options

type RequestHandler

type RequestHandler interface {
	// HandleTrieLeafsRequest handles trie leafs requests
	HandleTrieLeafsRequest(ctx context.Context, nodeID NodeID, requestID uint32, request LeafsRequest) ([]byte, error)

	// HandleBlockRequest handles block requests
	HandleBlockRequest(ctx context.Context, nodeID NodeID, requestID uint32, request BlockRequest) ([]byte, error)

	// HandleCodeRequest handles code requests
	HandleCodeRequest(ctx context.Context, nodeID NodeID, requestID uint32, request CodeRequest) ([]byte, error)

	// HandleMessageSignatureRequest handles message signature requests
	HandleMessageSignatureRequest(ctx context.Context, nodeID NodeID, requestID uint32, request MessageSignatureRequest) ([]byte, error)

	// HandleBlockSignatureRequest handles block signature requests
	HandleBlockSignatureRequest(ctx context.Context, nodeID NodeID, requestID uint32, request BlockSignatureRequest) ([]byte, error)
}

RequestHandler handles network requests

type SendConfig

type SendConfig struct {
	NodeIDs       Set
	Validators    int
	NonValidators int
	Peers         int
}

SendConfig configures message sending

type Set

type Set interface {
	Contains(NodeID) bool
	Len() int
	List() []NodeID
	Add(...NodeID)
	Remove(...NodeID)
}

Set represents a set of node IDs

type SharedMemory

type SharedMemory interface {
	// Get retrieves data from shared memory
	Get(key []byte) ([]byte, error)

	// Put stores data in shared memory
	Put(key []byte, value []byte) error

	// Remove deletes data from shared memory
	Remove(key []byte) error

	// NewBatch creates a new batch
	NewBatch() Batch
}

SharedMemory provides atomic operations across chains

type State

type State interface {
	// GetCurrentHeight returns the current blockchain height
	GetCurrentHeight(ctx context.Context) (uint64, error)

	// GetMinimumHeight returns the minimum height
	GetMinimumHeight(ctx context.Context) (uint64, error)

	// GetSubnetID returns the subnet ID for a chain
	GetSubnetID(ctx context.Context, chainID ID) (ID, error)

	// GetValidatorSet returns the validator set at a given height
	GetValidatorSet(ctx context.Context, height uint64, subnetID ID) (map[NodeID]*GetValidatorOutput, error)
}

State provides access to validator state

type StateDB

type StateDB interface {
	GetBalance(common.Address) *uint256.Int
	GetNonce(common.Address) uint64
	GetCode(common.Address) []byte
	GetState(common.Address, common.Hash) common.Hash
	Exist(common.Address) bool
	Empty(common.Address) bool
}

StateDB is an EVM database for full state querying

type Status

type Status int

Status represents the status of a block

type SubnetID

type SubnetID [32]byte

SubnetID is a 32-byte subnet identifier

func (SubnetID) String

func (id SubnetID) String() string

String returns the string representation of a SubnetID

type Subscription

type Subscription interface {
	// Unsubscribe cancels the sending of events to the data channel
	// and closes the error channel.
	Unsubscribe()
	// Err returns the subscription error channel. The error channel receives
	// a value if there is an issue with the subscription (e.g. the network connection
	// delivering the events has been closed). Only one value will ever be sent.
	// The error channel is closed by Unsubscribe.
	Err() <-chan error
}

Subscription represents an event subscription where events are delivered on a data channel.

type SyncProgress

type SyncProgress struct {
	StartingBlock uint64 // Block number where sync began
	CurrentBlock  uint64 // Current block number where sync is at
	HighestBlock  uint64 // Highest alleged block number in the chain
}

SyncProgress gives progress indications when the node is synchronising with the Ethereum network.

type Timestamp

type Timestamp struct {
	Unix int64
}

Timestamp represents a block timestamp

type TransactionReader

type TransactionReader interface {
	// TransactionByHash checks the pool of pending transactions in addition to the
	// blockchain. The isPending return value indicates whether the transaction has been
	// mined yet. Note that the transaction may not be part of the canonical chain even if
	// it's not pending.
	TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error)
	// TransactionReceipt returns the receipt of a mined transaction. Note that the
	// transaction may not be included in the current canonical chain even if a receipt
	// exists.
	TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
}

TransactionReader provides access to past transactions and their receipts. Implementations may impose arbitrary restrictions on the transactions and receipts that can be retrieved. Historic transactions may not be available.

Avoid relying on this interface if possible. Contract logs (through the LogFilterer interface) are more reliable and usually safer in the presence of chain reorganisations.

The returned error is NotFound if the requested item does not exist.

type TransactionSender

type TransactionSender interface {
	SendTransaction(ctx context.Context, tx *types.Transaction) error
}

TransactionSender wraps transaction sending. The SendTransaction method injects a signed transaction into the pending transaction pool for execution. If the transaction was a contract creation, the TransactionReceipt method can be used to retrieve the contract address after the transaction has been mined.

The transaction must be signed and have a valid nonce.

type TxContext

type TxContext struct {
	Origin   common.Address
	GasPrice *big.Int
}

TxContext provides context about the transaction

type UnsignedMessage

type UnsignedMessage struct {
	NetworkID     uint32
	SourceChainID common.Hash
	Payload       []byte
}

UnsignedMessage represents an unsigned warp message

func NewUnsignedMessage

func NewUnsignedMessage(networkID uint32, chainID [32]byte, payload []byte) (*UnsignedMessage, error)

NewUnsignedMessage creates a new unsigned warp message

func ParseUnsignedMessage

func ParseUnsignedMessage(bytes []byte) (*UnsignedMessage, error)

ParseUnsignedMessage parses raw bytes into an unsigned warp message

func (*UnsignedMessage) Bytes added in v0.8.1

func (m *UnsignedMessage) Bytes() []byte

Bytes returns the byte representation of the unsigned message

func (*UnsignedMessage) ID added in v0.8.1

func (m *UnsignedMessage) ID() common.Hash

ID returns the hash of the unsigned message

type VMContext

type VMContext interface {
	// CanTransfer checks if the account has enough balance
	CanTransfer(db StateDB, addr common.Address, amount *big.Int) bool

	// Transfer transfers amount from one account to another
	Transfer(db StateDB, sender, recipient common.Address, amount *big.Int) error

	// GetHash returns the hash of a block by number
	GetHash(n uint64) common.Hash

	// Message information
	Origin() common.Address
	GasPrice() *big.Int
	BlockNumber() *big.Int
	Time() uint64
	Difficulty() *big.Int
	GasLimit() uint64
	Coinbase() common.Address
}

VMContext provides the context for EVM execution

type VMFactory

type VMFactory interface {
	// New creates a new VM instance
	New() (interface{}, error)
}

VMFactory creates VM instances

type Validator

type Validator interface {
	// NodeID returns the validator's node ID
	NodeID() NodeID

	// Weight returns the validator's weight
	Weight() uint64
}

Validator represents a validator

type ValidatorData

type ValidatorData struct {
	NodeID    NodeID
	PublicKey []byte
	Weight    uint64
}

ValidatorData contains validator information

type ValidatorOutput added in v0.8.1

type ValidatorOutput struct {
	NodeID    common.Hash
	PublicKey *BLSPublicKey
	Weight    uint64
}

ValidatorOutput represents a validator in the validator set

type ValidatorState

type ValidatorState interface {
	// GetCurrentHeight returns the current P-chain height
	GetCurrentHeight(ctx context.Context) (uint64, error)

	// GetValidatorSet returns the validator set at a given height
	GetValidatorSet(ctx context.Context, height uint64, subnetID common.Hash) (map[common.Hash]*ValidatorOutput, error)

	// GetMinimumHeight returns the minimum height
	GetMinimumHeight(ctx context.Context) (uint64, error)

	// GetSubnetID returns the subnet ID for a given chain ID
	GetSubnetID(ctx context.Context, chainID common.Hash) (common.Hash, error)
}

ValidatorState provides access to validator information

type Version

type Version struct {
	// Application version
	App uint32

	// Application name
	AppName string

	// Version timestamp
	VersionTime time.Time

	// Git commit
	GitCommit string
}

Version represents peer version information

type VersionDB

type VersionDB interface {
	Database
	// Commit commits the current database state
	Commit() error
	// Abort aborts the current database operations
	Abort()
}

VersionDB provides versioned database operations

func NewVersionDB

func NewVersionDB(db Database) VersionDB

NewVersionDB creates a new version database

type WarpChainContext

type WarpChainContext interface {
	GetValidatorPublicKey(validationID [32]byte) ([]byte, error)
}

WarpChainContext interface for warp consensus operations

type WarpSignedMessage

type WarpSignedMessage struct {
	UnsignedMessage UnsignedMessage
	Signature       *BLSSignature
	SourceChainID   common.Hash
}

WarpSignedMessage represents a signed warp message

func NewMessage

func NewMessage(unsignedMsg *UnsignedMessage, sig *BLSSignature) (*WarpSignedMessage, error)

NewMessage creates a new signed warp message

func ParseMessage

func ParseMessage(bytes []byte) (*WarpSignedMessage, error)

ParseMessage parses raw bytes into a warp message

func (*WarpSignedMessage) ID added in v0.8.1

func (m *WarpSignedMessage) ID() common.Hash

ID returns the ID of the unsigned message

func (*WarpSignedMessage) Payload added in v0.8.1

func (m *WarpSignedMessage) Payload() []byte

Payload returns the payload from the unsigned message

type WarpValidator added in v0.8.1

type WarpValidator struct {
	PublicKey      *BLSPublicKey
	PublicKeyBytes []byte
	Weight         uint64
	NodeIDs        []common.Hash
}

WarpValidator represents a validator with BLS public key and weight

func (*WarpValidator) Compare added in v0.8.1

func (v *WarpValidator) Compare(o *WarpValidator) int

Directories

Path Synopsis
core
asm
eth
ethdb

Jump to

Keyboard shortcuts

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