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

441 lines
11 KiB
Go

// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package common
import (
"bytes"
"encoding/asn1"
"encoding/binary"
"fmt"
"github.com/luxfi/bft/host"
)
type Message struct {
// BFT Messages
BlockMessage *BlockMessage
EmptyNotarization *EmptyNotarization
VoteMessage *Vote
EmptyVoteMessage *EmptyVote
Notarization *Notarization
FinalizeVote *FinalizeVote
Finalization *Finalization
// Replication Messages
ReplicationResponse *ReplicationResponse
ReplicationRequest *ReplicationRequest
BlockDigestRequest *BlockDigestRequest
// Verified Messages
VerifiedBlockMessage *VerifiedBlockMessage
VerifiedReplicationResponse *VerifiedReplicationResponse
}
func (m *Message) IsReplicationMessage() bool {
switch {
case m.ReplicationResponse != nil:
return true
case m.ReplicationRequest != nil:
return true
case m.VerifiedReplicationResponse != nil:
return true
case m.BlockDigestRequest != nil:
return true
default:
return false
}
}
type EmptyVoteMetadata struct {
Round uint64
Epoch uint64
}
type ToBeSignedEmptyVote struct {
EmptyVoteMetadata
}
const emptyVoteLen = 1 + 8 + 8 // Version + Epoch + Round
func (v *ToBeSignedEmptyVote) Bytes() []byte {
bytes := make([]byte, emptyVoteLen)
binary.BigEndian.PutUint64(bytes[1:9], v.EmptyVoteMetadata.Epoch)
binary.BigEndian.PutUint64(bytes[9:17], v.EmptyVoteMetadata.Round)
return bytes
}
func (v *ToBeSignedEmptyVote) FromBytes(buff []byte) error {
if len(buff) != emptyVoteLen {
return fmt.Errorf("invalid buffer length, expected %d, got %d", emptyVoteLen, len(buff))
}
epoch := binary.BigEndian.Uint64(buff[1:9])
round := binary.BigEndian.Uint64(buff[9:17])
v.EmptyVoteMetadata = EmptyVoteMetadata{
Round: round,
Epoch: epoch,
}
return nil
}
func (v *ToBeSignedEmptyVote) Size() int {
return emptyVoteLen
}
func (v *ToBeSignedEmptyVote) Sign(signer Signer) ([]byte, error) {
context := "ToBeSignedEmptyVote"
msg := v.Bytes()
return signContext(signer, msg, context)
}
func (v *ToBeSignedEmptyVote) Verify(signature []byte, verifier SignatureVerifier, pk []byte) error {
context := "ToBeSignedEmptyVote"
msg := v.Bytes()
return verifyContext(signature, verifier, msg, context, pk)
}
type ToBeSignedVote struct {
BlockHeader
}
func (v *ToBeSignedVote) Sign(signer Signer) ([]byte, error) {
context := "ToBeSignedVote"
msg := v.Bytes()
return signContext(signer, msg, context)
}
func (v *ToBeSignedVote) Verify(signature []byte, verifier SignatureVerifier, pk []byte) error {
context := "ToBeSignedVote"
msg := v.Bytes()
return verifyContext(signature, verifier, msg, context, pk)
}
type ToBeSignedFinalization struct {
BlockHeader
}
func (f *ToBeSignedFinalization) Sign(signer Signer) ([]byte, error) {
context := "ToBeSignedFinalization"
msg := f.Bytes()
return signContext(signer, msg, context)
}
func (f *ToBeSignedFinalization) Verify(signature []byte, verifier SignatureVerifier, pk []byte) error {
context := "ToBeSignedFinalization"
msg := f.Bytes()
return verifyContext(signature, verifier, msg, context, pk)
}
func signContext(signer Signer, msg []byte, context string) ([]byte, error) {
sm := SignedMessage{Payload: msg, Context: context}
toBeSigned, err := asn1.Marshal(sm)
if err != nil {
return nil, err
}
return signer.Sign(toBeSigned)
}
func verifyContext(signature []byte, verifier SignatureVerifier, msg []byte, context string, pk []byte) error {
sm := SignedMessage{Payload: msg, Context: context}
toBeSigned, err := asn1.Marshal(sm)
if err != nil {
return err
}
return verifier.VerifySignature(toBeSigned, signature, pk)
}
func verifyContextQC(qc QuorumCertificate, msg []byte, context string, nodes Nodes) error {
sm := SignedMessage{Payload: msg, Context: context}
toBeSigned, err := asn1.Marshal(sm)
if err != nil {
return err
}
return qc.Verify(toBeSigned, nodes)
}
// Vote represents a signed vote for a block.
type Vote struct {
Vote ToBeSignedVote
Signature Signature
}
func (v *Vote) Signer() NodeID {
return v.Signature.Signer
}
// EmptyVote represents a signed vote for an empty block.
type EmptyVote struct {
Vote ToBeSignedEmptyVote
Signature Signature
}
func (v *EmptyVote) Signer() NodeID {
return v.Signature.Signer
}
// FinalizeVote represents a vote to finalize a block.
type FinalizeVote struct {
Finalization ToBeSignedFinalization
Signature Signature
}
func (v *FinalizeVote) Signer() NodeID {
return v.Signature.Signer
}
// Finalization represents a block that has reached quorum on block. This
// means that block can be included in the chain and finalized.
type Finalization struct {
Finalization ToBeSignedFinalization
QC QuorumCertificate
}
func (f *Finalization) Verify(nodes Nodes) error {
context := "ToBeSignedFinalization"
return verifyContextQC(f.QC, f.Finalization.Bytes(), context, nodes)
}
func (f *Finalization) Size() int {
return f.Finalization.Size() + f.QC.Size()
}
// Notarization represents a block that has reached a quorum of votes.
type Notarization struct {
Vote ToBeSignedVote
QC QuorumCertificate
}
func (n *Notarization) Verify(nodes Nodes) error {
context := "ToBeSignedVote"
return verifyContextQC(n.QC, n.Vote.Bytes(), context, nodes)
}
func (n *Notarization) Size() int {
return n.Vote.Size() + n.QC.Size()
}
type BlockMessage struct {
Block Block
Vote Vote
}
type VerifiedBlockMessage struct {
VerifiedBlock VerifiedBlock
Vote Vote
}
type EmptyNotarization struct {
Vote ToBeSignedEmptyVote
QC QuorumCertificate
}
func (en *EmptyNotarization) Verify(nodes Nodes) error {
context := "ToBeSignedEmptyVote"
return verifyContextQC(en.QC, en.Vote.Bytes(), context, nodes)
}
func (en *EmptyNotarization) Size() int {
return en.Vote.Size() + en.QC.Size()
}
type SignedMessage struct {
Payload []byte
Context string
}
// QuorumCertificate is equivalent to a collection of signatures from a quorum of nodes,
type QuorumCertificate interface {
// Signers returns who participated in creating this QuorumCertificate.
Signers() []NodeID
// Verify checks whether the nodes participated in creating this QuorumCertificate,
// signed the given message.
Verify(msg []byte, nodes Nodes) error
// Bytes returns a raw representation of the given QuorumCertificate.
Bytes() []byte
// Size returns the number of bytes
Size() int
}
type ReplicationRequest struct {
Seqs []uint64 // sequences we are requesting
Rounds []uint64 // rounds we are requesting
LatestRound uint64 // latest round that we are aware of
LatestFinalizedSeq uint64 // latest finalized sequence that we are aware of
}
type ReplicationResponse struct {
Data []QuorumRound
LatestRound *QuorumRound
LatestSeq *QuorumRound
}
type VerifiedReplicationResponse struct {
Data []VerifiedQuorumRound
LatestRound *VerifiedQuorumRound
LatestFinalizedSeq *VerifiedQuorumRound
}
// QuorumRound represents a round that has achieved quorum on either
// (empty notarization), (block & notarization), or (block, finalization)
type QuorumRound struct {
Block Block
Notarization *Notarization
Finalization *Finalization
EmptyNotarization *EmptyNotarization
}
// isWellFormed returns an error if the QuorumRound is not in one
// one of these formats
// (block, notarization), (block, finalization) or (empty notarization)
func (q *QuorumRound) IsWellFormed() error {
if q.Block == nil && q.EmptyNotarization == nil {
return fmt.Errorf("malformed QuorumRound, empty block and notarization fields")
}
if q.Block != nil && (q.Notarization == nil && q.Finalization == nil) {
return fmt.Errorf("malformed QuorumRound, block but no notarization or finalization")
}
if q.Finalization != nil && q.Block == nil {
return fmt.Errorf("malformed QuorumRound, finalization but no block")
}
if q.Notarization != nil && q.Block == nil {
return fmt.Errorf("malformed QuorumRound, notarization but no block")
}
return nil
}
func (q *QuorumRound) GetRound() uint64 {
if q.EmptyNotarization != nil {
return q.EmptyNotarization.Vote.Round
}
if q.Block != nil {
return q.Block.BlockHeader().Round
}
return 0
}
func (q *QuorumRound) GetSequence() uint64 {
if q.Block != nil {
return q.Block.BlockHeader().Seq
}
return 0
}
func (q *QuorumRound) VerifyQCConsistentWithBlock() error {
if err := q.IsWellFormed(); err != nil {
return err
}
if q.Block == nil {
return nil
}
// if an empty notarization is included, ensure the round is equal to the block round
if q.EmptyNotarization != nil && q.EmptyNotarization.Vote.Round != q.Block.BlockHeader().Round {
return fmt.Errorf("empty round does not match block round")
}
// ensure the finalization or notarization we get relates to the block
blockDigest := q.Block.BlockHeader().Digest
if q.Finalization != nil {
if !bytes.Equal(blockDigest[:], q.Finalization.Finalization.Digest[:]) {
return fmt.Errorf("finalization does not match the block")
}
}
if q.Notarization != nil {
if !bytes.Equal(blockDigest[:], q.Notarization.Vote.Digest[:]) {
return fmt.Errorf("notarization does not match the block")
}
}
return nil
}
// String returns a string representation of the QuorumRound.
// It is meant as a debugging aid for logs.
func (q *QuorumRound) String() string {
if q != nil {
err := q.IsWellFormed()
if err != nil {
return fmt.Sprintf("QuorumRound{Error: %s}", err)
} else {
return fmt.Sprintf("QuorumRound{Round: %d, Seq: %d, Finalized: %t}", q.GetRound(), q.GetSequence(), q.Finalization != nil)
}
}
return "QuorumRound{nil}"
}
type VerifiedQuorumRound struct {
VerifiedBlock VerifiedBlock
Notarization *Notarization
Finalization *Finalization
EmptyNotarization *EmptyNotarization
}
func (q *VerifiedQuorumRound) GetRound() uint64 {
if q.EmptyNotarization != nil {
return q.EmptyNotarization.Vote.Round
}
if q.VerifiedBlock != nil {
return q.VerifiedBlock.BlockHeader().Round
}
return 0
}
func (q *VerifiedQuorumRound) Size() int {
var size int
if q.VerifiedBlock != nil {
size += q.VerifiedBlock.Size()
}
if q.Notarization != nil {
size += q.Notarization.Size()
}
if q.Finalization != nil {
size += q.Finalization.Size()
}
if q.EmptyNotarization != nil {
size += q.EmptyNotarization.Size()
}
return size
}
type VerifiedFinalizedBlock struct {
VerifiedBlock VerifiedBlock
Finalization Finalization
}
type BlockDigestRequest struct {
Seq uint64
Digest Digest
}
// VersionID is an identifier for applications that care about epoch changes.
type VersionID uint32
type ValidatorSetApproval struct {
NodeID host.NodeID
AuxInfoDigest [32]byte
PChainHeight uint64
Signature []byte
}