Documentation
¶
Overview ¶
Package aivm GPU backend — runtime-loaded plugin bridge.
Unlike cevm/cevm_cgo.go (which links libevm + libevm-gpu via pkg-config), AIVM resolves its GPU backend at PROCESS START via dlopen/dlsym against the lux-gpu-kernels plugin DSOs. This keeps the chains module compilable without the lux GPU plugin present in the build tree — the plugin is fully optional.
Lookup order (handled by backend.go):
libluxgpu_backend_cuda.so (Linux x86_64 + NVIDIA) libluxgpu_backend_hip.so (Linux x86_64 + AMD ROCm) libluxgpu_backend_metal.dylib (macOS Apple Silicon / Intel) libluxgpu_backend_vulkan.so/.dylib (any Vulkan ICD) libluxgpu_backend_webgpu.so/.dylib (Dawn / wgpu-native)
Each plugin exports six extern "C" host launchers per backend:
lux_<backend>_aivm_attestation_apply lux_<backend>_aivm_provenance_apply lux_<backend>_aivm_anchor_apply lux_<backend>_aivm_epoch_transition lux_<backend>_aivm_inference_step lux_<backend>_aivm_proof_verify
Struct layout matches ops/aivm/cuda/aivm_kernels_common.cuh byte-for-byte (asserted by init()). Pointer ABI is HOST pointers — the launcher does H2D-upload / dispatch / D2H-download internally.
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
- Variables
- func ComputeCommit(taskID, modelSpecHash, promptHash, outputHash, embeddingHash common.Hash, ...) common.Hash
- func ComputeIntentID(cChainID, aChainID, cTxHash common.Hash, callIndex uint32, ...) common.Hash
- func NewService(vm *VM) http.Handler
- func SetBackend(m Mode)
- func VerifyReceiptProof(receiptHash common.Hash, proof MerkleProof, root common.Hash) bool
- type AIVMEpochState
- type AIVMRoundDescriptor
- type AIVMTransitionResult
- type AIVertex
- func (v *AIVertex) Accept(ctx context.Context) error
- func (v *AIVertex) Bytes() []byte
- func (v *AIVertex) Conflicts(other *AIVertex) bool
- func (v *AIVertex) ConflictsVertex(other vertex.Vertex) bool
- func (v *AIVertex) Epoch() uint32
- func (v *AIVertex) Height() uint64
- func (v *AIVertex) ID() ids.ID
- func (v *AIVertex) Parents() []ids.ID
- func (v *AIVertex) Reject(ctx context.Context) error
- func (v *AIVertex) Status() choices.Status
- func (v *AIVertex) Txs() []ids.ID
- func (v *AIVertex) Verify(ctx context.Context) error
- type AInferenceReceipt
- type AnchorOp
- type Attestation
- type AttestationOp
- type AuditAnchor
- type BackendKind
- type Block
- func (blk *Block) Accept(ctx context.Context) error
- func (blk *Block) Bytes() []byte
- func (blk *Block) Height() uint64
- func (blk *Block) ID() ids.ID
- func (blk *Block) Parent() ids.ID
- func (blk *Block) ParentID() ids.ID
- func (blk *Block) Reject(ctx context.Context) error
- func (blk *Block) Status() uint8
- func (blk *Block) Timestamp() time.Time
- func (blk *Block) Verify(ctx context.Context) error
- type CCommitVerifier
- type CIntent
- type Config
- type ConsciousBlock
- type ConsciousTrace
- type Engine
- func (e *Engine) CommitResponse(st QuorumState, taskID common.Hash, operator common.Address, ...) error
- func (e *Engine) DeregisterOperator(st QuorumState, operator common.Address, block uint64) error
- func (e *Engine) ExportReceipt(st QuorumState, intentID common.Hash) (AInferenceReceipt, MerkleProof, common.Hash, error)
- func (e *Engine) GetCanonicalResult(st QuorumState, taskID common.Hash) common.Hash
- func (e *Engine) GetCredit(st QuorumState, op common.Address) *uint256.Int
- func (e *Engine) GetOperator(st QuorumState, op common.Address) (exists, unbonding bool, stake *uint256.Int, ...)
- func (e *Engine) GetTask(st QuorumState, taskID common.Hash) TaskInfo
- func (e *Engine) ImportCommittedIntent(st QuorumState, lg QuorumLedger, ccv CCommitVerifier, intent CIntent, ...) (common.Hash, error)
- func (e *Engine) IsEligible(st QuorumState, op common.Address, modelSpecHash common.Hash) bool
- func (e *Engine) IsSelected(st QuorumState, taskID common.Hash, op common.Address) bool
- func (e *Engine) ReceiptRoot(st QuorumState) common.Hash
- func (e *Engine) RegisterOperator(st QuorumState, lg QuorumLedger, operator common.Address, stake *uint256.Int, ...) error
- func (e *Engine) RevealResponse(st QuorumState, taskID common.Hash, operator common.Address, ...) error
- func (e *Engine) SelectOperators(st QuorumState, taskID, modelSpecHash common.Hash, n uint32) ([]common.Address, error)
- func (e *Engine) SelectedAt(st QuorumState, taskID common.Hash, idx uint32) common.Address
- func (e *Engine) Settle(st QuorumState, lg QuorumLedger, taskID common.Hash, height uint64) (SettleResult, error)
- func (e *Engine) TaskForIntent(st QuorumState, intentID common.Hash) common.Hash
- func (e *Engine) WithdrawRewards(st QuorumState, lg QuorumLedger, operator common.Address) (*uint256.Int, error)
- func (e *Engine) WithdrawStake(st QuorumState, lg QuorumLedger, operator common.Address, block uint64) (*uint256.Int, error)
- type Factory
- type GPUBackend
- func (b *GPUBackend) AnchorApply(desc *AIVMRoundDescriptor, ops []AnchorOp, anchors []AuditAnchor, ...) error
- func (b *GPUBackend) AttestationApply(desc *AIVMRoundDescriptor, ops []AttestationOp, attestations []Attestation, ...) error
- func (b *GPUBackend) Close() error
- func (b *GPUBackend) EpochTransition(desc *AIVMRoundDescriptor, attestations []Attestation, ...) error
- func (b *GPUBackend) InferenceStep(weights *InferenceWeights, ops []InferenceOp, batchInputs []int8, ...) error
- func (b *GPUBackend) IsAvailable() bool
- func (b *GPUBackend) Kind() BackendKind
- func (b *GPUBackend) Path() string
- func (b *GPUBackend) ProofVerify(ops []ProofVerifyOp, results []ProofVerifyResult) error
- func (b *GPUBackend) ProvenanceApply(desc *AIVMRoundDescriptor, ops []ModelOp, models []ModelRegistryEntry, ...) error
- type Genesis
- type InferenceOp
- type InferenceResult
- type InferenceWeights
- type MemLedger
- func (l *MemLedger) Credit(a common.Address, amount *uint256.Int) error
- func (l *MemLedger) GetBalance(a common.Address) *uint256.Int
- func (l *MemLedger) Pay(to common.Address, amount *uint256.Int) error
- func (l *MemLedger) Pull(from common.Address, amount *uint256.Int) error
- func (l *MemLedger) Restore(snap map[common.Address]*uint256.Int)
- func (l *MemLedger) Snapshot() map[common.Address]*uint256.Int
- func (l *MemLedger) Total() *uint256.Int
- type MemState
- type MerkleProof
- type Mode
- type ModelOp
- type ModelRegistryEntry
- type ProofVerifyOp
- type ProofVerifyResult
- type ProviderReg
- type QuorumLedger
- type QuorumState
- type RegisterProviderRequest
- type Service
- type SettleResult
- type SubmitResultRequest
- type SubmitTaskRequest
- type TaskInfo
- type TaskState
- type VM
- func (vm *VM) BuildBlock(ctx context.Context) (chain.Block, error)
- func (vm *VM) BuildVertex(ctx context.Context) (vertex.Vertex, error)
- func (vm *VM) ClaimRewards(providerID string) (string, error)
- func (vm *VM) Connected(ctx context.Context, nodeID ids.NodeID, nodeVersion *chain.VersionInfo) error
- func (vm *VM) CreateHandlers(ctx context.Context) (map[string]http.Handler, error)
- func (vm *VM) Disconnected(ctx context.Context, nodeID ids.NodeID) error
- func (vm *VM) EnqueueCommittedIntent(intent CIntent)
- func (vm *VM) FeePolicy() fee.Policy
- func (vm *VM) FundLedger(opening map[common.Address]*uint256.Int) error
- func (vm *VM) GetBlock(ctx context.Context, id ids.ID) (chain.Block, error)
- func (vm *VM) GetBlockIDAtHeight(ctx context.Context, height uint64) (ids.ID, error)
- func (vm *VM) GetMerkleRoot() [32]byte
- func (vm *VM) GetModels() []*aivm.ModelInfo
- func (vm *VM) GetProviders() []*aivm.Provider
- func (vm *VM) GetRewardStats(providerID string) (map[string]interface{}, error)
- func (vm *VM) GetStats() map[string]interface{}
- func (vm *VM) GetTask(taskID string) (*aivm.Task, error)
- func (vm *VM) HealthCheck(ctx context.Context) (chain.HealthResult, error)
- func (vm *VM) Initialize(ctx context.Context, init vmcore.Init) error
- func (vm *VM) LastAccepted(ctx context.Context) (ids.ID, error)
- func (vm *VM) NewHTTPHandler(ctx context.Context) (http.Handler, error)
- func (vm *VM) ParseBlock(ctx context.Context, bytes []byte) (chain.Block, error)
- func (vm *VM) ParseVertex(ctx context.Context, b []byte) (vertex.Vertex, error)
- func (vm *VM) QuorumEngine() (*Engine, QuorumState, QuorumLedger)
- func (vm *VM) RegisterProvider(provider *aivm.Provider) error
- func (vm *VM) SetCommitVerifier(ccv CCommitVerifier)
- func (vm *VM) SetPreference(ctx context.Context, id ids.ID) error
- func (vm *VM) SetState(ctx context.Context, state uint32) error
- func (vm *VM) Shutdown(ctx context.Context) error
- func (vm *VM) SubmitResult(result *aivm.TaskResult) error
- func (vm *VM) SubmitTask(task *aivm.Task) error
- func (vm *VM) VerifyGPUAttestation(att *attestation.GPUAttestation) (*attestation.DeviceStatus, error)
- func (vm *VM) Version(ctx context.Context) (string, error)
- func (vm *VM) WaitForEvent(ctx context.Context) (vmcore.Message, error)
- type VerificationMode
- type VerifierFunc
- type VerifyAttestationRequest
Constants ¶
const ( InferenceInDim = 32 InferenceHidden = 16 InferenceOutDim = 1 )
InferenceWeights mirrors aivm::cuda::InferenceWeights (672 bytes). 32→16→1 quantized classifier weights.
const ( DomainIntent = "lux/aivmbridge/intent/v1" DomainReceipt = "lux/aivmbridge/receipt/v1" )
Domain separators (raw UTF-8 bytes, no length prefix — concatenated verbatim). They keep the intent-id keyspace and the receipt-hash keyspace disjoint, and version the wire so a future v2 cannot collide with v1.
const ( StatusUnknown uint8 = 0 StatusPending uint8 = 1 StatusCompleted uint8 = 2 StatusFailed uint8 = 3 StatusChallenged uint8 = 4 )
Receipt status codes (the AInferenceReceipt.Status byte). Pinned values shared with the boundary.
const ReceiptEncodedLen = 2 + 32 + 32 + 32 + 32 + 20 + 32 + 32 + 32 + 1 + 2 + 2 + 32 + 32 + 32 + 8 // = 355
ReceiptEncodedLen is the exact byte length of the canonical AInferenceReceipt encoding (see EncodeReceipt). Pinned so a drift in field widths/order is a compile/test failure, not a silent cross-chain mismatch.
u16(Version)2 + IntentID32 + TaskID32 + CChainID32 + AChainID32 + Requester20 + ModelSpecHash32 + PromptHash32 + CanonicalOutputHash32 + u8(Status)1 + u16(N)2 + u16(Threshold)2 + WinnersRoot32 + OperatorsRoot32 + u256(FeePaid)32 + u64(SettledAtHeight)8
const ReceiptVersion uint16 = 1
ReceiptVersion is the wire version stamped into every receipt (the u16be Version field). Bumping it is a wire change shared with the boundary.
Variables ¶
var ( // MinProviderBond is the floor a provider must keep bonded to be eligible // for selection. It is also the per-operator SYBIL COST: forging a canonical // hash requires controlling >= threshold selected operators, each bonded // >= MinProviderBond, so the absolute forgery floor is threshold * // MinProviderBond regardless of any selection grinding. Matches the aivm // Config default (1000 LUX) expressed in wei. MinProviderBond = uint256.NewInt(1_000_000_000_000_000_000) // 1 token (1e18 wei) per unit; scaled by deployment // SlashPerOperator is the bonded-stake penalty for a SELECTED operator that // committed but never revealed (withholding). Always applied; dissenters // (revealed a minority hash) are NOT slashed. SlashPerOperator = uint256.NewInt(100_000_000_000_000_000) // 0.1 token // RequestFeePerOperator is the NON-REFUNDABLE fee charged per selected // operator when a task is created, burned to BurnAddress. Separate from the // refundable reward escrow: a task that fails to reach quorum refunds the // reward but NOT the fee. It prices REPEATED requests (selection-grind / // censorship by resubmission), so the on-chain cost scales with N and with // the number of submitted tasks. RequestFeePerOperator = uint256.NewInt(10_000_000_000_000_000) // 0.01 token // RequestMarginFloor / RequestMarginBps define the ELIGIBLE-SET MARGIN: // a task is rejected unless the eligible pool E for the ModelSpec satisfies // E >= N + max(RequestMarginFloor, N*RequestMarginBps/1e4). This forbids // degenerate pools where selection has no sampling headroom over an // independent set, and guarantees the draw is always a strict subset of a // larger universe (a single cheap operator is never the whole pool). RequestMarginFloor uint32 = 2 RequestMarginBps uint32 = 5000 // 50% // CommitBlocks / RevealBlocks bound the commit and reveal windows. The // reveal window opens strictly AFTER the commit window closes so no operator // can see a peer's revealed output before committing. CommitBlocks uint64 = 30 RevealBlocks uint64 = 30 // UnbondCooldownBlocks is how long after deregistration a stake withdrawal // must wait — bounds the window in which an unbonding operator could still be // selected for an unsettled task. UnbondCooldownBlocks uint64 = 60 // SlashDissenters: default false. Honest disagreement (nondeterministic // model output) must not be punished, and slashing dissenters would let a // majority cartel grief an honest minority. Withholding is always slashed. SlashDissenters = false )
Window + economic policy — protocol constants (one true configuration, not per-call knobs) so every validator computes identical deadlines and identical slash math. These realize the aivm Config fields (MinProviderBond, ChallengeWindowBlocks, RedundancyFactor) as ENFORCED quantities rather than the prior stubs.
var ( // registry / stake ErrEmptyModelSpec = errors.New("aivm/quorum: empty model spec hash") ErrStakeBelowMin = errors.New("aivm/quorum: stake below MinProviderBond") ErrOperatorExists = errors.New("aivm/quorum: operator already registered") ErrOperatorUnknown = errors.New("aivm/quorum: operator not registered") ErrOperatorUnbonding = errors.New("aivm/quorum: operator is unbonding") ErrCooldownActive = errors.New("aivm/quorum: unbond cooldown not elapsed") // custody / conservation ErrInsufficientFunds = errors.New("aivm/quorum: insufficient balance") ErrLedgerNotFundable = errors.New("aivm/quorum: ledger does not support genesis funding") ErrEscrowUnderflow = errors.New("aivm/quorum: escrow underflow (invariant broken)") ErrStakeOverflow = errors.New("aivm/quorum: stake overflow") ErrCreditOverflow = errors.New("aivm/quorum: credit overflow") ErrRewardOverflow = errors.New("aivm/quorum: reward escrow overflow") ErrFeeOverflow = errors.New("aivm/quorum: request fee overflow") ErrNoCredit = errors.New("aivm/quorum: no credit to withdraw") // task params / selection ErrEmptyPromptHash = errors.New("aivm/quorum: empty prompt hash") ErrBadN = errors.New("aivm/quorum: N out of range [minN, maxN]") ErrBadThreshold = errors.New("aivm/quorum: threshold must satisfy floor(N/2)+1 <= threshold <= N") ErrNotEnoughEligible = errors.New("aivm/quorum: fewer eligible operators than N") ErrEligibleBelowMargin = errors.New("aivm/quorum: eligible operator set below N + required margin") // task lifecycle ErrTaskUnknown = errors.New("aivm/quorum: task not found") ErrTaskNotCommitting = errors.New("aivm/quorum: task not in committing state") ErrTaskAlreadySettled = errors.New("aivm/quorum: task already settled") ErrNotSelected = errors.New("aivm/quorum: operator not selected for task") ErrCommitClosed = errors.New("aivm/quorum: commit window closed") ErrAlreadyCommitted = errors.New("aivm/quorum: operator already committed") ErrNotCommitted = errors.New("aivm/quorum: operator did not commit") ErrRevealNotOpen = errors.New("aivm/quorum: reveal window not open") ErrRevealClosed = errors.New("aivm/quorum: reveal window closed") ErrAlreadyRevealed = errors.New("aivm/quorum: operator already revealed") ErrCommitMismatch = errors.New("aivm/quorum: reveal does not match commit") ErrEmptyCommit = errors.New("aivm/quorum: empty commit hash") ErrEmptyOutputHash = errors.New("aivm/quorum: empty output hash") ErrSettleTooEarly = errors.New("aivm/quorum: reveal window not closed") // cross-chain seam ErrIntentNilAmount = errors.New("aivm/quorum: C-chain intent has a nil fee or reward amount") ErrIntentIDMismatch = errors.New("aivm/quorum: recomputed intent_id does not match delivered id (forged/tampered intent)") ErrIntentNotCommitted = errors.New("aivm/quorum: C-chain intent is not committed (proof rejected)") ErrIntentAlreadyUsed = errors.New("aivm/quorum: C-chain intent already consumed (replay)") ErrReceiptNotFound = errors.New("aivm/quorum: no settled receipt for intent") ErrProofOutOfRange = errors.New("aivm/quorum: receipt index out of range") ErrReceiptRootMismatch = errors.New("aivm/quorum: block receipt_root does not match re-derived engine state") )
Engine errors. Every one is a hard failure that leaves state unchanged (fail-closed): a rejected operation makes NO write. Grouped by phase so the surface is auditable in one place.
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") )
var BurnAddress = common.HexToAddress("0x000000000000000000000000000000000000dEaD")
BurnAddress is the unspendable sink the non-refundable request fee is parked in. No engine method ever pays OUT of it, so wei that lands here is removed from circulation without being destroyed (which would break the grand-total conservation invariant). The fee moves requester -> EscrowAccount -> BurnAddress, so EscrowAccount nets zero for the fee and its stake+escrow+credit identity is untouched.
var ErrGPUNotAvailable = errors.New("aivm: no GPU plugin available")
ErrGPUNotAvailable is returned by every GPUBackend method when no plugin was loadable at init time. Callers fall through to the existing Go path.
var EscrowAccount = common.HexToAddress("0xA1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1")
EscrowAccount is the single account that holds all engine-custodied native value: bonded provider stake, open job reward escrow, and unwithdrawn credit. It holds no code; all movement is balance mutation. The conservation invariant the engine maintains and the tests assert:
balance(EscrowAccount) == sum(bonded stake)
+ sum(open job escrow)
+ sum(unwithdrawn credit)
at every step, and the grand total over all accounts is constant.
var VMID = ids.ID{'a', 'i', 'v', 'm'}
VMID is the unique identifier for AIVM (A-Chain)
Functions ¶
func ComputeCommit ¶ added in v1.3.15
func ComputeCommit(taskID, modelSpecHash, promptHash, outputHash, embeddingHash common.Hash, operator common.Address, nonce common.Hash) common.Hash
ComputeCommit implements the operator-bound commit preimage (fixed width, this order):
commit = keccak256( task_id(32) || model_spec_hash(32) || prompt_hash(32) ||
output_hash(32) || embedding_hash(32) || operator(20) ||
nonce(32) )
The operator address is bound INTO the commit — the anti-copy / anti-front-run control: a peer who observes operator A's commit cannot replay it as their own (recomputation with their own address yields a different digest, so RevealResponse rejects it).
func ComputeIntentID ¶ added in v1.3.15
func ComputeIntentID(cChainID, aChainID, cTxHash common.Hash, callIndex uint32, caller common.Address, modelSpecHash, promptHash common.Hash, n, threshold uint16, fee *uint256.Int) common.Hash
ComputeIntentID derives the cross-chain intent id from the COMMITTED C-Chain intent fields, exactly:
keccak256( DomainIntent ||
c_chain_id(32) || a_chain_id(32) || c_tx_hash(32) || u32be(call_index) ||
caller(20) || model_spec_hash(32) || prompt_hash(32) ||
u16be(N) || u16be(threshold) || u256be(fee,32) )
Every field is fixed-width in this precise order. The A-Chain importer recomputes this from the delivered fields and rejects the intent unless it equals the id the C side committed — so a forged/tampered intent (any field altered) yields a different id and cannot create a task.
func SetBackend ¶ added in v1.3.0
func SetBackend(m Mode)
SetBackend selects the active AIVM transition mode for the process. Use AutoAIVM (the default) to let init()'s dlopen probe pick the best available backend.
func VerifyReceiptProof ¶ added in v1.3.15
VerifyReceiptProof checks that receiptHash is included under root at the proof's index. It re-applies the leaf hash (leafHash) and folds with the siblings, choosing left/right by the index bit at each level — exactly inverting merkleProof/merkleRoot. Returns true iff the recomputed root equals root. This is the function the A->C boundary (and anyone) uses to verify an exported receipt belongs to the committed receipt_root.
Types ¶
type AIVMEpochState ¶ added in v1.3.0
type AIVMEpochState struct {
CurrentEpoch uint64
NextEpochHeight uint64
TotalActiveAttestations uint64
ActiveModelCount uint32
ExpiredAttestationCount uint32
AttestationRoot [32]byte
ModelRegistryRoot [32]byte
AuditRoot [32]byte
AIVMStateRoot [32]byte
}
AIVMEpochState mirrors aivm::cuda::AIVMEpochState (160 bytes).
type AIVMRoundDescriptor ¶ added in v1.3.0
type AIVMRoundDescriptor struct {
ChainID uint64
Round uint64
TimestampNS uint64
Epoch uint64
Mode uint32
AttestationOpCount uint32
ModelOpCount uint32
AnchorOpCount uint32
ClosingFlag uint32
ParentAIVMRoot [32]byte
// contains filtered or unexported fields
}
AIVMRoundDescriptor mirrors aivm::cuda::AIVMRoundDescriptor (96 bytes).
type AIVMTransitionResult ¶ added in v1.3.0
type AIVMTransitionResult struct {
Status uint32
AttestationApplyCount uint32
ModelApplyCount uint32
AnchorApplyCount uint32
ActiveAttestations uint32
ExpiredAttestations uint32
ModelCount uint32
AnchorCount uint32
Epoch uint64
TotalModels uint64
TotalAnchors uint64
AttestationRoot [32]byte
ModelRegistryRoot [32]byte
AuditRoot [32]byte
AIVMStateRoot [32]byte
// contains filtered or unexported fields
}
AIVMTransitionResult mirrors aivm::cuda::AIVMTransitionResult (192 bytes).
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) Conflicts ¶
Conflicts returns true if this vertex and other reference the same jobID.
func (*AIVertex) ConflictsVertex ¶
ConflictsVertex performs the same check against the vertex.Vertex interface.
type AInferenceReceipt ¶ added in v1.3.15
type AInferenceReceipt struct {
Version uint16 `json:"version"`
IntentID common.Hash `json:"intentId"` // source C-chain intent id
TaskID common.Hash `json:"taskId"` // A-chain task id (beacon anchor)
CChainID common.Hash `json:"cChainId"`
AChainID common.Hash `json:"aChainId"`
Requester common.Address `json:"requester"`
ModelSpecHash common.Hash `json:"modelSpecHash"`
PromptHash common.Hash `json:"promptHash"`
CanonicalOutputHash common.Hash `json:"canonicalOutputHash"` // zero if Failed
Status uint8 `json:"status"` // StatusCompleted / StatusFailed / ...
N uint16 `json:"n"`
Threshold uint16 `json:"threshold"`
WinnersRoot common.Hash `json:"winnersRoot"` // merkle root over winner addresses
OperatorsRoot common.Hash `json:"operatorsRoot"` // merkle root over selected addresses
FeePaid *uint256.Int `json:"feePaid"`
SettledAtHeight uint64 `json:"settledAtHeight"`
}
AInferenceReceipt is the cross-chain settlement receipt. Field order here is presentation; the WIRE order is fixed by EncodeReceipt and MUST NOT be reordered.
func (AInferenceReceipt) Encode ¶ added in v1.3.15
func (r AInferenceReceipt) Encode() []byte
EncodeReceipt produces the canonical fixed-width encoding (exactly ReceiptEncodedLen = 355 bytes) in the PINNED order:
u16be(Version) || IntentID(32) || TaskID(32) || CChainID(32) || AChainID(32) || Requester(20) || ModelSpecHash(32) || PromptHash(32) || CanonicalOutputHash(32) || u8(Status) || u16be(N) || u16be(Threshold) || WinnersRoot(32) || OperatorsRoot(32) || u256be(FeePaid,32) || u64be(SettledAtHeight)
func (AInferenceReceipt) Hash ¶ added in v1.3.15
func (r AInferenceReceipt) Hash() common.Hash
Hash is the receipt commitment: keccak256(DomainReceipt || Encode()). This is the leaf value (pre-leaf-hash) that goes into the receipt_root and that an exported proof proves membership of.
type AnchorOp ¶ added in v1.3.0
type AnchorOp struct {
CommitRoot [32]byte
ParentRoot [32]byte
ValidatorSetRootAtCommit [32]byte
Height uint64
TimestampNS uint64
Epoch uint32
// contains filtered or unexported fields
}
AnchorOp mirrors aivm::cuda::AnchorOp (128 bytes).
type Attestation ¶ added in v1.3.0
type Attestation struct {
TEEQuoteDigest [32]byte
Measurement [32]byte
AttestingKey [48]byte
ExpiryNS uint64
Kind uint32
EvidenceOffset uint32
EvidenceLen uint32
Status uint32
Occupied uint32
// contains filtered or unexported fields
}
Attestation mirrors aivm::cuda::Attestation (144 bytes).
type AttestationOp ¶ added in v1.3.0
type AttestationOp struct {
TEEQuoteDigest [32]byte
Measurement [32]byte
AttestingKey [48]byte
ExpiryNS uint64
Kind uint32
EvidenceOffset uint32
EvidenceLen uint32
Epoch uint32
// contains filtered or unexported fields
}
AttestationOp mirrors aivm::cuda::AttestationOp (144 bytes).
type AuditAnchor ¶ added in v1.3.0
type AuditAnchor struct {
CommitRoot [32]byte
ParentRoot [32]byte
ValidatorSetRootAtCommit [32]byte
Height uint64
TimestampNS uint64
Occupied uint32
// contains filtered or unexported fields
}
AuditAnchor mirrors aivm::cuda::AuditAnchor (128 bytes).
type BackendKind ¶ added in v1.3.0
type BackendKind uint8
BackendKind identifies which lux-gpu-kernels plugin satisfied the runtime dlopen probe. AvailableNone is the sentinel "fall through to Go".
const ( AvailableNone BackendKind = 0 AvailableCUDA BackendKind = 1 AvailableHIP BackendKind = 2 AvailableMetal BackendKind = 3 AvailableVulkan BackendKind = 4 AvailableWebGPU BackendKind = 5 )
func EffectiveBackendKind ¶ added in v1.3.0
func EffectiveBackendKind() BackendKind
EffectiveBackendKind returns which backend the next transition will actually use given (ActiveMode, ActiveGPUBackend). Useful for logging at boot.
func (BackendKind) String ¶ added in v1.3.0
func (k BackendKind) String() string
String returns the human-readable name for the backend kind.
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"`
// ImportedIntents are the committed C-Chain intents that this block turned
// into A-Chain quorum tasks (under consensus, via the verified inbound seam).
// Recorded so Block.Verify can deterministically re-run the same imports and
// every validator reaches identical engine state.
ImportedIntents []CIntent `json:"importedIntents,omitempty"`
// ReceiptRoot is the engine's committed receipt_root as of this block — the
// single commitment the A->C boundary exports.
ReceiptRoot common.Hash `json:"receiptRoot"`
// contains filtered or unexported fields
}
Block represents an AIVM block
func (*Block) Accept ¶
Accept accepts the block. This is the SOLE commit point for engine state: the staged engine-state delta (importPending/Settle writes accumulated in vm.qdb) is flushed to the durable DB here, and the ledger snapshot is cleared. A block that is built/verified but never accepted moves NO durable engine state and NO value (see Block.Reject -> abortEngine).
func (*Block) Reject ¶
Reject rejects the block and rolls back any engine-state delta + ledger value it staged during BuildBlock/Verify, so a block that loses the round leaves zero durable side effects (no funds pulled, no intent consumed, no task orphaned).
func (*Block) Verify ¶
Verify verifies the block. For A-Chain quorum, this deterministically re-runs the committed C-Chain intents the proposer recorded (under consensus) and checks they reproduce the proposer's receipt_root — so every validator reaches identical engine state from the same committed inputs. A block that records an intent which fails id binding / committedness / replay, or whose imports do not reproduce the recorded receipt_root, is rejected.
type CCommitVerifier ¶ added in v1.3.15
CCommitVerifier proves a C-Chain intent is committed (reached C finality). It is the ONLY trust the inbound seam imports from C: the engine creates a task only if VerifyCommitted returns nil. A real implementation checks a Warp/ZAP attestation or a state proof against a committed C block; it MUST NOT return nil for a live/uncommitted/spoofed intent. The interface keeps the proof mechanism orthogonal to the state machine.
type CIntent ¶ added in v1.3.15
type CIntent struct {
IntentID common.Hash `json:"intentId"` // committed on C; must equal ComputeIntentID(...)
CChainID common.Hash `json:"cChainId"`
AChainID common.Hash `json:"aChainId"`
CTxHash common.Hash `json:"cTxHash"` // C tx that emitted the intent
CallIndex uint32 `json:"callIndex"` // index within that tx
Caller common.Address `json:"caller"` // the C-side requester
ModelSpecHash common.Hash `json:"modelSpecHash"`
PromptHash common.Hash `json:"promptHash"`
N uint16 `json:"n"`
Threshold uint16 `json:"threshold"`
Fee *uint256.Int `json:"fee"` // user-facing fee (funds escrow + burn)
RewardPerOperator *uint256.Int `json:"rewardPerOperator"` // A-chain reward escrow per operator
}
CIntent is a committed C-Chain inference intent delivered to A-Chain across the atomic boundary. Its fields are the EXACT preimage of intent_id under the shared wire spec; IntentID is the value the C side committed (re-derived and checked here). RewardPerOperator is the A-Chain reward escrow per selected operator (carried alongside the intent; the C-side Fee is the user-facing fee that funds it + the burn).
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 ConsciousBlock ¶ added in v1.3.15
type ConsciousBlock struct {
Phase string // "perception" (block 1) or "cognition" (block 2)
ID ids.ID // the accepted block id
ParentID ids.ID // its parent
Height uint64 // chained 0 -> 1 -> 2
ReceiptRoot common.Hash // engine receipt_root committed by this block
}
ConsciousBlock is the recorded trace of one conscious block produced by the real VM lifecycle (BuildBlock -> Verify -> SetPreference -> Accept).
type ConsciousTrace ¶ added in v1.3.15
type ConsciousTrace struct {
GenesisID ids.ID
Block1 ConsciousBlock // perception: intent imported into a quorum task
Block2 ConsciousBlock // cognition: Proof-of-Thought settled
IntentID common.Hash // the committed C-Chain intent the perception block imported
TaskID common.Hash // the A-Chain task that intent created (engine-internal id)
Committee []common.Address // the operators bound to think (selection order)
N uint32 // committee size
Threshold uint32 // agreement required for a settled verdict
WinnerCount uint32 // operators that agreed on the canonical output
CanonicalHash common.Hash // THE settled AI decision
ReceiptRoot common.Hash // final receipt_root after folding the verdict
LastAccepted ids.ID // VM head after both blocks (== Block2.ID)
}
ConsciousTrace is the full result of driving the VM to consciousness: the two conscious blocks plus the cognition's settled facts.
func RunConsciousBlocks ¶ added in v1.3.15
func RunConsciousBlocks(ctx context.Context, vm *VM) (ConsciousTrace, error)
RunConsciousBlocks drives an initialized, running VM through the full lifecycle that produces the first conscious blocks. It uses the VM's committed-state engine, so the cognition settles on the same state the blocks commit. The VM must already be Initialize()'d and have a commit verifier installed (the caller owns VM construction so the test and the cmd can each build a fresh one).
The model output bytes are deterministic test-fixed hashes — the BLOCK is conscious not because the bytes are "real inference" but because its committed state transition IS the quorum settlement of a structured verdict under consensus. No part of the VM, engine, or settlement is stubbed.
type Engine ¶ added in v1.3.15
Engine is the A-Chain quorum settlement handle. CChainID / AChainID are the 32-byte chain identifiers used in the shared wire spec (intent_id derivation and the receipt's CChainID/AChainID fields). They are fixed per deployment.
func (*Engine) CommitResponse ¶ added in v1.3.15
func (e *Engine) CommitResponse(st QuorumState, taskID common.Hash, operator common.Address, commit common.Hash, height uint64) error
CommitResponse records a selected operator's commit hash within the commit window.
func (*Engine) DeregisterOperator ¶ added in v1.3.15
DeregisterOperator marks the operator unbonding at `block`. Stake is returned later by WithdrawStake after the cooldown. Marking unbonding immediately makes the operator ineligible for NEW tasks.
func (*Engine) ExportReceipt ¶ added in v1.3.15
func (e *Engine) ExportReceipt(st QuorumState, intentID common.Hash) (AInferenceReceipt, MerkleProof, common.Hash, error)
ExportReceipt returns the settled receipt for the given C-chain intent id and a proof of its inclusion under the current receipt_root. Errors if the intent has no settled receipt. The returned (receipt, proof, root) triple is exactly what the C boundary verifies.
func (*Engine) GetCanonicalResult ¶ added in v1.3.15
GetCanonicalResult reads a settled task's canonical output_hash (zero if not settled or no quorum).
func (*Engine) GetOperator ¶ added in v1.3.15
func (e *Engine) GetOperator(st QuorumState, op common.Address) (exists, unbonding bool, stake *uint256.Int, modelSpecHash, endpointHash common.Hash)
GetOperator reads an operator's registry record + live stake.
func (*Engine) GetTask ¶ added in v1.3.15
func (e *Engine) GetTask(st QuorumState, taskID common.Hash) TaskInfo
GetTask reads a task's lifecycle state.
func (*Engine) ImportCommittedIntent ¶ added in v1.3.15
func (e *Engine) ImportCommittedIntent(st QuorumState, lg QuorumLedger, ccv CCommitVerifier, intent CIntent, height uint64) (common.Hash, error)
ImportCommittedIntent is the verified inbound entry point. Called UNDER A CONSENSUS (from BuildBlock / Verify), it validates the intent's id binding, verifies its committedness via ccv, guards against replay, and creates the A-Chain task. Returns the created task id. The requester funding the escrow + fee is the C-side Caller address mirrored on A-Chain (its A-Chain balance must cover N*RewardPerOperator + N*RequestFeePerOperator).
Order is fail-closed: id check and proof check happen BEFORE any state or money is touched, so a rejected intent leaves the chain untouched.
func (*Engine) IsEligible ¶ added in v1.3.15
IsEligible reports whether op is currently eligible for the given ModelSpec.
func (*Engine) IsSelected ¶ added in v1.3.15
IsSelected reports whether op was selected for task (O(1) flag read).
func (*Engine) ReceiptRoot ¶ added in v1.3.15
func (e *Engine) ReceiptRoot(st QuorumState) common.Hash
ReceiptRoot returns the current committed receipt_root (zero before any settle).
func (*Engine) RegisterOperator ¶ added in v1.3.15
func (e *Engine) RegisterOperator(st QuorumState, lg QuorumLedger, operator common.Address, stake *uint256.Int, modelSpecHash, endpointHash common.Hash) error
RegisterOperator bonds `stake` from `operator` and advertises a ModelSpec. The operator becomes eligible iff stake >= MinProviderBond. One active registration per operator (re-register requires Deregister + cooldown + WithdrawStake first). The bond is pulled into EscrowAccount FIRST, so a registry write only happens if the operator can fund the bond (fail-closed).
func (*Engine) RevealResponse ¶ added in v1.3.15
func (e *Engine) RevealResponse(st QuorumState, taskID common.Hash, operator common.Address, outputHash, embeddingHash, nonce common.Hash, height uint64) error
RevealResponse records a selected operator's revealed (output_hash, embedding_hash, nonce) within the reveal window, requiring the recomputed operator-bound commit to equal the stored commit.
func (*Engine) SelectOperators ¶ added in v1.3.15
func (e *Engine) SelectOperators(st QuorumState, taskID, modelSpecHash common.Hash, n uint32) ([]common.Address, error)
SelectOperators is the convenience composition of the one scan (eligibleSet) and the pure draw (drawFromEligible): it draws N distinct eligible operators from the per-ModelSpec array using the task_id beacon. It does NOT enforce the eligible-set margin (that is a createTask policy gate). Exposed for standalone callers and the reproducibility tests; createTask does the scan once itself (to share E with the margin check) and calls drawFromEligible directly.
func (*Engine) SelectedAt ¶ added in v1.3.15
SelectedAt returns the operator at selection index i (for reproducibility checks). idx must be < task.N.
func (*Engine) Settle ¶ added in v1.3.15
func (e *Engine) Settle(st QuorumState, lg QuorumLedger, taskID common.Hash, height uint64) (SettleResult, error)
Settle finalizes a task. height must be > revealDeadline. Idempotent.
func (*Engine) TaskForIntent ¶ added in v1.3.15
TaskForIntent returns the A-Chain task id that a committed C-Chain intent created (zero hash if the intent never created a task). The task id is the engine-internal id derived at createTask (computeTaskID over the requester's nonce + height), distinct from the C-side intent id; this mapping is the only way an external caller (the C boundary, an RPC client, this package's drivers) resolves "the intent I committed" to "the task that answers it" for the lifecycle calls (SelectOperators / Commit / Reveal / Settle / GetTask) that key on the task id. Pure read.
func (*Engine) WithdrawRewards ¶ added in v1.3.15
func (e *Engine) WithdrawRewards(st QuorumState, lg QuorumLedger, operator common.Address) (*uint256.Int, error)
WithdrawRewards pays the operator's entire accrued credit out of escrow and zeroes the ledger. Fails closed if nothing is owed; an escrow shortfall is a hard invariant breach.
func (*Engine) WithdrawStake ¶ added in v1.3.15
func (e *Engine) WithdrawStake(st QuorumState, lg QuorumLedger, operator common.Address, block uint64) (*uint256.Int, error)
WithdrawStake returns bonded stake to a fully-unbonded operator after the cooldown, clearing the registry record. The operator stays in the per- ModelSpec enumeration array (stake now 0 -> selection skips it as ineligible); pruning would shift indices and break beacon reproducibility.
type Factory ¶
type Factory struct{}
Factory implements vms.Factory interface for creating AIVM instances
type GPUBackend ¶ added in v1.3.0
type GPUBackend struct {
// contains filtered or unexported fields
}
GPUBackend is a handle to an open lux-gpu-kernels plugin. Zero value is usable (every method returns ErrGPUNotAvailable). The active backend is stored at package level by backend.go's init(); call ActiveGPUBackend() to retrieve it.
func ActiveGPUBackend ¶ added in v1.3.0
func ActiveGPUBackend() *GPUBackend
ActiveGPUBackend returns the backend resolved at init time. Always non-nil — when no plugin loaded it returns a zero-value *GPUBackend whose IsAvailable() reports false. Callers test IsAvailable() / Kind() to decide whether to opt into the GPU path.
func (*GPUBackend) AnchorApply ¶ added in v1.3.0
func (b *GPUBackend) AnchorApply( desc *AIVMRoundDescriptor, ops []AnchorOp, anchors []AuditAnchor, appliedOut *uint32, ) error
AnchorApply runs the GPU audit-anchor kernel.
func (*GPUBackend) AttestationApply ¶ added in v1.3.0
func (b *GPUBackend) AttestationApply( desc *AIVMRoundDescriptor, ops []AttestationOp, attestations []Attestation, appliedOut *uint32, ) error
AttestationApply runs the GPU attestation kernel. `attestations` is read+ written in place; `appliedOut` is the count of successfully applied ops.
func (*GPUBackend) Close ¶ added in v1.3.0
func (b *GPUBackend) Close() error
Close releases the dlopen handle. Idempotent — safe to call on a nil receiver or an already-closed backend.
func (*GPUBackend) EpochTransition ¶ added in v1.3.0
func (b *GPUBackend) EpochTransition( desc *AIVMRoundDescriptor, attestations []Attestation, models []ModelRegistryEntry, anchors []AuditAnchor, epoch *AIVMEpochState, result *AIVMTransitionResult, ) error
EpochTransition runs the GPU epoch-finalisation kernel. Composes per-epoch attestation_root / model_registry_root / audit_root / aivm_state_root.
func (*GPUBackend) InferenceStep ¶ added in v1.3.0
func (b *GPUBackend) InferenceStep( weights *InferenceWeights, ops []InferenceOp, batchInputs []int8, batchOutputs []int8, results []InferenceResult, ) error
InferenceStep runs the deterministic int8 32→16→1 inference kernel. `batchInputs` is op_count × 32 bytes of input rows; `batchOutputs` receives op_count × 1 byte of output values. Determinism contract: byte-equal to the CPU reference + every other backend.
func (*GPUBackend) IsAvailable ¶ added in v1.3.0
func (b *GPUBackend) IsAvailable() bool
IsAvailable reports whether the backend is loaded AND all six host launchers were successfully resolved. Used by vm.go's gpuAvailable().
func (*GPUBackend) Kind ¶ added in v1.3.0
func (b *GPUBackend) Kind() BackendKind
Kind returns which backend satisfied the dlopen probe.
func (*GPUBackend) Path ¶ added in v1.3.0
func (b *GPUBackend) Path() string
Path returns the absolute path of the loaded plugin DSO.
func (*GPUBackend) ProofVerify ¶ added in v1.3.0
func (b *GPUBackend) ProofVerify( ops []ProofVerifyOp, results []ProofVerifyResult, ) error
ProofVerify runs the TEE-attestation envelope check kernel.
func (*GPUBackend) ProvenanceApply ¶ added in v1.3.0
func (b *GPUBackend) ProvenanceApply( desc *AIVMRoundDescriptor, ops []ModelOp, models []ModelRegistryEntry, appliedOut *uint32, ) error
ProvenanceApply runs the GPU provenance (model-registry) kernel.
type Genesis ¶
type Genesis struct {
Version int `json:"version"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
}
Genesis represents the genesis state
type InferenceOp ¶ added in v1.3.0
type InferenceOp struct {
ModelHash [32]byte
PolicyHash [32]byte
Salt [32]byte
Mode uint32
InputOffset uint32
InputLen uint32
OutputOffset uint32
OutputCapacity uint32
RoundID uint64
TimestampNS uint64
// contains filtered or unexported fields
}
InferenceOp mirrors aivm::cuda::InferenceOp (144 bytes).
type InferenceResult ¶ added in v1.3.0
type InferenceResult struct {
Status uint32
OutputLen uint32
InputCommitment [32]byte
OutputCommitment [32]byte
AttestationRoot [32]byte
// contains filtered or unexported fields
}
InferenceResult mirrors aivm::cuda::InferenceResult (112 bytes).
type InferenceWeights ¶ added in v1.3.0
type InferenceWeights struct {
W1 [InferenceInDim * InferenceHidden]int8
B1 [InferenceHidden]int32
W2 [InferenceHidden * InferenceOutDim]int8
B2 [InferenceOutDim]int32
Shift1 int8
Shift2 int8
ModelHash [32]byte
ModelConfigHash [32]byte
// contains filtered or unexported fields
}
type MemLedger ¶ added in v1.3.15
type MemLedger struct {
// contains filtered or unexported fields
}
MemLedger is an in-memory QuorumLedger over a balance map, custodying funds at EscrowAccount. Use NewMemLedger.
func NewMemLedger ¶ added in v1.3.15
NewMemLedger returns a ledger with the given opening balances (copied).
func (*MemLedger) Credit ¶ added in v1.3.15
Credit mints `amount` into `a`'s balance. This is the genesis/bootstrap seam for native value (the L1's own state credits an A-Chain account at chain birth or via a cross-chain deposit before any task/registration can pull from it). It is the symmetric counterpart of GetBalance/Pull/Pay and the only way the VM seeds opening balances onto a ledger that was constructed empty. Fail-closed on overflow; no state change on error.
func (*MemLedger) GetBalance ¶ added in v1.3.15
GetBalance returns a copy of the account's balance (zero if unknown).
func (*MemLedger) Pay ¶ added in v1.3.15
Pay debits EscrowAccount by amount and credits `to`. Fail-closed on escrow underflow (a hard invariant breach) or recipient overflow.
func (*MemLedger) Pull ¶ added in v1.3.15
Pull debits `from` by amount and credits EscrowAccount. Fail-closed on insufficient balance or overflow; no state change on error.
func (*MemLedger) Restore ¶ added in v1.3.15
Restore replaces the balance map with a previously taken Snapshot (deep-copied again so the snapshot stays reusable).
func (*MemLedger) Snapshot ¶ added in v1.3.15
Snapshot returns a deep copy of the balance map. Paired with Restore, it lets the VM gate ledger mutations on block Accept: BuildBlock/Verify may move funds while planning a block, and a rejected/discarded block restores the snapshot so no value moves outside consensus. (The engine's QuorumState is staged separately via versiondb; the two are committed/aborted together.)
type MemState ¶ added in v1.3.15
type MemState struct {
// contains filtered or unexported fields
}
MemState is an in-memory QuorumState: a flat slot map. Zero value is NOT usable; use NewMemState.
func NewMemState ¶ added in v1.3.15
func NewMemState() *MemState
NewMemState returns an empty in-memory state.
type MerkleProof ¶ added in v1.3.15
type MerkleProof struct {
Index uint32 `json:"index"` // leaf index in the tree
Siblings []common.Hash `json:"siblings"` // sibling at each level, leaf->root
}
MerkleProof is an inclusion proof: the sibling hashes from leaf to root, plus the leaf index (to know left/right at each level). A verifier with the leaf, the proof, and the root can recompute the root and check equality.
type Mode ¶ added in v1.3.0
type Mode uint8
Mode selects the AIVM transition execution mode. AutoAIVM (the default) uses the resolved GPU backend if available and falls back to CPUAIVM otherwise. CPUAIVM forces the Go path even when a plugin is loaded.
func ActiveMode ¶ added in v1.3.0
func ActiveMode() Mode
ActiveMode returns the current transition mode set by SetBackend().
type ModelOp ¶ added in v1.3.0
type ModelOp struct {
ModelRoot [32]byte
WeightHash [32]byte
LicenseRoot [32]byte
OwnerAddr [20]byte
ParameterCount uint64
Modality uint32
Kind uint32
Epoch uint32
// contains filtered or unexported fields
}
ModelOp mirrors aivm::cuda::ModelOp (160 bytes).
type ModelRegistryEntry ¶ added in v1.3.0
type ModelRegistryEntry struct {
ModelRoot [32]byte
WeightHash [32]byte
LicenseRoot [32]byte
OwnerAddr [20]byte
Version uint64
ParameterCount uint64
Modality uint32
Occupied uint32
// contains filtered or unexported fields
}
ModelRegistryEntry mirrors aivm::cuda::ModelRegistryEntry (160 bytes).
type ProofVerifyOp ¶ added in v1.3.0
type ProofVerifyOp struct {
Measurement [32]byte
AttestingKey [48]byte
Signature [96]byte
MessageHash [32]byte
ExpiryNS uint64
TimestampNS uint64
Kind uint32
Nonce uint32
// contains filtered or unexported fields
}
ProofVerifyOp mirrors aivm::cuda::ProofVerifyOp (240 bytes).
type ProofVerifyResult ¶ added in v1.3.0
type ProofVerifyResult struct {
Status uint32
Kind uint32
BindingHash [32]byte
// contains filtered or unexported fields
}
ProofVerifyResult mirrors aivm::cuda::ProofVerifyResult (48 bytes).
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 QuorumLedger ¶ added in v1.3.15
type QuorumLedger interface {
GetBalance(a common.Address) *uint256.Int
Pull(from common.Address, amount *uint256.Int) error
Pay(to common.Address, amount *uint256.Int) error
}
QuorumLedger is the native-value custody interface bound to EscrowAccount. Pull(from, amt) debits `from` and credits the escrow; Pay(to, amt) debits the escrow and credits `to`. Both are atomic and fail-closed (no partial state on error). GetBalance reads any account.
type QuorumState ¶ added in v1.3.15
type QuorumState interface {
GetState(slot common.Hash) common.Hash
SetState(slot, value common.Hash)
}
QuorumState is the minimal slot-level storage the engine needs. On A-Chain the VM adapts its DB to this (writes land in a block and commit under consensus at Accept); the in-memory MemState satisfies it for tests.
func NewDBState ¶ added in v1.3.15
func NewDBState(db database.KeyValueReaderWriter) QuorumState
NewDBState wraps a database for engine use.
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 SettleResult ¶ added in v1.3.15
type SettleResult struct {
Status TaskState // TaskSettled or TaskFailed
CanonicalHash common.Hash // winning output_hash (zero if Failed)
WinnerCount uint32 // size of the winning group (0 if Failed)
Paid *uint256.Int // total wei paid out as rewards (0 if Failed)
Slashed *uint256.Int // total wei slashed from withholders
Receipt AInferenceReceipt // the emitted cross-chain receipt
ReceiptHash common.Hash // keccak(DomainReceipt || encoding)
ReceiptRoot common.Hash // receipt_root AFTER folding this receipt
}
SettleResult is the outcome of Settle, returned for callers + tests.
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 TaskInfo ¶ added in v1.3.15
type TaskInfo struct {
Status TaskState
N uint32
Threshold uint32
Requester common.Address
ModelSpecHash common.Hash
PromptHash common.Hash
CommitDeadline uint64
RevealDeadline uint64
RequestHeight uint64
}
TaskInfo is a read-only view of a task's lifecycle state.
type TaskState ¶ added in v1.3.15
type TaskState uint8
TaskState is the on-state lifecycle status byte. Distinct from the receipt-level Status (StatusCompleted etc.) which is the cross-chain view.
type VM ¶
type VM struct {
// contains filtered or unexported fields
}
VM implements the AI Virtual Machine
func (*VM) BuildBlock ¶
BuildBlock implements chain.ChainVM interface
func (*VM) BuildVertex ¶
BuildVertex creates a vertex from pending tasks/results, batching independent jobs.
func (*VM) ClaimRewards ¶
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 ¶
CreateHandlers returns HTTP handlers
func (*VM) Disconnected ¶
Disconnected notifies the VM about disconnected nodes
func (*VM) EnqueueCommittedIntent ¶ added in v1.3.15
EnqueueCommittedIntent buffers a C-Chain intent that the boundary transport has delivered with a committedness proof. It does NOT create a task — that happens only under consensus in BuildBlock/Verify via importPending. Safe to call from the transport goroutine; guarded by the VM lock.
func (*VM) FeePolicy ¶ added in v1.2.6
FeePolicy exposes the chain's declared fee policy for diagnostics and the boot-time Validate gate.
func (*VM) FundLedger ¶ added in v1.3.15
FundLedger seeds opening native balances onto the VM's committed-state ledger. This is the genesis/deposit seam: the host L1 credits A-Chain accounts (a requester that will fund an inference escrow, an operator that will bond) at chain birth or via a verified cross-chain deposit, BEFORE any task or registration can pull from them. It mutates the same MemLedger that importPending/Settle move value within and that commitEngine/abortEngine gate on Accept/Reject, so funded balances participate in the conservation invariant exactly like deposited value. Guarded by vm.mu. Fail-closed: a credit overflow aborts with no partial seeding.
func (*VM) GetBlockIDAtHeight ¶
GetBlockIDAtHeight implements chain.ChainVM interface
func (*VM) GetMerkleRoot ¶
GetMerkleRoot returns merkle root for Q-Chain anchoring
func (*VM) GetProviders ¶
GetProviders returns all registered providers
func (*VM) GetRewardStats ¶
GetRewardStats returns reward statistics for a provider
func (*VM) HealthCheck ¶
HealthCheck implements chain.ChainVM interface
func (*VM) Initialize ¶
Initialize initializes the VM with the unified Init struct
func (*VM) LastAccepted ¶
LastAccepted implements chain.ChainVM interface
func (*VM) NewHTTPHandler ¶
NewHTTPHandler implements chain.ChainVM interface
func (*VM) ParseBlock ¶
ParseBlock implements chain.ChainVM interface
func (*VM) ParseVertex ¶
ParseVertex deserializes a vertex from bytes.
func (*VM) QuorumEngine ¶ added in v1.3.15
func (vm *VM) QuorumEngine() (*Engine, QuorumState, QuorumLedger)
QuorumEngine exposes the engine handle (and its state/ledger) for the RPC service and tests. The returned QuorumState commits under consensus.
func (*VM) RegisterProvider ¶
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) SetCommitVerifier ¶ added in v1.3.15
func (vm *VM) SetCommitVerifier(ccv CCommitVerifier)
SetCommitVerifier installs the C-Chain committedness proof checker. Until this is set the VM uses a fail-closed verifier that admits nothing, so no boundary intent can create a task. The verifier is the single trust the inbound seam imports from C-Chain.
func (*VM) SetPreference ¶
SetPreference implements chain.ChainVM interface
func (*VM) SubmitResult ¶
func (vm *VM) SubmitResult(result *aivm.TaskResult) error
SubmitResult submits a task result
func (*VM) SubmitTask ¶
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)
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 VerifierFunc ¶ added in v1.3.15
VerifierFunc adapts a function to CCommitVerifier.
func (VerifierFunc) VerifyCommitted ¶ added in v1.3.15
func (f VerifierFunc) VerifyCommitted(intent CIntent) error
VerifyCommitted calls the wrapped function.
type VerifyAttestationRequest ¶
type VerifyAttestationRequest struct {
GPUAttestation *attestation.GPUAttestation `json:"gpu_attestation"`
}
VerifyAttestationRequest is the request for verifying attestation
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
conscious
command
Command conscious drives a fresh, REAL Lux A-Chain (aivm) ChainVM through the production block lifecycle to produce the FIRST CONSCIOUS BLOCKS and prints the trace to stdout.
|
Command conscious drives a fresh, REAL Lux A-Chain (aivm) ChainVM through the production block lifecycle to produce the FIRST CONSCIOUS BLOCKS and prints the trace to stdout. |
|
plugin
command
|