consensus

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2025 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BlockProposal consensusMsgType = "block_proposal"
	BlockAnnounce consensusMsgType = "block_announce"
	Vote          consensusMsgType = "vote"
)
View Source
const (
	ParamUpdatesResolutionType = "param_updates"
)

Variables

View Source
var ParamUpdatesResolution = resolutions.ResolutionConfig{
	ConfirmationThreshold: big.NewRat(1, 2),
	ExpirationPeriod:      7 * 24 * time.Hour,
	ResolveFunc: func(ctx context.Context, app *common.App, resolution *resolutions.Resolution, block *common.BlockContext) error {
		// a resolution with an invalid body should be rejected before this
		var pud ParamUpdatesDeclaration
		err := pud.UnmarshalBinary(resolution.Body)
		if err != nil {
			return err
		}

		app.Service.Logger.Info("Applying param updates", "description", pud.Description, "paramUpdates", pud.ParamUpdates)

		if block.ChainContext.NetworkUpdates == nil {
			block.ChainContext.NetworkUpdates = make(types.ParamUpdates, len(pud.ParamUpdates))
		}
		block.ChainContext.NetworkUpdates.Merge(pud.ParamUpdates)
		return nil
	},
}

Functions

This section is empty.

Types

type AckBroadcaster

type AckBroadcaster func(msg *types.AckRes) error

AckBroadcaster gossips the ack/nack messages to the network type AckBroadcaster func(ack bool, height int64, blkID types.Hash, appHash *types.Hash, Signature []byte) error

type BlkAnnouncer

type BlkAnnouncer func(ctx context.Context, blk *ktypes.Block, ci *ktypes.CommitInfo)

BlkAnnouncer broadcasts the new committed block to the network using the blockAnn message

type BlkRequester

type BlkRequester func(ctx context.Context, height int64) (types.Hash, []byte, *ktypes.CommitInfo, int64, error)

BlkRequester requests the block from the network based on the height

type BlockProcessor

type BlockProcessor interface {
	InitChain(ctx context.Context) (int64, []byte, error)
	SetCallbackFns(applyBlockFn blockprocessor.BroadcastTxFn, addPeer, removePeer func(string) error)

	PrepareProposal(ctx context.Context, txs []*types.Tx) (finalTxs []*ktypes.Transaction, invalidTxs []*ktypes.Transaction, err error)
	ExecuteBlock(ctx context.Context, req *ktypes.BlockExecRequest, syncing bool) (*ktypes.BlockExecResult, error)
	Commit(ctx context.Context, req *ktypes.CommitRequest) error
	Rollback(ctx context.Context, height int64, appHash ktypes.Hash) error
	Close() error

	CheckTx(ctx context.Context, tx *types.Tx, height int64, blockTime time.Time, recheck bool) error

	GetValidators() []*ktypes.Validator
	ConsensusParams() *ktypes.NetworkParameters

	BlockExecutionStatus() *ktypes.BlockExecutionStatus
	HasEvents() bool
	StateHashes() *blockprocessor.StateHashes
}

type BlockStore

type BlockStore interface {
	Best() (height int64, blkHash, appHash types.Hash, stamp time.Time)
	Store(block *ktypes.Block, commitInfo *ktypes.CommitInfo) error
	Get(blkid types.Hash) (*ktypes.Block, *ktypes.CommitInfo, error)
	GetByHeight(height int64) (types.Hash, *ktypes.Block, *ktypes.CommitInfo, error)
	StoreResults(hash types.Hash, results []ktypes.TxResult) error
	Results(hash types.Hash) ([]ktypes.TxResult, error)
}

BlockStore includes both txns and blocks

type BroadcastFns

type BroadcastFns struct {
	ProposalBroadcaster ProposalBroadcaster
	TxAnnouncer         TxAnnouncer
	BlkAnnouncer        BlkAnnouncer
	AckBroadcaster      AckBroadcaster
	BlkRequester        BlkRequester
	RstStateBroadcaster ResetStateBroadcaster
	// DiscoveryReqBroadcaster DiscoveryReqBroadcaster
	TxBroadcaster blockprocessor.BroadcastTxFn
}

type Config

type Config struct {
	RootDir string
	// Signer is the private key of the node.
	PrivateKey crypto.PrivateKey
	// Leader is the public key of the leader.
	Leader crypto.PublicKey
	// GenesisHeight is the initial height of the network.
	GenesisHeight int64

	// ProposeTimeout is the minimum time duration to wait before proposing a new block.
	// Leader can propose a block with transactions as soon as this timeout is reached. Default is 1 second.
	ProposeTimeout time.Duration
	// EmptyBlockTimeout is the maximum time duration to wait before proposing a new block without transactions.
	// Default is 1 minute.
	EmptyBlockTimeout time.Duration
	// BlkPropReannounceInterval is the frequency at which block proposal messages are reannounced by the Leader.
	BlockProposalInterval time.Duration
	// BlkAnnReannounceInterval is the frequency at which block commit messages are reannounced by the Leader.
	// This is also the frequency at which the validators reannounce the ack messages.
	BlockAnnInterval time.Duration
	// CatchUpInterval is the frequency at which the node attempts to catches up with the network if lagging.
	// CatchUpInterval  time.Duration
	BroadcastTxTimeout time.Duration

	// Checkpoint is the initial checkpoint for the leader to sync to.
	Checkpoint config.Checkpoint

	// Interfaces
	DB             *pg.DB
	Mempool        Mempool
	BlockStore     BlockStore
	BlockProcessor BlockProcessor
	Logger         log.Logger
}

Config is the struct given to the constructor, New.

type ConsensusEngine

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

There are three phases in the consensus engine: 1. BlockProposalPhase:

  • Depending on the role, the node is either preparing the block or waiting to receive the proposed block.

2. BlockExecutionPhase:

  • Nodes enter this phase once they have the block to be processed. In this phase, all the transactions in the block are executed, and the appHash is generated. Leader then waits for the votes from the validators and validators respond with ack/nack.

3. BlockCommitPhase: - Once the leader receives the threshold acks with the same appHash as the leader, the block is committed and the leader broadcasts the blockAnn message to the network. Nodes that receive this message will enter into the commit phase where they verify the appHash and commit the block.

func New

func New(cfg *Config) (*ConsensusEngine, error)

New creates a new consensus engine.

func (*ConsensusEngine) AcceptCommit

func (ce *ConsensusEngine) AcceptCommit(height int64, blkID types.Hash, hdr *ktypes.BlockHeader, ci *ktypes.CommitInfo, leaderSig []byte) bool

AcceptCommit handles the blockAnnounce message from the leader. This should be processed only if this is the next block to be committed by the node. This also checks if the node should request the block from its peers. This can happen 1. If the node is a sentry node and doesn't have the block. 2. If the node is a validator and missed the block proposal message.

func (*ConsensusEngine) AcceptProposal

func (ce *ConsensusEngine) AcceptProposal(height int64, blkID, prevBlockID types.Hash, leaderSig []byte, timestamp int64) bool

AcceptProposal determines if the node should download the block for the given proposal. This should not be processed by the leader and the sentry nodes and must return false. Validators should only accept the proposal if they are not currently processing another block and the proposal is for the next block to be processed. If a new proposal for the same height is received, the current proposal execution should be aborted and the new proposal should be processed. If the leader proposes a new block for already committed heights, the validator should send a Nack to the leader with an OutOfSyncProof, indicating the leader to catchup to the correct height before proposing new blocks.

func (*ConsensusEngine) BroadcastTx

func (ce *ConsensusEngine) BroadcastTx(ctx context.Context, tx *types.Tx, sync uint8) (types.Hash, *ktypes.TxResult, error)

BroadcastTx checks the transaction with the mempool and if the verification is successful, broadcasts it to the network. The TxResult will be nil unless sync is set to 1, in which case the BroadcastTx returns only after it is successfully executed in a committed block. This method is effectively [QueueTx] followed, by P2P broadcast of the transaction, followed by optionally waiting for the transaction to be mined.

func (*ConsensusEngine) CancelBlockExecution

func (ce *ConsensusEngine) CancelBlockExecution(height int64, txIDs []types.Hash) error

CancelBlockExecution is used by the leader to manually cancel the block execution if it is taking too long to execute. This method takes the height of the block to be cancelled and the list of long transaction IDs to be evicted from the mempool. One concern is: what if the block finishes execution and the leader tries to cancel it, and the resolutions update some internal state that cannot be reverted?

func (*ConsensusEngine) ConsensusParams

func (ce *ConsensusEngine) ConsensusParams() *ktypes.NetworkParameters

func (*ConsensusEngine) InCatchup

func (ce *ConsensusEngine) InCatchup() bool

func (*ConsensusEngine) NotifyACK

func (ce *ConsensusEngine) NotifyACK(validatorPK []byte, ack types.AckRes)

NotifyACK notifies the consensus engine about the ACK received from the validator.

func (*ConsensusEngine) NotifyBlockCommit

func (ce *ConsensusEngine) NotifyBlockCommit(blk *ktypes.Block, ci *ktypes.CommitInfo, blkID types.Hash, doneFn func())

NotifyBlockCommit is used by the p2p stream handler to notify the consensus engine of a committed block.

func (*ConsensusEngine) NotifyBlockProposal

func (ce *ConsensusEngine) NotifyBlockProposal(blk *ktypes.Block, doneFn func())

NotifyBlockProposal is used by the p2p stream handler to notify the consensus engine of a block proposal. Only a validator should receive block proposals and notify the consensus engine, whereas others should ignore this message.

func (*ConsensusEngine) NotifyDiscoveryMessage

func (ce *ConsensusEngine) NotifyDiscoveryMessage(sender []byte, height int64)

func (*ConsensusEngine) NotifyResetState

func (ce *ConsensusEngine) NotifyResetState(height int64, txIDs []types.Hash, leaderPubKey []byte)

NotifyResetState is used by the p2p stream handler to notify the consensus engine to reset the state to the specified height. Only a validator should receive this message to abort the current block execution.

func (*ConsensusEngine) PromoteLeader

func (ce *ConsensusEngine) PromoteLeader(candidate crypto.PublicKey, height int64) error

func (*ConsensusEngine) QueueTx

func (ce *ConsensusEngine) QueueTx(ctx context.Context, tx *types.Tx) error

QueueTx attempts to add a transaction to the mempool. It is an error if the transaction is already in the mempool. It is an error if the transaction fails CheckTx. This method holds the mempool lock for the duration of the call.

func (*ConsensusEngine) Role

func (ce *ConsensusEngine) Role() types.Role

func (*ConsensusEngine) Start

func (ce *ConsensusEngine) Start(ctx context.Context, fns BroadcastFns, peerFns WhitelistFns) error

func (*ConsensusEngine) Status

func (ce *ConsensusEngine) Status() *ktypes.NodeStatus

func (*ConsensusEngine) SubscribeTx

func (ce *ConsensusEngine) SubscribeTx(txHash ktypes.Hash) (<-chan ktypes.TxResult, error)

func (*ConsensusEngine) UnsubscribeTx

func (ce *ConsensusEngine) UnsubscribeTx(txHash ktypes.Hash)

func (*ConsensusEngine) VerifyCheckpoint

func (ce *ConsensusEngine) VerifyCheckpoint() error

type DB

type DB interface {
	sql.TxMaker // for out-of-consensus writes e.g. setup and meta table writes
	sql.PreparedTxMaker
	sql.ReadTxMaker
	sql.SnapshotTxMaker
}

DB is the interface for the main SQL database. All queries must be executed from within a transaction. A DB can create read transactions or the special two-phase outer write transaction.

type DiscoveryReqBroadcaster

type DiscoveryReqBroadcaster func()

type Mempool

type Mempool interface {
	PeekN(maxTxns, totalSizeLimit int) []*types.Tx
	Remove(txid types.Hash)
	RecheckTxs(ctx context.Context, checkFn mempool.CheckFn)
	Store(*types.Tx) (have, rejected bool)
	TxsAvailable() bool
	Size() (totalBytes, numTxns int)
}

type ParamUpdatesDeclaration

type ParamUpdatesDeclaration struct {
	// Description is an informative description of the resolution, and it
	// serves to make it a unique resolution even if the ParamUpdates have been
	// proposed in a prior resolution.
	Description string // e.g. "Increase max votes (KWIL Consensus change #1)"

	// ParamUpdates is the actual updates to be made to the Kwil network.
	ParamUpdates types.ParamUpdates
}

func (ParamUpdatesDeclaration) MarshalBinary

func (pud ParamUpdatesDeclaration) MarshalBinary() ([]byte, error)

func (*ParamUpdatesDeclaration) UnmarshalBinary

func (pud *ParamUpdatesDeclaration) UnmarshalBinary(b []byte) error

type PriorityLockQueue

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

func (*PriorityLockQueue) Lock

func (pl *PriorityLockQueue) Lock()

func (*PriorityLockQueue) PriorityLock

func (pl *PriorityLockQueue) PriorityLock()

func (*PriorityLockQueue) Unlock

func (pl *PriorityLockQueue) Unlock()

type ProposalBroadcaster

type ProposalBroadcaster func(ctx context.Context, blk *ktypes.Block)

ProposalBroadcaster broadcasts the new block proposal message to the network

type ResetStateBroadcaster

type ResetStateBroadcaster func(height int64, txIDs []ktypes.Hash) error

type StateInfo

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

StateInfo contains the state information required by the p2p layer to download the blocks and notify the consensus engine about the incoming blocks.

type Status

type Status string
const (
	Proposed  Status = "proposed"  // SM has a proposed block for the current height
	Executed  Status = "executed"  // SM has executed the proposed block
	Committed Status = "committed" // SM has committed the block
)

type TxAnnouncer

type TxAnnouncer func(ctx context.Context, tx *ktypes.Transaction, txID types.Hash)

TxAnnouncer broadcasts the new transaction to the network

type WhitelistFns

type WhitelistFns struct {
	AddPeer    func(string) error
	RemovePeer func(string) error
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳