aivm

package
v1.2.7 Latest Latest
Warning

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

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

Documentation

Overview

Package aivm provides the AI Virtual Machine for the Lux network.

AIVM is the AI compute coordination layer. It works on ANY Lux L1/L2 (mainnet primary network, testnet, devnet, white-label chains) with NO trusted dealer, NO TEE requirement, and NO single point of trust.

Verification model (per VerificationMode):

  • ModeOptimistic (DEFAULT, public-BFT-safe): providers post results with hash-commitment + bond; N-block challenge period; uncontested results finalise; challenged results enter fraud-proof flow with slashing of the losing side. No TEE assumption. Works on any L1/L2 that has Pulsar/Corona for finality.

  • ModeMultiPartyRedundant: M-of-N validators run the same inference and consensus on the output hash. No single provider needs trust; malicious providers diverge from the majority and are slashed. Public-BFT-safe. Cost: M× compute per task.

  • ModeTEEAttested: when a provider has SGX/SEV-SNP/TDX/nvtrust available, the attestation is FOLDED INTO the trust score as an accelerator (skip the challenge period for high-trust-score providers). TEE never CHANGES the trust root — only reduces latency-to-finality for already-bonded providers.

The TEE path (luxfi/ai/pkg/attestation) is OPTIONAL across all modes. Setting RequireTEEAttestation=true is a deployment policy choice for permissioned/regulated subnets; the public-chain default is VerificationMode=ModeOptimistic + RequireTEEAttestation=false.

Other features:

  • Task submission and assignment (chain-agnostic)
  • Mining rewards (paid in the host chain's native token)
  • Optional anchoring to Q-Chain for cross-chain settlement (controlled by HostChainID: when "primary", anchor to Q-Chain; otherwise anchor to the host chain's own finality)

Index

Constants

This section is empty.

Variables

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

	ErrNotInitialized   = errors.New("vm not initialized")
	ErrInvalidTask      = errors.New("invalid task")
	ErrProviderNotFound = errors.New("provider not found")
)
View Source
var VMID = ids.ID{'a', 'i', 'v', 'm'}

VMID is the unique identifier for AIVM (A-Chain)

Functions

func NewService

func NewService(vm *VM) http.Handler

NewService creates a new AIVM service

Types

type AIVertex

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

AIVertex represents a DAG vertex in the AI chain. Conflict key: jobID. Independent jobs commute; same job conflicts.

func (*AIVertex) Accept

func (v *AIVertex) Accept(ctx context.Context) error

func (*AIVertex) Bytes

func (v *AIVertex) Bytes() []byte

func (*AIVertex) Conflicts

func (v *AIVertex) Conflicts(other *AIVertex) bool

Conflicts returns true if this vertex and other reference the same jobID.

func (*AIVertex) ConflictsVertex

func (v *AIVertex) ConflictsVertex(other vertex.Vertex) bool

ConflictsVertex performs the same check against the vertex.Vertex interface.

func (*AIVertex) Epoch

func (v *AIVertex) Epoch() uint32

func (*AIVertex) Height

func (v *AIVertex) Height() uint64

func (*AIVertex) ID

func (v *AIVertex) ID() ids.ID

func (*AIVertex) Parents

func (v *AIVertex) Parents() []ids.ID

func (*AIVertex) Reject

func (v *AIVertex) Reject(ctx context.Context) error

func (*AIVertex) Status

func (v *AIVertex) Status() choices.Status

func (*AIVertex) Txs

func (v *AIVertex) Txs() []ids.ID

func (*AIVertex) Verify

func (v *AIVertex) Verify(ctx context.Context) error

type Block

type Block struct {
	ID_        ids.ID    `json:"id"`
	ParentID_  ids.ID    `json:"parentID"`
	Height_    uint64    `json:"height"`
	Timestamp_ time.Time `json:"timestamp"`

	// AI-specific data
	Tasks        []aivm.Task       `json:"tasks,omitempty"`
	Results      []aivm.TaskResult `json:"results,omitempty"`
	MerkleRoot   [32]byte          `json:"merkleRoot"`
	ProviderRegs []ProviderReg     `json:"providerRegs,omitempty"`
	// contains filtered or unexported fields
}

Block represents an AIVM block

func (*Block) Accept

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

Accept accepts the block

func (*Block) Bytes

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

Bytes returns the serialized block

func (*Block) Height

func (blk *Block) Height() uint64

Height returns the block height

func (*Block) ID

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

ID returns the block ID

func (*Block) Parent

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

Parent returns the parent block ID

func (*Block) ParentID

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

ParentID returns the parent block ID

func (*Block) Reject

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

Reject rejects the block

func (*Block) Status

func (blk *Block) Status() uint8

Status returns the block status

func (*Block) Timestamp

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

Timestamp returns the block timestamp

func (*Block) Verify

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

Verify verifies the block

type Config

type Config struct {
	// Network settings
	MaxProvidersPerNode int `serialize:"true" json:"maxProvidersPerNode"`
	MaxTasksPerProvider int `serialize:"true" json:"maxTasksPerProvider"`

	// HostChainID identifies which Lux L1/L2 this AIVM instance runs on.
	// "primary" = primary network (mainnet/testnet/devnet); anchor to
	// Q-Chain for cross-chain settlement. Any other value = white-label
	// L1/L2 (Hanzo, Zoo, Pars, Liquidity); anchor to the host chain's
	// own finality. AIVM is chain-agnostic — same code runs everywhere.
	HostChainID string `serialize:"true" json:"hostChainID"`

	// VerificationMode selects the result-verification strategy.
	// Default: ModeOptimistic (public-BFT-safe).
	VerificationMode VerificationMode `serialize:"true" json:"verificationMode"`

	// ChallengeWindowBlocks is the number of L1/L2 blocks during which
	// any party can submit a fraud proof against a posted result. Only
	// used by ModeOptimistic. Default 100 blocks (~5-10 minutes on
	// most Lux L1/L2 instances).
	ChallengeWindowBlocks uint64 `serialize:"true" json:"challengeWindowBlocks"`

	// RedundancyFactor is M (signatures required) for
	// ModeMultiPartyRedundant. Total providers N is committed in the
	// task spec; M-of-N must produce the same result hash for
	// acceptance. Default 3-of-5.
	RedundancyFactor int `serialize:"true" json:"redundancyFactor"`

	// MinProviderBond is the minimum stake (in host-chain native tokens,
	// wei-equivalent) a provider must lock to register. Forfeited on
	// successful fraud proof or majority-divergence. Default 1000 LUX.
	MinProviderBond uint64 `serialize:"true" json:"minProviderBond"`

	// Attestation settings — TEE is OPT-IN, NOT required by default.
	// On public chains keep RequireTEEAttestation=false; setting it true
	// restricts the provider set to TEE-equipped operators only, which
	// is a permissioned-subnet policy choice.
	RequireTEEAttestation bool   `serialize:"true" json:"requireTEEAttestation"`
	MinTrustScore         uint8  `serialize:"true" json:"minTrustScore"`
	AttestationTimeout    string `serialize:"true" json:"attestationTimeout"`

	// Task settings
	MaxTaskQueueSize int    `serialize:"true" json:"maxTaskQueueSize"`
	TaskTimeout      string `serialize:"true" json:"taskTimeout"`

	// Reward settings
	BaseReward       uint64 `serialize:"true" json:"baseReward"`
	EpochDuration    string `serialize:"true" json:"epochDuration"`
	MerkleAnchorFreq int    `serialize:"true" json:"merkleAnchorFreq"` // Blocks between Q-Chain anchors
}

Config contains AIVM configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default AIVM configuration suitable for ANY public Lux L1/L2 (no trusted dealer, no TEE requirement). The public-BFT-safe defaults are:

  • VerificationMode = ModeOptimistic (fraud-proof flow)
  • RequireTEEAttestation = false (TEE is optional acceleration)
  • HostChainID = "primary" (override per L1/L2 instance)

Permissioned/regulated subnets can opt into ModeTEEAttested + RequireTEEAttestation=true as a policy choice.

func DefaultPermissionedConfig added in v1.2.6

func DefaultPermissionedConfig() Config

DefaultPermissionedConfig returns AIVM config for a permissioned subnet (regulated AI compute, KYC'd provider set). Sets RequireTEEAttestation=true and VerificationMode=ModeTEEAttested. NOT for public mainnet use.

type Factory

type Factory struct{}

Factory implements vms.Factory interface for creating AIVM instances

func (*Factory) New

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

New creates a new AIVM instance. Allocates a per-VM GPU session at PriorityNormal for future batch attestation verification and tensor proof checks.

type Genesis

type Genesis struct {
	Version   int    `json:"version"`
	Message   string `json:"message"`
	Timestamp int64  `json:"timestamp"`
}

Genesis represents the genesis state

type ProviderReg

type ProviderReg struct {
	ProviderID     string                        `json:"providerId"`
	WalletAddress  string                        `json:"walletAddress"`
	Endpoint       string                        `json:"endpoint"`
	CPUAttestation *attestation.AttestationQuote `json:"cpuAttestation,omitempty"`
	GPUAttestation *attestation.GPUAttestation   `json:"gpuAttestation,omitempty"`
}

ProviderReg represents a provider registration in a block

type RegisterProviderRequest

type RegisterProviderRequest struct {
	ID             string                      `json:"id"`
	WalletAddress  string                      `json:"wallet_address"`
	Endpoint       string                      `json:"endpoint"`
	GPUs           []aivm.GPUInfo              `json:"gpus"`
	GPUAttestation *attestation.GPUAttestation `json:"gpu_attestation,omitempty"`
}

RegisterProviderRequest is the request for registering a provider

type Service

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

Service provides AIVM RPC service

type SubmitResultRequest

type SubmitResultRequest struct {
	TaskID      string          `json:"task_id"`
	ProviderID  string          `json:"provider_id"`
	Output      json.RawMessage `json:"output"`
	ComputeTime uint64          `json:"compute_time_ms"`
	Proof       []byte          `json:"proof"`
	Error       string          `json:"error,omitempty"`
}

SubmitResultRequest is the request for submitting a task result

type SubmitTaskRequest

type SubmitTaskRequest struct {
	ID    string          `json:"id"`
	Type  string          `json:"type"`
	Model string          `json:"model"`
	Input json.RawMessage `json:"input"`
	Fee   uint64          `json:"fee"`
}

SubmitTaskRequest is the request for submitting a task

type VM

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

VM implements the AI Virtual Machine

func (*VM) BuildBlock

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

BuildBlock implements chain.ChainVM interface

func (*VM) BuildVertex

func (vm *VM) BuildVertex(ctx context.Context) (vertex.Vertex, error)

BuildVertex creates a vertex from pending tasks/results, batching independent jobs.

func (*VM) ClaimRewards

func (vm *VM) ClaimRewards(providerID string) (string, error)

ClaimRewards claims pending rewards for a provider

func (*VM) Connected

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

Connected notifies the VM about connected nodes

func (*VM) CreateHandlers

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

CreateHandlers returns HTTP handlers

func (*VM) Disconnected

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

Disconnected notifies the VM about disconnected nodes

func (*VM) FeePolicy added in v1.2.6

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

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

func (*VM) GetBlock

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

GetBlock implements chain.ChainVM interface

func (*VM) GetBlockIDAtHeight

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

GetBlockIDAtHeight implements chain.ChainVM interface

func (*VM) GetMerkleRoot

func (vm *VM) GetMerkleRoot() [32]byte

GetMerkleRoot returns merkle root for Q-Chain anchoring

func (*VM) GetModels

func (vm *VM) GetModels() []*aivm.ModelInfo

GetModels returns available AI models

func (*VM) GetProviders

func (vm *VM) GetProviders() []*aivm.Provider

GetProviders returns all registered providers

func (*VM) GetRewardStats

func (vm *VM) GetRewardStats(providerID string) (map[string]interface{}, error)

GetRewardStats returns reward statistics for a provider

func (*VM) GetStats

func (vm *VM) GetStats() map[string]interface{}

GetStats returns VM statistics

func (*VM) GetTask

func (vm *VM) GetTask(taskID string) (*aivm.Task, error)

GetTask returns a task by ID

func (*VM) HealthCheck

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

HealthCheck implements chain.ChainVM interface

func (*VM) Initialize

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

Initialize initializes the VM with the unified Init struct

func (*VM) LastAccepted

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

LastAccepted implements chain.ChainVM interface

func (*VM) NewHTTPHandler

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

NewHTTPHandler implements chain.ChainVM interface

func (*VM) ParseBlock

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

ParseBlock implements chain.ChainVM interface

func (*VM) ParseVertex

func (vm *VM) ParseVertex(ctx context.Context, b []byte) (vertex.Vertex, error)

ParseVertex deserializes a vertex from bytes.

func (*VM) RegisterProvider

func (vm *VM) RegisterProvider(provider *aivm.Provider) error

RegisterProvider registers a new AI compute provider.

Public-BFT-safe path (VerificationMode=ModeOptimistic, default):

  • Provider locks MinProviderBond in the host chain's escrow
  • TEE attestation is OPTIONAL — providers without TEE register under the optimistic-verification flow (challenge period + fraud proofs handle correctness without trusting the provider)

Permissioned path (RequireTEEAttestation=true, opt-in):

  • Provider MUST present valid TEE attestation
  • TrustScore must meet MinTrustScore
  • Used on permissioned subnets where the validator set vets hardware operators by policy

func (*VM) SetPreference

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

SetPreference implements chain.ChainVM interface

func (*VM) SetState

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

SetState implements chain.ChainVM interface

func (*VM) Shutdown

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

Shutdown shuts down the VM

func (*VM) SubmitResult

func (vm *VM) SubmitResult(result *aivm.TaskResult) error

SubmitResult submits a task result

func (*VM) SubmitTask

func (vm *VM) SubmitTask(task *aivm.Task) error

SubmitTask submits a new AI task. This is the canonical user-task admission point on A-Chain — the HTTP /tasks handler routes through here. The FeePolicy gate refuses zero-fee tasks before they touch the core queue. Internal callers (consensus replay) bypass by reaching vm.core.SubmitTask directly.

func (*VM) VerifyGPUAttestation

func (vm *VM) VerifyGPUAttestation(att *attestation.GPUAttestation) (*attestation.DeviceStatus, error)

VerifyGPUAttestation verifies GPU attestation (local nvtrust - no cloud)

func (*VM) Version

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

Version implements chain.ChainVM interface

func (*VM) WaitForEvent

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

WaitForEvent implements chain.ChainVM interface

type VerificationMode added in v1.2.6

type VerificationMode uint8

VerificationMode selects the AIVM result-verification strategy.

Public chains MUST use ModeOptimistic or ModeMultiPartyRedundant — these are public-BFT-safe and do not require any single trusted party. ModeTEEAttested is permitted but the TEE is treated as acceleration, never as the trust root.

const (
	// ModeOptimistic is the default for public chains.
	// Providers post results with bond. N-block challenge period.
	// Public-BFT-safe — anyone can submit a fraud proof.
	ModeOptimistic VerificationMode = 0

	// ModeMultiPartyRedundant has M-of-N providers run the same task;
	// consensus on the result hash. Divergent providers are slashed.
	// Public-BFT-safe — no single provider can corrupt the result.
	ModeMultiPartyRedundant VerificationMode = 1

	// ModeTEEAttested is OPT-IN. Providers with valid TEE attestation
	// can shortcut the challenge period. TEE never changes the trust
	// root; it accelerates settlement for high-trust providers.
	// Use only on permissioned/regulated subnets where TEE-vendor
	// trust is acceptable; not the default for public mainnet.
	ModeTEEAttested VerificationMode = 2
)

type VerifyAttestationRequest

type VerifyAttestationRequest struct {
	GPUAttestation *attestation.GPUAttestation `json:"gpu_attestation"`
}

VerifyAttestationRequest is the request for verifying attestation

Directories

Path Synopsis
cmd
plugin command

Jump to

Keyboard shortcuts

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