quasar

package
v1.22.45 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Overview

Package quasar provides post-quantum overlay: dual BLS + ring certificates.

Quasar prepares for the quantum age by running both BLS (fast, classical) and ring signatures (quantum-safe, larger) in parallel. The system can seamlessly transition when quantum computers arrive, making the consensus future-proof. Quasars are among the most energetic objects in the universe.

Package ringtail provides post-quantum cryptographic primitives for the Lux consensus. This is a stub implementation that forwards to the actual implementation in github.com/luxfi/crypto/ringtail.

Index

Constants

View Source
const (
	// MinEpochDuration is the minimum time between key rotations.
	// Changing keys frequently makes quantum attacks harder since any
	// progress toward breaking keys is invalidated when keys change.
	// At 10 minutes per epoch, uint64 supports 351 trillion years of epochs.
	MinEpochDuration = 10 * time.Minute

	// MaxEpochDuration is the maximum time keys can be used.
	// Forces rotation even if validator set hasn't changed.
	// With 10-minute epochs, force rotation after 1 hour (6 epochs).
	MaxEpochDuration = 1 * time.Hour

	// DefaultHistoryLimit is the default number of old epochs to keep.
	// With 10-minute epochs, 6 epochs = 1 hour of history for verification.
	DefaultHistoryLimit = 6

	// QuantumCheckpointInterval is how often we create quantum-safe signatures.
	// Every 3 seconds provides frequent quantum-safe anchors while keys rotate
	// every 10 minutes. With <100 validators, 3-second signing is achievable.
	QuantumCheckpointInterval = 3 * time.Second
)
View Source
const (
	// DefaultGroupSize is the optimal group size for Ringtail threshold signing.
	// Ringtail scales O(n²), so small groups are critical for performance:
	//   n=3: 243ms, n=10: 1.1s, n=21: 3.4s, n=100: 53s
	// Groups of 3 with 2-of-3 threshold provides 243ms signing.
	DefaultGroupSize = 3

	// DefaultGroupThreshold is the threshold within each group.
	// 2-of-3 = majority required within each group.
	DefaultGroupThreshold = 2

	// DefaultGroupQuorum is the fraction of groups that must sign.
	// 2/3 of groups must produce valid signatures for consensus.
	DefaultGroupQuorum = 2 // numerator (2/3)
	GroupQuorumDenom   = 3 // denominator
)

Variables

View Source
var (
	ErrEpochRateLimited    = errors.New("epoch keygen rate limited: must wait at least 10 minutes between rotations")
	ErrNoValidatorChange   = errors.New("validator set unchanged, no keygen needed")
	ErrEpochNotFound       = errors.New("epoch not found")
	ErrInvalidValidatorSet = errors.New("invalid validator set configuration")
)
View Source
var (
	ErrInsufficientGroups     = errors.New("insufficient groups signed")
	ErrGroupSignatureFailed   = errors.New("group signature failed")
	ErrInvalidGroupAssignment = errors.New("invalid group assignment")
)
View Source
var (
	ErrInvalidCertificate  = errors.New("invalid certificate")
	ErrMissingCertificate  = errors.New("missing certificate")
	ErrCertificateMismatch = errors.New("certificate mismatch")
)

Error variables

View Source
var DefaultConfig = Config{QThreshold: 3, QuasarTimeout: 30}

DefaultConfig for quasar protocol

View Source
var NewPChain = NewBLS

NewPChain is a deprecated alias for backward compatibility. Deprecated: Use NewBLS instead.

View Source
var NewQuasarHybridConsensus = NewHybrid

NewQuasarHybridConsensus is a deprecated alias for backward compatibility. Deprecated: Use NewHybrid instead.

Functions

func ComputeMerkleRoot added in v1.22.36

func ComputeMerkleRoot(hashes [][32]byte) [32]byte

ComputeMerkleRoot computes a Merkle root over block hashes.

func GenerateThresholdKeys added in v1.22.28

func GenerateThresholdKeys(schemeID threshold.SchemeID, t, n int) ([]threshold.KeyShare, threshold.PublicKey, error)

GenerateThresholdKeys generates threshold keys for a single scheme.

func KeyGen

func KeyGen(seed []byte) ([]byte, []byte, error)

KeyGen generates a key pair from seed

func ReleaseHybridSignature added in v1.22.23

func ReleaseHybridSignature(sig *HybridSignature)

ReleaseHybridSignature returns a HybridSignature to the pool.

func Verify

func Verify(pk []byte, msg []byte, cert []byte) bool

Verify verifies a certificate

func VerifyShare

func VerifyShare(pk []byte, msg []byte, share []byte) bool

VerifyShare verifies a share signature

Types

type AggregatedSignature

type AggregatedSignature struct {
	BLSAggregated      []byte
	RingtailAggregated []byte
	ValidatorIDs       []string
	SignerCount        int
	IsThreshold        bool
}

AggregatedSignature contains aggregated signatures.

type AsyncBundleSigner added in v1.22.36

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

AsyncBundleSigner wraps BundleSigner with async signing capabilities. BLS block production continues uninterrupted during Ringtail signing.

func NewAsyncBundleSigner added in v1.22.36

func NewAsyncBundleSigner(em *EpochManager) *AsyncBundleSigner

NewAsyncBundleSigner creates an async bundle signer.

func (*AsyncBundleSigner) AddBLSBlock added in v1.22.36

func (abs *AsyncBundleSigner) AddBLSBlock(height uint64, hash [32]byte)

AddBLSBlock adds a finalized BLS block hash to the pending bundle.

func (*AsyncBundleSigner) CreateBundle added in v1.22.36

func (abs *AsyncBundleSigner) CreateBundle() *QuantumBundle

CreateBundle bundles pending BLS blocks.

func (*AsyncBundleSigner) IsSigningInProgress added in v1.22.36

func (abs *AsyncBundleSigner) IsSigningInProgress() bool

IsSigningInProgress returns true if async signing is in progress.

func (*AsyncBundleSigner) LastBundle added in v1.22.36

func (abs *AsyncBundleSigner) LastBundle() *QuantumBundle

LastBundle returns the most recent bundle.

func (*AsyncBundleSigner) PendingCount added in v1.22.36

func (abs *AsyncBundleSigner) PendingCount() int

PendingCount returns the number of pending BLS blocks.

func (*AsyncBundleSigner) SignBundle added in v1.22.36

func (abs *AsyncBundleSigner) SignBundle(
	bundle *QuantumBundle,
	sessionID int,
	prfKey []byte,
	validators []string,
) error

SignBundle signs a bundle synchronously.

func (*AsyncBundleSigner) SignBundleAsync added in v1.22.36

func (abs *AsyncBundleSigner) SignBundleAsync(
	bundle *QuantumBundle,
	sessionID int,
	prfKey []byte,
	validators []string,
)

SignBundleAsync signs a bundle asynchronously. BLS block production continues uninterrupted during signing.

func (*AsyncBundleSigner) SignedBundles added in v1.22.36

func (abs *AsyncBundleSigner) SignedBundles() <-chan *QuantumBundle

SignedBundles returns the channel of signed bundles.

func (*AsyncBundleSigner) VerifyBundle added in v1.22.36

func (abs *AsyncBundleSigner) VerifyBundle(bundle *QuantumBundle) bool

VerifyBundle verifies a bundle's signature.

type BLS added in v1.22.22

type BLS struct {
	// Configuration
	K     int
	Alpha float64
	Beta  uint32
	// contains filtered or unexported fields
}

BLS implements BLS signature aggregation with event horizon finality

func NewBLS added in v1.22.22

func NewBLS(cfg config.Parameters, store dag.Store[VertexID]) *BLS

NewBLS creates a new BLS consensus instance

func (*BLS) ComputeCanonicalOrder added in v1.22.22

func (q *BLS) ComputeCanonicalOrder() []VertexID

ComputeCanonicalOrder returns the canonical order of finalized vertices

func (*BLS) EstablishHorizon added in v1.22.22

func (q *BLS) EstablishHorizon(ctx context.Context, checkpoint VertexID, validators []string) (*dag.EventHorizon[VertexID], error)

EstablishHorizon creates a new event horizon for BLS finality

func (*BLS) GetLatestHorizon added in v1.22.22

func (q *BLS) GetLatestHorizon() *dag.EventHorizon[VertexID]

GetLatestHorizon returns the most recent event horizon

func (*BLS) Initialize added in v1.22.22

func (q *BLS) Initialize(_ context.Context, blsKey, pqKey []byte) error

Initialize sets up keys for Quasar

func (*BLS) IsBeyondHorizon added in v1.22.22

func (q *BLS) IsBeyondHorizon(vertex VertexID) bool

IsBeyondHorizon checks if a vertex is beyond the event horizon (finalized)

func (*BLS) SetFinalizedCallback added in v1.22.22

func (q *BLS) SetFinalizedCallback(cb func(*Block))

SetFinalizedCallback sets the callback for finalized blocks.

type Block added in v1.22.1

type Block struct {
	ID        [32]byte   // Unique block identifier
	ChainID   [32]byte   // Chain this block belongs to
	ChainName string     // Human-readable chain name (e.g., "P-Chain", "X-Chain", "C-Chain")
	Height    uint64     // Block height
	Hash      string     // Block hash
	Timestamp time.Time  // Block timestamp
	Data      []byte     // Block payload data
	Cert      *BlockCert // Quantum certificate (nil if not finalized)
}

Block represents a finalized block in the Quasar consensus. This is the primary block type used throughout the system.

type BlockCert added in v1.22.4

type BlockCert struct {
	BLS      []byte            // BLS aggregate signature
	PQ       []byte            // Post-quantum certificate (ML-DSA/Ringtail)
	Sigs     map[string][]byte // Individual validator signatures
	Epoch    uint64            // Epoch number
	Finality time.Time         // Time of finality
}

BlockCert contains cryptographic certificates for quantum finality.

func (*BlockCert) Verify added in v1.22.4

func (c *BlockCert) Verify(validators []string) bool

Verify checks both BLS and PQ certificates.

type Bundle

type Bundle struct {
	Epoch   uint64
	Root    []byte
	BLSAgg  []byte
	PQBatch []byte
	Binding []byte
}

Bundle represents a finalized epoch bundle.

type BundleRunner added in v1.22.36

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

BundleRunner runs the quantum bundle production loop. It creates bundles every 3 seconds and signs them asynchronously.

func NewBundleRunner added in v1.22.36

func NewBundleRunner(signer *AsyncBundleSigner, validators []string, prfKey []byte) *BundleRunner

NewBundleRunner creates a new bundle runner.

func (*BundleRunner) Start added in v1.22.36

func (br *BundleRunner) Start()

Start begins the bundle production loop. Bundles are created every 3 seconds, signed asynchronously.

func (*BundleRunner) Stop added in v1.22.36

func (br *BundleRunner) Stop()

Stop stops the bundle production loop.

type BundleSigner added in v1.22.36

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

BundleSigner handles creating and verifying 3-second quantum bundles. Bundles accumulate multiple BLS blocks and sign them with Ringtail.

func NewBundleSigner added in v1.22.36

func NewBundleSigner(em *EpochManager) *BundleSigner

NewBundleSigner creates a bundle signer for the epoch manager.

func (*BundleSigner) AddBLSBlock added in v1.22.36

func (bs *BundleSigner) AddBLSBlock(height uint64, hash [32]byte)

AddBLSBlock adds a finalized BLS block hash to the pending bundle. Called whenever a BLS block achieves finality (~500ms).

func (*BundleSigner) CreateBundle added in v1.22.36

func (bs *BundleSigner) CreateBundle() *QuantumBundle

CreateBundle bundles pending BLS blocks into a quantum bundle. Call this every 3 seconds (QuantumCheckpointInterval). Returns nil if no pending blocks.

func (*BundleSigner) LastBundle added in v1.22.36

func (bs *BundleSigner) LastBundle() *QuantumBundle

LastBundle returns the most recent bundle.

func (*BundleSigner) PendingCount added in v1.22.36

func (bs *BundleSigner) PendingCount() int

PendingCount returns the number of pending BLS blocks.

func (*BundleSigner) SignBundle added in v1.22.36

func (bs *BundleSigner) SignBundle(
	bundle *QuantumBundle,
	sessionID int,
	prfKey []byte,
	participatingValidators []string,
) error

SignBundle performs the 2-round Ringtail signing for a bundle. This runs the full threshold signing protocol with participating validators.

func (*BundleSigner) VerifyBundle added in v1.22.36

func (bs *BundleSigner) VerifyBundle(bundle *QuantumBundle) bool

VerifyBundle verifies a quantum bundle's Ringtail signature.

type Cert

type Cert = []byte

Type aliases for cleaner API

func Aggregate

func Aggregate(shares []Share) (Cert, error)

Aggregate aggregates shares into a certificate

type CertBundle

type CertBundle struct {
	BLSAgg []byte // BLS aggregate signature
	PQCert []byte // Post-quantum certificate
}

CertBundle contains both BLS and PQ certificates for a block.

func (*CertBundle) Verify

func (c *CertBundle) Verify(_ []string) bool

Verify checks both BLS and PQ certificates.

type ChainBlock added in v1.22.1

type ChainBlock = Block

ChainBlock is an alias for Block for backward compatibility. Deprecated: Use Block instead.

type Client

type Client interface {
	SubmitCheckpoint(epoch uint64, root []byte, attest []byte) error
	FetchBundle(epoch uint64) (Bundle, error)
	Verify(Bundle) bool
}

Client interface for Quasar operations

type CompressedWitness

type CompressedWitness struct {
	CommitmentAndProof []byte // Combined commitment + proof
	Metadata           uint64 // Packed height + timestamp
	Validators         uint32 // Validator bitfield (up to 32 validators)
}

CompressedWitness creates an even smaller witness for network transmission

func (*CompressedWitness) Size

func (c *CompressedWitness) Size() int

Size returns size of compressed witness

type Config

type Config struct {
	QThreshold    int
	QuasarTimeout int
}

Config represents quasar protocol configuration

type Core added in v1.22.4

type Core = Quasar

Core is an alias for the aggregator implementation. Use NewCore() to create a new instance.

type Engine added in v1.22.4

type Engine interface {
	// Start begins the consensus engine
	Start(ctx context.Context) error

	// Stop gracefully shuts down the consensus engine
	Stop() error

	// Submit adds a block to the consensus pipeline
	Submit(block *Block) error

	// Finalized returns a channel of finalized blocks
	Finalized() <-chan *Block

	// IsFinalized checks if a block is finalized
	IsFinalized(blockID [32]byte) bool

	// Stats returns consensus metrics
	Stats() Stats
}

Engine is the main interface for quantum consensus.

func NewEngine added in v1.22.4

func NewEngine(cfg Config) (Engine, error)

NewEngine creates a new Quasar consensus engine.

type EpochCheckpoint added in v1.22.36

type EpochCheckpoint struct {
	Epoch          uint64   // Epoch number
	StartHeight    uint64   // First block in epoch
	EndHeight      uint64   // Last block in epoch
	BlockCount     int      // Number of blocks
	MerkleRoot     [32]byte // Merkle root of block hashes
	PreviousAnchor [32]byte // Previous checkpoint hash (chain of anchors)
	Timestamp      int64    // Unix timestamp

	// Quantum-safe signature (Ringtail grouped threshold)
	Signature *GroupedSignature
}

EpochCheckpoint represents a quantum-safe anchor for a range of blocks. Created every epoch (10 min), contains Ringtail signature over block hashes. Normal blocks use BLS for 500ms finality; checkpoints add quantum security.

func CreateEpochCheckpoint added in v1.22.36

func CreateEpochCheckpoint(
	epoch uint64,
	startHeight, endHeight uint64,
	blockHashes [][32]byte,
	previousAnchor [32]byte,
) *EpochCheckpoint

CreateEpochCheckpoint creates a new checkpoint for a range of blocks. blockHashes should be ordered from StartHeight to EndHeight.

func (*EpochCheckpoint) CheckpointHash added in v1.22.36

func (ec *EpochCheckpoint) CheckpointHash() [32]byte

CheckpointHash returns the hash of this checkpoint (for chaining).

func (*EpochCheckpoint) SignableMessage added in v1.22.36

func (ec *EpochCheckpoint) SignableMessage() string

SignableMessage returns the message to be signed by Ringtail.

type EpochKeys added in v1.22.36

type EpochKeys struct {
	Epoch        uint64
	CreatedAt    time.Time
	ExpiresAt    time.Time
	ValidatorSet []string
	Threshold    int
	TotalParties int
	GroupKey     *ringtailThreshold.GroupKey
	Shares       map[string]*ringtailThreshold.KeyShare
	Signers      map[string]*ringtailThreshold.Signer
}

EpochKeys holds the Ringtail keys for a specific epoch.

type EpochManager added in v1.22.36

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

EpochManager manages Ringtail key epochs for the validator set. Fresh keys are generated when validators change, with rate limiting to prevent excessive key churn while still rotating frequently enough to frustrate quantum attacks.

func NewEpochManager added in v1.22.36

func NewEpochManager(threshold int, historyLimit int) *EpochManager

NewEpochManager creates a new epoch manager.

func (*EpochManager) ForceRotateIfExpired added in v1.22.36

func (em *EpochManager) ForceRotateIfExpired() (*EpochKeys, bool, error)

ForceRotateIfExpired rotates keys if MaxEpochDuration has passed. This ensures keys don't stay valid indefinitely even if validator set is stable.

func (*EpochManager) GetCurrentEpoch added in v1.22.36

func (em *EpochManager) GetCurrentEpoch() uint64

GetCurrentEpoch returns the current epoch number.

func (*EpochManager) GetCurrentKeys added in v1.22.36

func (em *EpochManager) GetCurrentKeys() *EpochKeys

GetCurrentKeys returns the current epoch's keys.

func (*EpochManager) GetEpochKeys added in v1.22.36

func (em *EpochManager) GetEpochKeys(epoch uint64) (*EpochKeys, error)

GetEpochKeys returns keys for a specific epoch (current or historical).

func (*EpochManager) GetSigner added in v1.22.36

func (em *EpochManager) GetSigner(validatorID string) (*ringtailThreshold.Signer, error)

GetSigner returns the Ringtail signer for a validator in the current epoch.

func (*EpochManager) GetSignerForEpoch added in v1.22.36

func (em *EpochManager) GetSignerForEpoch(validatorID string, epoch uint64) (*ringtailThreshold.Signer, error)

GetSignerForEpoch returns the signer for a validator in a specific epoch.

func (*EpochManager) InitializeEpoch added in v1.22.36

func (em *EpochManager) InitializeEpoch(validators []string) (*EpochKeys, error)

InitializeEpoch creates the first epoch with the initial validator set. This should be called once at genesis or node startup.

func (*EpochManager) RotateEpoch added in v1.22.36

func (em *EpochManager) RotateEpoch(validators []string, force bool) (*EpochKeys, error)

RotateEpoch generates new keys for a new validator set. Returns ErrEpochRateLimited if called within MinEpochDuration of last rotation. Returns ErrNoValidatorChange if validator set hasn't changed (unless force=true).

func (*EpochManager) Stats added in v1.22.36

func (em *EpochManager) Stats() EpochStats

Stats returns current epoch statistics.

func (*EpochManager) TimeUntilNextRotation added in v1.22.36

func (em *EpochManager) TimeUntilNextRotation() time.Duration

TimeUntilNextRotation returns how long until the next rotation is allowed.

func (*EpochManager) VerifySignatureForEpoch added in v1.22.36

func (em *EpochManager) VerifySignatureForEpoch(message string, sig *ringtailThreshold.Signature, epoch uint64) bool

VerifySignatureForEpoch verifies a Ringtail signature using the epoch's keys.

type EpochStats added in v1.22.36

type EpochStats struct {
	CurrentEpoch      uint64
	EpochAge          time.Duration
	ValidatorCount    int
	Threshold         int
	HistorySize       int
	LastKeygenTime    time.Time
	TimeUntilRotation time.Duration
}

EpochStats provides statistics about the epoch manager.

type GroupedEpochManager added in v1.22.36

type GroupedEpochManager struct {
	*EpochManager
	// contains filtered or unexported fields
}

GroupedEpochManager extends EpochManager with grouped threshold signing. Instead of one global threshold key, validators are split into groups, each with their own Ringtail keys. This enables parallel signing and scales to 10,000+ validators with constant signing time.

func NewGroupedEpochManager added in v1.22.36

func NewGroupedEpochManager(groupSize, groupThreshold, historyLimit int) *GroupedEpochManager

NewGroupedEpochManager creates a grouped epoch manager.

func (*GroupedEpochManager) GetGroupKey added in v1.22.36

func (gem *GroupedEpochManager) GetGroupKey(groupIndex int) (*ringtailThreshold.GroupKey, error)

GetGroupKey returns the group's public key.

func (*GroupedEpochManager) GetGroupSigner added in v1.22.36

func (gem *GroupedEpochManager) GetGroupSigner(validatorID string) (*ringtailThreshold.Signer, int, error)

GetGroupSigner returns the Ringtail signer for a validator in their group.

func (*GroupedEpochManager) GetGroupValidators added in v1.22.36

func (gem *GroupedEpochManager) GetGroupValidators(groupIndex int) ([]string, error)

GetGroupValidators returns the validators in a specific group.

func (*GroupedEpochManager) GetValidatorGroup added in v1.22.36

func (gem *GroupedEpochManager) GetValidatorGroup(validatorID string) (int, error)

GetValidatorGroup returns the group index for a validator.

func (*GroupedEpochManager) GroupedStats added in v1.22.36

func (gem *GroupedEpochManager) GroupedStats() GroupedEpochStats

Stats returns grouped epoch statistics.

func (*GroupedEpochManager) InitializeGroupedEpoch added in v1.22.36

func (gem *GroupedEpochManager) InitializeGroupedEpoch(validators []string, epochSeed []byte) error

InitializeGroupedEpoch creates the first epoch with grouped validator assignment.

func (*GroupedEpochManager) ParallelGroupSign added in v1.22.36

func (gem *GroupedEpochManager) ParallelGroupSign(
	sessionID int,
	message string,
	prfKey []byte,
	signersByGroup map[int][]string,
) (map[int]*ringtailThreshold.Signature, error)

ParallelGroupSign runs threshold signing for all groups in parallel. Returns signatures from each group. Caller aggregates into GroupedSignature.

func (*GroupedEpochManager) SignCheckpoint added in v1.22.36

func (gem *GroupedEpochManager) SignCheckpoint(
	checkpoint *EpochCheckpoint,
	sessionID int,
	prfKey []byte,
	signersByGroup map[int][]string,
) error

SignCheckpoint signs an epoch checkpoint using grouped Ringtail. This runs asynchronously - doesn't block normal block production.

func (*GroupedEpochManager) VerifyCheckpoint added in v1.22.36

func (gem *GroupedEpochManager) VerifyCheckpoint(checkpoint *EpochCheckpoint) (bool, error)

VerifyCheckpoint verifies a checkpoint's Ringtail signature.

func (*GroupedEpochManager) VerifyGroupedSignature added in v1.22.36

func (gem *GroupedEpochManager) VerifyGroupedSignature(gs *GroupedSignature) (bool, error)

VerifyGroupedSignature verifies that enough groups signed the message.

type GroupedEpochStats added in v1.22.36

type GroupedEpochStats struct {
	EpochStats
	NumGroups       int
	GroupSize       int
	GroupThreshold  int
	GroupQuorum     int
	TotalValidators int
}

GroupedEpochStats extends EpochStats with group information.

type GroupedSignature added in v1.22.36

type GroupedSignature struct {
	Epoch           uint64
	Message         string
	GroupSignatures map[int]*ringtailThreshold.Signature // group index -> signature
	SignedGroups    []int
}

GroupedSignature holds signatures from multiple groups.

type Hybrid added in v1.22.22

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

Hybrid implements parallel BLS+Ringtail threshold signing for PQ-safe consensus. BLS provides fast classical threshold signatures. Ringtail provides post-quantum threshold signatures based on Ring-LWE. Both run in parallel to provide quantum-safe finality.

func NewHybrid added in v1.22.22

func NewHybrid(thresholdVal int) (*Hybrid, error)

NewHybrid creates a new hybrid consensus engine with basic BLS support.

func NewHybridWithDualThreshold added in v1.22.36

func NewHybridWithDualThreshold(config HybridConfig) (*Hybrid, error)

NewHybridWithDualThreshold creates a hybrid engine with full dual threshold signing.

func NewHybridWithThreshold added in v1.22.28

func NewHybridWithThreshold(config HybridConfig) (*Hybrid, error)

NewHybridWithThreshold is an alias for NewHybridWithDualThreshold.

func NewHybridWithThresholdConfig added in v1.22.36

func NewHybridWithThresholdConfig(config ThresholdConfig) (*Hybrid, error)

NewHybridWithThresholdConfig creates a hybrid engine from ThresholdConfig.

func (*Hybrid) AddValidator added in v1.22.22

func (h *Hybrid) AddValidator(id string, weight uint64) error

AddValidator adds a validator with legacy BLS key generation.

func (*Hybrid) AddValidatorThreshold added in v1.22.28

func (h *Hybrid) AddValidatorThreshold(id string, keyShare threshold.KeyShare, weight uint64) error

AddValidatorThreshold adds a validator with BLS threshold key share.

func (*Hybrid) AggregateSignatures added in v1.22.22

func (h *Hybrid) AggregateSignatures(message []byte, signatures []*HybridSignature) (*AggregatedSignature, error)

AggregateSignatures aggregates BLS threshold signature shares.

func (*Hybrid) AggregateSignaturesWithContext added in v1.22.23

func (h *Hybrid) AggregateSignaturesWithContext(ctx context.Context, message []byte, signatures []*HybridSignature) (*AggregatedSignature, error)

AggregateSignaturesWithContext aggregates signatures.

func (*Hybrid) AggregateThresholdSignatures added in v1.22.28

func (h *Hybrid) AggregateThresholdSignatures(ctx context.Context, message []byte, shares []threshold.SignatureShare) (threshold.Signature, error)

AggregateThresholdSignatures aggregates BLS threshold shares.

func (*Hybrid) DualSignRound1 added in v1.22.36

func (h *Hybrid) DualSignRound1(ctx context.Context, validatorID string, message []byte, sessionID int, prfKey []byte) (*HybridSignature, *ringtailThreshold.Round1Data, error)

DualSignRound1 performs Round 1 of both BLS and Ringtail in parallel. BLS: Computes signature share (single round) Ringtail: Computes D matrix + MACs (Round 1 of 2)

func (*Hybrid) DualSignRound2 added in v1.22.36

func (h *Hybrid) DualSignRound2(validatorID string, sessionID int, message string, prfKey []byte, round1Data map[int]*ringtailThreshold.Round1Data) (*ringtailThreshold.Round2Data, error)

DualSignRound2 performs Round 2 of Ringtail (BLS is already done in Round1).

func (*Hybrid) GetActiveValidatorCount added in v1.22.22

func (h *Hybrid) GetActiveValidatorCount() int

GetActiveValidatorCount returns the number of active validators.

func (*Hybrid) GetThreshold added in v1.22.22

func (h *Hybrid) GetThreshold() int

GetThreshold returns the consensus threshold.

func (*Hybrid) IsDualThresholdMode added in v1.22.36

func (h *Hybrid) IsDualThresholdMode() bool

IsDualThresholdMode returns true if both BLS and Ringtail are enabled.

func (*Hybrid) IsThresholdMode added in v1.22.28

func (h *Hybrid) IsThresholdMode() bool

IsThresholdMode returns true if BLS threshold signing is enabled.

func (*Hybrid) RingtailFinalize added in v1.22.36

func (h *Hybrid) RingtailFinalize(validatorID string, round2Data map[int]*ringtailThreshold.Round2Data) (*ringtailThreshold.Signature, error)

RingtailFinalize aggregates Round 2 data into the final signature. Any validator can call this.

func (*Hybrid) RingtailRound1 added in v1.22.36

func (h *Hybrid) RingtailRound1(validatorID string, sessionID int, prfKey []byte) (*ringtailThreshold.Round1Data, error)

RingtailRound1 performs Round 1 of Ringtail signing for a validator. Returns Round1Data to broadcast to other validators.

func (*Hybrid) RingtailRound2 added in v1.22.36

func (h *Hybrid) RingtailRound2(validatorID string, sessionID int, message string, prfKey []byte, round1Data map[int]*ringtailThreshold.Round1Data) (*ringtailThreshold.Round2Data, error)

RingtailRound2 performs Round 2 of Ringtail signing for a validator. Requires collected Round 1 data from all signers. Returns Round2Data to broadcast.

func (*Hybrid) SignMessage added in v1.22.22

func (h *Hybrid) SignMessage(validatorID string, message []byte) (*HybridSignature, error)

SignMessage signs a message with BLS (legacy mode or threshold).

func (*Hybrid) SignMessageThreshold added in v1.22.28

func (h *Hybrid) SignMessageThreshold(ctx context.Context, validatorID string, message []byte) (threshold.SignatureShare, error)

SignMessageThreshold signs using BLS threshold.

func (*Hybrid) SignMessageWithContext added in v1.22.23

func (h *Hybrid) SignMessageWithContext(ctx context.Context, validatorID string, message []byte) (*HybridSignature, error)

SignMessageWithContext signs a message.

func (*Hybrid) ThresholdGroupKey added in v1.22.28

func (h *Hybrid) ThresholdGroupKey() threshold.PublicKey

ThresholdGroupKey returns the BLS group public key.

func (*Hybrid) ThresholdScheme added in v1.22.28

func (h *Hybrid) ThresholdScheme() threshold.Scheme

ThresholdScheme returns the BLS threshold scheme.

func (*Hybrid) VerifyAggregatedSignature added in v1.22.22

func (h *Hybrid) VerifyAggregatedSignature(message []byte, aggSig *AggregatedSignature) bool

VerifyAggregatedSignature verifies an aggregated signature.

func (*Hybrid) VerifyAggregatedSignatureWithContext added in v1.22.23

func (h *Hybrid) VerifyAggregatedSignatureWithContext(ctx context.Context, message []byte, aggSig *AggregatedSignature) bool

VerifyAggregatedSignatureWithContext verifies an aggregated signature.

func (*Hybrid) VerifyHybridSignature added in v1.22.22

func (h *Hybrid) VerifyHybridSignature(message []byte, sig *HybridSignature) bool

VerifyHybridSignature verifies a signature.

func (*Hybrid) VerifyHybridSignatureWithContext added in v1.22.23

func (h *Hybrid) VerifyHybridSignatureWithContext(ctx context.Context, message []byte, sig *HybridSignature) bool

VerifyHybridSignatureWithContext verifies a signature.

func (*Hybrid) VerifyRingtailSignature added in v1.22.36

func (h *Hybrid) VerifyRingtailSignature(message string, sig *ringtailThreshold.Signature) bool

VerifyRingtailSignature verifies a Ringtail threshold signature.

func (*Hybrid) VerifyThresholdSignature added in v1.22.28

func (h *Hybrid) VerifyThresholdSignature(message []byte, sig threshold.Signature) bool

VerifyThresholdSignature verifies a BLS threshold signature.

func (*Hybrid) VerifyThresholdSignatureBytes added in v1.22.28

func (h *Hybrid) VerifyThresholdSignatureBytes(message, sig []byte) bool

VerifyThresholdSignatureBytes verifies serialized BLS threshold signature.

type HybridConfig added in v1.22.36

type HybridConfig struct {
	Threshold    int
	TotalParties int

	// BLS threshold (via crypto/threshold interface)
	BLSKeyShares map[string]threshold.KeyShare
	BLSGroupKey  threshold.PublicKey

	// Ringtail threshold (native 2-round protocol)
	RingtailShares   map[string]*ringtailThreshold.KeyShare
	RingtailGroupKey *ringtailThreshold.GroupKey
}

HybridConfig configures the dual threshold signing system.

func GenerateDualKeys added in v1.22.36

func GenerateDualKeys(t, n int) (*HybridConfig, error)

GenerateDualKeys generates both BLS and Ringtail threshold keys for an epoch. Call this when the validator set changes.

func GenerateDualThresholdKeys added in v1.22.36

func GenerateDualThresholdKeys(t, n int) (*HybridConfig, error)

GenerateDualThresholdKeys generates both BLS and Ringtail keys (backward compat).

type HybridConsensus added in v1.22.4

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

HybridConsensus handles BLS + PQ certificate generation.

func (*HybridConsensus) AddValidator added in v1.22.4

func (h *HybridConsensus) AddValidator(id string, weight int)

AddValidator adds a validator to the consensus.

func (*HybridConsensus) RemoveValidator added in v1.22.4

func (h *HybridConsensus) RemoveValidator(id string)

RemoveValidator removes a validator from the consensus.

type HybridSignature

type HybridSignature struct {
	BLS         []byte
	Ringtail    []byte
	ValidatorID string
	IsThreshold bool
	SignerIndex int
}

HybridSignature contains BLS and optionally Ringtail signature data.

type PChain added in v1.22.22

type PChain = BLS

PChain is a deprecated alias for backward compatibility. Deprecated: Use BLS instead.

type Precomp

type Precomp = []byte

Type aliases for cleaner API

func Precompute

func Precompute(sk []byte) (Precomp, error)

Precompute generates a precomputed share

type PublicKey

type PublicKey = []byte

Type aliases for cleaner API

type QBlock

type QBlock = Block

QBlock is an alias for Block for backward compatibility. Deprecated: Use Block instead.

type QuantumBlock added in v1.22.1

type QuantumBlock struct {
	Height        uint64
	SourceBlocks  []*Block
	QuantumHash   string
	BLSSignature  []byte
	RingtailProof []byte // ML-DSA signature
	Timestamp     time.Time
	ValidatorSigs map[string]*HybridSignature
}

QuantumBlock represents a quantum-finalized aggregate block.

type QuantumBundle added in v1.22.36

type QuantumBundle struct {
	Epoch        uint64     // Current key epoch
	Sequence     uint64     // Bundle sequence within epoch
	StartHeight  uint64     // First BLS block in this bundle
	EndHeight    uint64     // Last BLS block in this bundle
	BlockCount   int        // Number of BLS blocks bundled
	MerkleRoot   [32]byte   // Merkle root of BLS block hashes
	BlockHashes  [][32]byte // Individual block hashes (for Merkle proof)
	PreviousHash [32]byte   // Previous bundle hash (chain linkage)
	Timestamp    int64      // Unix timestamp

	// Ringtail threshold signature (post-quantum secure)
	Signature *ringtailThreshold.Signature
}

QuantumBundle bundles multiple BLS-signed blocks into a quantum-safe anchor. BLS blocks continue at 500ms pace; quantum bundles form every 3 seconds containing a Merkle root of ~6 BLS block hashes. Note: This is distinct from core.go's QuantumBlock which represents per-block finality.

func (*QuantumBundle) Hash added in v1.22.36

func (qb *QuantumBundle) Hash() [32]byte

Hash returns the hash of this bundle for chain linkage.

func (*QuantumBundle) SignableMessage added in v1.22.36

func (qb *QuantumBundle) SignableMessage() string

SignableMessage returns the message for Ringtail signing.

type Quasar

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

Quasar is the supermassive black hole at the center of the blockchain galaxy It collects blocks from ALL chains (P, X, C, + any new subnets) and applies quantum consensus External systems (bridges, contracts) can use RPC to add blocks to the event horizon

func NewQuasar added in v1.22.22

func NewQuasar(threshold int) (*Quasar, error)

NewQuasar creates the supermassive black hole at the center of the blockchain galaxy

func (*Quasar) AddValidator added in v1.22.36

func (q *Quasar) AddValidator(validatorID string, weight uint64) (rotated bool, err error)

AddValidator adds a single validator, triggering key rotation if rate limit allows.

func (*Quasar) ForceEpochRotation added in v1.22.36

func (q *Quasar) ForceEpochRotation() (rotated bool, err error)

ForceEpochRotation forces Ringtail key rotation if minimum time has passed. Use this for periodic security refreshes even without validator changes.

func (*Quasar) GetCurrentEpoch added in v1.22.36

func (q *Quasar) GetCurrentEpoch() uint64

GetCurrentEpoch returns the current Ringtail epoch number.

func (*Quasar) GetEpochManager added in v1.22.36

func (q *Quasar) GetEpochManager() *EpochManager

GetEpochManager returns the epoch manager for advanced operations.

func (*Quasar) GetEpochStats added in v1.22.36

func (q *Quasar) GetEpochStats() EpochStats

GetEpochStats returns current epoch statistics.

func (*Quasar) GetMetrics added in v1.22.22

func (q *Quasar) GetMetrics() (processedBlocks, quantumProofs uint64)

GetMetrics returns aggregator metrics

func (*Quasar) GetQuantumHeight added in v1.22.22

func (q *Quasar) GetQuantumHeight() uint64

GetQuantumHeight returns the current quantum finalized height

func (*Quasar) GetRegisteredChains added in v1.22.22

func (q *Quasar) GetRegisteredChains() []string

GetRegisteredChains returns all chains currently in the event horizon

func (*Quasar) InitializeValidators added in v1.22.36

func (q *Quasar) InitializeValidators(validatorIDs []string) error

InitializeValidators sets up the initial validator set with both BLS and Ringtail keys. This should be called once at genesis or node startup.

func (*Quasar) ProcessDynamicChains added in v1.22.22

func (q *Quasar) ProcessDynamicChains(ctx context.Context)

ProcessDynamicChains starts processors for all dynamically registered chains This runs alongside the legacy P/X/C chain processors

func (*Quasar) RegisterChain added in v1.22.22

func (q *Quasar) RegisterChain(chainName string) error

RegisterChain dynamically registers a new chain/subnet for automatic quantum security All new subnets are automatically protected by the event horizon

func (*Quasar) RemoveValidator added in v1.22.36

func (q *Quasar) RemoveValidator(validatorID string) (rotated bool, err error)

RemoveValidator removes a validator, triggering key rotation if rate limit allows.

func (*Quasar) Start added in v1.22.1

func (q *Quasar) Start(ctx context.Context) error

Start begins drawing blocks into the Quasar's gravitational pull

func (*Quasar) SubmitBlock added in v1.22.22

func (q *Quasar) SubmitBlock(block *ChainBlock) error

SubmitBlock is the universal RPC endpoint for ANY chain/contract to add blocks External systems (bridge, contracts) use this to enter the event horizon

func (*Quasar) SubmitCChainBlock added in v1.22.22

func (q *Quasar) SubmitCChainBlock(block *ChainBlock)

SubmitCChainBlock submits a C-Chain block for quantum consensus

func (*Quasar) SubmitPChainBlock added in v1.22.22

func (q *Quasar) SubmitPChainBlock(block *ChainBlock)

SubmitPChainBlock submits a P-Chain block for quantum consensus

func (*Quasar) SubmitXChainBlock added in v1.22.22

func (q *Quasar) SubmitXChainBlock(block *ChainBlock)

SubmitXChainBlock submits an X-Chain block for quantum consensus

func (*Quasar) UpdateValidatorSet added in v1.22.36

func (q *Quasar) UpdateValidatorSet(validatorIDs []string) (rotated bool, err error)

UpdateValidatorSet updates the validator set, rotating Ringtail keys if needed. Returns true if Ringtail keys were rotated. Rate-limited to at most 1 rotation per hour.

func (*Quasar) VerifyQuantumFinality added in v1.22.22

func (q *Quasar) VerifyQuantumFinality(blockHash string) bool

VerifyQuantumFinality checks if a block has quantum finality. For context-aware verification, use VerifyQuantumFinalityWithContext.

func (*Quasar) VerifyQuantumFinalityWithContext added in v1.22.23

func (q *Quasar) VerifyQuantumFinalityWithContext(ctx context.Context, blockHash string) bool

VerifyQuantumFinalityWithContext checks if a block has quantum finality, respecting context cancellation.

type QuasarCore added in v1.22.1

type QuasarCore = Quasar

QuasarCore is a deprecated alias for backward compatibility. Deprecated: Use Quasar or Core instead.

type QuasarHybridConsensus

type QuasarHybridConsensus = Hybrid

QuasarHybridConsensus is a deprecated alias for backward compatibility. Deprecated: Use Hybrid instead.

type RingtailEngine

type RingtailEngine interface {
	// Initialize the engine with security parameters
	Initialize(level SecurityLevel) error

	// Sign a message with the secret key
	Sign(msg []byte, sk SecretKey) (Signature, error)

	// Verify a signature
	Verify(msg []byte, sig Signature, pk PublicKey) bool

	// Generate a new key pair
	GenerateKeyPair() (SecretKey, PublicKey, error)

	// KEM operations for post-quantum key exchange
	Encapsulate(pk PublicKey) ([]byte, []byte, error)
	Decapsulate(ct []byte, sk SecretKey) ([]byte, error)

	// Shared secret operations
	CombineSharedSecrets(ss1, ss2 []byte) []byte
	DeriveKey(secret []byte, length int) []byte
}

RingtailEngine represents the post-quantum consensus engine

func NewRingtail

func NewRingtail() RingtailEngine

NewRingtail creates a new ringtail engine

type RingtailRound1State added in v1.22.36

type RingtailRound1State struct {
	SessionID  int
	PRFKey     []byte
	SignerIDs  []int
	Round1Data map[int]*ringtailThreshold.Round1Data
}

RingtailRound1State holds Round 1 data for all parties in a signing session.

type SecretKey

type SecretKey = []byte

Type aliases for cleaner API

type SecurityLevel

type SecurityLevel int

SecurityLevel represents the post-quantum security level

const (
	SecurityLow    SecurityLevel = 0
	SecurityMedium SecurityLevel = 1
	SecurityHigh   SecurityLevel = 2
)

type Share

type Share = []byte

Type aliases for cleaner API

func QuickSign

func QuickSign(precomp Precomp, msg []byte) (Share, error)

QuickSign signs using a precomputed share

type Signature

type Signature = []byte // Alias for Share or Cert depending on context

Type aliases for cleaner API

type Stats added in v1.22.4

type Stats struct {
	Height          uint64        // Current finalized height
	ProcessedBlocks uint64        // Total blocks processed
	FinalizedBlocks uint64        // Total blocks finalized
	PendingBlocks   int           // Blocks awaiting finality
	Validators      int           // Active validator count
	Uptime          time.Duration // Time since start
}

Stats contains consensus metrics.

type ThresholdConfig added in v1.22.28

type ThresholdConfig struct {
	SchemeID     threshold.SchemeID
	Threshold    int
	TotalParties int
	KeyShares    map[string]threshold.KeyShare
	GroupKey     threshold.PublicKey
}

ThresholdConfig for backward compatibility with single-scheme tests.

type Validator

type Validator struct {
	ID          string
	BLSPubKey   *bls.PublicKey
	RingtailPub []byte // Ringtail group public key contribution
	Weight      uint64
	Active      bool
}

Validator represents a consensus validator

type ValidatorGroup added in v1.22.36

type ValidatorGroup struct {
	Index      int
	Validators []string
	Threshold  int
	GroupKey   *ringtailThreshold.GroupKey
	Shares     map[string]*ringtailThreshold.KeyShare
	Signers    map[string]*ringtailThreshold.Signer
}

ValidatorGroup holds the Ringtail keys for a single group of validators.

type VerkleWitness

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

VerkleWitness provides hyper-efficient state verification Assumes every block is PQ-final via BLS+Ringtail threshold

func NewVerkleWitness

func NewVerkleWitness(threshold int) *VerkleWitness

NewVerkleWitness creates a lightweight Verkle witness verifier

func (*VerkleWitness) BatchVerify

func (v *VerkleWitness) BatchVerify(witnesses []*WitnessProof) error

BatchVerify verifies multiple witnesses in parallel (hyper-efficient)

func (*VerkleWitness) CreateWitness

func (v *VerkleWitness) CreateWitness(
	stateRoot []byte,
	blsAgg *bls.Signature,
	ringtailSigners []bool,
	height uint64,
) (*WitnessProof, error)

CreateWitness creates a minimal witness for a state transition

func (*VerkleWitness) GetCachedWitness

func (v *VerkleWitness) GetCachedWitness(stateRoot []byte) (*WitnessProof, bool)

GetCachedWitness retrieves a cached witness if available

func (*VerkleWitness) VerifyCompressed

func (v *VerkleWitness) VerifyCompressed(cw *CompressedWitness) error

VerifyCompressed verifies a compressed witness (ultra-fast)

func (*VerkleWitness) VerifyStateTransition

func (v *VerkleWitness) VerifyStateTransition(witness *WitnessProof) error

VerifyStateTransition verifies state transition with minimal overhead Assumes PQ finality via BLS+Ringtail threshold already met

type VertexID

type VertexID [32]byte

VertexID represents a vertex identifier

type WitnessProof

type WitnessProof struct {
	// Verkle proof components
	Commitment   []byte // 32 bytes banderwagon point
	Path         []byte // Compressed path in tree
	OpeningProof []byte // IPA opening proof

	// PQ finality certificate (lightweight)
	BLSAggregate []byte // Aggregated BLS signature
	RingtailBits []byte // Bitfield of Ringtail signers
	ValidatorSet []byte // Compressed validator set hash

	// Block metadata
	BlockHeight uint64
	StateRoot   []byte
	Timestamp   uint64
}

WitnessProof contains the minimal proof for state verification

func (*WitnessProof) Compress

func (w *WitnessProof) Compress() *CompressedWitness

Compress creates a compressed witness (< 200 bytes)

func (*WitnessProof) IsLightweight

func (w *WitnessProof) IsLightweight() bool

IsLightweight checks if witness is under 1KB (hyper-efficient)

func (*WitnessProof) Size

func (w *WitnessProof) Size() int

WitnessSize returns the size of a witness in bytes

Jump to

Keyboard shortcuts

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