api

package
v0.2300.10 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2024 License: Apache-2.0 Imports: 35 Imported by: 25

Documentation

Overview

Package api provides the implementation agnostic consensus API.

Index

Constants

View Source
const (
	// ModuleName is the module name used for error definitions.
	ModuleName = "consensus"

	// HeightLatest is the height that represents the most recent block height.
	HeightLatest int64 = 0
)
View Source
const BlockMetadataMaxSize = 16_384

BlockMetadataMaxSize is the maximum size of a fully populated and signed block metadata transaction.

This should be less than any reasonably configured MaxTxSize.

Variables

View Source
var (
	// ErrNoCommittedBlocks is the error returned when there are no committed
	// blocks and as such no state can be queried.
	ErrNoCommittedBlocks = errors.New(ModuleName, 1, "consensus: no committed blocks")

	// ErrOversizedTx is the error returned when the given transaction is too big to be processed.
	ErrOversizedTx = errors.New(ModuleName, 2, "consensus: oversized transaction")

	// ErrVersionNotFound is the error returned when the given version (height) cannot be found,
	// possibly because it was pruned.
	ErrVersionNotFound = errors.New(ModuleName, 3, "consensus: version not found")

	// ErrUnsupported is the error returned when the given method is not supported by the consensus
	// backend.
	ErrUnsupported = errors.New(ModuleName, 4, "consensus: method not supported")

	// ErrDuplicateTx is the error returned when the transaction already exists in the mempool.
	ErrDuplicateTx = errors.New(ModuleName, 5, "consensus: duplicate transaction")

	// ErrInvalidArgument is the error returned when the request contains an invalid argument.
	ErrInvalidArgument = errors.New(ModuleName, 6, "consensus: invalid argument")

	// SystemMethods is a map of all system methods.
	SystemMethods = map[transaction.MethodName]struct{}{
		MethodMeta: {},
	}
)

MethodMeta is the method name for the special block metadata transaction.

Functions

func NewBlockMetadataTx added in v0.2300.0

func NewBlockMetadataTx(meta *BlockMetadata) *transaction.Transaction

NewBlockMetadataTx creates a new block metadata transaction.

func RegisterService

func RegisterService(server *grpc.Server, service ClientBackend)

RegisterService registers a new client backend service with the given gRPC server.

func SignAndSubmitTx

func SignAndSubmitTx(ctx context.Context, backend Backend, signer signature.Signer, tx *transaction.Transaction) error

SignAndSubmitTx is a helper function that signs and submits a transaction to the consensus backend.

If the nonce is set to zero, it will be automatically filled in based on the current consensus state.

If the fee is set to nil, it will be automatically filled in based on gas estimation and current gas price discovery.

func SignAndSubmitTxWithProof added in v0.2202.0

func SignAndSubmitTxWithProof(ctx context.Context, backend Backend, signer signature.Signer, tx *transaction.Transaction) (*transaction.SignedTransaction, *transaction.Proof, error)

SignAndSubmitTxWithProof is a helper function that signs and submits a transaction to the consensus backend and creates a proof of inclusion.

If the nonce is set to zero, it will be automatically filled in based on the current consensus state.

If the fee is set to nil, it will be automatically filled in based on gas estimation and current gas price discovery.

Types

type Backend

type Backend interface {
	service.BackgroundService
	ServicesBackend

	// SupportedFeatures returns the features supported by this consensus backend.
	SupportedFeatures() FeatureMask

	// Synced returns a channel that is closed once synchronization is
	// complete.
	Synced() <-chan struct{}

	// ConsensusKey returns the consensus signing key.
	ConsensusKey() signature.PublicKey

	// GetAddresses returns the consensus backend addresses.
	GetAddresses() ([]node.ConsensusAddress, error)

	// Checkpointer returns the checkpointer associated with consensus state.
	//
	// This may be nil in case checkpoints are disabled.
	Checkpointer() checkpoint.Checkpointer

	// RegisterP2PService registers the P2P service used for light client state sync.
	RegisterP2PService(p2pAPI.Service) error
}

Backend is an interface that a consensus backend must provide.

type Block

type Block struct {
	// Height contains the block height.
	Height int64 `json:"height"`
	// Hash contains the block header hash.
	Hash hash.Hash `json:"hash"`
	// Time is the second-granular consensus time.
	Time time.Time `json:"time"`
	// StateRoot is the Merkle root of the consensus state tree.
	StateRoot mkvsNode.Root `json:"state_root"`
	// Meta contains the consensus backend specific block metadata.
	Meta cbor.RawMessage `json:"meta"`
}

Block is a consensus block.

While some common fields are provided, most of the structure is dependent on the actual backend implementation.

type BlockMetadata added in v0.2300.0

type BlockMetadata struct {
	// StateRoot is the state root after executing all logic in the block.
	StateRoot hash.Hash `json:"state_root"`
	// EventsRoot is the provable events root.
	EventsRoot []byte `json:"events_root"`
}

BlockMetadata contains additional metadata related to the executing block.

The metadata is included in the form of a special transaction where this structure is the transaction body.

func (*BlockMetadata) ValidateBasic added in v0.2300.0

func (bm *BlockMetadata) ValidateBasic() error

ValidateBasic performs basic block metadata structure validation.

type ClientBackend

type ClientBackend interface {
	TransactionAuthHandler

	// SubmitTx submits a signed consensus transaction and waits for the transaction to be included
	// in a block. Use SubmitTxNoWait if you only need to broadcast the transaction.
	SubmitTx(ctx context.Context, tx *transaction.SignedTransaction) error

	// SubmitTxNoWait submits a signed consensus transaction, but does not wait for the transaction
	// to be included in a block. Use SubmitTx if you need to wait for execution.
	SubmitTxNoWait(ctx context.Context, tx *transaction.SignedTransaction) error

	// SubmitTxWithProof submits a signed consensus transaction, waits for the transaction to be
	// included in a block and returns a proof of inclusion.
	SubmitTxWithProof(ctx context.Context, tx *transaction.SignedTransaction) (*transaction.Proof, error)

	// StateToGenesis returns the genesis state at the specified block height.
	StateToGenesis(ctx context.Context, height int64) (*genesis.Document, error)

	// EstimateGas calculates the amount of gas required to execute the given transaction.
	EstimateGas(ctx context.Context, req *EstimateGasRequest) (transaction.Gas, error)

	// GetBlock returns a consensus block at a specific height.
	GetBlock(ctx context.Context, height int64) (*Block, error)

	// GetLightBlock returns a light version of the consensus layer block that can be used for light
	// client verification.
	GetLightBlock(ctx context.Context, height int64) (*LightBlock, error)

	// GetLightBlockForState returns a light block for the state as of executing the consensus layer
	// block at the specified height. Note that the height of the returned block may differ
	// depending on consensus layer implementation details.
	//
	// In case light block for the given height is not yet available, it returns ErrVersionNotFound.
	GetLightBlockForState(ctx context.Context, height int64) (*LightBlock, error)

	// State returns a MKVS read syncer that can be used to read consensus state from a remote node
	// and verify it against the trusted local root.
	State() syncer.ReadSyncer

	// GetParameters returns the consensus parameters for a specific height.
	GetParameters(ctx context.Context, height int64) (*Parameters, error)

	// SubmitEvidence submits evidence of misbehavior.
	SubmitEvidence(ctx context.Context, evidence *Evidence) error

	// GetTransactions returns a list of all transactions contained within a
	// consensus block at a specific height.
	//
	// NOTE: Any of these transactions could be invalid.
	GetTransactions(ctx context.Context, height int64) ([][]byte, error)

	// GetTransactionsWithResults returns a list of transactions and their
	// execution results, contained within a consensus block at a specific
	// height.
	GetTransactionsWithResults(ctx context.Context, height int64) (*TransactionsWithResults, error)

	// GetTransactionsWithProofs returns a list of all transactions and their proofs of inclusion
	// contained within a consensus block at a specific height.
	GetTransactionsWithProofs(ctx context.Context, height int64) (*TransactionsWithProofs, error)

	// GetUnconfirmedTransactions returns a list of transactions currently in the local node's
	// mempool. These have not yet been included in a block.
	GetUnconfirmedTransactions(ctx context.Context) ([][]byte, error)

	// WatchBlocks returns a channel that produces a stream of consensus
	// blocks as they are being finalized.
	WatchBlocks(ctx context.Context) (<-chan *Block, pubsub.ClosableSubscription, error)

	// GetGenesisDocument returns the original genesis document.
	GetGenesisDocument(ctx context.Context) (*genesis.Document, error)

	// GetChainContext returns the chain domain separation context.
	GetChainContext(ctx context.Context) (string, error)

	// GetStatus returns the current status overview.
	GetStatus(ctx context.Context) (*Status, error)

	// GetNextBlockState returns the state of the next block being voted on by validators.
	GetNextBlockState(ctx context.Context) (*NextBlockState, error)

	// Beacon returns the beacon backend.
	Beacon() beacon.Backend

	// Registry returns the registry backend.
	Registry() registry.Backend

	// Staking returns the staking backend.
	Staking() staking.Backend

	// Scheduler returns the scheduler backend.
	Scheduler() scheduler.Backend

	// Governance returns the governance backend.
	Governance() governance.Backend

	// RootHash returns the roothash backend.
	RootHash() roothash.Backend
}

ClientBackend is a consensus interface used by clients that connect to the local full node.

func NewConsensusClient

func NewConsensusClient(c *grpc.ClientConn) ClientBackend

NewConsensusClient creates a new gRPC consensus client service.

type EstimateGasRequest

type EstimateGasRequest struct {
	Signer      signature.PublicKey      `json:"signer"`
	Transaction *transaction.Transaction `json:"transaction"`
}

EstimateGasRequest is a EstimateGas request.

type Evidence

type Evidence struct {
	// Meta contains the consensus backend specific evidence.
	Meta []byte `json:"meta"`
}

Evidence is evidence of a node's Byzantine behavior.

type FeatureMask

type FeatureMask uint8

FeatureMask is the consensus backend feature bitmask.

const (
	// FeatureServices indicates support for communicating with consensus services.
	FeatureServices FeatureMask = 1 << 0

	// FeatureFullNode indicates that the consensus backend is independently fully verifying all
	// consensus-layer blocks.
	FeatureFullNode FeatureMask = 1 << 1

	// FeatureArchiveNode indicates that the node is an archive node.
	FeatureArchiveNode FeatureMask = 1 << 2
)

func (FeatureMask) Has

func (m FeatureMask) Has(f FeatureMask) bool

Has checks whether the feature bitmask includes specific features.

func (FeatureMask) String

func (m FeatureMask) String() string

String returns a string representation of the consensus backend feature bitmask.

type GetSignerNonceRequest

type GetSignerNonceRequest struct {
	AccountAddress staking.Address `json:"account_address"`
	Height         int64           `json:"height"`
}

GetSignerNonceRequest is a GetSignerNonce request.

type HaltHook added in v0.2012.7

type HaltHook func(ctx context.Context, blockHeight int64, epoch beacon.EpochTime, err error)

HaltHook is a function that gets called when consensus needs to halt for some reason.

type LightBlock added in v0.2010.0

type LightBlock struct {
	// Height contains the block height.
	Height int64 `json:"height"`
	// Meta contains the consensus backend specific light block.
	Meta []byte `json:"meta"`
}

LightBlock is a light consensus block suitable for syncing light clients.

type LightClient added in v0.2300.0

type LightClient interface {
	// GetStoredLightBlock retrieves a light block from the local light block store without doing
	// any remote queries.
	GetStoredLightBlock(height int64) (*LightBlock, error)

	// GetLightBlock queries peers for a specific light block.
	GetLightBlock(ctx context.Context, height int64) (*LightBlock, rpc.PeerFeedback, error)

	// GetParameters queries peers for consensus parameters for a specific height.
	GetParameters(ctx context.Context, height int64) (*Parameters, rpc.PeerFeedback, error)

	// SubmitEvidence submits evidence of misbehavior to peers.
	SubmitEvidence(ctx context.Context, evidence *Evidence) (rpc.PeerFeedback, error)
}

LightClient is a consensus light client interface.

type LightClientStatus added in v0.2300.0

type LightClientStatus struct {
	// LatestHeight is the height of the latest block.
	LatestHeight int64 `json:"latest_height"`
	// LatestHash is the hash of the latest block.
	LatestHash hash.Hash `json:"latest_hash"`
	// LatestTime is the timestamp of the latest block.
	LatestTime time.Time `json:"latest_time"`

	// OldestHeight is the height of the oldest block.
	OldestHeight int64 `json:"oldest_height"`
	// LatestHash is the hash of the oldest block.
	OldestHash hash.Hash `json:"oldest_hash"`
	// OldestTime is the timestamp of the oldest block.
	OldestTime time.Time `json:"oldest_time"`

	// PeersIDs are the light client provider peer identifiers.
	PeerIDs []string `json:"peer_ids"`
}

LightClientStatus is the current light client status overview.

type LightService added in v0.2300.0

type LightService interface {
	service.BackgroundService

	LightClient

	// GetStatus returns the current status overview.
	GetStatus() (*LightClientStatus, error)
}

LightService is a consensus light client service.

type NextBlockState added in v0.2200.0

type NextBlockState struct {
	Height int64 `json:"height"`

	NumValidators uint64 `json:"num_validators"`
	VotingPower   uint64 `json:"voting_power"`

	Prevotes   Votes `json:"prevotes"`
	Precommits Votes `json:"precommits"`
}

NextBlockState has the state of the next block being voted on by validators.

type NoOpSubmissionManager added in v0.2103.13

type NoOpSubmissionManager struct{}

NoOpSubmissionManager implements a submission manager that doesn't support submitting transactions.

func (*NoOpSubmissionManager) EstimateGasAndSetFee added in v0.2103.13

EstimateGasAndSetFee implements SubmissionManager.

func (*NoOpSubmissionManager) PriceDiscovery added in v0.2103.13

func (m *NoOpSubmissionManager) PriceDiscovery() PriceDiscovery

PriceDiscovery implements SubmissionManager.

func (*NoOpSubmissionManager) SignAndSubmitTx added in v0.2103.13

SignAndSubmitTx implements SubmissionManager.

func (*NoOpSubmissionManager) SignAndSubmitTxWithProof added in v0.2202.0

SignAndSubmitTxWithProof implements SubmissionManager.

type P2PStatus added in v0.2300.0

type P2PStatus struct {
	// PubKey is the public key used for consensus P2P communication.
	PubKey signature.PublicKey `json:"pub_key"`

	// PeerID is the peer ID derived by hashing peer's public key.
	PeerID string `json:"peer_id"`

	// Addresses is a list of configured P2P addresses used when registering the node.
	Addresses []node.ConsensusAddress `json:"addresses"`

	// Peers is a list of node's peers.
	Peers []string `json:"peers"`
}

P2PStatus is the P2P status of a node.

type Parameters

type Parameters struct {
	// Height contains the block height these consensus parameters are for.
	Height int64 `json:"height"`
	// Parameters are the backend agnostic consensus parameters.
	Parameters genesis.Parameters `json:"parameters"`
	// Meta contains the consensus backend specific consensus parameters.
	Meta []byte `json:"meta"`
}

Parameters are the consensus backend parameters.

type PriceDiscovery

type PriceDiscovery interface {
	// GasPrice returns the current consensus gas price.
	GasPrice(ctx context.Context) (*quantity.Quantity, error)
}

PriceDiscovery is the consensus fee price discovery interface.

func NewStaticPriceDiscovery

func NewStaticPriceDiscovery(price uint64) (PriceDiscovery, error)

NewStaticPriceDiscovery creates a price discovery mechanism which always returns the same static price specified at construction time.

type ServicesBackend

type ServicesBackend interface {
	ClientBackend

	// RegisterHaltHook registers a function to be called when the consensus needs to halt.
	RegisterHaltHook(hook HaltHook)

	// SubmissionManager returns the transaction submission manager.
	SubmissionManager() SubmissionManager

	// KeyManager returns the keymanager backend.
	KeyManager() keymanager.Backend
}

ServicesBackend is an interface for consensus backends which indicate support for communicating with consensus services.

In case the feature is absent, these methods may return nil or ErrUnsupported.

type Status

type Status struct {
	// Status is an concise status of the consensus backend.
	Status StatusState `json:"status"`

	// Version is the version of the consensus protocol that the node is using.
	Version version.Version `json:"version"`
	// Backend is the consensus backend identifier.
	Backend string `json:"backend"`
	// Features are the indicated consensus backend features.
	Features FeatureMask `json:"features"`

	// LatestHeight is the height of the latest block.
	LatestHeight int64 `json:"latest_height"`
	// LatestHash is the hash of the latest block.
	LatestHash hash.Hash `json:"latest_hash"`
	// LatestTime is the timestamp of the latest block.
	LatestTime time.Time `json:"latest_time"`
	// LatestEpoch is the epoch of the latest block.
	LatestEpoch beacon.EpochTime `json:"latest_epoch"`
	// LatestStateRoot is the Merkle root of the consensus state tree.
	LatestStateRoot mkvsNode.Root `json:"latest_state_root"`

	// GenesisHeight is the height of the genesis block.
	GenesisHeight int64 `json:"genesis_height"`
	// GenesisHash is the hash of the genesis block.
	GenesisHash hash.Hash `json:"genesis_hash"`

	// LastRetainedHeight is the height of the oldest retained block.
	LastRetainedHeight int64 `json:"last_retained_height"`
	// LastRetainedHash is the hash of the oldest retained block.
	LastRetainedHash hash.Hash `json:"last_retained_hash"`

	// ChainContext is the chain domain separation context.
	ChainContext string `json:"chain_context"`

	// IsValidator returns whether the current node is part of the validator set.
	IsValidator bool `json:"is_validator"`

	// P2P is the P2P status of the node.
	P2P *P2PStatus `json:"p2p,omitempty"`
}

Status is the current status overview.

type StatusState added in v0.2202.0

type StatusState uint8

StatusState is the concise status state of the consensus backend.

var (
	// StatusStateReady is the ready status state.
	StatusStateReady StatusState
	// StatusStateSyncing is the syncing status state.
	StatusStateSyncing StatusState = 1
)

func (StatusState) MarshalText added in v0.2202.0

func (s StatusState) MarshalText() ([]byte, error)

MarshalText encodes a StatusState into text form.

func (StatusState) String added in v0.2202.0

func (s StatusState) String() string

String returns a string representation of a status state.

func (*StatusState) UnmarshalText added in v0.2202.0

func (s *StatusState) UnmarshalText(text []byte) error

UnmarshalText decodes a text slice into a StatusState.

type SubmissionManager

type SubmissionManager interface {
	// PriceDiscovery returns the configured price discovery mechanism instance.
	PriceDiscovery() PriceDiscovery

	// EstimateGasAndSetFee populates the fee field in the transaction if not already set.
	EstimateGasAndSetFee(ctx context.Context, signer signature.Signer, tx *transaction.Transaction) error

	// SignAndSubmitTx populates the nonce and fee fields in the transaction, signs the transaction
	// with the passed signer and submits it to consensus backend.
	//
	// It also automatically handles retries in case the nonce was incorrectly estimated.
	SignAndSubmitTx(ctx context.Context, signer signature.Signer, tx *transaction.Transaction) error

	// SignAndSubmitTxWithProof populates the nonce and fee fields in the transaction, signs
	// the transaction with the passed signer, submits it to consensus backend and creates
	// a proof of inclusion.
	//
	// It also automatically handles retries in case the nonce was incorrectly estimated.
	SignAndSubmitTxWithProof(ctx context.Context, signer signature.Signer, tx *transaction.Transaction) (*transaction.SignedTransaction, *transaction.Proof, error)
}

SubmissionManager is a transaction submission manager interface.

func NewSubmissionManager

func NewSubmissionManager(backend ClientBackend, priceDiscovery PriceDiscovery, maxFee uint64) SubmissionManager

NewSubmissionManager creates a new transaction submission manager.

type TransactionAuthHandler

type TransactionAuthHandler interface {
	// GetSignerNonce returns the nonce that should be used by the given
	// signer for transmitting the next transaction.
	GetSignerNonce(ctx context.Context, req *GetSignerNonceRequest) (uint64, error)
}

TransactionAuthHandler is the interface for handling transaction authentication (checking nonces and fees).

type TransactionsWithProofs added in v0.2300.0

type TransactionsWithProofs struct {
	Transactions [][]byte `json:"transactions"`
	Proofs       [][]byte `json:"proofs"`
}

TransactionsWithProofs is GetTransactionsWithProofs response.

Proofs[i] is a proof of block inclusion for Transactions[i].

type TransactionsWithResults

type TransactionsWithResults struct {
	Transactions [][]byte          `json:"transactions"`
	Results      []*results.Result `json:"results"`
}

TransactionsWithResults is GetTransactionsWithResults response.

Results[i] are the results of executing Transactions[i].

type Vote added in v0.2200.0

type Vote struct {
	NodeID        signature.PublicKey `json:"node_id"`
	EntityID      signature.PublicKey `json:"entity_id"`
	EntityAddress staking.Address     `json:"entity_address"`
	VotingPower   uint64              `json:"voting_power"`
}

Vote contains metadata about a vote for the next block.

type Votes added in v0.2200.0

type Votes struct {
	VotingPower uint64  `json:"voting_power"`
	Ratio       float64 `json:"ratio"`
	Votes       []Vote  `json:"votes"`
}

Votes are the votes for the next block.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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