Files
zeekayandHanzo Dev 974d0d5422 rename: drop the upstream protocol name from the tree
The module is luxfi/bft and that is now the only name it answers to.

- simplex/ -> engine/. Upstream's module is named for the protocol, so its root
  package and its engine package shared that name; under luxfi/bft the engine
  package would have collided with the module's own root package. It is the
  consensus engine, so engine.Epoch and engine.NewEpoch read without stutter.
- Identifiers keep the qualifier where it carries meaning and only change the
  word: a block produced by this protocol as against a pre-existing chain's block
  is a real distinction, so makeNonSimplexBlock became makeNonBFTBlock,
  lastNonSimplexInnerBlockHeight became lastNonBFTInnerBlockHeight,
  newSnowToSimplexChain became newSnowToBFTChain. Dropping the qualifier outright
  would have left names that assert nothing.
- The canoto-tagged fields of StateMachineMetadata lose the prefix entirely:
  EpochInfo, ProtocolMetadata, Blacklist. The wire format is unchanged — canoto
  keys off the tag numbers, which still read 1,2,3,4,5, and the generated
  .canoto.go files were renamed in step with the source. The msm fuzz and
  encoding round-trip tests cover this.
- Prose cites the protocol paper by reference number instead of by name, so the
  origin stays findable without the name. The HyperSDK sentence still says
  Avalanche because that sentence is about Avalanche's VM and is true.

Also here, from review of the logger port:
- monitor_test's Fatal panics instead of returning. It reported a state the
  caller had declared impossible and then carried on regardless, which made it
  the one Fatal in the tree that was weaker than the original.
- TestInstanceNonValidatorBootstraps asserts the property it is named for — that
  the node was still a non-validator when the bootstrap finished — rather than
  counting how many times a debug line was emitted. The count tracks how often
  onEpochChange happened to observe the branch, so transitions can coalesce; it
  measured 2 here where it had been reliably 3, and a logger-cost explanation was
  tested and refuted. The count never checked the property either way: a node
  that wrongly became a validator mid-bootstrap would still have counted 3.
- SilenceExceptKeywords documents last-call-wins, and Trace/Verbo now reaching
  hooks is recorded where a future hook author will see it.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-06 05:16:49 -07:00

324 lines
9.2 KiB
Go

// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package engine
import (
"context"
cryptoRand "crypto/rand"
"fmt"
"math/rand/v2"
"slices"
"sync"
"time"
"github.com/luxfi/bft/common"
"github.com/luxfi/log"
)
type verifiableMessage interface {
Verify(nodes common.Nodes) error
}
// RetrieveLastIndexFromStorage retrieves the latest block and finalization from storage.
// Returns an error if it cannot be retrieved but the storage has some block.
// Returns (nil, nil) if the storage is empty.
func RetrieveLastIndexFromStorage(s common.Storage) (*common.VerifiedFinalizedBlock, error) {
numBlocks := s.NumBlocks()
if numBlocks == 0 {
return nil, nil
}
lastBlock, finalization, err := s.Retrieve(numBlocks - 1)
if err != nil {
return nil, fmt.Errorf("failed retrieving last block from storage with seq %d: %w", numBlocks-1, err)
}
return &common.VerifiedFinalizedBlock{
VerifiedBlock: lastBlock,
Finalization: finalization,
}, nil
}
func hasSomeNodeSignedTwice(nodeIDs []common.NodeID) (common.NodeID, bool) {
seen := make(map[string]struct{}, len(nodeIDs))
for _, nodeID := range nodeIDs {
if _, alreadySeen := seen[string(nodeID)]; alreadySeen {
return nodeID, true
}
seen[string(nodeID)] = struct{}{}
}
return common.NodeID{}, false
}
func VerifyQC(qc common.QuorumCertificate, isQuorum func(signers []common.NodeID) bool, eligibleSigners map[string][]byte, messageToVerify verifiableMessage, nodes common.Nodes) error {
if qc == nil {
return fmt.Errorf("nil QuorumCertificate")
}
// Ensure no node signed the QuorumCertificate twice
doubleSigner, signedTwice := hasSomeNodeSignedTwice(qc.Signers())
if signedTwice {
return fmt.Errorf("quorum certificate is signed by the same node (%s) more than once", doubleSigner)
}
// Check enough signers signed the QuorumCertificate
if !isQuorum(qc.Signers()) {
return fmt.Errorf("quorum certificate signed by insufficient (%d) nodes", len(qc.Signers()))
}
// Check QuorumCertificate was signed by only eligible nodes
for _, signer := range qc.Signers() {
if _, exists := eligibleSigners[string(signer)]; !exists {
return fmt.Errorf("quorum certificate contains an unknown signer (%s)", signer)
}
}
return messageToVerify.Verify(nodes)
}
// GetLatestVerifiedQuorumRound returns the latest verified quorum round given
// a round and empty notarization. If both are nil, it returns nil.
func GetLatestVerifiedQuorumRound(round *Round, emptyNotarization *common.EmptyNotarization) *common.VerifiedQuorumRound {
var verifiedQuorumRound *common.VerifiedQuorumRound
var highestRound uint64
var exists bool
if round != nil && (round.finalization != nil || round.notarization != nil) {
highestRound = round.num
verifiedQuorumRound = &common.VerifiedQuorumRound{
VerifiedBlock: round.block,
Notarization: round.notarization,
Finalization: round.finalization,
}
exists = true
}
if emptyNotarization != nil {
emptyNoteRound := emptyNotarization.Vote.Round
if emptyNoteRound > highestRound || !exists {
verifiedQuorumRound = &common.VerifiedQuorumRound{
EmptyNotarization: emptyNotarization,
}
}
}
return verifiedQuorumRound
}
// SetRound is a helper function that is used for tests to create a round.
func SetRound(block common.VerifiedBlock, notarization *common.Notarization, finalization *common.Finalization) *Round {
round := &Round{
block: block,
notarization: notarization,
finalization: finalization,
num: block.BlockHeader().Round,
}
return round
}
type OneTimeVerifier struct {
lock sync.Mutex
digests map[common.Digest]verifiedResult
logger common.Logger
}
func NewOneTimeVerifier(logger common.Logger) *OneTimeVerifier {
return &OneTimeVerifier{
digests: make(map[common.Digest]verifiedResult),
logger: logger,
}
}
func (otv *OneTimeVerifier) Wrap(block common.Block) common.Block {
return &oneTimeVerifiedBlock{
otv: otv,
Block: block,
}
}
type verifiedResult struct {
seq uint64
vb common.VerifiedBlock
err error
}
type oneTimeVerifiedBlock struct {
otv *OneTimeVerifier
common.Block
}
func (block *oneTimeVerifiedBlock) Verify(ctx context.Context) (common.VerifiedBlock, error) {
block.otv.lock.Lock()
defer block.otv.lock.Unlock()
header := block.Block.BlockHeader()
digest := header.Digest
seq := header.Seq
if result, exists := block.otv.digests[digest]; exists {
block.otv.logger.Debug("Attempted to verify an already verified block", log.Uint64("round", header.Round), log.Err(result.err))
return result.vb, result.err
}
vb, err := block.Block.Verify(ctx)
if err != nil {
block.otv.logger.Debug("Block verification failed", log.Uint64("round", header.Round), log.Err(err))
return nil, err
}
// cleanup
defer func() {
for digest, vr := range block.otv.digests {
if vr.seq < seq {
delete(block.otv.digests, digest)
}
}
}()
block.otv.digests[digest] = verifiedResult{
seq: seq,
vb: vb,
err: err,
}
return vb, err
}
// BatchSequences distributes [seqs] as evenly as possible among [numNodes]
// nodes, returning one batch per node share. Every batch contains at most
// [maxSize] sequences. a share exceeding [maxSize] is emitted as multiple
// batches. [seqs] does not need to be sorted or contiguous, it is sorted in
// place, and the returned batches are sub-slices of it, ordered from lowest
// to highest sequence.
func BatchSequences(seqs []uint64, numNodes uint64, maxSize uint64) [][]uint64 {
if len(seqs) == 0 || numNodes == 0 || maxSize == 0 {
return nil
}
slices.Sort(seqs)
numSeqs := uint64(len(seqs))
seqsPerNode := (numSeqs + uint64(numNodes) - 1) / uint64(numNodes)
batchSize := min(seqsPerNode, maxSize)
return slices.Collect(slices.Chunk(seqs, int(batchSize)))
}
type NotarizationTime struct {
// config
getRound func() uint64
haveUnFinalizedNotarization func() (uint64, bool)
rebroadcastFinalizationVotes func()
checkInterval time.Duration
finalizeVoteRebroadcastTimeout time.Duration
// state
lastSampleTime time.Time
latestRound uint64
lastRebroadcastTime time.Time
oldestNotFinalizedRound uint64
}
func NewNotarizationTime(
finalizeVoteRebroadcastTimeout time.Duration,
haveUnFinalizedNotarization func() (uint64, bool),
rebroadcastFinalizationVotes func(),
getRound func() uint64,
) NotarizationTime {
return NotarizationTime{
finalizeVoteRebroadcastTimeout: finalizeVoteRebroadcastTimeout,
haveUnFinalizedNotarization: haveUnFinalizedNotarization,
rebroadcastFinalizationVotes: rebroadcastFinalizationVotes,
getRound: getRound,
checkInterval: finalizeVoteRebroadcastTimeout / 3,
}
}
func (nt *NotarizationTime) CheckForNotFinalizedNotarizedBlocks(now time.Time) {
// If we have recently checked, don't check again
if !nt.lastSampleTime.IsZero() && nt.lastSampleTime.Add(nt.checkInterval).After(now) {
return
}
nt.lastSampleTime = now
round := nt.getRound()
// As long as we make some progress, we don't check for a round not finalized.
if round > nt.latestRound {
nt.latestRound = round
return
}
// It is only if we didn't advance any round, that we check if we have made some progress in finalizing rounds.
oldestNotFinalizedRound, haveNotFinalizedRound := nt.haveUnFinalizedNotarization()
if !haveNotFinalizedRound {
nt.lastRebroadcastTime = time.Time{}
nt.oldestNotFinalizedRound = 0
return
}
lastRebroadcastTime := nt.lastRebroadcastTime
if lastRebroadcastTime.IsZero() {
nt.lastRebroadcastTime = now
nt.oldestNotFinalizedRound = oldestNotFinalizedRound
return
}
if lastRebroadcastTime.Add(nt.finalizeVoteRebroadcastTimeout).Before(now) &&
nt.oldestNotFinalizedRound == oldestNotFinalizedRound {
nt.rebroadcastFinalizationVotes()
nt.lastRebroadcastTime = now
}
}
type voteSigner interface {
Signer() common.NodeID
}
func NodeIDsFromVotes[VS voteSigner](votes []VS) []common.NodeID {
nodeIDs := make([]common.NodeID, 0, len(votes))
for _, vote := range votes {
nodeIDs = append(nodeIDs, vote.Signer())
}
return nodeIDs
}
func emptyVotesToSignatures(votes []*common.EmptyVote) []common.Signature {
sigs := make([]common.Signature, 0, len(votes))
for _, vote := range votes {
sigs = append(sigs, vote.Signature)
}
return sigs
}
type walRound struct {
round uint64
emptyNotarization *common.EmptyNotarization
emptyVote *common.ToBeSignedEmptyVote
notarization *common.Notarization
finalization *common.Finalization
block common.Block
}
func (t *walRound) String() string {
hasEmptyNotarization := t.emptyNotarization != nil
hasEmptyVote := t.emptyVote != nil
hasNotarization := t.notarization != nil
hasFinalization := t.finalization != nil
hasBlock := t.block != nil
return fmt.Sprintf("walRound{round: %d, hasEmptyNotarization: %t, hasEmptyVote: %t, hasNotarization: %t, hasFinalization: %t, hasBlock: %t}", t.round, hasEmptyNotarization, hasEmptyVote, hasNotarization, hasFinalization, hasBlock)
}
func NewRandomSource() (*rand.Rand, error) {
var seedBytes [32]byte
if _, err := cryptoRand.Read(seedBytes[:]); err != nil {
return nil, fmt.Errorf("failed to read random bytes: %w", err)
}
chacha := rand.NewChaCha8(seedBytes)
return rand.New(chacha), nil
}