Version: v0.2103.7 Latest Latest

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

Go to latest
Published: Dec 17, 2021 License: Apache-2.0 Imports: 32 Imported by: 11



Package consensus provides the implementation agnostic consensus backend.



View Source
const (

	// HeightLatest is the height that represents the most recent block height.
	HeightLatest int64 = 0


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


func RegisterLightService

func RegisterLightService(server *grpc.Server, service LightClientBackend)

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

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.


type Backend

type Backend interface {

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

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 ClientBackend

type ClientBackend interface {

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

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

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

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

	// 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 limited consensus interface used by clients that connect to the local full node. This is separate from light clients which use the LightClientBackend interface.

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

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 LightClientBackend

type LightClientBackend interface {
	// 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)

	// GetParameters returns the consensus parameters for a specific height.
	GetParameters(ctx context.Context, height int64) (*Parameters, 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

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

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

LightClientBackend is the limited consensus interface used by light clients.

func NewConsensusLightClient

func NewConsensusLightClient(c *grpc.ClientConn) LightClientBackend

NewConsensusLightClient creates a new gRPC consensus light client service.

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 {

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

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

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

Status is the current status overview.

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

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 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].


Path Synopsis

Jump to

Keyboard shortcuts

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