Skip to main content

AI Engine

QoreChain integrates AI capabilities at multiple levels of the protocol stack through the x/ai module. The on-chain layer provides deterministic heuristic-based analysis suitable for consensus-critical operations, while an off-chain sidecar extends capabilities with deep learning models for advisory and developer tooling.

Three-Layer Architecture

The QCAI (QoreChain AI) engine operates across three layers:

LayerScopeExecutionDeterministic
Consensus LevelBlock production, parameter tuningOn-chain (x/rlconsensus)Yes
Network LevelTransaction routing, fraud detection, fee optimizationOn-chain (x/ai)Yes
Application LevelContract generation, auditing, deep analysisOff-chain (sidecar)No

The consensus level is documented separately in the PRISM Consensus Engine. This page covers the network and application levels.

Transaction Router

The AI-enhanced router selects optimal validators and routes for each transaction using weighted multi-factor scoring.

Optimization Formula

OptimalRoute = argmin_r( alpha * Latency(r) + beta * Cost(r) + gamma * Security(r)^-1 )
WeightSymbolDefaultDescription
Latencyalpha0.4Normalized response time (0=best, 1=worst). 0ms maps to 0.0, 1000ms maps to 1.0.
Costbeta0.3Current load percentage as a proxy for cost.
Securitygamma0.3Inverse of reputation score. Higher reputation yields a lower (better) score.

The router maintains a metrics cache (default TTL: 30 seconds) with per-validator performance data including average latency, uptime percentage, load percentage, and reputation score. When cached metrics are unavailable, the system falls back to the heuristic router.

Routing Confidence

Confidence scales with the number of validators with available metrics:

Validators with MetricsConfidence
>= 100.95
>= 50.85
>= 20.75
10.60

Fraud Detection

The fraud detector implements a six-layer detection pipeline that analyzes each transaction against recent history using statistical methods.

Detection Layers

LayerDetectorMethodTrigger Threshold
1Isolation ForestStatistical Z-score across amount, gas, and sender frequency featuresAnomaly score > 0.7
2Sequence AnalyzerDetects alternating send/receive patterns (wash trading)> 3 alternating transfers between same pair
3Sybil DetectorTracks new unique addresses; flags spikes in new senders> 30% of recent transactions from new addresses
4DDoS DetectorMonitors per-sender transaction frequency> 100 transactions per minute from a single sender
5Flash Loan DetectorIdentifies borrow-manipulate-repay patterns within a single block>= 3 transactions in same block with > 10x amount variance
6Exploit DetectorFlags abnormal gas consumption in contract calls> 5x average gas for the same transaction type

Threat Classification

Confidence RangeThreat Level
>= 0.9Critical
>= 0.7High
>= 0.5Medium
>= 0.3Low
< 0.3None

Response Actions

Threat LevelConfidenceAction
Critical> 0.8circuit_break — Pause specific contract executions
Critical<= 0.8rate_limit — Temporarily reduce TX acceptance from source
High> 0.7rate_limit
High<= 0.7alert — Emit event for validators and operators
MediumAnyalert
Low / NoneAnyallow

When an action other than allow is triggered, a fraud investigation record is created with a unique ID (format: INV-{timestamp}-{txhash_prefix}).

Fee Optimizer

The fee optimizer predicts network congestion and suggests optimal fees for desired confirmation times using exponential moving average (EMA) congestion tracking.

Congestion Prediction

  • EMA smoothing factor (alpha): 0.2
  • History window: 100 blocks
  • Trend analysis: Compares the most recent 5 blocks against the prior 5 blocks to detect congestion trends, then projects forward with 50% dampening.

Urgency Tiers

UrgencyBase MultiplierEstimated Confirmation
fast2.0x1-2 blocks
normal1.0x3-5 blocks
slow0.5x6-10 blocks

The final fee incorporates a congestion multiplier (1.0x at 0% congestion, up to 5.0x at 100% congestion) and a trend premium when predicted congestion exceeds current congestion. The minimum fee floor is 500 uqor (0.0005 QOR).

Network Optimizer

The network optimizer continuously monitors performance metrics and generates governance parameter recommendations using a multi-objective reward function.

Reward Function

R(s, a, s') = alpha * DeltaPerformance + beta * DeltaLatency + gamma * DeltaEnergy - delta * StabilityPenalty
WeightValueObjective
alpha0.35Performance improvement
beta0.30Latency reduction
gamma0.15Energy/resource savings
delta0.20Stability preservation

Recommendation Types

The optimizer generates recommendations for:

  • Block gas limit: Increase when utilization > 80%, decrease when < 20%
  • Minimum commission rate: Lower when validator count is below 5
  • Maximum validators: Increase when block times are healthy and >= 10 validators active
  • Block time target: Alert when average block time exceeds 8 seconds

Each recommendation includes the current value, suggested value, expected impact, confidence score, and reasoning.

AI Sidecar

The QCAI Sidecar extends on-chain AI with off-chain deep learning models backed by the QCAI Backend. The sidecar is optional and non-consensus-critical, and is reached over an internal gRPC interface.

Capabilities

CapabilityDescription
Contract GenerationGenerates smart contracts from natural language specifications across 17 platforms
Contract AuditingDeep security analysis of smart contract code
Deep Fraud AnalysisExtended fraud investigation using trained models (supplements on-chain heuristics)
Network AdviceAdvanced parameter optimization recommendations

Models

Model NameUse Case
QCAI FastLow-latency responses for fee estimation and routing
QCAI BalancedDeeper analysis for auditing and fraud investigation

The sidecar runs as an independent off-chain service so that deep-learning workloads never block or influence consensus-critical execution.

EVM Precompiles

Two precompiled contracts expose on-chain AI capabilities to EVM smart contracts:

PrecompileAddressDescription
aiRiskScore0x0B01Returns a risk score (0-100) for a given address or transaction hash
aiAnomalyCheck0x0B02Returns a boolean anomaly flag and confidence score for a transaction

Important: EVM precompiles use the deterministic heuristic engine only. They never call the sidecar, ensuring all EVM execution remains fully deterministic and reproducible.

TEE Attestation

The AI module defines interfaces for Trusted Execution Environment attestation, enabling future verifiable AI model execution inside secure hardware enclaves.

Supported Platforms

PlatformIdentifierDescription
Intel SGXsgxSoftware Guard Extensions
Intel TDXtdxTrust Domain Extensions
AMD SEV-SNPsev-snpSecure Encrypted Virtualization - Secure Nested Paging
ARM CCAarm-ccaConfidential Compute Architecture

Attestation Flow

  1. Load model weights — The sidecar loads AI model weights into a TEE enclave.
  2. Run inference inside enclave — Inference runs inside the enclave's protected memory.
  3. Produce attestation report — The enclave produces an attestation report binding the model hash, input hash, and output hash.
  4. Verify attestation on-chain — Validators verify the attestation on-chain before accepting inference results.

TEE attestation is currently at the interface specification stage. Implementation is planned for a future release.

Federated Learning

The AI module defines interfaces for on-chain federated learning coordination, where validator nodes train local models and submit gradient updates that are aggregated into a global model without sharing raw training data.

Aggregation Methods

MethodDescription
fedavgFederated Averaging — weighted average of gradients by sample count
fedproxFederated Proximal — adds a proximal term to handle heterogeneous data
scaffoldSCAFFOLD — uses control variates to correct for client drift

Round Lifecycle

Pending --> Training --> Aggregating --> Complete
\-> Failed (timeout or insufficient participants)

Each round is configured with minimum/maximum participants, timeout, learning rate, gradient clipping norm, and an optional differential privacy noise multiplier. All gradient submissions are signed with PQC (Dilithium-5) signatures.

Federated learning is currently at the interface specification stage. Implementation is planned for a future release.

REST Endpoints

EndpointDescription
/ai/v1/fee-estimateReturns fee estimates for fast, normal, and slow urgency tiers
/ai/v1/fraud/investigationsLists active and resolved fraud investigations
/ai/v1/network/recommendationsReturns current network parameter optimization recommendations
/ai/v1/circuit-breakersLists active circuit breaker states for contracts