AI/ML with Blockchain: Decentralized Intelligence Systems
Comprehensive analysis of the intersection of artificial intelligence and blockchain technology covering decentralized machine learning, data marketplace architectures, model provenance and attribution, federated learning on-chain, tokenized AI economies, and emerging Web3 AI applications.
The convergence of artificial intelligence and blockchain technology represents one of the most significant technological intersections of our era. AI systems increasingly require massive datasets, computational resources, and trust mechanisms, while blockchain provides decentralized infrastructure, cryptographic guarantees, and economic incentive structures. Combining these technologies enables new paradigms of AI development: decentralized data markets, verifiable model provenance, federated learning networks, and tokenized AI economies.
Understanding the intersection of AI and blockchain requires examining multiple dimensions: data acquisition and marketplace architectures, decentralized training mechanisms, model governance and attribution, privacy-preserving computation, and economic models for AI resources. Each dimension presents unique challenges and opportunities for innovation.
This comprehensive exploration covers the technical architectures, economic models, and practical applications of AI-blockchain integration, providing actionable insights for developers building the next generation of decentralized AI systems.
Decentralized Data Markets
Architecture Overview
Decentralized data marketplaces enable secure, privacy-preserving data exchange:
┌─────────────────────────────────────────────────────────────────────┐
│ DECENTRALIZED DATA MARKETPLACE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ FRONTEND/API LAYER │ │
│ │ - User interfaces (web, mobile) │ │
│ │ - Discovery and search │ │
│ │ - Transaction management │ │
│ │ - Access control interfaces │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ MARKETPLACE CONTRACT │ │
│ │ - Listings registry │ │
│ │ - Pricing mechanisms │ │
│ │ - Access grants │ │
│ │ - Payment distribution │ │
│ │ - Dispute resolution │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ DATA STORAGE LAYER │ │
│ │ - Encrypted data (IPFS, Filecoin) │ │
│ │ - Access credentials (zero-knowledge) │ │
│ │ - Verification proofs │ │
│ │ - Caching layer │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ VERIFICATION LAYER │ │
│ │ - Data quality proofs │ │
│ │ - Schema validation │ │
│ │ - Source attribution │ │
│ │ - Tamper detection │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Data Marketplace Smart Contracts
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract DataMarketplace is ERC1155, ReentrancyGuard {
struct DataListing {
uint256 pricePerAccess;
uint256 totalSupply;
uint256 currentSupply;
address creator;
string metadataURI;
bytes32 dataHash;
bool isActive;
}
mapping(uint256 => DataListing) public listings;
mapping(uint256 => mapping(address => uint256)) public accessCredits;
mapping(uint256 => mapping(address => uint256)) public creatorRewards;
uint256 public nextListingId;
uint256 public platformFee = 25; // 2.5%
event ListingCreated(
uint256 indexed listingId,
address indexed creator,
uint256 price,
string metadataURI
);
event DataPurchased(
uint256 indexed listingId,
address indexed buyer,
uint256 amount
);
event AccessGranted(
uint256 indexed listingId,
address indexed buyer,
uint256 accessCount
);
function createListing(
uint256 _supply,
uint256 _pricePerAccess,
string calldata _metadataURI,
bytes32 _dataHash
) external returns (uint256) {
uint256 listingId = nextListingId++;
listings[listingId] = DataListing({
pricePerAccess: _pricePerAccess,
totalSupply: _supply,
currentSupply: _supply,
creator: msg.sender,
metadataURI: _metadataURI,
dataHash: _dataHash,
isActive: true
});
// Mint data tokens to marketplace (escrowed)
_mint(address(this), listingId, _supply, "");
emit ListingCreated(listingId, msg.sender, _pricePerAccess, _metadataURI);
return listingId;
}
function purchaseAccess(uint256 _listingId, uint256 _accessCount)
external
payable
nonReentrant
{
DataListing storage listing = listings[_listingId];
require(listing.isActive, "Listing not active");
require(msg.value >= listing.pricePerAccess * _accessCount, "Insufficient payment");
uint256 totalCost = listing.pricePerAccess * _accessCount;
uint256 platformFeeAmount = (totalCost * platformFee) / 1000;
uint256 creatorAmount = totalCost - platformFeeAmount;
// Distribute payments
payable(listing.creator).transfer(creatorAmount);
payable(owner()).transfer(platformFeeAmount);
// Grant access credits
accessCredits[_listingId][msg.sender] += _accessCount;
listing.currentSupply -= _accessCount;
emit DataPurchased(_listingId, msg.sender, _accessCount);
}
function verifyAccess(
uint256 _listingId,
address _user,
bytes calldata _proof
) external view returns (bool) {
require(listings[_listingId].isActive, "Listing not active");
uint256 credits = accessCredits[_listingId][_user];
require(credits > 0, "No access credits");
// Verify zero-knowledge proof of eligibility
return verifyZeroKnowledgeProof(_listingId, _user, _proof, credits);
}
function verifyZeroKnowledgeProof(
uint256 _listingId,
address _user,
bytes calldata _proof,
uint256 _credits
) internal pure returns (bool) {
// Implementation of ZK verification
// Would typically use a dedicated verifier contract
return true; // Placeholder
}
}Data Quality Verification
import hashlib
from typing import Dict, List, Tuple
class DataQualityVerifier:
"""
Verify data quality for marketplace listings
"""
def __init__(self, reputation_contract):
self.contract = reputation_contract
def compute_data_hash(self, data) -> bytes32:
"""
Compute cryptographic hash of data
"""
return hashlib.sha256(data).digest()
def verify_schema(self, data: Dict, schema: Dict) -> Tuple[bool, List[str]]:
"""
Verify data matches expected schema
"""
errors = []
is_valid = True
for field, expected_type in schema.items():
if field not in data:
errors.append(f"Missing field: {field}")
is_valid = False
elif not self._type_check(data[field], expected_type):
errors.append(f"Invalid type for {field}")
is_valid = False
return is_valid, errors
def _type_check(self, value, expected_type) -> bool:
"""Check value type"""
type_map = {
'string': str,
'integer': int,
'float': float,
'boolean': bool,
'list': list,
'dict': dict
}
return isinstance(value, type_map.get(expected_type, str))
def compute_quality_score(
self,
data: Dict,
quality_metrics: Dict
) -> float:
"""
Compute quality score based on metrics
"""
scores = []
weights = []
if 'completeness' in quality_metrics:
completeness = self._measure_completeness(data)
scores.append(completeness)
weights.append(quality_metrics['completeness'])
if 'consistency' in quality_metrics:
consistency = self._measure_consistency(data)
scores.append(consistency)
weights.append(quality_metrics['consistency'])
if 'accuracy' in quality_metrics:
accuracy = self._measure_accuracy(data)
scores.append(accuracy)
weights.append(quality_metrics['accuracy'])
if not scores:
return 0.0
# Weighted average
total_weight = sum(weights)
weighted_sum = sum(s * w for s, w in zip(scores, weights))
return weighted_sum / total_weight
def _measure_completeness(self, data: Dict) -> float:
"""Measure data completeness"""
if not data:
return 0.0
filled_fields = sum(1 for v in data.values() if v is not None)
return filled_fields / len(data)
def _measure_consistency(self, data: Dict) -> float:
"""Measure data consistency"""
# Check for type consistency, value ranges, etc.
return 0.9 # Placeholder implementation
def _measure_accuracy(self, data: Dict) -> float:
"""Measure data accuracy (would need ground truth)"""
return 0.85 # Placeholder implementationFederated Learning on Blockchain
Architecture
Federated learning enables collaborative model training without centralized data:
┌─────────────────────────────────────────────────────────────────────┐
│ FEDERATED LEARNING ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ AGGREGATION CONTRACT │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ • Receive model updates from participants │ │ │
│ │ │ • Weight updates by stake/quality │ │ │
│ │ │ • Aggregate into global model │ │ │
│ │ │ • Distribute aggregated model │ │ │
│ │ │ • Manage rewards and penalties │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ PARTICIPANT NODES │ │
│ │ │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Node A │ │ Node B │ │ Node C │ │ Node D │ │ │
│ │ │ (Local │ │ (Local │ │ (Local │ │ (Local │ │ │
│ │ │ data) │ │ data) │ │ data) │ │ data) │ │ │
│ │ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │ │
│ │ │ │ │ │ │ │
│ │ ▼ ▼ ▼ ▼ │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ LOCAL MODEL TRAINING │ │ │
│ │ │ - Gradient computation on local data │ │ │
│ │ │ - Privacy-preserving updates │ │ │
│ │ │ - Differential privacy addition │ │ │
│ │ └─────────────────────────────────────────────────┘ │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ INCENTIVE LAYER │ │
│ │ - Token rewards for quality contributions │ │
│ │ - Stake-based participation │ │
│ │ - Slashing for malicious updates │ │
│ │ - Reputation tracking │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Federated Learning Smart Contracts
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract FederatedLearning is Ownable {
struct Participant {
address node;
uint256 stake;
uint256 reputation;
uint256 totalUpdates;
uint256 acceptedUpdates;
bool isActive;
}
struct ModelUpdate {
address participant;
bytes32 modelHash;
uint256 accuracy;
uint256 timestamp;
bool isAccepted;
}
mapping(address => Participant) public participants;
mapping(uint256 => ModelUpdate) public updates;
uint256 public currentRound;
uint256 public totalRounds;
uint256 public minStake = 100 * 10**18;
uint256 public updateCount;
ERC20 public rewardToken;
event ParticipantJoined(address indexed node, uint256 stake);
event ModelUpdateSubmitted(
address indexed participant,
uint256 indexed round,
bytes32 modelHash
);
event ModelAggregated(uint256 indexed round, bytes32 aggregatedModelHash);
event RewardsDistributed(address indexed participant, uint256 amount);
constructor(address _rewardToken) {
rewardToken = ERC20(_rewardToken);
currentRound = 1;
totalRounds = 100;
}
function joinNetwork(uint256 _stake) external {
require(_stake >= minStake, "Insufficient stake");
require(!participants[msg.sender].isActive, "Already joined");
rewardToken.transferFrom(msg.sender, address(this), _stake);
participants[msg.sender] = Participant({
node: msg.sender,
stake: _stake,
reputation: 1000, // Initial reputation
totalUpdates: 0,
acceptedUpdates: 0,
isActive: true
});
emit ParticipantJoined(msg.sender, _stake);
}
function submitModelUpdate(
bytes32 _modelHash,
uint256 _accuracy,
bytes calldata _proof
) external {
require(participants[msg.sender].isActive, "Not a participant");
require(currentRound <= totalRounds, "Training complete");
// Verify model update proof (simplified)
require(verifyUpdateProof(msg.sender, _modelHash, _accuracy, _proof), "Invalid proof");
uint256 updateId = updateCount++;
updates[updateId] = ModelUpdate({
participant: msg.sender,
modelHash: _modelHash,
accuracy: _accuracy,
timestamp: block.timestamp,
isAccepted: false
});
participants[msg.sender].totalUpdates++;
emit ModelUpdateSubmitted(msg.sender, currentRound, _modelHash);
}
function aggregateModels() external onlyOwner {
require(getUpdateCountForRound(currentRound) >= 3, "Insufficient updates");
// Weighted aggregation based on stake and reputation
bytes32 aggregatedHash = keccak256(abi.encode(
currentRound,
block.timestamp
));
// Distribute rewards based on contribution quality
distributeRewards();
currentRound++;
emit ModelAggregated(currentRound, aggregatedHash);
}
function distributeRewards() internal {
uint256 roundUpdates = getUpdateCountForRound(currentRound);
uint256 totalAccuracy = 0;
// Calculate total accuracy
for (uint256 i = 0; i < updateCount; i++) {
if (updates[i].timestamp == currentRound) {
totalAccuracy += updates[i].accuracy;
}
}
// Distribute rewards proportional to contribution
for (uint256 i = 0; i < updateCount; i++) {
if (updates[i].timestamp == currentRound) {
uint256 reward = (updates[i].accuracy * 1000) / totalAccuracy;
rewardToken.transfer(updates[i].participant, reward);
participants[updates[i].participant].acceptedUpdates++;
participants[updates[i].participant].reputation += 10;
emit RewardsDistributed(updates[i].participant, reward);
}
}
}
function verifyUpdateProof(
address _participant,
bytes32 _modelHash,
uint256 _accuracy,
bytes calldata _proof
) internal pure returns (bool) {
// In production, this would verify cryptographic proofs
// of model training (e.g., via ZK-SNARKs)
return true;
}
function getUpdateCountForRound(uint256 _round) internal view returns (uint256) {
uint256 count = 0;
for (uint256 i = 0; i < updateCount; i++) {
// Simplified - would need better round tracking
if (updates[i].timestamp >= block.timestamp - 3600) {
count++;
}
}
return count;
}
}Local Training with Privacy
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Dict, Tuple
import numpy as np
class FederatedTrainer:
"""
Federated learning participant node
"""
def __init__(
self,
model: nn.Module,
local_data: Dataset,
privacy_budget: float = 1.0
):
self.model = model
self.local_data = local_data
self.privacy_budget = privacy_budget
self.optimizer = torch.optim.Adam(model.parameters())
def train_local(
self,
global_weights: Dict[str, torch.Tensor],
local_epochs: int = 5,
batch_size: int = 32
) -> Tuple[Dict[str, torch.Tensor], float]:
"""
Train on local data and return model update
"""
# Load global weights
self.model.load_state_dict(global_weights)
# Train locally
self.model.train()
dataloader = DataLoader(self.local_data, batch_size, shuffle=True)
total_loss = 0.0
for epoch in range(local_epochs):
for batch in dataloader:
inputs, targets = batch
self.optimizer.zero_grad()
outputs = self.model(inputs)
loss = self.compute_loss(outputs, targets)
loss.backward()
self.optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / (len(dataloader) * local_epochs)
# Add differential privacy noise
self._add_dp_noise()
# Compute update (difference from global)
local_update = self._compute_update(global_weights)
return local_update, avg_loss
def _add_dp_noise(self, epsilon: float = 1.0):
"""
Add noise for differential privacy
"""
with torch.no_grad():
for param in self.model.parameters():
noise = torch.randn_like(param) * epsilon / self.privacy_budget
param.add_(noise)
def _compute_update(
self,
global_weights: Dict[str, torch.Tensor]
) -> Dict[str, torch.Tensor]:
"""
Compute weight update (local - global)
"""
update = {}
for name, param in self.model.named_parameters():
update[name] = param - global_weights[name]
return update
def compute_loss(self, outputs, targets):
"""Compute training loss"""
return nn.functional.cross_entropy(outputs, targets)
class FederatedAggregator:
"""
Coordinate federated learning aggregation
"""
def __init__(self, model: nn.Module):
self.model = model
self.global_weights = dict(model.named_parameters())
self.participant_weights = {}
def aggregate_updates(
self,
updates: Dict[address, Tuple[Dict, float]],
aggregation_strategy: str = "weighted"
) -> Dict[str, torch.Tensor]:
"""
Aggregate model updates from participants
"""
if aggregation_strategy == "weighted":
return self._weighted_aggregation(updates)
elif aggregation_strategy == "median":
return self._robust_aggregation(updates)
else:
return self._simple_average(updates)
def _weighted_aggregation(
self,
updates: Dict[address, Tuple[Dict, float]]
) -> Dict[str, torch.Tensor]:
"""
Weight updates by accuracy and participation
"""
aggregated = {}
for name in self.global_weights.keys():
weighted_sum = torch.zeros_like(self.global_weights[name])
total_weight = 0.0
for participant, (update, accuracy) in updates.items():
weight = accuracy * self._get_participant_weight(participant)
weighted_sum += update[name] * weight
total_weight += weight
aggregated[name] = self.global_weights[name] + (weighted_sum / total_weight)
return aggregated
def _get_participant_weight(self, participant: address) -> float:
"""
Get participant weight based on reputation/stake
"""
return 1.0 # Would query blockchain contractModel Provenance and Attribution
Tracking Model Lineage
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ModelRegistry {
struct ModelVersion {
uint256 versionId;
bytes32 modelHash;
address creator;
uint256 timestamp;
bytes32 parentVersion;
uint256[] trainingDataIds;
uint256 performanceMetrics;
string metadataURI;
}
struct TrainingData {
uint256 dataId;
bytes32 dataHash;
address provider;
uint256 licensingFee;
bool isVerified;
}
mapping(bytes32 => ModelVersion) public modelVersions;
mapping(uint256 => TrainingData) public trainingData;
mapping(bytes32 => uint256[]) public modelLineage;
uint256 public nextVersionId;
event ModelRegistered(
bytes32 indexed modelHash,
uint256 indexed versionId,
address indexed creator
);
event ModelVersionCreated(
bytes32 indexed parentHash,
bytes32 indexed newHash,
uint256 indexed versionId
);
event DataLicensed(
uint256 indexed dataId,
address indexed model,
uint256 amount
);
function registerModel(
bytes32 _modelHash,
uint256[] calldata _trainingDataIds,
uint256 _performanceMetrics,
string calldata _metadataURI
) external returns (uint256) {
uint256 versionId = nextVersionId++;
modelVersions[_modelHash] = ModelVersion({
versionId: versionId,
modelHash: _modelHash,
creator: msg.sender,
timestamp: block.timestamp,
parentVersion: bytes32(0),
trainingDataIds: _trainingDataIds,
performanceMetrics: _performanceMetrics,
metadataURI: _metadataURI
});
// License training data
for (uint256 i = 0; i < _trainingDataIds.length; i++) {
_licenseData(_trainingDataIds[i], _modelHash);
}
emit ModelRegistered(_modelHash, versionId, msg.sender);
return versionId;
}
function createModelVersion(
bytes32 _parentHash,
bytes32 _newModelHash,
uint256 _performanceMetrics,
string calldata _metadataURI
) external returns (uint256) {
require(modelVersions[_parentHash].versionId != 0, "Parent not found");
uint256 versionId = nextVersionId++;
modelVersions[_newModelHash] = ModelVersion({
versionId: versionId,
modelHash: _newModelHash,
creator: msg.sender,
timestamp: block.timestamp,
parentVersion: _parentHash,
trainingDataIds: modelVersions[_parentHash].trainingDataIds,
performanceMetrics: _performanceMetrics,
metadataURI: _metadataURI
});
// Track lineage
modelLineage[_parentHash].push(versionId);
emit ModelVersionCreated(_parentHash, _newModelHash, versionId);
return versionId;
}
function _licenseData(uint256 _dataId, bytes32 _modelHash) internal {
TrainingData storage data = trainingData[_dataId];
if (data.licensingFee > 0) {
payable(data.provider).transfer(data.licensingFee);
}
emit DataLicensed(_dataId], _modelHash, data.licensingFee);
}
function verifyAttribution(
bytes32 _modelHash,
address _candidateCreator
) external view returns (bool, uint256) {
ModelVersion storage model = modelVersions[_modelHash];
require(model.versionId != 0, "Model not found");
return (
model.creator == _candidateCreator,
model.versionId
);
}
function traceLineage(bytes32 _modelHash)
external
view
returns (uint256[] memory lineage)
{
return modelLineage[_modelHash];
}
}Tokenized AI Economies
AI Token Economics
┌─────────────────────────────────────────────────────────────────────┐
│ AI TOKEN ECONOMICS MODEL │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ TOKEN UTILITIES │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ • Payment for data access │ │ │
│ │ │ • Payment for model inference │ │ │
│ │ │ • Staking for compute resources │ │ │
│ │ │ • Governance participation │ │ │
│ │ │ • Rewards for model contributions │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ VALUE CREATION │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ • High-quality data contributions │ │ │
│ │ │ • Accurate model predictions │ │ │
│ │ │ • Compute resource provision │ │ │
│ │ │ • Governance participation │ │ │
│ │ │ • Network adoption and usage │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ VALUE DISTRIBUTION │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ • Data providers (proportional to quality) │ │ │
│ │ │ • Model trainers (proportional to contributions) │ │ │
│ │ │ • Compute providers (proportional to resources) │ │ │
│ │ │ • Stakers (proportional to stake) │ │ │
│ │ │ • Treasury (for ecosystem development) │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
AI Resource Marketplace
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract AIResourceMarket is ERC20 {
struct ComputeListing {
address provider;
uint256 pricePerSecond;
uint256 gpuCount;
uint256 memoryGB;
uint256 storageGB;
bool isActive;
}
struct InferenceRequest {
address requester;
bytes modelHash;
uint256 maxPrice;
uint256 timeout;
bool isFulfilled;
}
mapping(uint256 => ComputeListing) public computeListings;
mapping(uint256 => InferenceRequest) public inferenceRequests;
uint256 public nextListingId;
uint256 public nextRequestId;
mapping(address => uint256) public providerEarnings;
mapping(address => uint256) public requesterDeposits;
event ComputeListed(
uint256 indexed listingId,
address indexed provider,
uint256 pricePerSecond
);
event ComputePurchased(
uint256 indexed listingId,
address indexed renter,
uint256 duration
);
event InferenceRequested(
uint256 indexed requestId,
address indexed requester,
bytes32 modelHash
);
event InferenceFulfilled(
uint256 indexed requestId,
address indexed provider,
bytes resultHash
);
constructor() ERC20("AI Compute Token", "AIC") {
_mint(msg.sender, 1000000 * 10**18);
}
function listCompute(
uint256 _pricePerSecond,
uint256 _gpuCount,
uint256 _memoryGB,
uint256 _storageGB
) external returns (uint256) {
uint256 listingId = nextListingId++;
computeListings[listingId] = ComputeListing({
provider: msg.sender,
pricePerSecond: _pricePerSecond,
gpuCount: _gpuCount,
memoryGB: _memoryGB,
storageGB: _storageGB,
isActive: true
});
emit ComputeListed(listingId, msg.sender, _pricePerSecond);
return listingId;
}
function purchaseCompute(uint256 _listingId, uint256 _duration) external {
ComputeListing storage listing = computeListings[_listingId];
require(listing.isActive, "Listing not active");
uint256 totalCost = listing.pricePerSecond * _duration;
require(balanceOf(msg.sender) >= totalCost, "Insufficient balance");
_transfer(msg.sender, listing.provider, totalCost);
providerEarnings[listing.provider] += totalCost;
emit ComputePurchased(_listingId, msg.sender, _duration);
}
function requestInference(
bytes32 _modelHash,
uint256 _maxPrice,
uint256 _timeout
) external returns (uint256) {
uint256 requestId = nextRequestId++;
inferenceRequests[requestId] = InferenceRequest({
requester: msg.sender,
modelHash: _modelHash,
maxPrice: _maxPrice,
timeout: _timeout,
isFulfilled: false
});
// Lock deposit
require(balanceOf(msg.sender) >= _maxPrice, "Insufficient balance");
requesterDeposits[msg.sender] += _maxPrice;
emit InferenceRequested(requestId, msg.sender, _modelHash);
return requestId;
}
function fulfillInference(
uint256 _requestId,
bytes32 _resultHash
) external {
InferenceRequest storage request = inferenceRequests[_requestId];
require(!request.isFulfilled, "Already fulfilled");
require(block.timestamp <= request.timeout, "Request expired");
// Pay provider
uint256 payment = request.maxPrice;
requesterDeposits[request.requester] -= payment;
_mint(msg.sender, payment);
request.isFulfilled = true;
emit InferenceFulfilled(_requestId, msg.sender, _resultHash);
}
}Privacy-Preserving AI
Secure Multi-Party Computation
class SecureAggregation:
"""
Secure aggregation for federated learning using secret sharing
"""
def __init__(self, threshold: int = 3):
self.threshold = threshold
self.prime = 2**61 - 1 # Mersenne prime
def share_secret(self, secret: np.ndarray, num_shares: int) -> List[np.ndarray]:
"""
Split secret into shares using Shamir's secret sharing
"""
shares = []
for i in range(num_shares):
# Generate random coefficients
coeffs = [secret.flatten()]
for _ in range(self.threshold - 1):
coeff = np.random.randint(0, self.prime, secret.shape)
coeffs.append(coeff)
# Evaluate polynomial at x = i + 1
x = i + 1
share = coeffs[0].copy()
power = np.ones_like(share)
for j in range(1, self.threshold):
power = power * x % self.prime
share = (share + coeffs[j] * power) % self.prime
shares.append(share)
return shares
def aggregate_shares(
self,
shares: List[np.ndarray],
indices: List[int]
) -> np.ndarray:
"""
Reconstruct secret from shares using Lagrange interpolation
"""
reconstructed = np.zeros_like(shares[0])
for i, share in enumerate(shares):
x_i = indices[i]
# Compute Lagrange basis polynomial
lagrange = np.ones_like(reconstructed)
for j, x_j in enumerate(indices):
if i != j:
numerator = -x_j
denominator = x_i - x_j
lagrange = lagrange * numerator / denominator
reconstructed = (reconstructed + share * lagrange) % self.prime
return reconstructed
def secure_federated_average(
self,
updates: Dict[int, np.ndarray],
num_nodes: int
) -> np.ndarray:
"""
Perform secure aggregation of model updates
"""
# Generate shares for each update
all_shares = {}
for node_id, update in updates.items():
shares = self.share_secret(update, num_nodes)
all_shares[node_id] = shares
# Distribute shares to nodes (simplified)
aggregated_shares = [np.zeros_like(list(updates.values())[0]) for _ in range(num_nodes)]
for node_id, shares in all_shares.items():
for i, share in enumerate(shares):
aggregated_shares[i] = (aggregated_shares[i] + share) % self.prime
# Reconstruct aggregated update
indices = list(range(1, num_nodes + 1))
return self.aggregate_shares(aggregated_shares, indices)Practical Applications
Use Cases Matrix
| Application | Blockchain Role | AI Component | Status |
|---|---|---|---|
| Data marketplaces | Access control, payments | Data quality | Production |
| Federated learning | Aggregation, incentives | Training | Development |
| Model provenance | Attribution, licensing | Version tracking | Production |
| Inference markets | Pricing, payments | Prediction | Early stage |
| DAO governance | Voting, execution | Decision-making | Production |
| Decentralized compute | Resource allocation | Job scheduling | Development |
Example: Prediction Market DAO
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract PredictionMarket is ERC20 {
struct Prediction {
uint256 id;
address predictor;
bytes32 outcomeHash;
uint256 amount;
bool isResolved;
bool outcome;
}
struct Market {
uint256 id;
string question;
uint256 endTime;
uint256 totalYes;
uint256 totalNo;
bool isResolved;
bool finalOutcome;
}
mapping(uint256 => Market) public markets;
mapping(uint256 => Prediction[]) public predictions;
uint256 public nextMarketId;
uint256 public nextPredictionId;
event MarketCreated(uint256 indexed marketId, string question);
event PredictionMade(
uint256 indexed marketId,
uint256 indexed predictionId,
address predictor,
uint256 amount,
bool outcome
);
event MarketResolved(uint256 indexed marketId, bool outcome);
function createMarket(
string calldata _question,
uint256 _duration
) external returns (uint256) {
uint256 marketId = nextMarketId++;
markets[marketId] = Market({
id: marketId,
question: _question,
endTime: block.timestamp + _duration,
totalYes: 0,
totalNo: 0,
isResolved: false,
finalOutcome: false
});
emit MarketCreated(marketId, _question);
return marketId;
}
function makePrediction(
uint256 _marketId,
bool _outcome,
uint256 _amount
) external returns (uint256) {
require(block.timestamp < markets[_marketId].endTime, "Market closed");
require(balanceOf(msg.sender) >= _amount, "Insufficient balance");
_transfer(msg.sender, address(this), _amount);
uint256 predictionId = nextPredictionId++;
Prediction memory prediction = Prediction({
id: predictionId,
predictor: msg.sender,
outcomeHash: keccak256(abi.encodePacked(_outcome)),
amount: _amount,
isResolved: false,
outcome: _outcome
});
predictions[_marketId].push(prediction);
if (_outcome) {
markets[_marketId].totalYes += _amount;
} else {
markets[_marketId].totalNo += _amount;
}
emit PredictionMade(_marketId, predictionId, msg.sender, _amount, _outcome);
return predictionId;
}
function resolveMarket(uint256 _marketId, bool _outcome) external {
require(block.timestamp >= markets[_marketId].endTime, "Not yet ended");
require(!markets[_marketId].isResolved, "Already resolved");
markets[_marketId].isResolved = true;
markets[_marketId].finalOutcome = _outcome;
// Distribute winnings
uint256 winningPool = markets[_marketId].totalYes + markets[_marketId].totalNo;
uint256 totalWinning = _outcome
? markets[_marketId].totalYes
: markets[_marketId].totalNo;
for (Prediction storage prediction : predictions[_marketId]) {
if (prediction.outcome == _outcome && !prediction.isResolved) {
uint256 payout = (prediction.amount * winningPool) / totalWinning;
_mint(prediction.predictor, payout);
prediction.isResolved = true;
}
}
emit MarketResolved(_marketId, _outcome);
}
}Conclusion
The intersection of AI and blockchain creates powerful possibilities for decentralized intelligence systems. From data marketplaces enabling privacy-preserving data exchange to federated learning networks training models without centralization, these technologies complement each other's strengths and address mutual weaknesses.
Key architectural patterns include tokenized incentive mechanisms for data contribution and model training, smart contract-based governance for AI resource allocation, and cryptographic primitives for privacy-preserving computation. The maturation of these patterns will enable increasingly sophisticated decentralized AI applications.
The economic models underlying AI-blockchain systems require careful design to balance contributor incentives with network sustainability. Token economics, reputation systems, and governance mechanisms all play crucial roles in creating thriving decentralized AI ecosystems.
As both AI and blockchain technologies continue to evolve, their convergence will likely accelerate, enabling new categories of applications that are simultaneously powerful, private, and decentralized. Understanding these intersection points positions developers to build the next generation of Web3 AI applications.