thresholdvm

package
v1.3.1 Latest Latest
Warning

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

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

README

ThresholdVM

ThresholdVM is a Go library, not a chain.

Per LP-134 (Lux Chain Topology), the legacy T-Chain custody monolith is split into two operational chains, both served by this substrate:

  • thresholdvm in MPC mode → M-Chain — bridge custody for external wallets, threshold signing ceremonies (CGGMP21 / FROST / Ringtail-gen).
  • thresholdvm in FHE mode → F-Chain — TFHE keygen, encrypted EVM, confidential compute.

chains/thresholdvm/ is the shared library; the runtime presence lives on M-Chain or F-Chain depending on which adapter the runtime registers. The legacy "T-Chain" name is retained only for teleportvm (LP-6332), an unrelated cross-chain teleport message bus.

                    +--------------------------------+
                    |         ThresholdVM            |
                    |  (ceremony state machine,      |
                    |   share envelope, lane API,    |
                    |   subject binding)             |
                    +----------------+---------------+
                                     |
                 +-------------------+-------------------+
                 |                                       |
        +--------v--------+                     +--------v--------+
        |     M-Chain     |                     |     F-Chain     |
        |  (MPC: CGGMP21, |                     | (FHE: TFHE,     |
        |   FROST,        |                     |  bootstrap-key  |
        |   Ringtail-gen) |  --bootstrap key--> |  gen, encrypted |
        |                 |                     |  EVM)           |
        +-----------------+                     +-----------------+
        ceremony_root:                          ceremony_root:
        mchain_ceremony_root                    fchain_fhe_root
        block time ~500ms                       block time ~2s
        sign-oriented                           compute-oriented

What this directory contains

Path Role
types/ Ceremony, Participant, Share, Proof — pure data types, no chain logic
protocol/ Protocol-specific verifier interfaces (impl ships with the chain that uses it)
cert/ QuasarCertLane integration: lane registration + certificate-subject binding
runtime/ MChainAdapter and FChainAdapter interfaces the two chains implement
docs/ Architecture + per-chain integration notes

What this directory is not

  • Not a Lux VM. There is no factory.go exposed to chains.Manager.
  • Not a chain ID. M-Chain and F-Chain are the chains; they have their own validator sets, ceremony roots, and block cadence.
  • Not a registry of secrets, keys, or signed material. State lives on M-Chain or F-Chain, never here.

Why split

LP-134 deprecates LP-5013 ("T-Chain MPC Custody"). T-Chain previously mixed MPC ceremonies and FHE compute under one validator set, one ceremony root, one block cadence. Sign-oriented (sub-second, latency critical) and compute-oriented (multi-second, throughput critical) workloads have incompatible scaling profiles. Splitting them lets each scale on its own validator set.

The substrate stays one piece because the ceremony state machine is identical across both: registered participants → round 1 commitments → round 2 shares → finalized cert. Only the per-protocol payload (carried by (offset, len) indirection in the share envelope) differs.

Permissionless participation

Both M-Chain and F-Chain inherit P-Chain's permissionless validator model. Anyone with stake on P-Chain can delegate to the M-Chain or F-Chain validator subset (or both). No allowlist. No central authority. Bitcoin-like decentralization carries through — the threshold scheme itself enforces honest-majority safety, the chain enforces liveness.

Cross-chain handoff

When M-Chain finishes a ceremony whose output feeds F-Chain (e.g., a TFHE bootstrap key generated by FROST DKG on M-Chain), the output crosses via a CertLane artifact:

  1. M-Chain finalizes ceremony, emits cert with lane MChainFROST and mchain_ceremony_root updated.
  2. F-Chain consumes the artifact via its FChainBootstrap lane, binds it into fchain_fhe_root.
  3. Quasar 3.0's certificate_subject binds both roots in the same round, making cross-chain replay structurally impossible.

The handoff envelope is defined in cert/lane.go; the typed adapter in runtime/.

Migration from T-Chain

LP-5013 is deprecated. The legacy chain at chains/thresholdvm/ (this directory's vm.go, block.go, factory.go, fhe/, cmd/) hosts the migration shims that route legacy TChain* cert lanes to the appropriate MChain* / FChain* verifiers during the one-epoch grace window. After the grace window closes, the shims are removed and only the substrate (this README's directory tree) remains.

Activation

ThresholdVM substrate activates with Quasar 3.0 on 2025-12-25, alongside the M-Chain and F-Chain genesis events. Versions before that date target the legacy T-Chain layout.

References

LP Topic
LP-019 Threshold MPC for Bridge Signing (M-Chain protocols)
LP-013 FHE on GPU (F-Chain compute)
LP-076 Universal Threshold Cryptography Framework
LP-134 Lux Chain Topology — defines the M/F split
LP-132 QuasarGPU Execution Adapter — lane verifiers run here
LP-020 Quasar Consensus 3.0 — certificate_subject binding

License

Copyright (C) 2019-2025 Lux Industries Inc. MIT licensed.

Documentation

Overview

Package tvm implements the Threshold VM substrate (M-Chain MPC and F-Chain FHE per LP-134). The legacy "T-Chain" label predates the LP-134 split; new code targets M-Chain (MPC ceremonies for bridge custody of external wallets) or F-Chain (FHE compute). See ../README.md.

Index

Constants

View Source
const (
	OpTypeKeygen  = "keygen"
	OpTypeSign    = "sign"
	OpTypeReshare = "reshare"
	OpTypeRefresh = "refresh"
)

Operation types

View Source
const (
	RPCErrorInvalidRequest   = -32600
	RPCErrorMethodNotFound   = -32601
	RPCErrorInvalidParams    = -32602
	RPCErrorInternal         = -32603
	RPCErrorMPCNotReady      = -32001
	RPCErrorUnauthorized     = -32002
	RPCErrorQuotaExceeded    = -32003
	RPCErrorSessionNotFound  = -32004
	RPCErrorKeyNotFound      = -32005
	RPCErrorProtocolNotFound = -32006
	RPCErrorKeygenInProgress = -32007
	RPCErrorInvalidProtocol  = -32008
)

Error codes

Variables

View Source
var (
	Version = &version.Semantic{
		Major: 1,
		Minor: 0,
		Patch: 0,
	}

	// Error definitions
	ErrNotInitialized      = errors.New("MPC not initialized")
	ErrKeygenInProgress    = errors.New("keygen already in progress")
	ErrSigningInProgress   = errors.New("signing session already in progress")
	ErrInvalidThreshold    = errors.New("invalid threshold configuration")
	ErrInsufficientParties = errors.New("insufficient parties for operation")
	ErrSessionNotFound     = errors.New("session not found")
	ErrSessionExpired      = errors.New("session expired")
	ErrUnauthorizedChain   = errors.New("unauthorized chain")
	ErrQuotaExceeded       = errors.New("signing quota exceeded")
	ErrInvalidSignature    = errors.New("invalid signature")
	ErrKeyNotFound         = errors.New("key not found")
)

Codec is the codec for the threshold VM

View Source
var ErrGPUNotAvailable = errors.New("thresholdvm: GPU backend not available (no plugin dlopened)")

ErrGPUNotAvailable is returned by GPUBackend methods when no plugin was resolved at init() time. Callers check this to fall back to the CPU reference (the protocol/ + executor.go state machine, which is unchanged by this bridge).

View Source
var ErrInvalidOperation = &BlockError{Message: "invalid operation"}
View Source
var VMID = ids.ID{'t', 'h', 'r', 'e', 's', 'h', 'o', 'l', 'd', 'v', 'm', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

VMID is the unique identifier for ThresholdVM (M-Chain — Threshold MPC; T-Chain is reserved for TeleportVM, not yet built)

Functions

func ComputeAttestationPayload

func ComputeAttestationPayload(domain AttestationDomain, subjectID, commitmentRoot [32]byte, epoch uint64) [32]byte

ComputeAttestationPayload computes the payload to be signed for an attestation

func DetectEquivocation

func DetectEquivocation(a, b *QuantumAttestation) bool

DetectEquivocation checks if two attestations represent equivocation (slashable) Two attestations are equivocating if they have the same domain, subject, and epoch but different commitment roots

Types

type AttestationDomain

type AttestationDomain string

AttestationDomain defines the domain for a threshold attestation

const (
	// DomainOracleWrite attests to external write request commitments
	DomainOracleWrite AttestationDomain = "oracle/write"
	// DomainOracleRead attests to external read request commitments
	DomainOracleRead AttestationDomain = "oracle/read"
	// DomainSessionComplete attests to session completion (output hash + oracle obs + receipts root)
	DomainSessionComplete AttestationDomain = "session/complete"
	// DomainEpochBeacon attests to epoch beacon signatures for randomness
	DomainEpochBeacon AttestationDomain = "epoch/beacon"
)

type BLSHandler

type BLSHandler struct{}

BLSHandler implements ProtocolHandler for BLS threshold signatures

func (*BLSHandler) Keygen

func (h *BLSHandler) Keygen(ctx context.Context, partyID party.ID, partyIDs []party.ID, threshold int) (KeyShare, error)

func (*BLSHandler) Name

func (h *BLSHandler) Name() Protocol

func (*BLSHandler) Refresh

func (h *BLSHandler) Refresh(ctx context.Context, share KeyShare) (KeyShare, error)

func (*BLSHandler) Reshare

func (h *BLSHandler) Reshare(ctx context.Context, share KeyShare, newPartyIDs []party.ID, newThreshold int) (KeyShare, error)

func (*BLSHandler) Sign

func (h *BLSHandler) Sign(ctx context.Context, share KeyShare, message []byte, signers []party.ID) (Signature, error)

func (*BLSHandler) SupportedCurves

func (h *BLSHandler) SupportedCurves() []string

func (*BLSHandler) Verify

func (h *BLSHandler) Verify(pubKey []byte, message []byte, signature Signature) (bool, error)

type BatchSignParams

type BatchSignParams struct {
	KeyID           string   `json:"keyId"`
	MessageHashes   []string `json:"messageHashes"` // Hex encoded
	RequestingChain string   `json:"requestingChain"`
}

BatchSignParams contains parameters for batch signing

type BatchSignResult

type BatchSignResult struct {
	SessionIDs []string `json:"sessionIds"`
	Status     string   `json:"status"`
}

BatchSignResult contains batch signing results

type Block

type Block struct {
	ID_            ids.ID       `json:"id"`
	ParentID_      ids.ID       `json:"parentId"`
	BlockHeight    uint64       `json:"height"`
	BlockTimestamp int64        `json:"timestamp"`
	Operations     []*Operation `json:"operations"`
	// contains filtered or unexported fields
}

Block represents a T-Chain block

func (*Block) Accept

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

Accept marks the block as accepted

func (*Block) Bytes

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

Bytes returns the block's serialized bytes

func (*Block) ChoicesStatus

func (b *Block) ChoicesStatus() choices.Status

ChoicesStatus returns the block's status as choices.Status

func (*Block) Height

func (b *Block) Height() uint64

Height returns the block's height

func (*Block) ID

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

ID returns the block's ID

func (*Block) Parent

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

Parent returns the parent block's ID (legacy)

func (*Block) ParentID

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

ParentID returns the parent block's ID (implements block.Block interface)

func (*Block) Reject

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

Reject marks the block as rejected

func (*Block) SetStatus

func (b *Block) SetStatus(status choices.Status)

SetStatus sets the block's status

func (*Block) Status

func (b *Block) Status() uint8

Status returns the block's status as uint8 (implements block.Block interface)

func (*Block) Timestamp

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

Timestamp returns the block's timestamp

func (*Block) Verify

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

Verify verifies the block is valid

type BlockError

type BlockError struct {
	Message string
}

func (*BlockError) Error

func (e *BlockError) Error() string

type CGGMP21Handler

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

CGGMP21Handler implements ProtocolHandler for CGGMP21/CMP

func (*CGGMP21Handler) Keygen

func (h *CGGMP21Handler) Keygen(ctx context.Context, partyID party.ID, partyIDs []party.ID, threshold int) (KeyShare, error)

func (*CGGMP21Handler) Name

func (h *CGGMP21Handler) Name() Protocol

func (*CGGMP21Handler) Refresh

func (h *CGGMP21Handler) Refresh(ctx context.Context, share KeyShare) (KeyShare, error)

func (*CGGMP21Handler) Reshare

func (h *CGGMP21Handler) Reshare(ctx context.Context, share KeyShare, newPartyIDs []party.ID, newThreshold int) (KeyShare, error)

func (*CGGMP21Handler) SetExecutor

func (h *CGGMP21Handler) SetExecutor(executor *ProtocolExecutor)

SetExecutor sets the protocol executor for the handler

func (*CGGMP21Handler) SetMessageRouter

func (h *CGGMP21Handler) SetMessageRouter(router MessageRouter)

SetMessageRouter sets the message router for multi-party communication

func (*CGGMP21Handler) Sign

func (h *CGGMP21Handler) Sign(ctx context.Context, share KeyShare, message []byte, signers []party.ID) (Signature, error)

func (*CGGMP21Handler) SupportedCurves

func (h *CGGMP21Handler) SupportedCurves() []string

func (*CGGMP21Handler) Verify

func (h *CGGMP21Handler) Verify(pubKey []byte, message []byte, signature Signature) (bool, error)

type CMPKeyShare

type CMPKeyShare struct {
	Config *cmpconfig.Config
}

CMPKeyShare wraps cmpconfig.Config to implement KeyShare.

func (*CMPKeyShare) Generation

func (s *CMPKeyShare) Generation() uint64

Generation returns the key generation number.

func (*CMPKeyShare) PartyID

func (s *CMPKeyShare) PartyID() party.ID

PartyID returns this party's ID.

func (*CMPKeyShare) Protocol

func (s *CMPKeyShare) Protocol() Protocol

Protocol returns which protocol this share is for.

func (*CMPKeyShare) PublicKey

func (s *CMPKeyShare) PublicKey() []byte

PublicKey returns the group public key.

func (*CMPKeyShare) Serialize

func (s *CMPKeyShare) Serialize() ([]byte, error)

Serialize converts the share to bytes for storage.

func (*CMPKeyShare) Threshold

func (s *CMPKeyShare) Threshold() int

Threshold returns the threshold t.

func (*CMPKeyShare) TotalParties

func (s *CMPKeyShare) TotalParties() int

TotalParties returns total parties n.

type CancelSessionParams

type CancelSessionParams struct {
	SessionID string `json:"sessionId"`
}

CancelSessionParams contains parameters for canceling a session

type ChainPermissions

type ChainPermissions struct {
	ChainID           string   `json:"chainId"`
	ChainName         string   `json:"chainName"`
	CanSign           bool     `json:"canSign"`           // Can request signatures
	CanKeygen         bool     `json:"canKeygen"`         // Can request new key generation
	CanReshare        bool     `json:"canReshare"`        // Can request key resharing
	AllowedKeyTypes   []string `json:"allowedKeyTypes"`   // secp256k1, ed25519, etc.
	MaxSigningSize    int      `json:"maxSigningSize"`    // Max message size to sign
	RequirePreHash    bool     `json:"requirePreHash"`    // Require pre-hashed messages
	DailySigningLimit uint64   `json:"dailySigningLimit"` // Override global quota
}

ChainPermissions defines what a chain can do with MPC services

type Client

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

Client provides access to thresholdvm services. Per LP-134, this serves M-Chain (MPC mode) and F-Chain (FHE mode); legacy T-Chain MPC routes here.

func NewClient

func NewClient(endpoint, chainID string) *Client

NewClient creates a new T-Chain client

func (*Client) BatchSign

func (c *Client) BatchSign(ctx context.Context, keyID string, messageHashes [][]byte) ([]string, error)

BatchSign requests multiple signatures

func (*Client) GetAddress

func (c *Client) GetAddress(ctx context.Context, keyID string) ([]byte, error)

GetAddress retrieves the address for a key ID

func (*Client) GetInfo

func (c *Client) GetInfo(ctx context.Context) (*ThresholdInfo, error)

GetInfo retrieves T-Chain information

func (*Client) GetKey

func (c *Client) GetKey(ctx context.Context, keyID string) (*KeyInfo, error)

GetKey retrieves key information

func (*Client) GetKeygenStatus

func (c *Client) GetKeygenStatus(ctx context.Context, sessionID string) (*KeygenResponse, error)

GetKeygenStatus retrieves the status of a keygen session

func (*Client) GetProtocolInfo

func (c *Client) GetProtocolInfo(ctx context.Context, protocol string) (*ProtocolInfo, error)

GetProtocolInfo retrieves info for a specific protocol

func (*Client) GetProtocols

func (c *Client) GetProtocols(ctx context.Context) ([]ProtocolInfo, error)

GetProtocols retrieves all supported protocols

func (*Client) GetPublicKey

func (c *Client) GetPublicKey(ctx context.Context, keyID string) ([]byte, error)

GetPublicKey retrieves the public key for a key ID

func (*Client) GetQuota

func (c *Client) GetQuota(ctx context.Context) (*QuotaInfo, error)

GetQuota retrieves quota information for this chain

func (*Client) GetSignature

func (c *Client) GetSignature(ctx context.Context, sessionID string) (*SignatureResponse, error)

GetSignature retrieves a signature from T-Chain

func (*Client) GetStats

func (c *Client) GetStats(ctx context.Context) (*NetworkStats, error)

GetStats retrieves T-Chain statistics

func (*Client) Health

func (c *Client) Health(ctx context.Context) (map[string]interface{}, error)

Health retrieves T-Chain health status

func (*Client) IsReady

func (c *Client) IsReady(ctx context.Context) (bool, error)

IsReady checks if thresholdvm (M-Chain MPC mode per LP-134) is ready

func (*Client) Keygen

func (c *Client) Keygen(ctx context.Context, req KeygenRequest) (*KeygenResponse, error)

Keygen initiates key generation on T-Chain

func (*Client) ListKeys

func (c *Client) ListKeys(ctx context.Context) ([]KeyInfo, error)

ListKeys lists all keys on T-Chain

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, keyID string) (*KeygenResponse, error)

Refresh triggers key refresh

func (*Client) Reshare

func (c *Client) Reshare(ctx context.Context, keyID string, newPartyIDs []string, newThreshold int) (*KeygenResponse, error)

Reshare triggers key resharing

func (*Client) Sign

func (c *Client) Sign(ctx context.Context, req SignRequest) (*SignResponse, error)

Sign requests a signature from T-Chain

func (*Client) SignAndWait

func (c *Client) SignAndWait(ctx context.Context, req SignRequest, timeout time.Duration) (*SignatureResponse, error)

SignAndWait signs a message and waits for completion

func (*Client) WaitForKeygen

func (c *Client) WaitForKeygen(ctx context.Context, sessionID string, timeout time.Duration) (*KeygenResponse, error)

WaitForKeygen waits for keygen to complete

func (*Client) WaitForSignature

func (c *Client) WaitForSignature(ctx context.Context, sessionID string, timeout time.Duration) (*SignatureResponse, error)

WaitForSignature waits for signature to complete

type CoronaHandler added in v1.2.3

type CoronaHandler struct{}

CoronaHandler implements ProtocolHandler for post-quantum threshold signatures

func (*CoronaHandler) Keygen added in v1.2.3

func (h *CoronaHandler) Keygen(ctx context.Context, partyID party.ID, partyIDs []party.ID, threshold int) (KeyShare, error)

func (*CoronaHandler) Name added in v1.2.3

func (h *CoronaHandler) Name() Protocol

func (*CoronaHandler) Refresh added in v1.2.3

func (h *CoronaHandler) Refresh(ctx context.Context, share KeyShare) (KeyShare, error)

func (*CoronaHandler) Reshare added in v1.2.3

func (h *CoronaHandler) Reshare(ctx context.Context, share KeyShare, newPartyIDs []party.ID, newThreshold int) (KeyShare, error)

func (*CoronaHandler) Sign added in v1.2.3

func (h *CoronaHandler) Sign(ctx context.Context, share KeyShare, message []byte, signers []party.ID) (Signature, error)

func (*CoronaHandler) SupportedCurves added in v1.2.3

func (h *CoronaHandler) SupportedCurves() []string

func (*CoronaHandler) Verify added in v1.2.3

func (h *CoronaHandler) Verify(pubKey []byte, message []byte, signature Signature) (bool, error)

type CrossChainMPCRequest

type CrossChainMPCRequest struct {
	Type            string `json:"type"` // sign, keygen, reshare
	RequestingChain string `json:"requestingChain"`
	KeyID           string `json:"keyId"`
	KeyType         string `json:"keyType,omitempty"`
	MessageHash     []byte `json:"messageHash,omitempty"`
	MessageType     string `json:"messageType,omitempty"`
}

CrossChainMPCRequest is the request format for cross-chain MPC operations

type ECDSASignature

type ECDSASignature struct {
	R []byte
	S []byte
	V byte
}

ECDSASignature wraps ECDSA signature from threshold library.

type EpochBeaconAttestation

type EpochBeaconAttestation struct {
	Epoch       uint64   `json:"epoch"`
	Randomness  [32]byte `json:"randomness"`
	PreviousRef [32]byte `json:"previousRef"`
}

EpochBeaconAttestation contains details for epoch beacon attestations

type FROSTKeyShare

type FROSTKeyShare struct {
	Config *frostconfig.Config
}

FROSTKeyShare wraps frostconfig.Config to implement KeyShare.

func (*FROSTKeyShare) Generation

func (s *FROSTKeyShare) Generation() uint64

Generation returns the key generation number.

func (*FROSTKeyShare) PartyID

func (s *FROSTKeyShare) PartyID() party.ID

PartyID returns this party's ID.

func (*FROSTKeyShare) Protocol

func (s *FROSTKeyShare) Protocol() Protocol

Protocol returns which protocol this share is for.

func (*FROSTKeyShare) PublicKey

func (s *FROSTKeyShare) PublicKey() []byte

PublicKey returns the group public key.

func (*FROSTKeyShare) Serialize

func (s *FROSTKeyShare) Serialize() ([]byte, error)

Serialize converts the share to bytes for storage.

func (*FROSTKeyShare) Threshold

func (s *FROSTKeyShare) Threshold() int

Threshold returns the threshold t.

func (*FROSTKeyShare) TotalParties

func (s *FROSTKeyShare) TotalParties() int

TotalParties returns total parties n.

type Factory

type Factory struct{}

Factory creates new ThresholdVM instances

func (*Factory) New

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

New returns a new instance of the ThresholdVM

type GPUBackend added in v1.3.0

type GPUBackend struct {
	Kind GPUBackendKind
	Path string // dlopen'd library path, for diagnostics
	// contains filtered or unexported fields
}

GPUBackend is the resolved plugin substrate. Zero value = not available.

func Backend added in v1.3.0

func Backend() *GPUBackend

Backend returns the resolved GPU plugin. nil means no plugin was loaded.

func (*GPUBackend) CeremonyApply added in v1.3.0

func (g *GPUBackend) CeremonyApply(
	desc *GPUMPCVMRoundDescriptor,
	ceremonyOps []GPUCeremonyOp,
	ceremonies []GPUCeremony,
) (applied uint32, err error)

CeremonyApply applies ceremony begin/cancel ops to the ceremony table. Contribution slots are not touched (callers passing nil contribution_ops get the lean ceremony-admin dispatch).

ceremonies is the open-addressed ceremony hash table (must be a power-of-2 length on the device-side; the Go caller owns the buffer). The kernel mutates it in place; the round descriptor's CeremonyOpCount tells the kernel how many ops to consume from ceremonyOps.

next_contribution_id_in is the substrate's monotonically increasing contribution-id counter at the start of the round; the kernel doesn't advance it on the ceremony-only path but the parameter is part of the shared launcher signature.

func (*GPUBackend) ContributionApply added in v1.3.0

func (g *GPUBackend) ContributionApply(
	desc *GPUMPCVMRoundDescriptor,
	contributionOps []GPUContributionOp,
	ceremonies []GPUCeremony,
	contributions []GPUContribution,
	nextContributionID uint64,
) (applied uint32, err error)

ContributionApply applies contribution payloads to the contribution table. Ceremony slots are not touched (callers passing nil ceremonyOps get the lean contribution-only dispatch). Uses the same ceremony_apply kernel because the dedup-and-write path is the same on the device side; only the op stream differs.

func (*GPUBackend) IsAvailable added in v1.3.0

func (g *GPUBackend) IsAvailable() bool

IsAvailable reports whether the bridge has a usable plugin with at least the ceremony_apply and ceremony_sweep launchers resolved. compute_leaves and compose_root are required for MPCTransition but are checked per-method to allow partial GPU coverage when a plugin ships fewer symbols (e.g. an early Vulkan port).

func (*GPUBackend) KeyShareApply added in v1.3.0

func (g *GPUBackend) KeyShareApply(
	desc *GPUMPCVMRoundDescriptor,
	ceremonies []GPUCeremony,
	keyShares []GPUKeyShare,
	contributions []GPUContribution,
	nextShareID uint64,
) (roundAdvance, finalized, failed uint32, err error)

KeyShareApply runs the per-slot fan-out sweep that advances ceremonies, finalizes keygens (assigning canonical share_ids), and times out expired ceremonies. Backed by lux_<X>_mpcvm_ceremony_sweep.

On DKG finalize, fresh KeyShare slots are written into keyShares with the share_data_len matching the scheme (Frost=65, CGGMP21=65, Corona=256). next_share_id_in seeds the prefix-sum scheme that gives every finalized share a deterministic share_id.

func (*GPUBackend) MPCTransition added in v1.3.0

func (g *GPUBackend) MPCTransition(
	desc *GPUMPCVMRoundDescriptor,
	ceremonies []GPUCeremony,
	keyShares []GPUKeyShare,
	contributions []GPUContribution,
	state *GPUMPCVMState,
) (*GPUMPCVMTransitionResult, error)

MPCTransition runs the per-leaf keccak pass and the canonical-order fold pass, producing the round's MPCVMTransitionResult and advancing the substrate state. This is the composition of compute_leaves and compose_root — one substrate state transition per call.

Returns the result envelope written by compose_root. The substrate state in `state` is also updated in place (cur_epoch, now_ns, counts, all four roots).

type GPUBackendKind added in v1.3.0

type GPUBackendKind uint8

GPUBackendKind is the resolved plugin family. Matches the dlopen probe order in backend.go: cuda → hip → metal → vulkan → webgpu.

const (
	GPUBackendNone   GPUBackendKind = 0
	GPUBackendCUDA   GPUBackendKind = 1
	GPUBackendHIP    GPUBackendKind = 2
	GPUBackendMetal  GPUBackendKind = 3
	GPUBackendVulkan GPUBackendKind = 4
	GPUBackendWebGPU GPUBackendKind = 5
)

func (GPUBackendKind) String added in v1.3.0

func (k GPUBackendKind) String() string

String returns the launcher prefix used in symbol resolution.

type GPUCeremony added in v1.3.0

type GPUCeremony struct {
	CeremonyID         uint64
	StartedAtNs        uint64
	DeadlineNs         uint64
	ParticipantsBitmap uint64
	Kind               uint32
	Round              uint32
	Threshold          uint32
	TotalParticipants  uint32
	Status             uint32
	ContributionCount  uint32
	Subject            [32]byte
	CeremonySeed       [32]byte
	// contains filtered or unexported fields
}

GPUCeremony is the on-GPU ceremony state. 128 bytes, __align__(16). The GPU prefix distinguishes the wire mirror from the domain-level Ceremony types in protocols.go / runtime/. ONLY the GPU bridge ever touches these.

type GPUCeremonyOp added in v1.3.0

type GPUCeremonyOp struct {
	CeremonyID        uint64
	DeadlineNs        uint64
	Kind              uint32
	CeremonyKind      uint32
	Threshold         uint32
	TotalParticipants uint32
	Subject           [32]byte
	CeremonySeed      [32]byte
}

GPUCeremonyOp is one inbound ceremony op (begin/cancel). 96 bytes.

type GPUContribution added in v1.3.0

type GPUContribution struct {
	ContributionID uint64
	CeremonyID     uint64
	HolderAddr     uint64
	Round          uint32
	HolderIndex    uint32
	PayloadLen     uint32
	Status         uint32
	Payload        [384]byte
	Pad0           uint64
}

GPUContribution is the on-GPU contribution record. 432 bytes, __align__(16).

type GPUContributionOp added in v1.3.0

type GPUContributionOp struct {
	CeremonyID  uint64
	HolderAddr  uint64
	Round       uint32
	HolderIndex uint32
	PayloadLen  uint32
	Pad0        uint32
	Payload     [384]byte
}

GPUContributionOp is one inbound contribution payload. 416 bytes.

type GPUKeyShare added in v1.3.0

type GPUKeyShare struct {
	ShareID      uint64
	CeremonyID   uint64
	HolderAddr   uint64
	Scheme       uint32
	HolderIndex  uint32
	ShareDataLen uint32
	Occupied     uint32
	ShareData    [320]byte
	Pad0         uint64
}

GPUKeyShare is the on-GPU key share record. 368 bytes, __align__(16).

type GPUMPCVMRoundDescriptor added in v1.3.0

type GPUMPCVMRoundDescriptor struct {
	ChainID             uint64
	Round               uint64
	TimestampNs         uint64
	Epoch               uint64
	Mode                uint32
	CeremonyOpCount     uint32
	ContributionOpCount uint32
	ClosingFlag         uint32
	Pad0                uint32
	Pad1                uint32
	Pad2                uint64
	ParentStateRoot     [32]byte
}

GPUMPCVMRoundDescriptor describes one round's input envelope. 96 bytes.

type GPUMPCVMState added in v1.3.0

type GPUMPCVMState struct {
	CurrentEpoch           uint64
	NowNs                  uint64
	ActiveCeremonyCount    uint32
	FinalizedCeremonyCount uint32
	FailedCeremonyCount    uint32
	KeyShareCount          uint32
	CeremonyRoot           [32]byte
	KeyShareRoot           [32]byte
	ContributionRoot       [32]byte
	MPCVMStateRoot         [32]byte
}

GPUMPCVMState is the on-GPU substrate state. 160 bytes, __align__(16).

type GPUMPCVMTransitionResult added in v1.3.0

type GPUMPCVMTransitionResult struct {
	Status                 uint32
	CeremonyApplyCount     uint32
	ContributionApplyCount uint32
	FinalizedThisRound     uint32
	FailedThisRound        uint32
	ActiveCeremonyCount    uint32
	KeyShareCount          uint32
	RoundAdvanceCount      uint32
	Epoch                  uint64
	NowNs                  uint64
	CeremonyRoot           [32]byte
	KeyShareRoot           [32]byte
	ContributionRoot       [32]byte
	MPCVMStateRoot         [32]byte
}

GPUMPCVMTransitionResult is the transition envelope written by compose_root. 176 bytes.

type Genesis

type Genesis struct {
	Timestamp int64 `json:"timestamp"`
}

Genesis represents the genesis state

type GetChainPermissionsParams

type GetChainPermissionsParams struct {
	ChainID string `json:"chainId"`
}

GetChainPermissionsParams contains parameters for getting chain permissions

type GetKeyParams

type GetKeyParams struct {
	KeyID string `json:"keyId"`
}

GetKeyParams contains parameters for getting a key

type GetKeygenStatusParams

type GetKeygenStatusParams struct {
	SessionID string `json:"sessionId"`
}

GetKeygenStatusParams contains parameters for getting keygen status

type GetProtocolInfoParams

type GetProtocolInfoParams struct {
	Protocol string `json:"protocol"`
}

GetProtocolInfoParams contains parameters for getting protocol info

type GetQuotaParams

type GetQuotaParams struct {
	ChainID string `json:"chainId"`
}

GetQuotaParams contains parameters for getting quota

type GetSessionsParams

type GetSessionsParams struct {
	ChainID string `json:"chainId,omitempty"`
	Status  string `json:"status,omitempty"`
	Limit   int    `json:"limit,omitempty"`
}

GetSessionsParams contains parameters for listing sessions

type GetSignatureParams

type GetSignatureParams struct {
	SessionID string `json:"sessionId"`
}

GetSignatureParams contains parameters for getting a signature

type KeyInfo

type KeyInfo struct {
	KeyID        string   `json:"keyId"`
	Protocol     string   `json:"protocol"`
	PublicKey    string   `json:"publicKey"`
	Address      string   `json:"address,omitempty"`
	Threshold    int      `json:"threshold"`
	TotalParties int      `json:"totalParties"`
	Generation   uint64   `json:"generation"`
	Status       string   `json:"status"`
	SignCount    uint64   `json:"signCount"`
	CreatedAt    int64    `json:"createdAt"`
	LastUsedAt   int64    `json:"lastUsedAt,omitempty"`
	PartyIDs     []string `json:"partyIds"`
}

KeyInfo contains key information

type KeyShare

type KeyShare interface {
	// PublicKey returns the group public key
	PublicKey() []byte

	// PartyID returns this party's ID
	PartyID() party.ID

	// Threshold returns the threshold t
	Threshold() int

	// TotalParties returns total parties n
	TotalParties() int

	// Generation returns the key generation number
	Generation() uint64

	// Protocol returns which protocol this share is for
	Protocol() Protocol

	// Serialize converts the share to bytes for storage
	Serialize() ([]byte, error)
}

KeyShare represents a threshold key share (abstract)

type KeygenParams

type KeygenParams struct {
	KeyID        string `json:"keyId"`
	Protocol     string `json:"protocol"`     // lss, cggmp21, bls, corona
	RequestedBy  string `json:"requestedBy"`  // Chain ID
	Threshold    int    `json:"threshold"`    // Optional override
	TotalParties int    `json:"totalParties"` // Optional override
}

KeygenParams contains parameters for key generation

type KeygenRequest

type KeygenRequest struct {
	KeyID        string `json:"keyId"`
	Protocol     string `json:"protocol"`     // lss, cggmp21, bls, corona
	Threshold    int    `json:"threshold"`    // Optional
	TotalParties int    `json:"totalParties"` // Optional
}

KeygenRequest contains parameters for key generation

type KeygenResponse

type KeygenResponse struct {
	SessionID    string `json:"sessionId"`
	KeyID        string `json:"keyId"`
	Protocol     string `json:"protocol"`
	Status       string `json:"status"`
	Threshold    int    `json:"threshold"`
	TotalParties int    `json:"totalParties"`
	StartedAt    int64  `json:"startedAt"`
}

KeygenResponse contains the keygen result

type KeygenResult

type KeygenResult struct {
	SessionID    string `json:"sessionId"`
	KeyID        string `json:"keyId"`
	Protocol     string `json:"protocol"`
	Status       string `json:"status"`
	Threshold    int    `json:"threshold"`
	TotalParties int    `json:"totalParties"`
	StartedAt    int64  `json:"startedAt"`
}

KeygenResult contains the result of key generation

type KeygenSession

type KeygenSession struct {
	SessionID    string     `json:"sessionId"`
	KeyID        string     `json:"keyId"`
	KeyType      string     `json:"keyType"`
	Threshold    int        `json:"threshold"`
	TotalParties int        `json:"totalParties"`
	PartyIDs     []party.ID `json:"partyIds"`
	Status       string     `json:"status"` // pending, running, completed, failed
	RequestedBy  string     `json:"requestedBy"`
	StartedAt    time.Time  `json:"startedAt"`
	CompletedAt  time.Time  `json:"completedAt,omitempty"`
	Error        string     `json:"error,omitempty"`
	ProtocolName Protocol   `json:"-"` // Our local Protocol type
}

KeygenSession tracks a key generation in progress

type LSSHandler

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

LSSHandler implements ProtocolHandler for LSS

func (*LSSHandler) Keygen

func (h *LSSHandler) Keygen(ctx context.Context, partyID party.ID, partyIDs []party.ID, threshold int) (KeyShare, error)

func (*LSSHandler) Name

func (h *LSSHandler) Name() Protocol

func (*LSSHandler) Refresh

func (h *LSSHandler) Refresh(ctx context.Context, share KeyShare) (KeyShare, error)

func (*LSSHandler) Reshare

func (h *LSSHandler) Reshare(ctx context.Context, share KeyShare, newPartyIDs []party.ID, newThreshold int) (KeyShare, error)

func (*LSSHandler) Sign

func (h *LSSHandler) Sign(ctx context.Context, share KeyShare, message []byte, signers []party.ID) (Signature, error)

func (*LSSHandler) SupportedCurves

func (h *LSSHandler) SupportedCurves() []string

func (*LSSHandler) Verify

func (h *LSSHandler) Verify(pubKey []byte, message []byte, signature Signature) (bool, error)

type LSSKeyShare

type LSSKeyShare struct {
	Config *lssconfig.Config
}

LSSKeyShare wraps lssconfig.Config to implement KeyShare.

func (*LSSKeyShare) Generation

func (s *LSSKeyShare) Generation() uint64

Generation returns the key generation number.

func (*LSSKeyShare) PartyID

func (s *LSSKeyShare) PartyID() party.ID

PartyID returns this party's ID.

func (*LSSKeyShare) Protocol

func (s *LSSKeyShare) Protocol() Protocol

Protocol returns which protocol this share is for.

func (*LSSKeyShare) PublicKey

func (s *LSSKeyShare) PublicKey() []byte

PublicKey returns the group public key.

func (*LSSKeyShare) Serialize

func (s *LSSKeyShare) Serialize() ([]byte, error)

Serialize converts the share to bytes for storage.

func (*LSSKeyShare) Threshold

func (s *LSSKeyShare) Threshold() int

Threshold returns the threshold t.

func (*LSSKeyShare) TotalParties

func (s *LSSKeyShare) TotalParties() int

TotalParties returns total parties n.

type ManagedKey

type ManagedKey struct {
	KeyID        string            `json:"keyId"`
	KeyType      string            `json:"keyType"`      // secp256k1, ed25519
	PublicKey    []byte            `json:"publicKey"`    // Compressed public key
	Address      []byte            `json:"address"`      // Ethereum-style address (for secp256k1)
	Threshold    int               `json:"threshold"`    // t value
	TotalParties int               `json:"totalParties"` // n value
	Generation   uint64            `json:"generation"`   // Key generation number
	CreatedAt    time.Time         `json:"createdAt"`
	LastUsedAt   time.Time         `json:"lastUsedAt"`
	SignCount    uint64            `json:"signCount"` // Total signatures made
	Status       string            `json:"status"`    // active, rotating, expired
	Config       *lssconfig.Config `json:"-"`         // LSS configuration (not serialized)
	PartyIDs     []party.ID        `json:"partyIds"`
}

ManagedKey represents a threshold key managed by the T-Chain

type MessageRouter

type MessageRouter interface {
	// Send sends a message to the specified party (or broadcasts if To is empty)
	Send(msg *protocol.Message) error
	// Receive returns a channel for receiving incoming messages
	Receive() <-chan *protocol.Message
}

MessageRouter defines the interface for routing MPC messages between parties.

type NetworkStats

type NetworkStats struct {
	TotalSignatures    uint64            `json:"totalSignatures"`
	TotalKeygens       uint64            `json:"totalKeygens"`
	ActiveSessions     int               `json:"activeSessions"`
	SignaturesByChain  map[string]uint64 `json:"signaturesByChain"`
	AverageSigningTime int64             `json:"averageSigningTime"` // nanoseconds
	SuccessRate        float64           `json:"successRate"`
}

NetworkStats contains network statistics

type Operation

type Operation struct {
	Type            string `json:"type"` // keygen, sign, reshare, refresh
	SessionID       string `json:"sessionId"`
	KeyID           string `json:"keyId"`
	Protocol        string `json:"protocol,omitempty"`
	RequestingChain string `json:"requestingChain,omitempty"`
	MessageHash     []byte `json:"messageHash,omitempty"`
	Signature       []byte `json:"signature,omitempty"`
	Timestamp       int64  `json:"timestamp"`
	Success         bool   `json:"success"`
	Error           string `json:"error,omitempty"`
}

Operation represents an MPC operation recorded in a block

type OracleCommitAttestation

type OracleCommitAttestation struct {
	RequestID   [32]byte `json:"requestId"`
	Kind        uint8    `json:"kind"` // 0 = write, 1 = read
	Root        [32]byte `json:"root"`
	RecordCount uint32   `json:"recordCount"`
}

OracleCommitAttestation contains details for oracle commit attestations

type PartyInfo

type PartyInfo struct {
	PartyID string `json:"partyId"`
	NodeID  string `json:"nodeId"`
	IsLocal bool   `json:"isLocal"`
	Active  bool   `json:"active"`
}

PartyInfo contains party information

type Protocol

type Protocol string

Protocol represents a threshold signing protocol

const (
	// ECDSA Threshold Protocols
	ProtocolLSS     Protocol = "lss"     // Lux Secret Sharing - optimized for Lux
	ProtocolCGGMP21 Protocol = "cggmp21" // Canetti-Gennaro-Goldfeder-Makriyannis-Peled 2021

	// BLS Threshold (for validators)
	ProtocolBLS Protocol = "bls" // BLS threshold signatures

	// Post-Quantum Threshold
	ProtocolCorona Protocol = "corona" // Post-quantum lattice-based threshold

	// Experimental
	ProtocolFrost Protocol = "frost" // FROST (Flexible Round-Optimized Schnorr Threshold)
	ProtocolEDDSA Protocol = "eddsa" // EdDSA threshold (Ed25519)
)

type ProtocolConfig

type ProtocolConfig struct {
	Protocol     Protocol        `json:"protocol"`
	Threshold    int             `json:"threshold"`    // t: number of parties required
	TotalParties int             `json:"totalParties"` // n: total parties
	Curve        string          `json:"curve"`        // secp256k1, ed25519, bls12-381, etc.
	Options      ProtocolOptions `json:"options"`
}

ProtocolConfig contains configuration for a specific protocol

type ProtocolExecutor

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

ProtocolExecutor manages MPC protocol execution using the threshold library. It provides the bridge between ThresholdVM session management and the actual MPC protocol implementations.

func NewProtocolExecutor

func NewProtocolExecutor(workerPool *pool.Pool, logger log.Logger) *ProtocolExecutor

NewProtocolExecutor creates a new protocol executor.

func (*ProtocolExecutor) AcceptMessage

func (pe *ProtocolExecutor) AcceptMessage(sessionID string, msg *protocol.Message) error

AcceptMessage routes an incoming message to the appropriate handler.

func (*ProtocolExecutor) CMPKeygenStartFunc

func (pe *ProtocolExecutor) CMPKeygenStartFunc(
	selfID party.ID,
	participants []party.ID,
	threshold int,
) protocol.StartFunc

CMPKeygenStartFunc returns a StartFunc for CMP key generation.

func (*ProtocolExecutor) CMPRefreshStartFunc

func (pe *ProtocolExecutor) CMPRefreshStartFunc(config *cmpconfig.Config) protocol.StartFunc

CMPRefreshStartFunc returns a StartFunc for CMP key refresh.

func (*ProtocolExecutor) CMPSignStartFunc

func (pe *ProtocolExecutor) CMPSignStartFunc(
	config *cmpconfig.Config,
	signers []party.ID,
	messageHash []byte,
) protocol.StartFunc

CMPSignStartFunc returns a StartFunc for CMP signing.

func (*ProtocolExecutor) CreateHandler

func (pe *ProtocolExecutor) CreateHandler(
	ctx context.Context,
	sessionID string,
	startFunc protocol.StartFunc,
) (*protocol.Handler, error)

CreateHandler creates a new protocol handler for a session.

func (*ProtocolExecutor) FROSTKeygenStartFunc

func (pe *ProtocolExecutor) FROSTKeygenStartFunc(
	selfID party.ID,
	participants []party.ID,
	threshold int,
) protocol.StartFunc

FROSTKeygenStartFunc returns a StartFunc for FROST key generation.

func (*ProtocolExecutor) FROSTKeygenTaprootStartFunc

func (pe *ProtocolExecutor) FROSTKeygenTaprootStartFunc(
	selfID party.ID,
	participants []party.ID,
	threshold int,
) protocol.StartFunc

FROSTKeygenTaprootStartFunc returns a StartFunc for FROST Taproot key generation.

func (*ProtocolExecutor) FROSTRefreshStartFunc

func (pe *ProtocolExecutor) FROSTRefreshStartFunc(
	config *frostconfig.Config,
	participants []party.ID,
) protocol.StartFunc

FROSTRefreshStartFunc returns a StartFunc for FROST key refresh.

func (*ProtocolExecutor) FROSTSignStartFunc

func (pe *ProtocolExecutor) FROSTSignStartFunc(
	config *frostconfig.Config,
	signers []party.ID,
	messageHash []byte,
) protocol.StartFunc

FROSTSignStartFunc returns a StartFunc for FROST signing.

func (*ProtocolExecutor) GetHandler

func (pe *ProtocolExecutor) GetHandler(sessionID string) (*protocol.Handler, bool)

GetHandler retrieves an active handler by session ID.

func (*ProtocolExecutor) LSSKeygenStartFunc

func (pe *ProtocolExecutor) LSSKeygenStartFunc(
	selfID party.ID,
	participants []party.ID,
	threshold int,
) protocol.StartFunc

LSSKeygenStartFunc returns a StartFunc for LSS key generation.

func (*ProtocolExecutor) LSSRefreshStartFunc

func (pe *ProtocolExecutor) LSSRefreshStartFunc(config *lssconfig.Config) protocol.StartFunc

LSSRefreshStartFunc returns a StartFunc for LSS key refresh.

func (*ProtocolExecutor) LSSReshareStartFunc

func (pe *ProtocolExecutor) LSSReshareStartFunc(
	config *lssconfig.Config,
	newParticipants []party.ID,
	newThreshold int,
) protocol.StartFunc

LSSReshareStartFunc returns a StartFunc for LSS resharing.

func (*ProtocolExecutor) LSSSignStartFunc

func (pe *ProtocolExecutor) LSSSignStartFunc(
	config *lssconfig.Config,
	signers []party.ID,
	messageHash []byte,
) protocol.StartFunc

LSSSignStartFunc returns a StartFunc for LSS signing.

func (*ProtocolExecutor) RemoveHandler

func (pe *ProtocolExecutor) RemoveHandler(sessionID string)

RemoveHandler removes a handler from active tracking.

func (*ProtocolExecutor) RunCMPKeygen

func (pe *ProtocolExecutor) RunCMPKeygen(
	ctx context.Context,
	sessionID string,
	selfID party.ID,
	participants []party.ID,
	threshold int,
	messageRouter MessageRouter,
) (*cmpconfig.Config, error)

RunCMPKeygen executes a complete CMP key generation protocol.

func (*ProtocolExecutor) RunCMPRefresh

func (pe *ProtocolExecutor) RunCMPRefresh(
	ctx context.Context,
	sessionID string,
	config *cmpconfig.Config,
	messageRouter MessageRouter,
) (*cmpconfig.Config, error)

RunCMPRefresh executes a complete CMP key refresh protocol.

func (*ProtocolExecutor) RunCMPSign

func (pe *ProtocolExecutor) RunCMPSign(
	ctx context.Context,
	sessionID string,
	config *cmpconfig.Config,
	signers []party.ID,
	messageHash []byte,
	messageRouter MessageRouter,
) (*ECDSASignature, error)

RunCMPSign executes a complete CMP signing protocol.

func (*ProtocolExecutor) RunFROSTKeygen

func (pe *ProtocolExecutor) RunFROSTKeygen(
	ctx context.Context,
	sessionID string,
	selfID party.ID,
	participants []party.ID,
	threshold int,
	messageRouter MessageRouter,
) (*frostconfig.Config, error)

RunFROSTKeygen executes a complete FROST key generation protocol.

func (*ProtocolExecutor) RunLSSKeygen

func (pe *ProtocolExecutor) RunLSSKeygen(
	ctx context.Context,
	sessionID string,
	selfID party.ID,
	participants []party.ID,
	threshold int,
	messageRouter MessageRouter,
) (*lssconfig.Config, error)

RunLSSKeygen executes a complete LSS key generation protocol. This is a convenience method that creates a handler and waits for completion. For multi-party scenarios, use CreateHandler and manage message routing manually.

func (*ProtocolExecutor) RunLSSSign

func (pe *ProtocolExecutor) RunLSSSign(
	ctx context.Context,
	sessionID string,
	config *lssconfig.Config,
	signers []party.ID,
	messageHash []byte,
	messageRouter MessageRouter,
) (*ECDSASignature, error)

RunLSSSign executes a complete LSS signing protocol.

type ProtocolHandler

type ProtocolHandler interface {
	// Keygen generates a new threshold key
	Keygen(ctx context.Context, partyID party.ID, partyIDs []party.ID, threshold int) (KeyShare, error)

	// Sign creates a threshold signature
	Sign(ctx context.Context, share KeyShare, message []byte, signers []party.ID) (Signature, error)

	// Verify verifies a threshold signature
	Verify(pubKey []byte, message []byte, signature Signature) (bool, error)

	// Reshare reshares the key to a new set of parties
	Reshare(ctx context.Context, share KeyShare, newPartyIDs []party.ID, newThreshold int) (KeyShare, error)

	// Refresh refreshes the key shares without changing the public key
	Refresh(ctx context.Context, share KeyShare) (KeyShare, error)

	// Name returns the protocol name
	Name() Protocol

	// SupportedCurves returns the curves this protocol supports
	SupportedCurves() []string
}

ProtocolHandler defines the interface for all threshold protocols. Real implementations are in github.com/luxfi/threshold (LSS, CMP, FROST). Use ProtocolExecutor in executor.go for actual protocol execution.

type ProtocolInfo

type ProtocolInfo struct {
	Name            string   `json:"name"`
	Description     string   `json:"description"`
	SupportedCurves []string `json:"supportedCurves"`
	KeySize         int      `json:"keySize"`
	SignatureSize   int      `json:"signatureSize"`
	IsPostQuantum   bool     `json:"isPostQuantum"`
	SupportsReshare bool     `json:"supportsReshare"`
	SupportsRefresh bool     `json:"supportsRefresh"`
}

ProtocolInfo contains protocol information

func GetProtocolInfo

func GetProtocolInfo() []ProtocolInfo

GetProtocolInfo returns information about all supported protocols

type ProtocolOptions

type ProtocolOptions struct {
	// LSS Options
	LSSGeneration uint64 `json:"lssGeneration,omitempty"` // LSS generation number

	// CGGMP21 Options
	CMPPrecompute bool `json:"cmpPrecompute,omitempty"` // Enable precomputation for faster signing

	// BLS Options
	BLSScheme string `json:"blsScheme,omitempty"` // basic, min-pk, min-sig

	// Corona Options
	CoronaSecurityLevel int `json:"coronaSecurityLevel,omitempty"` // 128, 192, 256

	// General Options
	TimeoutSeconds int  `json:"timeoutSeconds,omitempty"`
	RetryOnFailure bool `json:"retryOnFailure,omitempty"`
}

ProtocolOptions contains protocol-specific options

type ProtocolRegistry

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

ProtocolRegistry manages available protocols

func NewProtocolRegistry

func NewProtocolRegistry(workerPool *pool.Pool) *ProtocolRegistry

NewProtocolRegistry creates a new protocol registry

func (*ProtocolRegistry) Available

func (r *ProtocolRegistry) Available() []Protocol

Available returns all available protocols

func (*ProtocolRegistry) Get

func (r *ProtocolRegistry) Get(protocol Protocol) (ProtocolHandler, error)

Get retrieves a protocol handler

func (*ProtocolRegistry) Register

func (r *ProtocolRegistry) Register(handler ProtocolHandler)

Register adds a protocol handler

type QuantumAttestation

type QuantumAttestation struct {
	// Domain specifies what is being attested (oracle/write, session/complete, etc.)
	Domain AttestationDomain `json:"domain"`

	// AttestationID is a unique identifier for this attestation
	AttestationID [32]byte `json:"attestationId"`

	// SubjectID is the ID of what is being attested (request_id, session_id, epoch number)
	SubjectID [32]byte `json:"subjectId"`

	// CommitmentRoot is the Merkle root being attested
	CommitmentRoot [32]byte `json:"commitmentRoot"`

	// Epoch in which this attestation was created
	Epoch uint64 `json:"epoch"`

	// Timestamp when attestation was created
	Timestamp time.Time `json:"timestamp"`

	// KeyID of the threshold key used for signing
	KeyID string `json:"keyId"`

	// Threshold used for this attestation
	Threshold int `json:"threshold"`

	// SignerCount is the number of parties that signed
	SignerCount int `json:"signerCount"`

	// Signature is the threshold signature over the attestation payload
	Signature *ecdsaSignature `json:"signature"`

	// SigningParties are the party IDs that participated
	SigningParties []party.ID `json:"signingParties"`
}

QuantumAttestation represents a threshold attestation over a commitment

type QuotaInfo

type QuotaInfo struct {
	ChainID    string `json:"chainId"`
	DailyLimit uint64 `json:"dailyLimit"`
	UsedToday  uint64 `json:"usedToday"`
	Remaining  uint64 `json:"remaining"`
	ResetTime  int64  `json:"resetTime"`
}

QuotaInfo contains quota information

type RPCError

type RPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

RPCError represents a JSON-RPC error

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface

type RPCRequest

type RPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
}

RPCRequest represents a JSON-RPC request

type RPCResponse

type RPCResponse struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Result  interface{} `json:"result,omitempty"`
	Error   *RPCError   `json:"error,omitempty"`
}

RPCResponse represents a JSON-RPC response

type RefreshParams

type RefreshParams struct {
	KeyID       string `json:"keyId"`
	RequestedBy string `json:"requestedBy"`
}

RefreshParams contains parameters for key refresh

type ReshareParams

type ReshareParams struct {
	KeyID        string   `json:"keyId"`
	NewPartyIDs  []string `json:"newPartyIds"`
	NewThreshold int      `json:"newThreshold"`
	RequestedBy  string   `json:"requestedBy"`
}

ReshareParams contains parameters for key resharing

type SchnorrSignature

type SchnorrSignature struct {
	R []byte
	Z []byte
}

SchnorrSignature wraps Schnorr signature from FROST.

type SessionCompleteAttestation

type SessionCompleteAttestation struct {
	SessionID    [32]byte `json:"sessionId"`
	OutputHash   [32]byte `json:"outputHash"`
	OracleRoot   [32]byte `json:"oracleRoot"`
	ReceiptsRoot [32]byte `json:"receiptsRoot"`
	StepCount    uint32   `json:"stepCount"`
}

SessionCompleteAttestation contains details for session completion attestations

type SessionInfo

type SessionInfo struct {
	SessionID       string `json:"sessionId"`
	Type            string `json:"type"` // keygen, sign, reshare
	KeyID           string `json:"keyId"`
	Status          string `json:"status"`
	RequestingChain string `json:"requestingChain,omitempty"`
	CreatedAt       int64  `json:"createdAt"`
	ExpiresAt       int64  `json:"expiresAt,omitempty"`
	CompletedAt     int64  `json:"completedAt,omitempty"`
	Error           string `json:"error,omitempty"`
}

SessionInfo contains session information

type SignParams

type SignParams struct {
	KeyID           string `json:"keyId"`
	MessageHash     string `json:"messageHash"`     // Hex encoded
	MessageType     string `json:"messageType"`     // raw, eth_sign, typed_data
	RequestingChain string `json:"requestingChain"` // Chain ID requesting signature
}

SignParams contains parameters for signing

type SignRequest

type SignRequest struct {
	KeyID       string `json:"keyId"`
	MessageHash []byte `json:"messageHash"`
	MessageType string `json:"messageType"` // raw, eth_sign, typed_data
}

SignRequest contains parameters for signing

type SignResponse

type SignResponse struct {
	SessionID string `json:"sessionId"`
	KeyID     string `json:"keyId"`
	Status    string `json:"status"`
	CreatedAt int64  `json:"createdAt"`
	ExpiresAt int64  `json:"expiresAt"`
}

SignResponse contains the signing session info

type SignResult

type SignResult struct {
	SessionID       string `json:"sessionId"`
	KeyID           string `json:"keyId"`
	Status          string `json:"status"`
	RequestingChain string `json:"requestingChain"`
	CreatedAt       int64  `json:"createdAt"`
	ExpiresAt       int64  `json:"expiresAt"`
}

SignResult contains the signing session info

type Signature

type Signature interface {
	// Bytes returns the raw signature bytes
	Bytes() []byte

	// R returns R component (for ECDSA)
	R() *big.Int

	// S returns S component (for ECDSA)
	S() *big.Int

	// V returns recovery ID (for ECDSA/Ethereum)
	V() byte

	// Protocol returns which protocol created this signature
	Protocol() Protocol
}

Signature represents a threshold signature (abstract)

type SignatureResponse

type SignatureResponse struct {
	SessionID     string   `json:"sessionId"`
	Status        string   `json:"status"`
	Signature     string   `json:"signature,omitempty"`
	R             string   `json:"r,omitempty"`
	S             string   `json:"s,omitempty"`
	V             int      `json:"v,omitempty"`
	SignerParties []string `json:"signerParties,omitempty"`
	CompletedAt   int64    `json:"completedAt,omitempty"`
	Error         string   `json:"error,omitempty"`
}

SignatureResponse contains a completed signature

type SignatureResult

type SignatureResult struct {
	SessionID     string   `json:"sessionId"`
	Status        string   `json:"status"`
	Signature     string   `json:"signature,omitempty"` // Hex encoded
	R             string   `json:"r,omitempty"`         // Hex encoded
	S             string   `json:"s,omitempty"`         // Hex encoded
	V             int      `json:"v,omitempty"`         // Recovery ID
	SignerParties []string `json:"signerParties,omitempty"`
	CompletedAt   int64    `json:"completedAt,omitempty"`
	Error         string   `json:"error,omitempty"`
}

SignatureResult contains the completed signature

type SigningSession

type SigningSession struct {
	SessionID       string          `json:"sessionId"`
	KeyID           string          `json:"keyId"`
	RequestingChain string          `json:"requestingChain"`
	MessageHash     []byte          `json:"messageHash"`
	MessageType     string          `json:"messageType"` // raw, eth_sign, typed_data
	Status          string          `json:"status"`      // pending, signing, completed, failed
	Signature       *ecdsaSignature `json:"signature,omitempty"`
	SignerParties   []party.ID      `json:"signerParties"`
	CreatedAt       time.Time       `json:"createdAt"`
	ExpiresAt       time.Time       `json:"expiresAt"`
	CompletedAt     time.Time       `json:"completedAt,omitempty"`
	Error           string          `json:"error,omitempty"`
	ProtocolName    Protocol        `json:"-"` // Our local Protocol type
}

SigningSession tracks a signing operation in progress

type ThresholdConfig

type ThresholdConfig struct {
	// MPC Configuration
	Threshold    int `json:"threshold"`    // t: Threshold (t+1 parties needed)
	TotalParties int `json:"totalParties"` // n: Total number of MPC nodes

	// Session Configuration
	SessionTimeout      time.Duration `json:"sessionTimeout"`      // Max time for a signing session
	MaxActiveSessions   int           `json:"maxActiveSessions"`   // Max concurrent signing sessions
	MaxSessionsPerChain int           `json:"maxSessionsPerChain"` // Max sessions per requesting chain

	// Quota Configuration (daily limits)
	DailySigningQuota map[string]uint64 `json:"dailySigningQuota"` // ChainID -> daily signing limit

	// Authorized Chains that can request MPC services
	AuthorizedChains map[string]*ChainPermissions `json:"authorizedChains"`

	// Key Management
	KeyRotationPeriod time.Duration `json:"keyRotationPeriod"` // How often to rotate keys
	MaxKeyAge         time.Duration `json:"maxKeyAge"`         // Maximum age of a key before forced rotation
}

ThresholdConfig contains VM configuration

type ThresholdInfo

type ThresholdInfo struct {
	Version            string   `json:"version"`
	NodeID             string   `json:"nodeId"`
	ChainID            string   `json:"chainId"`
	MPCReady           bool     `json:"mpcReady"`
	ActiveKeyID        string   `json:"activeKeyId,omitempty"`
	Threshold          int      `json:"threshold"`
	TotalParties       int      `json:"totalParties"`
	SupportedProtocols []string `json:"supportedProtocols"`
	AuthorizedChains   []string `json:"authorizedChains"`
	TotalKeys          int      `json:"totalKeys"`
	ActiveSessions     int      `json:"activeSessions"`
}

ThresholdInfo contains T-Chain information

type VM

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

VM implements the Threshold VM for MPC-as-a-service

func (*VM) AttestEpochBeacon

func (vm *VM) AttestEpochBeacon(
	requestingChain string,
	epoch uint64,
	previousRef [32]byte,
) (*QuantumAttestation, error)

AttestEpochBeacon creates a threshold attestation for epoch beacon randomness

func (*VM) AttestOracleCommit

func (vm *VM) AttestOracleCommit(
	requestingChain string,
	requestID [32]byte,
	kind uint8,
	commitRoot [32]byte,
	epoch uint64,
) (*QuantumAttestation, error)

AttestOracleCommit creates a threshold attestation for an oracle commitment

func (*VM) AttestSessionComplete

func (vm *VM) AttestSessionComplete(
	requestingChain string,
	sessionID [32]byte,
	outputHash [32]byte,
	oracleRoot [32]byte,
	receiptsRoot [32]byte,
	epoch uint64,
) (*QuantumAttestation, error)

AttestSessionComplete creates a threshold attestation for session completion

func (*VM) BuildBlock

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

BuildBlock implements the chain.ChainVM interface

func (*VM) Connected

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

Connected implements the common.VM interface

func (*VM) CreateHandlers

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

CreateHandlers implements the common.VM interface

func (*VM) CreateStaticHandlers

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

CreateStaticHandlers implements the common.VM interface

func (*VM) CrossChainRequest

func (vm *VM) CrossChainRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error

CrossChainRequest implements the common.VM interface This is how other chains request MPC services

func (*VM) CrossChainRequestFailed

func (vm *VM) CrossChainRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *warp.Error) error

CrossChainRequestFailed implements the common.VM interface

func (*VM) CrossChainResponse

func (vm *VM) CrossChainResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error

CrossChainResponse implements the common.VM interface

func (*VM) Disconnected

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

Disconnected implements the common.VM interface

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) GetAddress

func (vm *VM) GetAddress(keyID string) ([]byte, error)

GetAddress returns the Ethereum-style address for a key

func (*VM) GetBlock

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

GetBlock implements the chain.ChainVM interface

func (*VM) GetBlockIDAtHeight

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

GetBlockIDAtHeight implements the chain.HeightIndexedChainVM interface

func (*VM) GetPublicKey

func (vm *VM) GetPublicKey(keyID string) ([]byte, error)

GetPublicKey returns the public key for a key ID

func (*VM) GetSignature

func (vm *VM) GetSignature(sessionID string) (*SigningSession, error)

GetSignature retrieves a completed signature

func (*VM) Gossip

func (vm *VM) Gossip(ctx context.Context, nodeID ids.NodeID, msg []byte) error

Gossip implements the common.VM interface

func (*VM) HealthCheck

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

HealthCheck implements the common.VM interface

func (*VM) Initialize

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

Initialize implements the chain.ChainVM interface

func (*VM) InitializeMPC

func (vm *VM) InitializeMPC(partyIDs []party.ID) error

InitializeMPC sets up the MPC group with party IDs

func (*VM) LastAccepted

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

LastAccepted implements the chain.ChainVM interface

func (*VM) NewHTTPHandler

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

NewHTTPHandler returns HTTP handlers for the VM

func (*VM) ParseBlock

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

ParseBlock implements the chain.ChainVM interface

func (*VM) RefreshKey

func (vm *VM) RefreshKey(keyID string, requestedBy string) (*KeygenSession, error)

RefreshKey refreshes key shares without changing the public key

func (*VM) Request

func (vm *VM) Request(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, request []byte) error

Request implements the common.VM interface

func (*VM) RequestFailed

func (vm *VM) RequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *warp.Error) error

RequestFailed implements the common.VM interface

func (*VM) RequestSignature

func (vm *VM) RequestSignature(
	requestingChain string,
	keyID string,
	messageHash []byte,
	messageType string,
) (*SigningSession, error)

RequestSignature requests a threshold signature from the T-Chain

func (*VM) ReshareKey

func (vm *VM) ReshareKey(keyID string, newPartyIDs []party.ID, requestedBy string) (*KeygenSession, error)

ReshareKey triggers key resharing (for adding/removing parties)

func (*VM) Response

func (vm *VM) Response(ctx context.Context, nodeID ids.NodeID, requestID uint32, response []byte) error

Response implements the common.VM interface

func (*VM) SetPreference

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

SetPreference implements the chain.ChainVM interface

func (*VM) SetState

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

SetState implements the common.VM interface

func (*VM) Shutdown

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

Shutdown implements the common.VM interface

func (*VM) StartKeygen

func (vm *VM) StartKeygen(keyID, keyType, requestedBy string) (*KeygenSession, error)

StartKeygen initiates distributed key generation (uses default LSS protocol)

func (*VM) StartKeygenWithProtocol

func (vm *VM) StartKeygenWithProtocol(keyID, protocol, requestedBy string, threshold, totalParties int) (*KeygenSession, error)

StartKeygenWithProtocol initiates distributed key generation with a specific protocol

func (*VM) VerifyAttestation

func (vm *VM) VerifyAttestation(attestation *QuantumAttestation) error

VerifyAttestation verifies a QuantumAttestation is valid

func (*VM) Version

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

Version implements the common.VM interface

func (*VM) WaitForEvent

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

WaitForEvent blocks until an event occurs

Directories

Path Synopsis
Package cert provides the QuasarCertLane registration and certificate-subject binding logic shared by M-Chain and F-Chain.
Package cert provides the QuasarCertLane registration and certificate-subject binding logic shared by M-Chain and F-Chain.
cmd
plugin command
Package fhe provides GPU-accelerated FHE operations for ThresholdVM.
Package fhe provides GPU-accelerated FHE operations for ThresholdVM.
protocol
cggmp21
Package cggmp21 declares the M-Chain CGGMP21 protocol surface.
Package cggmp21 declares the M-Chain CGGMP21 protocol surface.
corona_general
Package corona_general declares the M-Chain general-purpose Corona (Ring-LWE) threshold protocol surface.
Package corona_general declares the M-Chain general-purpose Corona (Ring-LWE) threshold protocol surface.
frost
Package frost declares the M-Chain FROST protocol surface.
Package frost declares the M-Chain FROST protocol surface.
tfhe_keygen
Package tfhe_keygen declares the cross-chain TFHE bootstrap-key generation surface.
Package tfhe_keygen declares the cross-chain TFHE bootstrap-key generation surface.
Package runtime defines the adapter contracts the host chains (M-Chain and F-Chain) implement to plug into the ThresholdVM substrate.
Package runtime defines the adapter contracts the host chains (M-Chain and F-Chain) implement to plug into the ThresholdVM substrate.
Package types defines the data types of the ThresholdVM substrate.
Package types defines the data types of the ThresholdVM substrate.

Jump to

Keyboard shortcuts

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