fhe

package
v1.4.7 Latest Latest
Warning

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

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

Documentation

Overview

Package fhe provides GPU-accelerated FHE operations for ThresholdVM.

This file provides GPU acceleration for:

  • NTT forward/inverse transforms (40x speedup on Apple Silicon)
  • Polynomial multiplication in CKKS scheme
  • Batch FHE operations for throughput

Architecture:

lux/accel (unified GPU) → ThresholdVM FHE

Index

Constants

View Source
const (
	// Function selectors (first 4 bytes of keccak256 hash)
	SelectorRequestDecryption         = 0x5a6d3af9 // requestDecryption(bytes32,uint8)
	SelectorRequestDecryptionCallback = 0x7b8c4d12 // requestDecryptionWithCallback(bytes32,uint8,address,bytes4)
)
View Source
const (
	PermitOpDecrypt uint32 = 1 << iota
	PermitOpReencrypt
	PermitOpCompute
	PermitOpTransfer
)

PermitOps defines allowed operations in permits

View Source
const (
	// V1 payload types
	PayloadTypeFHEDecryptRequestV1   uint8 = 0x01
	PayloadTypeFHEDecryptResultV1    uint8 = 0x02
	PayloadTypeFHEReencryptRequestV1 uint8 = 0x03
	PayloadTypeFHETaskResultV1       uint8 = 0x04
	PayloadTypeFHEKeyRotationV1      uint8 = 0x05

	// Version byte
	PayloadVersionV1 uint8 = 0x01
)

Warp payload type identifiers (versioned)

View Source
const (
	DecryptStatusSuccess uint8 = 0x00
	DecryptStatusFailed  uint8 = 0x01
	DecryptStatusExpired uint8 = 0x02
	DecryptStatusDenied  uint8 = 0x03
)
View Source
const (
	TaskStatusCompleted uint8 = 0x00
	TaskStatusFailed    uint8 = 0x01
	TaskStatusTimeout   uint8 = 0x02
)
View Source
const (
	MaxBatchSize = 100
)

Variables

View Source
var (
	ErrInvalidSelector = errors.New("invalid function selector")
	ErrInvalidPayload  = errors.New("invalid payload format")
)
View Source
var (
	ErrEpochNotActive       = errors.New("epoch not active")
	ErrEpochAlreadyActive   = errors.New("epoch already active")
	ErrCommitteeFull        = errors.New("committee is full")
	ErrMemberNotFound       = errors.New("committee member not found")
	ErrMemberAlreadyExists  = errors.New("committee member already exists")
	ErrInsufficientWeight   = errors.New("insufficient committee weight")
	ErrDKGInProgress        = errors.New("DKG ceremony in progress")
	ErrDKGNotStarted        = errors.New("DKG ceremony not started")
	ErrDKGFailed            = errors.New("DKG ceremony failed")
	ErrMissingCommitment    = errors.New("participant must submit commitment first")
	ErrNotParticipant       = errors.New("node is not a DKG participant")
	ErrTransitionInProgress = errors.New("epoch transition in progress")
	ErrInvalidThreshold     = errors.New("invalid threshold")
	ErrEpochExpired         = errors.New("epoch has expired")
)
View Source
var (

	// Note: ErrCiphertextNotFound and ErrRequestNotFound are defined in relayer.go
	ErrPermitNotFound  = errors.New("permit not found")
	ErrSessionNotFound = errors.New("session not found")
	ErrPermitExpired   = errors.New("permit expired")
	ErrPermitInvalid   = errors.New("permit invalid")
	ErrEpochMismatch   = errors.New("epoch mismatch")
)
View Source
var (
	ErrDecryptionFailed   = errors.New("threshold decryption failed")
	ErrInsufficientShares = errors.New("insufficient decryption shares")
	ErrRequestNotFound    = errors.New("decryption request not found")
	ErrAlreadyFulfilled   = errors.New("request already fulfilled")
	ErrCiphertextNotFound = errors.New("ciphertext not found in storage")
)
View Source
var (
	ErrNotInitialized    = errors.New("FHE service not initialized")
	ErrInvalidHandle     = errors.New("invalid ciphertext handle")
	ErrInvalidPermit     = errors.New("invalid permit")
	ErrRequestInProgress = errors.New("request already in progress")
	ErrBatchTooLarge     = errors.New("batch size exceeds maximum")
	ErrEpochNotReady     = errors.New("epoch not ready")
	ErrUnauthorized      = errors.New("caller not authorized")
	ErrAuthRequired      = errors.New("authentication required")
)
View Source
var (
	ErrInvalidPayloadVersion = errors.New("invalid payload version")
	ErrInvalidPayloadType    = errors.New("invalid payload type")
	ErrPayloadTooShort       = errors.New("payload too short")
	ErrPayloadMalformed      = errors.New("payload malformed")
	ErrRequestExpired        = errors.New("request has expired")
)

Functions

func ParsePayload

func ParsePayload(data []byte) (uint8, interface{}, error)

ParsePayload parses any FHE Warp payload and returns the type and data

Types

type Authenticator

type Authenticator interface {
	// GetCallerAddress extracts the authenticated caller address from context
	GetCallerAddress(ctx context.Context) ([20]byte, error)
}

Authenticator verifies RPC caller identity

type CiphertextMeta

type CiphertextMeta struct {
	Handle       [32]byte `json:"handle"`
	Owner        [20]byte `json:"owner"`
	Type         uint8    `json:"type"`
	Level        int      `json:"level"`
	Epoch        uint64   `json:"epoch"`
	RegisteredAt int64    `json:"registered_at"`
	Size         uint32   `json:"size"`
	ChainID      ids.ID   `json:"chain_id"`
}

CiphertextMeta stores metadata for registered ciphertexts

type CiphertextStorage

type CiphertextStorage interface {
	Get(handle common.Hash) ([]byte, error)
	Put(handle common.Hash, data []byte) error
	Delete(handle common.Hash) error
}

CiphertextStorage interface for accessing FHE ciphertext storage

type CommitteeMember

type CommitteeMember struct {
	NodeID    ids.NodeID `json:"node_id"`
	PublicKey []byte     `json:"public_key"`
	Weight    uint64     `json:"weight"`
	Index     int        `json:"index"`
}

CommitteeMember represents a threshold committee member

type CommitteeMemberInfo

type CommitteeMemberInfo struct {
	NodeID    string `json:"nodeId"`
	PublicKey string `json:"publicKey"`
	Weight    uint64 `json:"weight"`
	Index     int    `json:"index"`
}

CommitteeMemberInfo represents a committee member

type CreatePermitArgs

type CreatePermitArgs struct {
	Handle      string `json:"handle"`                // hex-encoded 32 bytes
	Grantee     string `json:"grantee"`               // hex-encoded 20 bytes
	Grantor     string `json:"grantor"`               // hex-encoded 20 bytes
	Operations  uint32 `json:"operations"`            // bitmask
	Expiry      int64  `json:"expiry"`                // Unix timestamp
	Attestation string `json:"attestation,omitempty"` // hex-encoded
	ChainID     string `json:"chainId,omitempty"`
}

CreatePermitArgs contains permit creation parameters

type CreatePermitReply

type CreatePermitReply struct {
	PermitID  string `json:"permitId"`
	CreatedAt int64  `json:"createdAt"`
}

CreatePermitReply contains the permit ID

type DKGState

type DKGState struct {
	CeremonyID   [32]byte          `json:"ceremony_id"`
	Epoch        uint64            `json:"epoch"`
	Participants []ids.NodeID      `json:"participants"`
	Threshold    int               `json:"threshold"`
	Shares       map[string][]byte `json:"shares"` // NodeID hex -> encrypted share
	Commitments  map[string][]byte `json:"commitments"`
	PublicKey    []byte            `json:"public_key,omitempty"`
	Status       DKGStatus         `json:"status"`
	StartedAt    int64             `json:"started_at"`
	CompletedAt  int64             `json:"completed_at,omitempty"`
	Error        string            `json:"error,omitempty"`
}

DKGState represents the state of a DKG ceremony

type DKGStatus

type DKGStatus uint8
const (
	DKGPending DKGStatus = iota
	DKGCommitPhase
	DKGSharePhase
	DKGCompleted
	DKGFailed
	DKGAborted
)

func (DKGStatus) String

func (s DKGStatus) String() string

type DecryptRequest

type DecryptRequest struct {
	RequestID        [32]byte      `json:"request_id"`
	CiphertextHandle [32]byte      `json:"ciphertext_handle"`
	Requester        [20]byte      `json:"requester"`
	Callback         [20]byte      `json:"callback"`
	CallbackSelector [4]byte       `json:"callback_selector"`
	SourceChain      ids.ID        `json:"source_chain"`
	Epoch            uint64        `json:"epoch"`
	Nonce            uint64        `json:"nonce"`
	Expiry           int64         `json:"expiry"`
	Status           RequestStatus `json:"status"`
	CreatedAt        int64         `json:"created_at"`
	CompletedAt      int64         `json:"completed_at,omitempty"`
	ResultHandle     [32]byte      `json:"result_handle,omitempty"`
	Error            string        `json:"error,omitempty"`
}

DecryptRequest represents a threshold decryption request

type DecryptionRequest

type DecryptionRequest struct {
	RequestID        common.Hash
	CiphertextHash   common.Hash
	DecryptionType   uint8
	Requester        common.Address
	SourceChainID    ids.ID
	CallbackAddress  common.Address
	CallbackSelector uint32
	HasCallback      bool
	Timestamp        time.Time
	Fulfilled        bool
	Result           []byte
}

DecryptionRequest represents a pending decryption request from C-Chain

type DecryptionResult

type DecryptionResult struct {
	RequestID common.Hash
	Plaintext []byte
	Error     error
}

DecryptionResult contains the result of a threshold decryption

type DecryptionSession

type DecryptionSession struct {
	ID         string
	RequestID  common.Hash
	Ciphertext *rlwe.Ciphertext

	// E2S protocol shares from each party
	PublicShares    []multiparty.KeySwitchShare
	SecretShares    []multiparty.AdditiveShareBigint
	OwnSecretShare  *multiparty.AdditiveShareBigint
	OwnPublicShare  *multiparty.KeySwitchShare
	AggregatedShare *multiparty.KeySwitchShare

	ShareCount   int
	Complete     bool
	Result       []byte
	Participants map[ids.NodeID]bool
}

DecryptionSession tracks an ongoing threshold decryption

type EpochInfo

type EpochInfo struct {
	Epoch     uint64            `json:"epoch"`
	StartTime int64             `json:"start_time"`
	EndTime   int64             `json:"end_time,omitempty"`
	Committee []CommitteeMember `json:"committee"`
	Threshold int               `json:"threshold"`
	PublicKey []byte            `json:"public_key"`
	Status    EpochStatus       `json:"status"`
}

EpochInfo stores epoch-related information

type EpochKeyInfo

type EpochKeyInfo struct {
	Epoch     uint64 `json:"epoch"`
	PublicKey []byte `json:"public_key"`
	Threshold int    `json:"threshold"`
	Committee int    `json:"committee_size"`
	IsActive  bool   `json:"is_active"`
}

EpochKeyInfo returns the public key info for an epoch

type EpochStatus

type EpochStatus uint8
const (
	EpochActive EpochStatus = iota
	EpochEnded
	EpochPending
)

type FHEAccelerator

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

FHEAccelerator provides GPU-accelerated FHE operations for ThresholdVM. It uses the unified accel package to accelerate CKKS operations.

func GetFHEAccelerator

func GetFHEAccelerator() (*FHEAccelerator, error)

GetFHEAccelerator returns the global GPU FHE accelerator instance.

func NewFHEAccelerator

func NewFHEAccelerator(logger log.Logger) (*FHEAccelerator, error)

NewFHEAccelerator creates a new GPU FHE accelerator for ThresholdVM.

func NewFHEAcceleratorWithOptions

func NewFHEAcceleratorWithOptions(logger log.Logger, opts FHEOptions) (*FHEAccelerator, error)

NewFHEAcceleratorWithOptions creates a new GPU FHE accelerator with custom options. If options are zero-valued, it uses the global GPU config.

func (*FHEAccelerator) Backend

func (g *FHEAccelerator) Backend() string

Backend returns the active GPU backend name.

func (*FHEAccelerator) BatchNTTForward

func (g *FHEAccelerator) BatchNTTForward(r *ring.Ring, polys []ring.Poly) error

BatchNTTForward performs forward NTT on multiple polynomials. This is the primary use case for GPU acceleration - batch operations.

func (*FHEAccelerator) BatchNTTInverse

func (g *FHEAccelerator) BatchNTTInverse(r *ring.Ring, polys []ring.Poly) error

BatchNTTInverse performs inverse NTT on multiple polynomials.

func (*FHEAccelerator) BatchPolyMul

func (g *FHEAccelerator) BatchPolyMul(r *ring.Ring, a, b, out []ring.Poly) error

BatchPolyMul performs polynomial multiplication on batches using GPU.

func (*FHEAccelerator) ClearCache

func (g *FHEAccelerator) ClearCache()

ClearCache clears any cached state.

func (*FHEAccelerator) Close

func (g *FHEAccelerator) Close()

Close releases all GPU resources.

func (*FHEAccelerator) IsEnabled

func (g *FHEAccelerator) IsEnabled() bool

IsEnabled returns whether GPU acceleration is available.

func (*FHEAccelerator) Stats

func (g *FHEAccelerator) Stats() FHEStats

Stats returns current GPU statistics.

type FHEDecryptRequestV1

type FHEDecryptRequestV1 struct {
	RequestID        [32]byte
	CiphertextHandle [32]byte
	PermitID         [32]byte
	SourceChainID    ids.ID
	Epoch            uint64
	Nonce            uint64
	Expiry           int64
	Requester        [20]byte
	Callback         [20]byte
	CallbackSelector [4]byte
	GasLimit         uint32
}

FHEDecryptRequestV1 is the canonical Warp payload for decrypt requests Wire format:

[0]:     version (1 byte)
[1]:     type (1 byte)
[2:34]:  request_id (32 bytes)
[34:66]: ciphertext_handle (32 bytes)
[66:98]: permit_id (32 bytes)
[98:130]: source_chain_id (32 bytes)
[130:138]: epoch (8 bytes)
[138:146]: nonce (8 bytes)
[146:154]: expiry (8 bytes)
[154:174]: requester (20 bytes)
[174:194]: callback (20 bytes)
[194:198]: callback_selector (4 bytes)
[198:202]: gas_limit (4 bytes)

func ParseFHEDecryptRequestV1

func ParseFHEDecryptRequestV1(data []byte) (*FHEDecryptRequestV1, error)

ParseFHEDecryptRequestV1 parses a decrypt request from wire format

func (*FHEDecryptRequestV1) Bytes

func (r *FHEDecryptRequestV1) Bytes() []byte

Bytes serializes the request to wire format

func (*FHEDecryptRequestV1) Validate

func (r *FHEDecryptRequestV1) Validate() error

Validate checks if the request is valid and not expired. An Expiry of 0 means no expiration (infinite validity).

type FHEDecryptResultV1

type FHEDecryptResultV1 struct {
	RequestID          [32]byte
	ResultHandle       [32]byte
	SourceChainID      ids.ID
	Epoch              uint64
	Status             uint8
	CommitteeSignature [32]byte
	Plaintext          []byte
}

FHEDecryptResultV1 is the canonical Warp payload for decrypt results Wire format:

[0]:      version (1 byte)
[1]:      type (1 byte)
[2:34]:   request_id (32 bytes)
[34:66]:  result_handle (32 bytes)
[66:98]:  source_chain_id (32 bytes)
[98:106]: epoch (8 bytes)
[106]:    status (1 byte)
[107:139]: committee_signature (32 bytes) - aggregated BLS signature
[139:143]: plaintext_len (4 bytes)
[143:...]: plaintext (variable)

func ParseFHEDecryptResultV1

func ParseFHEDecryptResultV1(data []byte) (*FHEDecryptResultV1, error)

ParseFHEDecryptResultV1 parses a decrypt result from wire format

func (*FHEDecryptResultV1) Bytes

func (r *FHEDecryptResultV1) Bytes() []byte

Bytes serializes the result to wire format

type FHEDecryptionService

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

FHEDecryptionService manages FHE decryption operations

func NewFHEDecryptionService

func NewFHEDecryptionService(logger log.Logger) *FHEDecryptionService

NewFHEDecryptionService creates a new FHE decryption service

func (*FHEDecryptionService) GetHandler

func (s *FHEDecryptionService) GetHandler(chainID ids.ID) (*WarpHandler, bool)

GetHandler returns the handler for a specific chain

func (*FHEDecryptionService) RegisterHandler

func (s *FHEDecryptionService) RegisterHandler(chainID ids.ID, handler *WarpHandler)

RegisterHandler registers a Warp handler for a specific chain

func (*FHEDecryptionService) Start

func (s *FHEDecryptionService) Start(ctx context.Context) error

Start begins the FHE decryption service

func (*FHEDecryptionService) Stop

func (s *FHEDecryptionService) Stop() error

Stop shuts down the FHE decryption service

type FHEKeyRotationV1

type FHEKeyRotationV1 struct {
	OldEpoch      uint64
	NewEpoch      uint64
	NewThreshold  uint32
	CommitteeSize uint32
	NewPublicKey  []byte
}

FHEKeyRotationV1 announces a key rotation event Wire format:

[0]:      version (1 byte)
[1]:      type (1 byte)
[2:10]:   old_epoch (8 bytes)
[10:18]:  new_epoch (8 bytes)
[18:22]:  new_threshold (4 bytes)
[22:26]:  committee_size (4 bytes)
[26:...]: new_public_key (variable, prefixed with length)

func ParseFHEKeyRotationV1

func ParseFHEKeyRotationV1(data []byte) (*FHEKeyRotationV1, error)

ParseFHEKeyRotationV1 parses a key rotation from wire format

func (*FHEKeyRotationV1) Bytes

func (r *FHEKeyRotationV1) Bytes() []byte

Bytes serializes the key rotation to wire format

type FHEOptions

type FHEOptions struct {
	// Enabled controls whether GPU acceleration is used
	Enabled bool
	// Backend specifies which GPU backend to use: "auto", "metal", "cuda", "cpu"
	Backend string
}

FHEOptions holds options for creating a GPU FHE accelerator.

type FHEReencryptRequestV1

type FHEReencryptRequestV1 struct {
	RequestID          [32]byte
	CiphertextHandle   [32]byte
	PermitID           [32]byte
	SourceChainID      ids.ID
	Epoch              uint64
	Recipient          [20]byte
	RecipientPublicKey []byte
}

FHEReencryptRequestV1 is for recipient-specific re-encryption Wire format:

[0]:      version (1 byte)
[1]:      type (1 byte)
[2:34]:   request_id (32 bytes)
[34:66]:  ciphertext_handle (32 bytes)
[66:98]:  permit_id (32 bytes)
[98:130]: source_chain_id (32 bytes)
[130:138]: epoch (8 bytes)
[138:158]: recipient (20 bytes)
[158:...]: recipient_public_key (variable, prefixed with length)

func ParseFHEReencryptRequestV1

func ParseFHEReencryptRequestV1(data []byte) (*FHEReencryptRequestV1, error)

ParseFHEReencryptRequestV1 parses a reencrypt request from wire format

func (*FHEReencryptRequestV1) Bytes

func (r *FHEReencryptRequestV1) Bytes() []byte

Bytes serializes the request to wire format

type FHEService

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

FHEService provides the RPC interface for FHE operations

func NewFHEService

func NewFHEService(registry *Registry, integration *ThresholdFHEIntegration, logger log.Logger, chainID ids.ID, opts ...FHEServiceOption) *FHEService

NewFHEService creates a new FHE RPC service

func (*FHEService) CreatePermit

func (s *FHEService) CreatePermit(ctx context.Context, args *CreatePermitArgs, reply *CreatePermitReply) error

CreatePermit creates a new access permit

func (*FHEService) GetCiphertextMeta

func (s *FHEService) GetCiphertextMeta(_ context.Context, args *GetCiphertextMetaArgs, reply *GetCiphertextMetaReply) error

GetCiphertextMeta retrieves ciphertext metadata

func (*FHEService) GetCommittee

func (s *FHEService) GetCommittee(_ context.Context, args *GetCommitteeArgs, reply *GetCommitteeReply) error

GetCommittee returns the current threshold committee

func (*FHEService) GetDecryptBatchResult

func (s *FHEService) GetDecryptBatchResult(ctx context.Context, args *GetDecryptBatchResultArgs, reply *GetDecryptBatchResultReply) error

GetDecryptBatchResult retrieves multiple decrypt results

func (*FHEService) GetDecryptResult

func (s *FHEService) GetDecryptResult(_ context.Context, args *GetDecryptResultArgs, reply *GetDecryptResultReply) error

GetDecryptResult retrieves the result of a decrypt request

func (*FHEService) GetPublicParams

func (s *FHEService) GetPublicParams(_ context.Context, _ *GetPublicParamsArgs, reply *GetPublicParamsReply) error

GetPublicParams returns the current FHE public parameters

func (*FHEService) GetRequestReceipt

func (s *FHEService) GetRequestReceipt(_ context.Context, args *GetRequestReceiptArgs, reply *GetRequestReceiptReply) error

GetRequestReceipt retrieves Warp receipt info for a request

func (*FHEService) RegisterCiphertext

func (s *FHEService) RegisterCiphertext(ctx context.Context, args *RegisterCiphertextArgs, reply *RegisterCiphertextReply) error

RegisterCiphertext registers a new ciphertext

func (*FHEService) RequestDecrypt

func (s *FHEService) RequestDecrypt(_ context.Context, args *RequestDecryptArgs, reply *RequestDecryptReply) error

RequestDecrypt submits a threshold decryption request

func (*FHEService) RequestDecryptBatch

func (s *FHEService) RequestDecryptBatch(ctx context.Context, args *RequestDecryptBatchArgs, reply *RequestDecryptBatchReply) error

RequestDecryptBatch submits multiple decrypt requests

func (*FHEService) VerifyPermit

func (s *FHEService) VerifyPermit(_ context.Context, args *VerifyPermitArgs, reply *VerifyPermitReply) error

VerifyPermit verifies a permit is valid for an operation

type FHEServiceOption

type FHEServiceOption func(*FHEService)

FHEServiceOption configures an FHEService

func WithAuthenticator

func WithAuthenticator(auth Authenticator) FHEServiceOption

WithAuthenticator sets the authenticator for RPC caller verification

type FHEStats

type FHEStats struct {
	NTTForwardCalls  uint64
	NTTInverseCalls  uint64
	PolyMulCalls     uint64
	BatchCalls       uint64
	GPUFallbackCalls uint64
	TotalGPUTimeNs   uint64
}

FHEStats tracks GPU acceleration statistics

type FHETaskResultV1

type FHETaskResultV1 struct {
	TaskID           [32]byte
	ResultHandle     [32]byte
	SourceChainID    ids.ID
	Epoch            uint64
	Status           uint8
	Callback         [20]byte
	CallbackSelector [4]byte
	Signature        [32]byte
}

FHETaskResultV1 is for coprocessor task results Wire format:

[0]:      version (1 byte)
[1]:      type (1 byte)
[2:34]:   task_id (32 bytes)
[34:66]:  result_handle (32 bytes)
[66:98]:  source_chain_id (32 bytes)
[98:106]: epoch (8 bytes)
[106]:    status (1 byte)
[107:127]: callback (20 bytes)
[127:131]: callback_selector (4 bytes)
[131:163]: signature (32 bytes)

func ParseFHETaskResultV1

func ParseFHETaskResultV1(data []byte) (*FHETaskResultV1, error)

ParseFHETaskResultV1 parses a task result from wire format

func (*FHETaskResultV1) Bytes

func (r *FHETaskResultV1) Bytes() []byte

Bytes serializes the task result to wire format

type GetCiphertextMetaArgs

type GetCiphertextMetaArgs struct {
	Handle string `json:"handle"` // hex-encoded 32 bytes
}

GetCiphertextMetaArgs contains the handle to query

type GetCiphertextMetaReply

type GetCiphertextMetaReply struct {
	Handle       string `json:"handle"`
	Owner        string `json:"owner"`
	Type         uint8  `json:"type"`
	Level        int    `json:"level"`
	Epoch        uint64 `json:"epoch"`
	RegisteredAt int64  `json:"registeredAt"`
	Size         uint32 `json:"size"`
	ChainID      string `json:"chainId"`
}

GetCiphertextMetaReply contains ciphertext metadata

type GetCommitteeArgs

type GetCommitteeArgs struct {
	Epoch *uint64 `json:"epoch,omitempty"`
}

GetCommitteeArgs contains no arguments

type GetCommitteeReply

type GetCommitteeReply struct {
	Epoch     uint64                `json:"epoch"`
	Threshold int                   `json:"threshold"`
	Members   []CommitteeMemberInfo `json:"members"`
}

GetCommitteeReply contains the current committee

type GetDecryptBatchResultArgs

type GetDecryptBatchResultArgs struct {
	RequestIDs []string `json:"requestIds"`
}

GetDecryptBatchResultArgs contains multiple request IDs

type GetDecryptBatchResultReply

type GetDecryptBatchResultReply struct {
	Results []GetDecryptResultReply `json:"results"`
}

GetDecryptBatchResultReply contains multiple results

type GetDecryptResultArgs

type GetDecryptResultArgs struct {
	RequestID string `json:"requestId"` // hex-encoded 32 bytes
}

GetDecryptResultArgs contains the request ID to query

type GetDecryptResultReply

type GetDecryptResultReply struct {
	RequestID    string `json:"requestId"`
	Status       string `json:"status"`
	ResultHandle string `json:"resultHandle,omitempty"`
	Plaintext    string `json:"plaintext,omitempty"` // hex-encoded
	Error        string `json:"error,omitempty"`
	CreatedAt    int64  `json:"createdAt"`
	CompletedAt  int64  `json:"completedAt,omitempty"`
}

GetDecryptResultReply contains the decryption result

type GetPublicParamsArgs

type GetPublicParamsArgs struct{}

GetPublicParamsArgs contains no arguments

type GetPublicParamsReply

type GetPublicParamsReply struct {
	Epoch     uint64 `json:"epoch"`
	LogN      int    `json:"logN"`
	LogQP     int    `json:"logQP"` // Total bits for Q*P
	LogScale  int    `json:"logScale"`
	Threshold int    `json:"threshold"`
	PublicKey string `json:"publicKey"` // hex-encoded
	ChainID   string `json:"chainId"`
}

GetPublicParamsReply contains FHE public parameters

type GetRequestReceiptArgs

type GetRequestReceiptArgs struct {
	RequestID string `json:"requestId"`
}

GetRequestReceiptArgs contains the request ID

type GetRequestReceiptReply

type GetRequestReceiptReply struct {
	RequestID     string `json:"requestId"`
	Status        string `json:"status"`
	WarpMessageID string `json:"warpMessageId,omitempty"`
	TxID          string `json:"txId,omitempty"`
	Epoch         uint64 `json:"epoch"`
	SourceChain   string `json:"sourceChain"`
	CreatedAt     int64  `json:"createdAt"`
	ProcessedAt   int64  `json:"processedAt,omitempty"`
}

GetRequestReceiptReply contains the Warp receipt info

type InMemoryCiphertextStorage

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

InMemoryCiphertextStorage is a simple in-memory implementation of CiphertextStorage

func NewInMemoryCiphertextStorage

func NewInMemoryCiphertextStorage() *InMemoryCiphertextStorage

NewInMemoryCiphertextStorage creates a new in-memory storage

func (*InMemoryCiphertextStorage) Delete

func (s *InMemoryCiphertextStorage) Delete(handle common.Hash) error

Delete removes ciphertext

func (*InMemoryCiphertextStorage) Get

func (s *InMemoryCiphertextStorage) Get(handle common.Hash) ([]byte, error)

Get retrieves ciphertext by handle

func (*InMemoryCiphertextStorage) Put

func (s *InMemoryCiphertextStorage) Put(handle common.Hash, data []byte) error

Put stores ciphertext

type LifecycleConfig

type LifecycleConfig struct {
	// EpochDuration is the duration of each epoch in blocks
	EpochDuration uint64 `json:"epoch_duration"`
	// GracePeriod is the number of blocks to allow pending requests during transition
	GracePeriod uint64 `json:"grace_period"`
	// MinCommitteeSize is the minimum number of committee members
	MinCommitteeSize int `json:"min_committee_size"`
	// MaxCommitteeSize is the maximum number of committee members
	MaxCommitteeSize int `json:"max_committee_size"`
	// DefaultThreshold is the default threshold (e.g., 67 for 67-of-100)
	DefaultThreshold int `json:"default_threshold"`
	// DKGTimeout is the timeout for DKG ceremonies
	DKGTimeout time.Duration `json:"dkg_timeout"`
	// KeyRotationBlocks is how often to rotate keys (0 = never)
	KeyRotationBlocks uint64 `json:"key_rotation_blocks"`
}

LifecycleConfig configures the lifecycle manager

func DefaultLifecycleConfig

func DefaultLifecycleConfig() *LifecycleConfig

DefaultLifecycleConfig returns sensible defaults

type LifecycleManager

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

LifecycleManager manages epoch and committee lifecycle

func NewLifecycleManager

func NewLifecycleManager(registry *Registry, config *LifecycleConfig, logger log.Logger) *LifecycleManager

NewLifecycleManager creates a new lifecycle manager

func (*LifecycleManager) AbortDKG

func (lm *LifecycleManager) AbortDKG(reason string) error

AbortDKG aborts a DKG ceremony

func (*LifecycleManager) ForceEpochTransition

func (lm *LifecycleManager) ForceEpochTransition() error

ForceEpochTransition manually triggers an epoch transition (admin only)

func (*LifecycleManager) GetCommitteeWeight

func (lm *LifecycleManager) GetCommitteeWeight() (uint64, error)

GetCommitteeWeight calculates total committee weight

func (*LifecycleManager) GetDKGState

func (lm *LifecycleManager) GetDKGState() *DKGState

GetDKGState returns the current DKG state

func (*LifecycleManager) GetEpochKeyInfo

func (lm *LifecycleManager) GetEpochKeyInfo(epoch uint64) (*EpochKeyInfo, error)

GetEpochKeyInfo returns key information for a specific epoch

func (*LifecycleManager) GetStatus

func (lm *LifecycleManager) GetStatus() (*LifecycleStatus, error)

func (*LifecycleManager) GetTransitionState

func (lm *LifecycleManager) GetTransitionState() *TransitionState

GetTransitionState returns the current transition state

func (*LifecycleManager) InitiateEpoch

func (lm *LifecycleManager) InitiateEpoch(committee []CommitteeMember, threshold int, publicKey []byte) error

InitiateEpoch creates the first epoch (genesis)

func (*LifecycleManager) IsTransitioning

func (lm *LifecycleManager) IsTransitioning() bool

IsTransitioning returns whether an epoch transition is in progress

func (*LifecycleManager) OnBlock

func (lm *LifecycleManager) OnBlock(blockHeight uint64) error

OnBlock processes a new block for lifecycle events

func (*LifecycleManager) RegisterMember

func (lm *LifecycleManager) RegisterMember(nodeID ids.NodeID, publicKey []byte, stake uint64) error

RegisterMember registers a new committee member candidate

func (*LifecycleManager) RemoveMember

func (lm *LifecycleManager) RemoveMember(nodeID ids.NodeID) error

RemoveMember removes a committee member (effective next epoch)

func (*LifecycleManager) SetCallbacks

func (lm *LifecycleManager) SetCallbacks(
	onEpochChange func(oldEpoch, newEpoch uint64),
	onCommitteeChange func(members []CommitteeMember),
	onDKGComplete func(epoch uint64, publicKey []byte),
)

SetCallbacks sets lifecycle event callbacks

func (*LifecycleManager) SetDKGCallbacks

func (lm *LifecycleManager) SetDKGCallbacks(
	onDKGStart func(ceremonyID [32]byte, epoch uint64, participants []ids.NodeID),
	onDKGPhaseChange func(ceremonyID [32]byte, phase DKGStatus),
)

SetDKGCallbacks sets DKG-specific event callbacks

func (*LifecycleManager) SetSlashCallback

func (lm *LifecycleManager) SetSlashCallback(onSlash func(nodeID ids.NodeID, reason string))

SetSlashCallback sets the slashing event callback

func (*LifecycleManager) SlashMember

func (lm *LifecycleManager) SlashMember(nodeID ids.NodeID, reason string) error

SlashMember slashes a misbehaving committee member

func (*LifecycleManager) Start

func (lm *LifecycleManager) Start() error

Start begins lifecycle management

func (*LifecycleManager) StartDKG

func (lm *LifecycleManager) StartDKG(epoch uint64, participants []ids.NodeID, threshold int) error

StartDKG initiates a DKG ceremony for a new epoch

func (*LifecycleManager) Stop

func (lm *LifecycleManager) Stop()

Stop halts lifecycle management

func (*LifecycleManager) SubmitDKGCommitment

func (lm *LifecycleManager) SubmitDKGCommitment(nodeID ids.NodeID, commitment []byte) error

SubmitDKGCommitment receives a commitment from a participant

func (*LifecycleManager) SubmitDKGShare

func (lm *LifecycleManager) SubmitDKGShare(nodeID ids.NodeID, share []byte) error

SubmitDKGShare receives an encrypted share from a participant

func (*LifecycleManager) ValidateThresholdMet

func (lm *LifecycleManager) ValidateThresholdMet(participantCount int) error

ValidateThresholdMet checks if threshold requirements are met

type LifecycleStatus

type LifecycleStatus struct {
	CurrentEpoch     uint64  `json:"current_epoch"`
	CurrentBlock     uint64  `json:"current_block"`
	CommitteeSize    int     `json:"committee_size"`
	Threshold        int     `json:"threshold"`
	IsTransitioning  bool    `json:"is_transitioning"`
	DKGStatus        string  `json:"dkg_status,omitempty"`
	TransitionStatus string  `json:"transition_status,omitempty"`
	EpochProgress    float64 `json:"epoch_progress"`
}

GetLifecycleStatus returns overall lifecycle status

type MemberRegistration

type MemberRegistration struct {
	NodeID       ids.NodeID   `json:"node_id"`
	PublicKey    []byte       `json:"public_key"`
	Stake        uint64       `json:"stake"`
	RegisteredAt int64        `json:"registered_at"`
	ActivatedAt  int64        `json:"activated_at,omitempty"`
	Status       MemberStatus `json:"status"`
}

MemberRegistration represents a pending committee member registration

type MemberStatus

type MemberStatus uint8
const (
	MemberPending MemberStatus = iota
	MemberActive
	MemberInactive
	MemberSlashed
	MemberExiting
)

func (MemberStatus) String

func (s MemberStatus) String() string

type Permit

type Permit struct {
	PermitID    [32]byte `json:"permit_id"`
	Handle      [32]byte `json:"handle"`
	Grantee     [20]byte `json:"grantee"`
	Grantor     [20]byte `json:"grantor"`
	Operations  uint32   `json:"operations"` // Bitmask of allowed operations
	Expiry      int64    `json:"expiry"`
	CreatedAt   int64    `json:"created_at"`
	Attestation []byte   `json:"attestation,omitempty"`
	ChainID     ids.ID   `json:"chain_id"`
}

Permit represents an access control permit for FHE operations

type RegisterCiphertextArgs

type RegisterCiphertextArgs struct {
	Handle  string `json:"handle"` // hex-encoded 32 bytes
	Owner   string `json:"owner"`  // hex-encoded 20 bytes
	Type    uint8  `json:"type"`
	Level   int    `json:"level"`
	Size    uint32 `json:"size"`
	ChainID string `json:"chainId,omitempty"`
}

RegisterCiphertextArgs contains the ciphertext to register

type RegisterCiphertextReply

type RegisterCiphertextReply struct {
	Handle       string `json:"handle"`
	Epoch        uint64 `json:"epoch"`
	RegisteredAt int64  `json:"registeredAt"`
}

RegisterCiphertextReply contains the registration result

type Registry

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

Registry provides persistent storage for FHE-related data

func NewRegistry

func NewRegistry(db database.Database) (*Registry, error)

NewRegistry creates a new FHE registry with persistent storage

func (*Registry) AddCommitteeMember

func (r *Registry) AddCommitteeMember(member *CommitteeMember) error

AddCommitteeMember adds a member to the current epoch's committee

func (*Registry) Close

func (r *Registry) Close() error

Close closes the registry

func (*Registry) CreateDecryptRequest

func (r *Registry) CreateDecryptRequest(req *DecryptRequest) error

CreateDecryptRequest stores a new decrypt request

func (*Registry) CreatePermit

func (r *Registry) CreatePermit(permit *Permit) error

CreatePermit stores a new permit

func (*Registry) DeleteCiphertext

func (r *Registry) DeleteCiphertext(handle [32]byte) error

DeleteCiphertext removes ciphertext metadata

func (*Registry) DeleteSession

func (r *Registry) DeleteSession(sessionID string) error

DeleteSession removes a session

func (*Registry) GetCiphertextMeta

func (r *Registry) GetCiphertextMeta(handle [32]byte) (*CiphertextMeta, error)

GetCiphertextMeta retrieves ciphertext metadata

func (*Registry) GetCommittee

func (r *Registry) GetCommittee() ([]CommitteeMember, error)

GetCommittee returns the committee for the current epoch

func (*Registry) GetCommitteeMember

func (r *Registry) GetCommitteeMember(nodeID ids.NodeID) (*CommitteeMember, error)

GetCommitteeMember returns a specific committee member

func (*Registry) GetCurrentEpoch

func (r *Registry) GetCurrentEpoch() uint64

GetCurrentEpoch returns the current epoch number

func (*Registry) GetDecryptRequest

func (r *Registry) GetDecryptRequest(requestID [32]byte) (*DecryptRequest, error)

GetDecryptRequest retrieves a decrypt request

func (*Registry) GetEpoch

func (r *Registry) GetEpoch(epoch uint64) (*EpochInfo, error)

GetEpoch retrieves epoch information

func (*Registry) GetPermit

func (r *Registry) GetPermit(permitID [32]byte) (*Permit, error)

GetPermit retrieves a permit

func (*Registry) GetSession

func (r *Registry) GetSession(sessionID string) (*SessionState, error)

GetSession retrieves a session state

func (*Registry) RegisterCiphertext

func (r *Registry) RegisterCiphertext(meta *CiphertextMeta) error

RegisterCiphertext stores ciphertext metadata

func (*Registry) RemoveCommitteeMember

func (r *Registry) RemoveCommitteeMember(nodeID ids.NodeID) error

RemoveCommitteeMember removes a member from the current epoch's committee

func (*Registry) RevokePermit

func (r *Registry) RevokePermit(permitID [32]byte) error

RevokePermit removes a permit

func (*Registry) SaveSession

func (r *Registry) SaveSession(session *SessionState) error

SaveSession persists a session state

func (*Registry) SetEpoch

func (r *Registry) SetEpoch(epoch uint64, info *EpochInfo) error

SetEpoch updates the current epoch

func (*Registry) UpdateDecryptRequest

func (r *Registry) UpdateDecryptRequest(requestID [32]byte, status RequestStatus, result [32]byte, errMsg string) error

UpdateDecryptRequest updates a decrypt request status

func (*Registry) VerifyPermit

func (r *Registry) VerifyPermit(permitID [32]byte, handle [32]byte, grantee [20]byte, operation uint32) error

VerifyPermit checks if a permit is valid for the given operation

type Relayer

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

Relayer coordinates threshold decryption between C-Chain and F-Chain (FHE compute per LP-134; legacy: T-Chain)

func NewRelayer

func NewRelayer(
	logger log.Logger,
	decryptor *ThresholdDecryptor,
	storage CiphertextStorage,
	networkID uint32,
	chainID ids.ID,
	zChainID ids.ID,
	signer warp.Signer,
	onMessage func(context.Context, *warp.Envelope) error,
) *Relayer

NewRelayer creates a new decryption relayer

func (*Relayer) GetResult

func (r *Relayer) GetResult(requestID common.Hash) ([]byte, bool, error)

GetResult retrieves the result of a decryption request

func (*Relayer) Start

func (r *Relayer) Start(ctx context.Context) error

Start begins processing decryption requests

func (*Relayer) Stop

func (r *Relayer) Stop() error

Stop shuts down the relayer

func (*Relayer) SubmitRequest

func (r *Relayer) SubmitRequest(_ context.Context, req *DecryptionRequest) error

SubmitRequest adds a new decryption request from C-Chain

type RequestDecryptArgs

type RequestDecryptArgs struct {
	CiphertextHandle string `json:"ciphertextHandle"` // hex-encoded 32 bytes
	PermitID         string `json:"permitId"`         // hex-encoded 32 bytes
	Callback         string `json:"callback"`         // hex-encoded 20 bytes
	CallbackSelector string `json:"callbackSelector"` // hex-encoded 4 bytes
	SourceChain      string `json:"sourceChain,omitempty"`
	Expiry           int64  `json:"expiry,omitempty"` // Unix timestamp
	GasLimit         uint32 `json:"gasLimit,omitempty"`
}

RequestDecryptArgs contains the decrypt request parameters

type RequestDecryptBatchArgs

type RequestDecryptBatchArgs struct {
	Requests []RequestDecryptArgs `json:"requests"`
}

RequestDecryptBatchArgs contains multiple decrypt requests

type RequestDecryptBatchReply

type RequestDecryptBatchReply struct {
	RequestIDs []string `json:"requestIds"`
	Epoch      uint64   `json:"epoch"`
}

RequestDecryptBatchReply contains multiple request IDs

type RequestDecryptReply

type RequestDecryptReply struct {
	RequestID string `json:"requestId"`
	Epoch     uint64 `json:"epoch"`
	Status    string `json:"status"`
}

RequestDecryptReply contains the request ID

type RequestStatus

type RequestStatus uint8

RequestStatus represents the status of a decrypt request

const (
	RequestPending RequestStatus = iota
	RequestProcessing
	RequestCompleted
	RequestFailed
	RequestExpired
)

func (RequestStatus) String

func (s RequestStatus) String() string

type SessionState

type SessionState struct {
	SessionID        string        `json:"session_id"`
	CiphertextHandle [32]byte      `json:"ciphertext_handle"`
	Epoch            uint64        `json:"epoch"`
	Threshold        int           `json:"threshold"`
	Participants     []ids.NodeID  `json:"participants"`
	SharesReceived   int           `json:"shares_received"`
	Status           SessionStatus `json:"status"`
	CreatedAt        int64         `json:"created_at"`
	CompletedAt      int64         `json:"completed_at,omitempty"`
	Result           []byte        `json:"result,omitempty"`
}

SessionState stores the state of a threshold decryption session

type SessionStatus

type SessionStatus uint8
const (
	SessionActive SessionStatus = iota
	SessionCompleted
	SessionFailed
	SessionExpired
)

type ThresholdConfig

type ThresholdConfig struct {
	// Threshold is the minimum number of parties required (e.g., 67)
	Threshold int
	// TotalParties is the total number of parties (e.g., 100)
	TotalParties int
	// CKKSParams are the CKKS scheme parameters
	CKKSParams ckks.Parameters
	// LogBound is the bit length of masks for E2S protocol security
	LogBound uint
}

ThresholdConfig contains configuration for threshold FHE decryption

func DefaultThresholdConfig

func DefaultThresholdConfig() ThresholdConfig

DefaultThresholdConfig returns the default 67-of-100 configuration

type ThresholdDecryptor

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

ThresholdDecryptor performs threshold CKKS decryption using the E2S multiparty protocol

func NewThresholdDecryptor

func NewThresholdDecryptor(
	logger log.Logger,
	params ckks.Parameters,
	threshold, totalParties, partyID int,
	logBound uint,
	broadcastShare func(sessionID string, share []byte) error,
) (*ThresholdDecryptor, error)

NewThresholdDecryptor creates a new threshold decryptor

func (*ThresholdDecryptor) AddShare

func (d *ThresholdDecryptor) AddShare(sessionID string, partyID int, shareBytes []byte) error

AddShare adds a decryption share from another party

func (*ThresholdDecryptor) Decrypt

func (d *ThresholdDecryptor) Decrypt(ctx context.Context, sessionID string, ciphertextBytes []byte) ([]byte, error)

Decrypt performs threshold decryption of the ciphertext

func (*ThresholdDecryptor) SetSecretKey

func (d *ThresholdDecryptor) SetSecretKey(sk *rlwe.SecretKey)

SetSecretKey sets this party's secret key

type ThresholdFHEIntegration

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

ThresholdFHEIntegration integrates threshold FHE with ThresholdVM

func NewThresholdFHEIntegration

func NewThresholdFHEIntegration(logger log.Logger, config ThresholdConfig, partyID int) (*ThresholdFHEIntegration, error)

NewThresholdFHEIntegration creates a new integration instance

func (*ThresholdFHEIntegration) CleanupSession

func (i *ThresholdFHEIntegration) CleanupSession(sessionID string)

CleanupSession removes a completed session

func (*ThresholdFHEIntegration) ContributeShare

func (i *ThresholdFHEIntegration) ContributeShare(
	sessionID string,
	nodeID ids.NodeID,
	publicShareBytes []byte,
) (bool, error)

ContributeShare adds a decryption share from a validator

func (*ThresholdFHEIntegration) GenerateShare

func (i *ThresholdFHEIntegration) GenerateShare(sessionID string) (publicShareBytes []byte, err error)

GenerateShare generates this party's decryption share for a session

func (*ThresholdFHEIntegration) GetNetworkKey

func (i *ThresholdFHEIntegration) GetNetworkKey() *rlwe.PublicKey

GetNetworkKey returns the network's combined public key

func (*ThresholdFHEIntegration) GetSessionResult

func (i *ThresholdFHEIntegration) GetSessionResult(sessionID string) ([]byte, bool, error)

GetSessionResult retrieves the result of a completed session

func (*ThresholdFHEIntegration) InitiateDecryption

func (i *ThresholdFHEIntegration) InitiateDecryption(
	sessionID string,
	requestID common.Hash,
	ciphertextBytes []byte,
) error

InitiateDecryption starts a new threshold decryption session

func (*ThresholdFHEIntegration) SetNetworkKey

func (i *ThresholdFHEIntegration) SetNetworkKey(pk *rlwe.PublicKey)

SetNetworkKey sets the combined public key for the network

func (*ThresholdFHEIntegration) SetSecretKey

func (i *ThresholdFHEIntegration) SetSecretKey(sk *rlwe.SecretKey)

SetSecretKey sets this party's secret key share

func (*ThresholdFHEIntegration) Start

Start begins the FHE integration service

func (*ThresholdFHEIntegration) Stop

func (i *ThresholdFHEIntegration) Stop() error

Stop shuts down the FHE integration

type TransitionState

type TransitionState struct {
	FromEpoch       uint64           `json:"from_epoch"`
	ToEpoch         uint64           `json:"to_epoch"`
	Status          TransitionStatus `json:"status"`
	StartedAt       int64            `json:"started_at"`
	CompletedAt     int64            `json:"completed_at,omitempty"`
	PendingRequests int              `json:"pending_requests"`
	MigratedCount   int              `json:"migrated_count"`
	Error           string           `json:"error,omitempty"`
}

TransitionState tracks epoch transition progress

type TransitionStatus

type TransitionStatus uint8
const (
	TransitionPending TransitionStatus = iota
	TransitionDKGPhase
	TransitionMigrationPhase
	TransitionFinalizingPhase
	TransitionCompleted
	TransitionFailed
)

func (TransitionStatus) String

func (s TransitionStatus) String() string

type VerifyPermitArgs

type VerifyPermitArgs struct {
	PermitID  string `json:"permitId"`  // hex-encoded 32 bytes
	Handle    string `json:"handle"`    // hex-encoded 32 bytes
	Grantee   string `json:"grantee"`   // hex-encoded 20 bytes
	Operation uint32 `json:"operation"` // operation to check
}

VerifyPermitArgs contains permit verification parameters

type VerifyPermitReply

type VerifyPermitReply struct {
	Valid  bool   `json:"valid"`
	Error  string `json:"error,omitempty"`
	Expiry int64  `json:"expiry,omitempty"`
}

VerifyPermitReply contains verification result

type WarpHandler

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

WarpHandler processes FHE-related Warp messages from C-Chain

func NewWarpHandler

func NewWarpHandler(logger log.Logger, relayer *Relayer) *WarpHandler

NewWarpHandler creates a new Warp message handler for FHE decryption

func (*WarpHandler) HandleMessage

func (h *WarpHandler) HandleMessage(ctx context.Context, env *warp.Envelope) error

HandleMessage processes an incoming signed Warp envelope for FHE decryption. The envelope's Beam BitSetSignature is aggregated and verified against the canonical validator set by the node warp backend before delivery; this handler reads the authenticated content from env.Message.

Jump to

Keyboard shortcuts

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