quantumvm

package
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: BSD-3-Clause Imports: 35 Imported by: 0

README

Q-chain Virtual Machine (QVM)

The Q-chain Virtual Machine (QVM) hosts the Q lane of Lux's parallel-witness finality model (LP-020 Quasar). When the operator-selected witness set includes WitnessQ (policies PolicyPQ or PolicyQuantum), Q-Chain runs a Ringtail 2-round threshold ceremony per consensus round and emits the resulting threshold signature as the round's Q-witness. Q-Chain is one of three parallel finality producers (P, Q, Z); adding it does not change finality latency, only parallel verification cost.

The VM also provides per-validator ML-DSA-65 (FIPS 204) identity signatures and a quantum stamp for individual transactions.

Features

Q-witness production (Quasar parallel-witness finality)
  • Ringtail threshold (Module-LWE, eprint 2024/1113): 2-round threshold signing per consensus round, t = ⌊2n/3⌋ + 1 of n validators, combined public key rooted in qchain_ceremony_root.
  • Per-validator ML-DSA-65 (FIPS 204): identity signatures over round digests, used by the Z lane (chains/zkvm) to produce the Groth16 rollup.
  • Quantum stamp: time-windowed transaction-level binding.
Performance Optimization
  • Parallel Transaction Processing: Process multiple transactions concurrently
  • Configurable Batch Sizes: Optimize throughput based on network conditions
  • Worker Pool Architecture: Efficient resource utilization with pooled workers
Configuration

The QVM can be configured through the config.Config structure:

type Config struct {
    TxFee                   uint64        // Base transaction fee
    CreateAssetTxFee        uint64        // Asset creation fee
    QuantumVerificationFee  uint64        // Fee for quantum signature verification
    MaxParallelTxs          int           // Maximum parallel transactions
    QuantumAlgorithmVersion uint32        // Quantum algorithm version
    RingtailKeySize         int           // Size of Ringtail keys in bytes
    QuantumStampEnabled     bool          // Enable quantum stamp validation
    QuantumStampWindow      time.Duration // Validity window for quantum stamps
    ParallelBatchSize       int           // Batch size for parallel processing
    QuantumSigCacheSize     int           // Cache size for quantum signatures
    RingtailEnabled         bool          // Enable Ringtail key support
    MinQuantumConfirmations uint32        // Minimum confirmations for quantum stamps
}

Architecture

Core Components
  1. VM (vm.go): Main virtual machine implementation
  2. Factory (factory.go): VM factory for creating QVM instances
  3. Config (config/config.go): Configuration management
  4. Quantum Signer (quantum/signer.go): Quantum signature implementation
Transaction Flow
  1. Transactions are submitted to the transaction pool
  2. Worker threads process transactions in parallel batches
  3. Quantum signatures are verified using the quantum signer
  4. Valid transactions are included in blocks
  5. Blocks are signed with quantum stamps
RPC API

The QVM exposes the following RPC endpoints:

  • qvm.getBlock: Retrieve a block by ID
  • qvm.generateRingtailKey: Generate a new Ringtail key pair
  • qvm.verifyQuantumSignature: Verify a quantum signature
  • qvm.getPendingTransactions: Get pending transactions
  • qvm.getHealth: Get VM health status
  • qvm.getConfig: Get current configuration

Security Features

Quantum Signatures

The QVM uses ML-DSA (FIPS 204, NIST module-lattice DSA) for per-validator quantum-resistant signatures:

  • ML-DSA-44/65/87 supported (NIST Level 2/3/5)
  • Quantum stamp: time-windowed binding of message + nonce + timestamp, prevents stamp replay
  • GPU batch verification via accel.DilithiumVerifyBatch (accel.Available(), threshold 64+ signatures)
Validator key material

Two distinct categories live on Q-Chain validators:

  • Per-validator ML-DSA-65 identity key: MLDSAValidatorKey in quantum/signer.go (kept exposed via the legacy GenerateRingtailKey RPC name). Used for individual round attestations and the Z-witness rollup input.
  • Ringtail threshold share: per-validator share of the combined Ringtail key, produced by the Q-Chain DKG ceremony (rooted in qchain_ceremony_root). Lives in luxfi/threshold/protocols/ringtail.
Parallel Processing Safety
  • Thread-safe transaction pool with mutex protection
  • Isolated worker threads for transaction processing
  • Atomic operations for state updates

Usage

Creating a QVM Instance
factory := &qvm.Factory{
    Config: config.DefaultConfig(),
}

vm, err := factory.New(logger)
if err != nil {
    return err
}
Initializing the VM
err := vm.Initialize(
    ctx,
    chainRuntime,
    db,
    genesisBytes,
    upgradeBytes,
    configBytes,
    toEngine,
    fxs,
    appSender,
)
Building Blocks
block, err := vm.BuildBlock(ctx)
if err != nil {
    return err
}

Testing

The QVM includes comprehensive error handling and logging for production use:

  • Error recovery for parallel processing failures
  • Detailed logging at all levels (Info, Debug, Error)
  • Health check monitoring
  • Metrics collection

Future Enhancements

Planned improvements include:

  • Additional quantum-resistant algorithms (SPHINCS+, Dilithium, Falcon)
  • Enhanced parallel processing with GPU acceleration
  • Cross-chain quantum signature verification
  • Advanced caching strategies for improved performance

License

Copyright (C) 2019-2025, Lux Industries Inc All rights reserved. See the file LICENSE for licensing terms.

Documentation

Overview

Package quantumvm GPU backend — runtime-loaded plugin bridge via the ABI v14 vtbl entry point.

Unlike cevm/cevm_cgo.go (which links libevm + libevm-gpu via pkg-config and reaches the C ABI through extern "C" gpu_* helpers), Q-Chain resolves its GPU substrate at PROCESS START via dlopen / dlsym against the lux-gpu-kernels plugin DSO and reaches the per-op kernel through function pointers inside a vtbl populated by the plugin's `lux_gpu_backend_init` entry point. This keeps the chains module compilable without the lux GPU plugin present in the build tree — the plugin is fully optional. When no libluxgpu_backend_*.{so,dylib} is findable on the dlopen search path, AutoBackend() returns BackendNone, every GPUBackend method returns ErrGPUNotAvailable, and the existing CPU verify path stays unchanged.

Probe order (init()): cuda → hip → metal → vulkan → webgpu. First plugin that resolves the entry point AND reports a v14 ABI matching the header we compiled against AND exposes the three Q-Chain slots (op_mldsa_verify_batch, op_mldsa_sign_batch, op_slhdsa_verify_batch[_shake192f]) wins; remaining probes are skipped. The cookie checks (abi_version + vtbl_size) defend against a plugin that lies about its ABI version while shipping a truncated vtable (see backend_plugin.h §"Backend Descriptor" comment).

Search path: the dlopen library name is the bare basename (libluxgpu_backend_<x>.{so,dylib}); the loader's standard LD_LIBRARY_PATH / DYLD_LIBRARY_PATH / rpath resolution finds it. LUX_GPU_PLUGIN_DIR overrides — if set, every probe joins it to the basename before calling dlopen.

Index

Constants

View Source
const (
	MLDSA65PublicKeySize = 1952
	MLDSA65SecretKeySize = 4032
	MLDSA65SignatureSize = 3309
)

ML-DSA-65 byte sizes per FIPS 204 §4. Pinned constants — the plugin rejects mismatched sk_stride at the boundary, so we surface them up front to keep the call sites unambiguous.

View Source
const (
	// Version of the QVM
	Version = "1.0.0"

	// MaxParallelVerifications is the maximum number of parallel verifications
	MaxParallelVerifications = 100

	// DefaultBatchSize is the default batch size for parallel processing
	DefaultBatchSize = 10
)

Variables

View Source
var ErrGPUNotAvailable = errors.New("quantumvm: GPU backend not available")

ErrGPUNotAvailable is returned by every GPUBackend method when no plugin is loaded — either because the binary was built without CGo, no libluxgpu_backend_*.{so,dylib} was findable on the dlopen search path, the loaded plugin reported a non-v14 ABI version, or its vtbl was missing one of the three Q-Chain slots.

The error is sentinel-comparable via errors.Is so callers can route the CPU verify path cleanly:

if errors.Is(err, quantumvm.ErrGPUNotAvailable) {
    return cpuVerify(pk, msg, sig)
}
View Source
var ErrQWitnessNotWired = errors.New("Q-Chain per-round Corona driver not wired (TODO LP-020 §9)")

ErrQWitnessNotWired is returned by QWitnessAdapter.Witness until the per-round Corona driver lands. The interface is in place so the consensus driver can be configured today.

View Source
var VMID = ids.ID{'q', 'u', 'a', 'n', 't', 'u', 'm', 'v', 'm'}

VMID is the unique identifier for QuantumVM (Q-Chain)

Functions

This section is empty.

Types

type BCLookup

type BCLookup interface {
	Lookup(string) (ids.ID, error)
	PrimaryAlias(ids.ID) (string, error)
}

BCLookup provides blockchain alias lookup

type Backend added in v1.3.0

type Backend uint8

Backend identifies which GPU plugin satisfied the runtime dlopen probe.

Probe order is fixed by the spec: cuda → hip → metal → vulkan → webgpu. The first plugin that resolves the `lux_gpu_backend_init` entry point and reports a v14 vtbl with the three Q-Chain slots (op_mldsa_verify_batch, op_mldsa_sign_batch, op_slhdsa_verify_batch) wins; remaining probes are skipped. Each plugin is fully self-contained — there is no fallback chain once one is chosen (this keeps backend selection deterministic across reboots, matching consensus-safety expectations).

const (
	// BackendNone means no GPU plugin is loaded — every GPUBackend method
	// returns ErrGPUNotAvailable. This is the value reported by
	// AutoBackend() under !cgo, and under cgo when no
	// libluxgpu_backend_*.{so,dylib} was findable.
	BackendNone Backend = 0
	// BackendCUDA selects libluxgpu_backend_cuda.so (NVIDIA, Linux/Windows).
	BackendCUDA Backend = 1
	// BackendHIP selects libluxgpu_backend_hip.so (AMD ROCm, Linux/Windows).
	BackendHIP Backend = 2
	// BackendMetal selects libluxgpu_backend_metal.dylib (Apple, darwin).
	BackendMetal Backend = 3
	// BackendVulkan selects libluxgpu_backend_vulkan.{so,dylib} (portable).
	BackendVulkan Backend = 4
	// BackendWebGPU selects libluxgpu_backend_webgpu.{so,dylib} (portable).
	BackendWebGPU Backend = 5
)

func AutoBackend added in v1.3.0

func AutoBackend() Backend

AutoBackend returns the GPU plugin chosen by the dlopen probe at process start. BackendNone means no plugin is loaded — callers should route to the CPU verify path. The probe runs exactly once at init time; this getter is one atomic load and safe to call from any goroutine.

func (Backend) String added in v1.3.0

func (b Backend) String() string

String returns the canonical lowercase name of the backend. The same name appears in the plugin DSO filename (libluxgpu_backend_<name>.*) and in the lux_gpu_backend_desc.backend_name field reported by the loaded plugin.

type BaseTransaction

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

BaseTransaction provides common transaction functionality

func (*BaseTransaction) Bytes

func (tx *BaseTransaction) Bytes() []byte

Bytes returns the transaction bytes

func (*BaseTransaction) Execute

func (tx *BaseTransaction) Execute() error

Execute executes the transaction

func (*BaseTransaction) Fee added in v1.2.6

func (tx *BaseTransaction) Fee() uint64

Fee returns the user-paid tx burn (nLUX). Defaults to zero on a zero-value BaseTransaction — callers must set it explicitly for the fee gate to accept the tx.

func (*BaseTransaction) GetQuantumSignature

func (tx *BaseTransaction) GetQuantumSignature() *quantum.QuantumSignature

GetQuantumSignature returns the quantum signature

func (*BaseTransaction) ID

func (tx *BaseTransaction) ID() ids.ID

ID returns the transaction ID

func (*BaseTransaction) SetFee added in v1.2.6

func (tx *BaseTransaction) SetFee(f uint64)

SetFee sets the user-paid tx burn in nLUX. Convenience setter for tests + tx builders; production callers should pass the fee at construction time.

func (*BaseTransaction) Timestamp

func (tx *BaseTransaction) Timestamp() time.Time

Timestamp returns the transaction timestamp

func (*BaseTransaction) Verify

func (tx *BaseTransaction) Verify() error

Verify verifies the transaction

type Block

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

Block represents a QVM block with quantum features

func (*Block) Accept

func (b *Block) Accept(context.Context) error

Accept marks the block as accepted

func (*Block) Bytes

func (b *Block) Bytes() []byte

Bytes returns the block bytes

func (*Block) Height

func (b *Block) Height() uint64

Height returns the block height

func (*Block) ID

func (b *Block) ID() ids.ID

ID returns the block ID

func (*Block) Parent

func (b *Block) Parent() ids.ID

Parent returns the parent block ID

func (*Block) ParentID

func (b *Block) ParentID() ids.ID

ParentID returns the parent block ID (implements consensus Block interface)

func (*Block) Reject

func (b *Block) Reject(context.Context) error

Reject marks the block as rejected

func (*Block) Status

func (b *Block) Status() uint8

Status returns the block status. Q-Chain does not yet track per-block status separately (all blocks reaching here are processing or accepted), so we return 0 (Unknown) until a status field is added.

func (*Block) String

func (b *Block) String() string

String returns a string representation of the block

func (*Block) Timestamp

func (b *Block) Timestamp() time.Time

Timestamp returns the block timestamp (implements block.Block interface)

func (*Block) TimestampUnix

func (b *Block) TimestampUnix() int64

TimestampUnix returns the block timestamp as Unix seconds.

func (*Block) Verify

func (b *Block) Verify(ctx context.Context) error

Verify verifies the block validity

type BlockSigs

type BlockSigs struct {
	BLS    *quasar.BLSSignature
	Corona *quasar.CoronaSignature
}

BlockSigs contains both BLS and Corona signatures for a block. Both are produced in parallel during signing.

type Factory

type Factory struct {
	config.Config
}

Factory implements vms.Factory interface for creating QVM instances

func (*Factory) New

func (f *Factory) New(logger log.Logger) (interface{}, error)

New creates a new QVM instance

type GPUBackend added in v1.3.0

type GPUBackend interface {
	// MLDSAVerifyBatch verifies a batch of ML-DSA signatures. mode pins
	// the FIPS 204 parameter set; only MLDSAMode65 is wired through the
	// v14 vtbl (modes 44/87 return ErrGPUNotAvailable). pubkeys[i],
	// messages[i], and signatures[i] supply the per-element inputs;
	// msgLens[i] is the byte length of messages[i] (NULL slice means
	// every message is exactly msgWidthHint bytes — see the
	// op_mldsa_verify_batch comment in backend_plugin.h for the
	// uniform-batch convenience contract). results[i] is set to true
	// iff verification succeeds.
	//
	// The slices must all have the same length; mismatched lengths are
	// caught at the boundary and returned as an error (no UB into C).
	MLDSAVerifyBatch(
		mode MLDSAMode,
		pubkeys [][]byte,
		messages [][]byte,
		msgLens []int,
		msgWidthHint uint32,
		signatures [][]byte,
		results []bool,
	) error

	// MLDSASignBatch signs a batch of messages with packed ML-DSA secret
	// keys. mode pins the FIPS 204 parameter set; only MLDSAMode65 is
	// wired through the v14 vtbl. skeys is the contiguous pool of
	// per-element packed secret keys (each MLDSA65SecretKeySize = 4032
	// bytes); the wrapper feeds the pool through cudaMemcpy2D directly
	// in one shot. msgs is the contiguous pool of per-element message
	// payloads (msgLens[i] bytes from offset sum(msgLens[0..i-1])).
	// sigsOut receives count × MLDSA65SignatureSize bytes; sigLensOut
	// returns the per-element actual signature length (3309 on accept,
	// 0 on kappa-cap reject — see backend_plugin.h v14 block).
	MLDSASignBatch(
		mode MLDSAMode,
		skeys []byte,
		msgs []byte,
		msgLens []int,
		msgWidthHint uint32,
		count int,
		sigsOut []byte,
		sigLensOut []uint32,
	) error

	// SLHDSAVerifyBatch verifies a batch of SLH-DSA signatures. variant
	// pins the FIPS 205 parameter set; only SHAKE-128f and SHAKE-192f
	// are wired through the v14 vtbl (the other 10 variants return
	// ErrGPUNotAvailable). pubkeys[i], messages[i], and signatures[i]
	// supply the per-element inputs at the FIPS 205 widths reported by
	// variant.PublicKeySize() / variant.SignatureSize(); msgLens[i] is
	// the byte length of messages[i] (any value in [0, INT32_MAX-2]).
	// results[i] is set to true iff verification succeeds.
	SLHDSAVerifyBatch(
		variant SLHDSAVariant,
		pubkeys [][]byte,
		messages [][]byte,
		msgLens []int,
		signatures [][]byte,
		results []bool,
	) error

	// Backend reports which plugin is currently loaded.
	Backend() Backend

	// Close releases the dlopen handle and the LuxBackendContext. Safe
	// on a nil receiver and idempotent.
	Close() error
}

GPUBackend is the narrow Q-Chain surface that vm.go's batch verify / sign paths can opt into. Three 1:1 mappings to the ABI v14 vtbl slots, plus Backend() / Close() lifecycle.

Buffer ownership: callers own every slice / struct passed in. The vtbl slot does H2D / D2H internally. On return every output slice has been overwritten with the kernel's result; the caller can read immediately, no further sync needed.

Composition: the three batch methods are orthogonal — a "round" that verifies a mixed batch of ML-DSA + SLH-DSA stamps composes them in the round applier. We do NOT try to express a "verify all PQ sigs" supercall here; that would couple the round-level policy to the substrate, and the substrate intentionally only exposes primitives.

func ActiveGPUBackend added in v1.3.0

func ActiveGPUBackend() GPUBackend

ActiveGPUBackend returns the package-level GPUBackend handle. Under cgo this is the *gpuBackend chosen by init()'s probe, or a sentinel noGPUBackend stub when no plugin loaded. The returned handle's methods are safe to call from any goroutine — every vtbl call holds the backend mutex.

type GenerateCoronaKeyArgs added in v1.2.3

type GenerateCoronaKeyArgs struct{}

GenerateCoronaKeyArgs are the arguments for GenerateCoronaKey

type GenerateCoronaKeyReply added in v1.2.3

type GenerateCoronaKeyReply struct {
	PublicKey string `json:"publicKey"`
	Version   uint32 `json:"version"`
	KeySize   int    `json:"keySize"`
}

GenerateCoronaKeyReply is the reply for GenerateCoronaKey

type GetBlockArgs

type GetBlockArgs struct {
	BlockID string `json:"blockID"`
}

GetBlockArgs are the arguments for GetBlock

type GetBlockReply

type GetBlockReply struct {
	Block      json.RawMessage `json:"block"`
	Height     uint64          `json:"height"`
	Timestamp  int64           `json:"timestamp"`
	TxCount    int             `json:"txCount"`
	QuantumSig bool            `json:"quantumSig"`
}

GetBlockReply is the reply for GetBlock

type GetConfigArgs

type GetConfigArgs struct{}

GetConfigArgs are the arguments for GetConfig

type GetConfigReply

type GetConfigReply struct {
	TxFee                   uint64 `json:"txFee"`
	CreateAssetTxFee        uint64 `json:"createAssetTxFee"`
	QuantumVerificationFee  uint64 `json:"quantumVerificationFee"`
	MaxParallelTxs          int    `json:"maxParallelTxs"`
	QuantumAlgorithmVersion uint32 `json:"quantumAlgorithmVersion"`
	CoronaKeySize           int    `json:"coronaKeySize"`
	QuantumStampEnabled     bool   `json:"quantumStampEnabled"`
	CoronaEnabled           bool   `json:"coronaEnabled"`
	ParallelBatchSize       int    `json:"parallelBatchSize"`
}

GetConfigReply is the reply for GetConfig

type GetHealthArgs

type GetHealthArgs struct{}

GetHealthArgs are the arguments for GetHealth

type GetHealthReply

type GetHealthReply struct {
	Healthy         bool   `json:"healthy"`
	Version         string `json:"version"`
	QuantumEnabled  bool   `json:"quantumEnabled"`
	CoronaEnabled   bool   `json:"coronaEnabled"`
	PendingTxCount  int    `json:"pendingTxCount"`
	ParallelWorkers int    `json:"parallelWorkers"`
}

GetHealthReply is the reply for GetHealth

type GetPendingTransactionsArgs

type GetPendingTransactionsArgs struct {
	Limit int `json:"limit"`
}

GetPendingTransactionsArgs are the arguments for GetPendingTransactions

type GetPendingTransactionsReply

type GetPendingTransactionsReply struct {
	Transactions []json.RawMessage `json:"transactions"`
	Count        int               `json:"count"`
}

GetPendingTransactionsReply is the reply for GetPendingTransactions

type MLDSAMode added in v1.3.0

type MLDSAMode uint8

MLDSAMode selects which ML-DSA security parameter set the batch targets. The ABI v14 vtbl currently exposes only ML-DSA-65 (mode 3, FIPS 204 Dilithium3) — modes 44 and 87 will land at their own vtbl slots in a future ABI bump (see backend_plugin.h v14 block). Callers pass the mode through so the wrapper can validate batch byte widths at the boundary, even though only MLDSA65 round-trips through the plugin today.

const (
	// MLDSAMode44 is FIPS 204 Dilithium2. Not yet wired through the v14
	// vtbl — passing this to a batch method returns ErrGPUNotAvailable
	// (caller falls through to the CPU path).
	MLDSAMode44 MLDSAMode = 1
	// MLDSAMode65 is FIPS 204 Dilithium3 — the canonical Q-Chain mode.
	// pk=1952 B, sig=3309 B (max), sk=4032 B.
	MLDSAMode65 MLDSAMode = 2
	// MLDSAMode87 is FIPS 204 Dilithium5. Not yet wired through the v14
	// vtbl — passing this returns ErrGPUNotAvailable.
	MLDSAMode87 MLDSAMode = 3
)

type PendingBlock

type PendingBlock struct {
	BlockID          ids.ID
	BlockHash        []byte
	Height           uint64
	BLSSignatures    []*quasar.BLSSignature    // Classical threshold signatures (parallel)
	CoronaSignatures []*quasar.CoronaSignature // Post-quantum threshold signatures (parallel)
	BLSFinalized     bool                      // BLS threshold reached
	CoronaFinalized  bool                      // Corona threshold reached
	Finalized        bool                      // BOTH complete = quantum finality
}

PendingBlock tracks a block awaiting dual signature finality. Both BLS AND Corona must reach threshold for quantum finality. Signatures are collected in parallel - either can complete first.

type QWitnessAdapter

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

QWitnessAdapter adapts the Q-Chain Quasar engine to the consensus QWitnessProducer interface used by the Quasar round driver.

TODO(pqz): wire to a real per-round Corona ceremony driver. The current quantumvm.Quasar engine signs per-block by validator id; a per-consensus- round driver is required to land a true Q-witness. See LP-020 §9 Implementation, "Three-lane signing".

func NewQWitnessAdapter

func NewQWitnessAdapter(engine *Quasar) *QWitnessAdapter

NewQWitnessAdapter constructs a Q-witness adapter backed by the given Q-Chain Quasar engine. Pass the engine returned by NewQuasar.

func (*QWitnessAdapter) Witness

func (a *QWitnessAdapter) Witness(ctx context.Context, digest [32]byte) ([]byte, error)

Witness produces a Corona threshold signature over the round digest. Signature matches consensus/protocol/quasar.QWitnessProducer.

Returns ErrQWitnessNotWired today; the round driver treats this as the witness being unavailable and finalizes at PolicyQuorum (or PolicyPZ if Z is enabled).

type Quasar

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

Quasar is the core Post-Quantum BFT consensus engine for Q-Chain. Like a supermassive black hole, it pulls all blocks to quantum finality using dual BLS+Corona threshold signatures: - BLS threshold signatures (classical security, fast path) - Corona threshold signatures (post-quantum, Ring-LWE based)

Blocks are NOT considered produced without BOTH thresholds being met.

func NewQuasar

func NewQuasar(cfg QuasarConfig) (*Quasar, error)

NewQuasar creates a new Quasar PQ-BFT consensus engine

func (*Quasar) AddBLSSignature

func (q *Quasar) AddBLSSignature(blockID ids.ID, sig *quasar.BLSSignature) error

AddBLSSignature adds a BLS signature from another validator

func (*Quasar) AddCoronaSignature

func (q *Quasar) AddCoronaSignature(blockID ids.ID, sig *quasar.CoronaSignature) error

AddCoronaSignature adds a Corona signature from another validator

func (*Quasar) AddValidator

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

AddValidator adds a new validator to the Quasar consensus

func (*Quasar) BatchNTTForwardCorona added in v1.2.3

func (q *Quasar) BatchNTTForwardCorona(polys [][]uint64) ([][]uint64, error)

BatchNTTForwardCorona transforms multiple polynomials in parallel on GPU. Used when processing multiple Corona signature shares simultaneously.

func (*Quasar) Cleanup

func (q *Quasar) Cleanup(minHeight uint64)

Cleanup removes finalized blocks older than the given height

func (*Quasar) GPUAccelAvailable

func (q *Quasar) GPUAccelAvailable() bool

GPUAccelAvailable reports whether GPU acceleration is available for lattice operations (NTT, batch ML-DSA verify).

func (*Quasar) GetActiveValidators

func (q *Quasar) GetActiveValidators() int

GetActiveValidators returns the count of active validators

func (*Quasar) GetQuasar

func (q *Quasar) GetQuasar() *quasar.Quasar

GetQuasar returns the underlying Quasar core engine

func (*Quasar) GetThreshold

func (q *Quasar) GetThreshold() int

GetThreshold returns the consensus threshold

func (*Quasar) InitializeDualThreshold

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

InitializeDualThreshold sets up BLS and Corona threshold keys for a new epoch

func (*Quasar) IsFinalized

func (q *Quasar) IsFinalized(blockID ids.ID) bool

IsFinalized checks if a block has been finalized with BOTH signature types

func (*Quasar) NTTForwardCorona added in v1.2.3

func (q *Quasar) NTTForwardCorona(coefficients []uint64) ([]uint64, error)

NTTForwardCorona transforms Corona polynomial coefficients to NTT domain using GPU acceleration when available. This enables O(n log n) polynomial multiplication in the Ring-LWE scheme used by Corona threshold signatures.

func (*Quasar) NTTInverseCorona added in v1.2.3

func (q *Quasar) NTTInverseCorona(evaluations []uint64) ([]uint64, error)

NTTInverseCorona transforms NTT-domain values back to coefficient form using GPU acceleration when available.

func (*Quasar) SignBlock

func (q *Quasar) SignBlock(ctx context.Context, blockID ids.ID, blockHash []byte, height uint64) (*BlockSigs, error)

SignBlock creates both BLS and Corona signatures for a block in parallel. Returns both signatures; both must reach threshold for quantum finality.

func (*Quasar) TryFinalize

func (q *Quasar) TryFinalize(ctx context.Context, blockID ids.ID) (*quasar.AggregatedSignature, bool, error)

TryFinalize attempts to finalize a block if BOTH threshold signatures are collected. Quantum finality requires both BLS AND Corona thresholds to be met.

type QuasarBridge

type QuasarBridge = Quasar

QuasarBridge is an alias for Quasar - the hybrid P/Q consensus bridge that connects P-Chain BLS + Q-Chain Corona for dual signature finality

func NewQuasarBridge

func NewQuasarBridge(cfg QuasarBridgeConfig, _ interface{}) (*QuasarBridge, error)

NewQuasarBridge creates a new Quasar bridge (alias for NewQuasar) The quantumSigner parameter is reserved for future quantum signer integration

type QuasarBridgeConfig

type QuasarBridgeConfig = QuasarConfig

QuasarBridgeConfig is an alias for QuasarConfig

type QuasarConfig

type QuasarConfig struct {
	ValidatorID string
	Threshold   int
	TotalNodes  int
	Logger      log.Logger
}

QuasarConfig configures the Quasar PQ-BFT consensus

type SLHDSAVariant added in v1.3.0

type SLHDSAVariant uint8

SLHDSAVariant enumerates the 12 FIPS 205 SLH-DSA parameter sets. Each variant has its own (pk, sig) byte width — surfaced via PublicKeySize() and SignatureSize() so callers can build the batch arrays correctly.

At ABI v14 only the SHAKE-128f and SHAKE-192f verify slots are wired (op_slhdsa_verify_batch and op_slhdsa_verify_batch_shake192f). The remaining 10 variants land at their own vtbl slots in future ABI bumps; passing them today returns ErrGPUNotAvailable.

const (
	SLHDSAShake128f SLHDSAVariant = iota
	SLHDSAShake128s
	SLHDSAShake192f
	SLHDSAShake192s
	SLHDSAShake256f
	SLHDSAShake256s
	SLHDSASha2128f
	SLHDSASha2128s
	SLHDSASha2192f
	SLHDSASha2192s
	SLHDSASha2256f
	SLHDSASha2256s
)

func (SLHDSAVariant) PublicKeySize added in v1.3.0

func (v SLHDSAVariant) PublicKeySize() int

PublicKeySize returns the FIPS 205 byte width of an SLH-DSA public key for this variant. {128,192,256}{f,s} all share the same width per security level (32 / 48 / 64 bytes).

func (SLHDSAVariant) SignatureSize added in v1.3.0

func (v SLHDSAVariant) SignatureSize() int

SignatureSize returns the FIPS 205 byte width of an SLH-DSA signature for this variant. The 12 widths are fixed by parameter set; see the FIPS 205 standard §11 width table.

func (SLHDSAVariant) String added in v1.3.0

func (v SLHDSAVariant) String() string

String returns the FIPS 205 canonical name of the variant.

type Service

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

Service provides QVM RPC service

func (*Service) GenerateCoronaKey added in v1.2.3

func (s *Service) GenerateCoronaKey(r *http.Request, args *GenerateCoronaKeyArgs, reply *GenerateCoronaKeyReply) error

GenerateCoronaKey generates a new Corona key pair

func (*Service) GetBlock

func (s *Service) GetBlock(r *http.Request, args *GetBlockArgs, reply *GetBlockReply) error

GetBlock returns a block by ID

func (*Service) GetConfig

func (s *Service) GetConfig(r *http.Request, args *GetConfigArgs, reply *GetConfigReply) error

GetConfig returns the QVM configuration

func (*Service) GetHealth

func (s *Service) GetHealth(r *http.Request, args *GetHealthArgs, reply *GetHealthReply) error

GetHealth returns the health status of the QVM

func (*Service) GetPendingTransactions

func (s *Service) GetPendingTransactions(r *http.Request, args *GetPendingTransactionsArgs, reply *GetPendingTransactionsReply) error

GetPendingTransactions returns pending transactions

func (*Service) SignWithQuantum

func (s *Service) SignWithQuantum(r *http.Request, args *SignWithQuantumArgs, reply *SignWithQuantumReply) error

SignWithQuantum signs a message with quantum signature

func (*Service) VerifyQuantumSignature

func (s *Service) VerifyQuantumSignature(r *http.Request, args *VerifyQuantumSignatureArgs, reply *VerifyQuantumSignatureReply) error

VerifyQuantumSignature verifies a quantum signature

type SharedMemory

type SharedMemory interface {
	Get(peerChainID ids.ID, keys [][]byte) ([][]byte, error)
	Apply(map[ids.ID]interface{}, ...interface{}) error
}

SharedMemory provides cross-chain shared memory

type SignWithQuantumArgs

type SignWithQuantumArgs struct {
	Message    string `json:"message"`
	PrivateKey string `json:"privateKey"`
}

SignWithQuantumArgs are the arguments for SignWithQuantum

type SignWithQuantumReply

type SignWithQuantumReply struct {
	Signature string `json:"signature"`
	Algorithm uint32 `json:"algorithm"`
	Timestamp int64  `json:"timestamp"`
}

SignWithQuantumReply is the reply for SignWithQuantum

type Transaction

type Transaction interface {
	ID() ids.ID
	Bytes() []byte
	Verify() error
	Execute() error
	GetQuantumSignature() *quantum.QuantumSignature
	Timestamp() time.Time
	// Fee returns the user-paid tx burn in nLUX. Must satisfy the
	// chain's FeePolicy (>= fee.MinTxFeeFloor on Q-Chain).
	Fee() uint64
}

Transaction represents a QVM transaction

type TransactionPool

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

TransactionPool manages pending transactions

func NewTransactionPool

func NewTransactionPool(maxSize, batchSize int, logger log.Logger) *TransactionPool

NewTransactionPool creates a new transaction pool

func (*TransactionPool) AddTransaction

func (p *TransactionPool) AddTransaction(tx Transaction) error

AddTransaction adds a transaction to the pool

func (*TransactionPool) Close

func (p *TransactionPool) Close()

Close closes the transaction pool

func (*TransactionPool) GetPendingTransactions

func (p *TransactionPool) GetPendingTransactions(limit int) []Transaction

GetPendingTransactions returns pending transactions up to the limit

func (*TransactionPool) PendingCount

func (p *TransactionPool) PendingCount() int

PendingCount returns the number of pending transactions

func (*TransactionPool) RemoveTransaction

func (p *TransactionPool) RemoveTransaction(txID ids.ID) error

RemoveTransaction removes a transaction from the pool

type TransactionWorker

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

TransactionWorker processes transactions in parallel

func (*TransactionWorker) ProcessBatch

func (w *TransactionWorker) ProcessBatch(txs []Transaction) ([]Transaction, error)

ProcessBatch processes a batch of transactions. Uses GPU batch ML-DSA verification when available and batch is large enough.

type VM

type VM struct {
	config.Config

	ChainAlias string
	NetworkID  uint32
	// contains filtered or unexported fields
}

VM implements the Q-chain Virtual Machine with quantum features

func (*VM) BuildBlock

func (vm *VM) BuildBlock(ctx context.Context) (chain.Block, error)

BuildBlock builds a new block with pending transactions. Implements chain.ChainVM.

func (*VM) Connected

func (vm *VM) Connected(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error

Connected notifies the VM that a validator has connected

func (*VM) CreateHandlers

func (vm *VM) CreateHandlers(ctx context.Context) (map[string]http.Handler, error)

CreateHandlers returns HTTP handlers for the VM

func (*VM) CreateStaticHandlers

func (vm *VM) CreateStaticHandlers(ctx context.Context) (map[string]http.Handler, error)

CreateStaticHandlers returns static HTTP handlers

func (*VM) Disconnected

func (vm *VM) Disconnected(ctx context.Context, nodeID ids.NodeID) error

Disconnected notifies the VM that a validator has disconnected

func (*VM) FeePolicy added in v1.2.6

func (vm *VM) FeePolicy() fee.Policy

FeePolicy exposes the chain's declared fee policy for diagnostics and the boot-time Validate gate.

func (*VM) GetBlock

func (vm *VM) GetBlock(ctx context.Context, blockID ids.ID) (chain.Block, error)

GetBlock retrieves a block by its ID. Implements chain.ChainVM.

func (*VM) GetBlockIDAtHeight

func (vm *VM) GetBlockIDAtHeight(ctx context.Context, height uint64) (ids.ID, error)

GetBlockIDAtHeight returns the block ID at the given height. Implements chain.ChainVM. Q-Chain does not yet maintain a height index, so this returns errNotImplemented until indexer integration lands.

func (*VM) GetEngine

func (vm *VM) GetEngine() consensusdag.Engine

GetEngine returns the DAG consensus engine

func (*VM) GetHybridBridge

func (vm *VM) GetHybridBridge() interface{}

GetHybridBridge returns the hybrid finality bridge for P/Q chain consensus This connects P-Chain BLS signatures with Q-Chain Corona for quantum finality Deprecated: Use GetQuasarBridge() for proper type safety

func (*VM) GetQuasarBridge

func (vm *VM) GetQuasarBridge() *QuasarBridge

GetQuasarBridge returns the Quasar hybrid consensus bridge This provides BLS + Corona dual threshold signatures for PQ finality

func (*VM) HealthCheck

func (vm *VM) HealthCheck(ctx context.Context) (chain.HealthResult, error)

HealthCheck returns the health status of the VM

func (*VM) Initialize

func (vm *VM) Initialize(ctx context.Context, init luxvm.Init) error

Initialize initializes the VM. Implements chain.ChainVM.

func (*VM) IssueTx added in v1.2.6

func (vm *VM) IssueTx(tx Transaction) error

IssueTx is the canonical user-tx admission point on Q-Chain. The FeePolicy gate refuses zero-fee txs before they touch the pool.

func (*VM) LastAccepted

func (vm *VM) LastAccepted(ctx context.Context) (ids.ID, error)

LastAccepted returns the last accepted block ID. Implements chain.ChainVM.

func (*VM) NewHTTPHandler

func (vm *VM) NewHTTPHandler(ctx context.Context) (http.Handler, error)

NewHTTPHandler returns the VM's HTTP handler. Implements chain.ChainVM.

func (*VM) ParseBlock

func (vm *VM) ParseBlock(ctx context.Context, blockBytes []byte) (chain.Block, error)

ParseBlock parses a block from bytes. Implements chain.ChainVM.

func (*VM) SetHybridBridge

func (vm *VM) SetHybridBridge(bridge interface{})

SetHybridBridge sets the hybrid finality bridge (called by chain manager) Deprecated: Bridge is now auto-initialized in VM.Initialize()

func (*VM) SetPreference

func (vm *VM) SetPreference(ctx context.Context, blockID ids.ID) error

SetPreference sets the preferred block. Implements chain.ChainVM. Q-Chain uses BLS+Corona threshold finality rather than preference, so this is a no-op until preference-based fork choice is wired in.

func (*VM) SetState

func (vm *VM) SetState(ctx context.Context, state uint32) error

SetState sets the VM state. Implements chain.ChainVM.

func (*VM) Shutdown

func (vm *VM) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the VM

func (*VM) StampBlock

func (vm *VM) StampBlock(blockID interface{}, pChainHeight uint64, message []byte) (interface{}, error)

StampBlock implements QChainStamper interface for hybrid finality Uses Quasar BLS+Corona for dual post-quantum threshold signatures

func (*VM) VerifyStamp

func (vm *VM) VerifyStamp(stamp interface{}) error

VerifyStamp implements QChainStamper interface for quasar finality Supports both Quasar QuasarSignature and ML-DSA QuantumSignature

func (*VM) Version

func (vm *VM) Version(ctx context.Context) (string, error)

Version returns the version of the VM

func (*VM) WaitForEvent

func (vm *VM) WaitForEvent(ctx context.Context) (luxvm.Message, error)

WaitForEvent blocks until an event triggers block building. Implements chain.ChainVM. CRITICAL: must block on ctx.Done() to avoid the notification flood loop in node/chains/manager.go (matches the relayvm contract).

type VerifyQuantumSignatureArgs

type VerifyQuantumSignatureArgs struct {
	Message   string          `json:"message"`
	Signature json.RawMessage `json:"signature"`
}

VerifyQuantumSignatureArgs are the arguments for VerifyQuantumSignature

type VerifyQuantumSignatureReply

type VerifyQuantumSignatureReply struct {
	Valid     bool   `json:"valid"`
	Algorithm uint32 `json:"algorithm"`
}

VerifyQuantumSignatureReply is the reply for VerifyQuantumSignature

Directories

Path Synopsis
cmd
plugin command

Jump to

Keyboard shortcuts

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