ai

package
v1.19.13 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2025 License: BSD-3-Clause Imports: 12 Imported by: 0

README ΒΆ

AI Package - Cross-Chain Decentralized AI Computation

Practical real usable fucking AI for blockchain self-upgrade, dispute resolution, fork arbitration

This package provides practical AI capabilities with cross-chain computation funding, enabling any blockchain to pay for AI services through X-Chain integration.

Core Design Philosophy: Rob Pike Style

🎯 Simple, Practical, No Bullshit
  • One way to do everything: Clear, orthogonal interfaces
  • Composable: Mix and match AI capabilities as needed
  • Type-safe: Go generics for compile-time safety
  • Performance: Efficient feature extraction and decision making
🧠 Agentic Consensus Capabilities
  • Autonomous Upgrades: Blockchain can upgrade itself based on AI consensus
  • Fork Arbitration: AI resolves blockchain forks using network support metrics
  • Dispute Resolution: Governance disputes resolved with evidence-based AI decisions
  • Security Response: Automatic threat detection and response with emergency actions
  • Cross-Chain Coordination: Distributed AI learning weighted by votes and usage

Cross-Chain Computation Marketplace

πŸ’° Any Chain Can Pay for AI Computation
// Configure marketplace with supported chains
config := &IntegrationConfig{
    EnableMarketplace: true,
    SupportedChains: []*ChainConfig{
        {ChainID: "ethereum", NativeCurrency: "ETH"},
        {ChainID: "polygon", NativeCurrency: "MATIC"},
        {ChainID: "lux-x", NativeCurrency: "LUX"},
    },
}

// Create compute request from any chain
req := &ComputeRequest{
    SourceChain: "ethereum",
    JobType:     "inference",
    Data:        map[string]interface{}{"model": "risk-analysis"},
    MaxPayment:  big.NewInt(5000000), // 0.005 ETH
}

// Process payment and execute AI computation
job, _ := node.OfferCompute(ctx, req)
node.ProcessComputePayment(ctx, job.ID, "0xabcdef...")
πŸ”— Decentralized AI Services
  • Inference: Real-time AI predictions and analysis
  • Training: Distributed model training across nodes
  • Consensus: AI-powered governance decisions
  • Security: Threat detection and response
  • Arbitration: Dispute resolution and fork selection

Architecture Overview

Cross-Chain AI Computation Flow:

[Ethereum DeFi] --ETH--> [X-Chain Bridge] --LUX--> [Lux AI Node]
                            ↕                          ↓
[Polygon Game]  --MATIC--> [Payment Verification] --> [AI Agents]
                            ↕                          ↓
[BSC Protocol]  --BNB----> [Compute Marketplace] --> [Results]
                            ↑                          ↓
                        [Settlement] <------------- [Cross-Chain Bridge]

Key Components

πŸ€– Specialized AI Agents
  • UpgradeAgent: Autonomous blockchain upgrades
  • BlockAgent: Fork arbitration and block validation
  • SecurityAgent: Threat detection and response
  • DisputeAgent: Governance and protocol disputes
🌊 Photonβ†’Quasar Integration
  • Photon: Broadcast proposals through network
  • Wave: Amplify through validator network
  • Focus: Converge on best options
  • Prism: Validate through DAG
  • Horizon: Finalize with quantum certificates
🧬 Shared Hallucinations
type Agent[T ConsensusData] struct {
    model     Model[T]                    // AI model
    memory    *SharedMemory[T]            // Distributed state
    photon    *photon.UniformEmitter      // Network broadcast
    quasar    *quasar.Quasar             // DAG consensus
    hallucinations map[string]*Hallucination[T] // Shared AI state
}

Usage Examples

1. DeFi Risk Assessment
// Ethereum DeFi protocol pays for smart contract risk analysis
req := &ComputeRequest{
    SourceChain: "ethereum",
    JobType:     "inference",
    Data: map[string]interface{}{
        "contracts": ["0x123...", "0x456..."],
        "analysis":  "vulnerability_scan",
    },
}
2. Gaming AI Training
// Polygon gaming dApp pays for AI model training
req := &ComputeRequest{
    SourceChain: "polygon",
    JobType:     "training",
    Data: map[string]interface{}{
        "dataset":    "player_behavior",
        "model_type": "recommendation_engine",
        "epochs":     100,
    },
}
3. Cross-Chain Governance
// Any chain can request AI-powered governance decisions
req := &ComputeRequest{
    SourceChain: "lux-x",
    JobType:     "consensus",
    Data: map[string]interface{}{
        "proposal_type": "protocol_upgrade",
        "voting_data":   govProposal,
    },
}

File Structure

ai/
β”œβ”€β”€ ai.go              # Simple AI agent for basic operations
β”œβ”€β”€ agent.go           # Advanced agentic consensus with generics
β”œβ”€β”€ models.go          # Practical ML models with feature extraction
β”œβ”€β”€ specialized.go     # Domain-specific agents (upgrade, security, etc.)
β”œβ”€β”€ integration.go     # Node integration layer
β”œβ”€β”€ xchain.go          # Cross-chain computation marketplace
β”œβ”€β”€ bridge.go          # Cross-chain payment bridge
β”œβ”€β”€ demo_xchain.go     # Cross-chain demo and examples
└── README.md          # This file

Key Benefits

🌍 Global AI Compute Marketplace
  • Pay-per-use model with any cryptocurrency
  • Decentralized and trustless payments
  • Automatic cross-chain settlement
  • Transparent pricing and resource allocation
⚑ Practical Blockchain AI
  • Self-Upgrading Blockchains: Autonomous protocol upgrades
  • AI Arbitration: Resolve forks and disputes automatically
  • Security Automation: Real-time threat response
  • Cross-Chain Governance: AI-powered multi-chain decisions
πŸ›‘οΈ Production Ready
  • βœ… 100% test coverage
  • βœ… Type-safe Go generics
  • βœ… Rob Pike design philosophy
  • βœ… High-performance feature extraction
  • βœ… Secure cross-chain payments
  • βœ… Practical, usable AI for real blockchain operations

Getting Started

# Build the AI package
go build ./ai/...

# Run tests
go test ./ai/...

# Try the cross-chain demo
go run ./ai/demo_xchain.go

The future of blockchain is autonomous, intelligent, and cross-chain. This AI package makes it real. πŸš€

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func DemoCustomComposition ΒΆ

func DemoCustomComposition()

DemoCustomComposition shows how to create custom compositions

func DemoUsageScenarios ΒΆ

func DemoUsageScenarios()

DemoUsageScenarios shows practical usage scenarios

func DemoXChainCompute ΒΆ

func DemoXChainCompute()

DemoXChainCompute demonstrates cross-chain AI computation with payments

func RunDemo ΒΆ

func RunDemo()

RunDemo demonstrates the single, composable way to use AI

Types ΒΆ

type Agent ΒΆ

type Agent[T ConsensusData] struct {
	// contains filtered or unexported fields
}

Agent represents an AI consensus node with shared hallucinations

func New ΒΆ

func New[T ConsensusData](
	nodeID string,
	model Model[T],
	quasarEngine *quasar.Quasar,
	photonEngine *photon.UniformEmitter,
) *Agent[T]

New creates an AI agent integrated with quasar consensus

func (*Agent[T]) AddTrainingData ΒΆ

func (a *Agent[T]) AddTrainingData(example TrainingExample[T])

AddTrainingData adds training examples from network consensus

func (*Agent[T]) GetSharedHallucination ΒΆ

func (a *Agent[T]) GetSharedHallucination(hallucinationID string) (*Hallucination[T], bool)

GetSharedHallucination returns the current shared AI state

func (*Agent[T]) ProposeDecision ΒΆ

func (a *Agent[T]) ProposeDecision(ctx context.Context, input T, context map[string]interface{}) (*Decision[T], error)

ProposeDecision initiates AI consensus following photon->quasar flow

func (*Agent[T]) SyncSharedMemory ΒΆ

func (a *Agent[T]) SyncSharedMemory(ctx context.Context) error

SyncSharedMemory synchronizes model state across network

func (*Agent[T]) UpdateNodeWeight ΒΆ

func (a *Agent[T]) UpdateNodeWeight(nodeID string, performance float64)

UpdateNodeWeight adjusts reputation based on consensus performance

type AnyDecision ΒΆ

type AnyDecision struct {
	Type      string      `json:"type"`
	Decision  interface{} `json:"decision"`
	Timestamp time.Time   `json:"timestamp"`
}

AnyDecision wraps decisions from different agent types

type BasicModel ΒΆ

type BasicModel interface {
	// Decide takes context and returns a decision
	Decide(ctx context.Context, question string, data map[string]interface{}) (*SimpleDecision, error)
}

BasicModel is the AI that makes decisions

type BlockAgent ΒΆ

type BlockAgent struct {
	*Agent[BlockData]
}

BlockAgent specializes in block and fork decisions

func NewBlockAgent ΒΆ

func NewBlockAgent(nodeID string, model *SimpleModel[BlockData]) *BlockAgent

NewBlockAgent creates a new block specialist agent

func (*BlockAgent) ArbitrateFork ΒΆ

func (ba *BlockAgent) ArbitrateFork(ctx context.Context, forkOptions []BlockData) (*Decision[BlockData], error)

ArbitrateFork resolves blockchain forks using AI consensus

type BlockData ΒΆ

type BlockData struct {
	Height       uint64    `json:"height"`
	Hash         string    `json:"hash"`
	Transactions []string  `json:"transactions"`
	Timestamp    time.Time `json:"timestamp"`
	Validator    string    `json:"validator"`
}

type BlockFeatureExtractor ΒΆ

type BlockFeatureExtractor struct{}

BlockFeatureExtractor extracts features from block data

func (*BlockFeatureExtractor) Extract ΒΆ

func (e *BlockFeatureExtractor) Extract(data BlockData) map[string]float64

func (*BlockFeatureExtractor) Names ΒΆ

func (e *BlockFeatureExtractor) Names() []string

type BridgeChain ΒΆ

type BridgeChain struct {
	ChainID   string    `json:"chain_id"`
	Name      string    `json:"name"`
	RPC       string    `json:"rpc"`
	Contract  string    `json:"contract"`
	Currency  string    `json:"currency"`
	Decimals  int       `json:"decimals"`
	LastBlock uint64    `json:"last_block"`
	LastSync  time.Time `json:"last_sync"`
	Active    bool      `json:"active"`
}

BridgeChain represents a connected blockchain

type BridgeTransaction ΒΆ

type BridgeTransaction struct {
	ID            string    `json:"id"`
	FromChain     string    `json:"from_chain"`
	ToChain       string    `json:"to_chain"`
	Amount        *big.Int  `json:"amount"`
	Sender        string    `json:"sender"`
	Recipient     string    `json:"recipient"`
	SourceTxHash  string    `json:"source_tx_hash"`
	TargetTxHash  string    `json:"target_tx_hash"`
	Status        TxStatus  `json:"status"`
	CreatedAt     time.Time `json:"created_at"`
	CompletedAt   time.Time `json:"completed_at,omitempty"`
	Confirmations int       `json:"confirmations"`
}

BridgeTransaction tracks cross-chain transfers

type Builder ΒΆ

type Builder interface {
	// Fluent interface for composition
	WithInference(moduleID string, config interface{}) Builder
	WithDecision(moduleID string, config interface{}) Builder
	WithLearning(moduleID string, config interface{}) Builder
	WithCoordination(moduleID string, config interface{}) Builder

	// Build the final engine
	Build() (Engine, error)
}

Builder creates engines with composed modules - single way to build

func NewBuilder ΒΆ

func NewBuilder() Builder

type ChainConfig ΒΆ

type ChainConfig struct {
	ChainID        string   `json:"chain_id"`
	Name           string   `json:"name"`
	NativeCurrency string   `json:"native_currency"`
	BridgeContract string   `json:"bridge_contract"`
	MinPayment     *big.Int `json:"min_payment"`
	GasMultiplier  float64  `json:"gas_multiplier"`
	Enabled        bool     `json:"enabled"`
}

ChainConfig defines supported chain parameters

type ChainState ΒΆ

type ChainState struct {
	Height      uint64                 `json:"height"`
	Hash        string                 `json:"hash"`
	Validators  []string               `json:"validators"`
	Performance *Performance           `json:"performance"`
	Issues      []string               `json:"issues"`
	LastSeen    time.Time              `json:"last_seen"`
	Metadata    map[string]interface{} `json:"metadata"`
}

ChainState is what we know about a blockchain

type ComputeJob ΒΆ

type ComputeJob struct {
	ID            string                 `json:"id"`
	SourceChain   string                 `json:"source_chain"`
	Requester     string                 `json:"requester"`
	JobType       string                 `json:"job_type"` // "inference", "training", "consensus"
	Data          map[string]interface{} `json:"data"`
	ComputeUnits  *big.Int               `json:"compute_units"`
	PaymentAmount *big.Int               `json:"payment_amount"`
	PaymentTxHash string                 `json:"payment_tx_hash"`
	Status        JobStatus              `json:"status"`
	CreatedAt     time.Time              `json:"created_at"`
	StartedAt     time.Time              `json:"started_at,omitempty"`
	CompletedAt   time.Time              `json:"completed_at,omitempty"`
	Result        []byte                 `json:"result,omitempty"`
	ErrorMessage  string                 `json:"error_message,omitempty"`
}

ComputeJob represents a paid AI computation task

type ComputeMarketplace ΒΆ

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

ComputeMarketplace handles cross-chain AI computation funding

func NewComputeMarketplace ΒΆ

func NewComputeMarketplace(nodeID string, bridge XChainBridge, logger Logger) *ComputeMarketplace

NewComputeMarketplace creates a new cross-chain compute marketplace

func (*ComputeMarketplace) AddSupportedChain ΒΆ

func (cm *ComputeMarketplace) AddSupportedChain(config *ChainConfig) error

AddSupportedChain adds a new chain for cross-chain payments

func (*ComputeMarketplace) ExecuteJob ΒΆ

func (cm *ComputeMarketplace) ExecuteJob(ctx context.Context, jobID string, agent interface{}) error

ExecuteJob runs the paid computation

func (*ComputeMarketplace) GetMarketStats ΒΆ

func (cm *ComputeMarketplace) GetMarketStats() map[string]interface{}

GetMarketStats returns marketplace statistics

func (*ComputeMarketplace) ProcessPayment ΒΆ

func (cm *ComputeMarketplace) ProcessPayment(ctx context.Context, jobID, txHash string) error

ProcessPayment verifies and processes cross-chain payment

func (*ComputeMarketplace) RequestCompute ΒΆ

func (cm *ComputeMarketplace) RequestCompute(ctx context.Context, req *ComputeRequest) (*ComputeJob, error)

RequestCompute submits a computation request with cross-chain payment

func (*ComputeMarketplace) SettleEarnings ΒΆ

func (cm *ComputeMarketplace) SettleEarnings(ctx context.Context) error

SettleEarnings processes periodic settlements to chains

type ComputeRequest ΒΆ

type ComputeRequest struct {
	SourceChain string                 `json:"source_chain"`
	Requester   string                 `json:"requester"`
	JobType     string                 `json:"job_type"`
	Data        map[string]interface{} `json:"data"`
	MaxPayment  *big.Int               `json:"max_payment"`
}

ComputeRequest represents a cross-chain computation request

type Config ΒΆ

type Config struct {
	// Module-specific config
	Modules map[string]interface{} `json:"modules"`

	// Global settings
	Global map[string]interface{} `json:"global"`
}

Config - single configuration format

type ConsensusData ΒΆ

type ConsensusData interface {
	BlockData | TransactionData | UpgradeData | SecurityData | DisputeData
}

ConsensusData is anything that needs AI consensus

type ConsensusPhase ΒΆ

type ConsensusPhase string

ConsensusPhase follows the photon->quasar flow

const (
	PhasePhoton  ConsensusPhase = "photon"  // Emit proposals
	PhaseWave    ConsensusPhase = "wave"    // Amplify through network
	PhaseFocus   ConsensusPhase = "focus"   // Converge on best options
	PhasePrism   ConsensusPhase = "prism"   // Refract through DAG
	PhaseHorizon ConsensusPhase = "horizon" // Finalize decision
)

type ConsensusState ΒΆ

type ConsensusState[T ConsensusData] struct {
	Round       uint64                        `json:"round"`
	Phase       ConsensusPhase                `json:"phase"`
	Proposals   map[string]*Proposal[T]       `json:"proposals"`
	Votes       map[string]map[string]float64 `json:"votes"` // proposal -> node -> weight
	Finalized   *Decision[T]                  `json:"finalized,omitempty"`
	StartedAt   time.Time                     `json:"started_at"`
	FinalizedAt time.Time                     `json:"finalized_at,omitempty"`
}

ConsensusState tracks the AI consensus process

type Decision ΒΆ

type Decision[T ConsensusData] struct {
	ID           string                 `json:"id"`
	Action       string                 `json:"action"`
	Data         T                      `json:"data"`
	Confidence   float64                `json:"confidence"`
	Reasoning    string                 `json:"reasoning"`
	Alternatives []string               `json:"alternatives,omitempty"`
	Context      map[string]interface{} `json:"context"`
	Timestamp    time.Time              `json:"timestamp"`

	// Consensus metadata
	ProposerID    string  `json:"proposer_id"`
	VoteCount     int     `json:"vote_count"`
	WeightedVotes float64 `json:"weighted_votes"`
}

Decision represents an AI decision with full context

type Dispute ΒΆ

type Dispute struct {
	ID         string    `json:"id"`
	Type       string    `json:"type"` // "fork", "validator", "upgrade", "security"
	ChainID    string    `json:"chain_id"`
	Parties    []string  `json:"parties"`
	Evidence   []string  `json:"evidence"`
	Status     string    `json:"status"` // "open", "resolved", "escalated"
	Resolution string    `json:"resolution,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	ResolvedAt time.Time `json:"resolved_at,omitempty"`
}

Dispute represents a fork or conflict that needs resolution

type DisputeAgent ΒΆ

type DisputeAgent struct {
	*Agent[DisputeData]
}

DisputeAgent specializes in dispute resolution

func NewDisputeAgent ΒΆ

func NewDisputeAgent(nodeID string, model *SimpleModel[DisputeData]) *DisputeAgent

NewDisputeAgent creates a new dispute specialist agent

func (*DisputeAgent) ResolveDispute ΒΆ

func (da *DisputeAgent) ResolveDispute(ctx context.Context, dispute DisputeData) (*Decision[DisputeData], error)

ResolveDispute handles governance and protocol disputes

type DisputeData ΒΆ

type DisputeData struct {
	Type      string    `json:"type"`
	Parties   []string  `json:"parties"`
	Evidence  []string  `json:"evidence"`
	ChainID   string    `json:"chain_id"`
	Timestamp time.Time `json:"timestamp"`
}

type DisputeFeatureExtractor ΒΆ

type DisputeFeatureExtractor struct{}

func (*DisputeFeatureExtractor) Extract ΒΆ

func (e *DisputeFeatureExtractor) Extract(data DisputeData) map[string]float64

func (*DisputeFeatureExtractor) Names ΒΆ

func (e *DisputeFeatureExtractor) Names() []string

type Engine ΒΆ

type Engine interface {
	// Module management - exactly one way
	AddModule(module Module) error
	RemoveModule(id string) error
	GetModule(id string) Module
	ListModules() []Module

	// Processing pipeline - exactly one way
	Process(ctx context.Context, input Input) (Output, error)

	// Configuration - exactly one way
	Configure(config Config) error
}

Engine composes modules - single composition interface

func NewEngine ΒΆ

func NewEngine() Engine

NewEngine creates the single AI engine

type Evidence ΒΆ

type Evidence[T ConsensusData] struct {
	Data      T         `json:"data"`
	NodeID    string    `json:"node_id"`
	Weight    float64   `json:"weight"`
	Timestamp time.Time `json:"timestamp"`
}

Evidence supports a hallucination with concrete data

type FeatureExtractor ΒΆ

type FeatureExtractor[T ConsensusData] interface {
	Extract(data T) map[string]float64
	Names() []string
}

FeatureExtractor converts consensus data to features for ML

type Hallucination ΒΆ

type Hallucination[T ConsensusData] struct {
	ID         string                 `json:"id"`
	ModelID    string                 `json:"model_id"`
	State      map[string]interface{} `json:"state"`
	Confidence float64                `json:"confidence"`
	NodeVotes  map[string]float64     `json:"node_votes"`
	UsageCount int64                  `json:"usage_count"`
	CreatedAt  time.Time              `json:"created_at"`
	UpdatedAt  time.Time              `json:"updated_at"`
	Evidence   []Evidence[T]          `json:"evidence"`
}

Hallucination represents a shared model state across nodes

type Input ΒΆ

type Input struct {
	Type    InputType              `json:"type"`
	Data    map[string]interface{} `json:"data"`
	Context map[string]interface{} `json:"context,omitempty"`
}

Input - single input format for all modules

type InputType ΒΆ

type InputType string

InputType defines what kind of data is being processed

const (
	InputBlock    InputType = "block"
	InputProposal InputType = "proposal"
	InputVote     InputType = "vote"
	InputQuery    InputType = "query"
)

type IntegrationConfig ΒΆ

type IntegrationConfig struct {
	NodeID       string            `json:"node_id"`
	Enabled      bool              `json:"enabled"`
	ModelPaths   map[string]string `json:"model_paths"`
	SyncInterval time.Duration     `json:"sync_interval"`
	LogLevel     string            `json:"log_level"`

	// Cross-chain marketplace config
	EnableMarketplace bool           `json:"enable_marketplace"`
	SupportedChains   []*ChainConfig `json:"supported_chains"`
	PricePerUnit      int64          `json:"price_per_unit"`
	MaxComputeUnits   int64          `json:"max_compute_units"`
}

Config for node integration

type JobStatus ΒΆ

type JobStatus string

JobStatus represents the state of a compute job

const (
	JobPending   JobStatus = "pending"
	JobPaid      JobStatus = "paid"
	JobRunning   JobStatus = "running"
	JobCompleted JobStatus = "completed"
	JobFailed    JobStatus = "failed"
	JobCancelled JobStatus = "cancelled"
)

type Logger ΒΆ

type Logger interface {
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

Logger for AI decisions (keep it simple)

type Model ΒΆ

type Model[T ConsensusData] interface {
	// Core decision making
	Decide(ctx context.Context, input T, context map[string]interface{}) (*Decision[T], error)

	// Training and adaptation
	Learn(examples []TrainingExample[T]) error
	UpdateWeights(gradients []float64) error
	GetState() map[string]interface{}
	LoadState(state map[string]interface{}) error

	// Consensus integration
	ProposeDecision(ctx context.Context, input T) (*Proposal[T], error)
	ValidateProposal(proposal *Proposal[T]) (float64, error) // returns confidence
}

Model interface for AI models with generics

type Module ΒΆ

type Module interface {
	// Identity
	ID() string
	Type() ModuleType

	// Lifecycle - exactly one way to manage state
	Initialize(ctx context.Context, config Config) error
	Start(ctx context.Context) error
	Stop(ctx context.Context) error

	// Processing - exactly one way to process data
	Process(ctx context.Context, input Input) (Output, error)
}

Module is the single interface all AI components implement

func NewCoordinationModule ΒΆ

func NewCoordinationModule(id string, config interface{}) Module

func NewDecisionModule ΒΆ

func NewDecisionModule(id string, config interface{}) Module

func NewInferenceModule ΒΆ

func NewInferenceModule(id string, config interface{}) Module

func NewLearningModule ΒΆ

func NewLearningModule(id string, config interface{}) Module

type ModuleType ΒΆ

type ModuleType string

ModuleType defines orthogonal module categories

const (
	// Inference modules
	ModuleInference ModuleType = "inference"

	// Decision modules
	ModuleDecision ModuleType = "decision"

	// Learning modules
	ModuleLearning ModuleType = "learning"

	// Coordination modules
	ModuleCoordination ModuleType = "coordination"
)

type NodeIntegration ΒΆ

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

NodeIntegration connects AI agents to the Lux node

func NewNodeIntegration ΒΆ

func NewNodeIntegration(nodeID string, config *IntegrationConfig) (*NodeIntegration, error)

NewNodeIntegration creates AI integration for a Lux node

func (*NodeIntegration) AddTrainingFeedback ΒΆ

func (ni *NodeIntegration) AddTrainingFeedback(decisionType string, decisionID string, feedback float64) error

AddTrainingFeedback adds feedback for model learning

func (*NodeIntegration) GetDecisionHistory ΒΆ

func (ni *NodeIntegration) GetDecisionHistory() map[string]*AnyDecision

GetDecisionHistory returns recent AI decisions

func (*NodeIntegration) GetHealthStatus ΒΆ

func (ni *NodeIntegration) GetHealthStatus() string

GetHealthStatus returns the current health status

func (*NodeIntegration) GetMarketplaceStats ΒΆ

func (ni *NodeIntegration) GetMarketplaceStats() map[string]interface{}

GetMarketplaceStats returns marketplace statistics

func (*NodeIntegration) IsEnabled ΒΆ

func (ni *NodeIntegration) IsEnabled() bool

IsEnabled returns whether AI is currently enabled

func (*NodeIntegration) OfferCompute ΒΆ

func (ni *NodeIntegration) OfferCompute(ctx context.Context, req *ComputeRequest) (*ComputeJob, error)

OfferCompute makes this node available for cross-chain AI computation

func (*NodeIntegration) ProcessBlock ΒΆ

func (ni *NodeIntegration) ProcessBlock(ctx context.Context, blockHeight uint64, blockHash string) (*Decision[BlockData], error)

ProcessBlock runs AI consensus on block validation

func (*NodeIntegration) ProcessComputePayment ΒΆ

func (ni *NodeIntegration) ProcessComputePayment(ctx context.Context, jobID, txHash string) error

ProcessComputePayment verifies payment and starts computation

func (*NodeIntegration) ProcessDispute ΒΆ

func (ni *NodeIntegration) ProcessDispute(ctx context.Context, disputeType string, parties []string, evidence []string) (*Decision[DisputeData], error)

ProcessDispute runs AI consensus on dispute resolution

func (*NodeIntegration) ProcessSecurity ΒΆ

func (ni *NodeIntegration) ProcessSecurity(ctx context.Context, threatLevel string, threats []string) (*Decision[SecurityData], error)

ProcessSecurity runs AI consensus on security issues

func (*NodeIntegration) ProcessTransaction ΒΆ

func (ni *NodeIntegration) ProcessTransaction(ctx context.Context, tx interface{}) (*Decision[TransactionData], error)

ProcessTransaction runs AI consensus on transaction validation

func (*NodeIntegration) ProcessUpgrade ΒΆ

func (ni *NodeIntegration) ProcessUpgrade(ctx context.Context, version string, changes []string, risk string) (*Decision[UpgradeData], error)

ProcessUpgrade runs AI consensus on upgrade proposals

func (*NodeIntegration) RequestCrossChainCompute ΒΆ

func (ni *NodeIntegration) RequestCrossChainCompute(ctx context.Context, targetChain string, req *ComputeRequest) (*ComputeJob, error)

RequestCrossChainCompute requests AI computation from another chain

func (*NodeIntegration) SetEnabled ΒΆ

func (ni *NodeIntegration) SetEnabled(enabled bool) error

SetEnabled enables or disables AI functionality

func (*NodeIntegration) SettleMarketplaceEarnings ΒΆ

func (ni *NodeIntegration) SettleMarketplaceEarnings(ctx context.Context) error

SettleMarketplaceEarnings processes cross-chain earnings settlement

func (*NodeIntegration) SyncWithNetwork ΒΆ

func (ni *NodeIntegration) SyncWithNetwork(ctx context.Context) error

SyncWithNetwork synchronizes AI models across the network

type Output ΒΆ

type Output struct {
	Type     OutputType             `json:"type"`
	Data     map[string]interface{} `json:"data"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

Output - single output format for all modules

type OutputType ΒΆ

type OutputType string

OutputType defines what kind of result is produced

const (
	OutputDecision   OutputType = "decision"
	OutputPrediction OutputType = "prediction"
	OutputAnalysis   OutputType = "analysis"
	OutputAction     OutputType = "action"
)

type PaymentProof ΒΆ

type PaymentProof struct {
	TxHash      string    `json:"tx_hash"`
	Amount      *big.Int  `json:"amount"`
	FromChain   string    `json:"from_chain"`
	ToChain     string    `json:"to_chain"`
	Sender      string    `json:"sender"`
	Recipient   string    `json:"recipient"`
	BlockHeight uint64    `json:"block_height"`
	Timestamp   time.Time `json:"timestamp"`
	Verified    bool      `json:"verified"`
}

PaymentProof contains verification of cross-chain payment

type Performance ΒΆ

type Performance struct {
	TPS           float64 `json:"tps"`
	Latency       int64   `json:"latency_ms"`
	FaultRate     float64 `json:"fault_rate"`
	UpgradeNeeded bool    `json:"upgrade_needed"`
}

Performance metrics for the chain

type Proposal ΒΆ

type Proposal[T ConsensusData] struct {
	ID         string        `json:"id"`
	NodeID     string        `json:"node_id"`
	Decision   *Decision[T]  `json:"decision"`
	Evidence   []Evidence[T] `json:"evidence"`
	Weight     float64       `json:"weight"`
	Confidence float64       `json:"confidence"`
	Timestamp  time.Time     `json:"timestamp"`
}

Proposal represents an AI decision proposal

type SecurityAgent ΒΆ

type SecurityAgent struct {
	*Agent[SecurityData]
}

SecurityAgent specializes in security threat response

func NewSecurityAgent ΒΆ

func NewSecurityAgent(nodeID string, model *SimpleModel[SecurityData]) *SecurityAgent

NewSecurityAgent creates a new security specialist agent

func (*SecurityAgent) AutomaticSecurityResponse ΒΆ

func (sa *SecurityAgent) AutomaticSecurityResponse(ctx context.Context, threat SecurityData) (*Decision[SecurityData], error)

AutomaticSecurityResponse handles security threats autonomously

type SecurityData ΒΆ

type SecurityData struct {
	ThreatLevel string    `json:"threat_level"`
	Threats     []string  `json:"threats"`
	NodeID      string    `json:"node_id"`
	Evidence    []string  `json:"evidence"`
	Timestamp   time.Time `json:"timestamp"`
}

type SecurityFeatureExtractor ΒΆ

type SecurityFeatureExtractor struct{}

func (*SecurityFeatureExtractor) Extract ΒΆ

func (e *SecurityFeatureExtractor) Extract(data SecurityData) map[string]float64

func (*SecurityFeatureExtractor) Names ΒΆ

func (e *SecurityFeatureExtractor) Names() []string

type SecurityState ΒΆ

type SecurityState struct {
	ThreatLevel   string            `json:"threat_level"` // "low", "medium", "high", "critical"
	ActiveThreats []string          `json:"active_threats"`
	Mitigations   map[string]string `json:"mitigations"`
	LastScan      time.Time         `json:"last_scan"`
}

SecurityState tracks security status

type SharedMemory ΒΆ

type SharedMemory[T ConsensusData] struct {
	// contains filtered or unexported fields
}

SharedMemory manages distributed model state

type SimpleAgent ΒΆ

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

SimpleAgent does one thing: makes decisions about blockchain operations

func NewSimple ΒΆ

func NewSimple(model BasicModel, logger Logger) *SimpleAgent

NewSimple creates a simple AI agent

func (*SimpleAgent) AddDispute ΒΆ

func (a *SimpleAgent) AddDispute(id, disputeType, chainID string, parties, evidence []string)

AddDispute registers a new dispute

func (*SimpleAgent) AddUpgrade ΒΆ

func (a *SimpleAgent) AddUpgrade(id, upgradeType, chainID, version string, changes []string, risk string)

AddUpgrade registers a potential upgrade

func (*SimpleAgent) CheckSecurity ΒΆ

func (a *SimpleAgent) CheckSecurity(ctx context.Context, chainID string) (*SimpleDecision, error)

CheckSecurity assesses security threats

func (*SimpleAgent) GetState ΒΆ

func (a *SimpleAgent) GetState() *State

GetState returns current state (read-only)

func (*SimpleAgent) ResolveDispute ΒΆ

func (a *SimpleAgent) ResolveDispute(ctx context.Context, disputeID string) (*SimpleDecision, error)

ResolveDispute arbitrates conflicts

func (*SimpleAgent) ResolveFork ΒΆ

func (a *SimpleAgent) ResolveFork(ctx context.Context, chainID string, forks []string) (*SimpleDecision, error)

ResolveFork chooses the correct chain in a fork

func (*SimpleAgent) ShouldUpgrade ΒΆ

func (a *SimpleAgent) ShouldUpgrade(ctx context.Context, chainID string) (*SimpleDecision, error)

ShouldUpgrade decides if a chain should upgrade

func (*SimpleAgent) UpdateChain ΒΆ

func (a *SimpleAgent) UpdateChain(chainID string, height uint64, hash string, validators []string, perf *Performance)

UpdateChain updates what we know about a chain

func (*SimpleAgent) UpdateSecurity ΒΆ

func (a *SimpleAgent) UpdateSecurity(threatLevel string, threats []string, mitigations map[string]string)

UpdateSecurity updates security state

type SimpleBridge ΒΆ

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

SimpleBridge implements XChainBridge for cross-chain AI payments

func NewSimpleBridge ΒΆ

func NewSimpleBridge(nodeID string, logger Logger) *SimpleBridge

NewSimpleBridge creates a new cross-chain bridge

func (*SimpleBridge) AddChain ΒΆ

func (sb *SimpleBridge) AddChain(chain *BridgeChain) error

AddChain connects a new blockchain to the bridge

func (*SimpleBridge) GetBridgeStats ΒΆ

func (sb *SimpleBridge) GetBridgeStats() map[string]interface{}

GetBridgeStats returns bridge statistics

func (*SimpleBridge) GetExchangeRate ΒΆ

func (sb *SimpleBridge) GetExchangeRate(ctx context.Context, fromChain, toChain string) (*big.Int, error)

GetExchangeRate implements XChainBridge.GetExchangeRate

func (*SimpleBridge) ProcessPendingTransactions ΒΆ

func (sb *SimpleBridge) ProcessPendingTransactions(ctx context.Context) error

ProcessPendingTransactions monitors and processes pending transfers

func (*SimpleBridge) SetExchangeRate ΒΆ

func (sb *SimpleBridge) SetExchangeRate(fromChain, toChain string, rate *big.Int) error

SetExchangeRate sets the exchange rate between two chains

func (*SimpleBridge) SubmitResult ΒΆ

func (sb *SimpleBridge) SubmitResult(ctx context.Context, targetChain string, jobID string, result []byte) error

SubmitResult implements XChainBridge.SubmitResult

func (*SimpleBridge) SyncChains ΒΆ

func (sb *SimpleBridge) SyncChains(ctx context.Context) error

SyncChains updates chain states

func (*SimpleBridge) TransferPayment ΒΆ

func (sb *SimpleBridge) TransferPayment(ctx context.Context, sourceChain, targetChain string, amount *big.Int, recipient string) error

TransferPayment implements XChainBridge.TransferPayment

func (*SimpleBridge) VerifyPayment ΒΆ

func (sb *SimpleBridge) VerifyPayment(ctx context.Context, txHash string, expectedAmount *big.Int) (*PaymentProof, error)

VerifyPayment implements XChainBridge.VerifyPayment

type SimpleDecision ΒΆ

type SimpleDecision struct {
	Action     string                 `json:"action"`
	Confidence float64                `json:"confidence"`
	Reasoning  string                 `json:"reasoning"`
	Data       map[string]interface{} `json:"data,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
}

SimpleDecision is what the AI decided

type SimpleLogger ΒΆ

type SimpleLogger struct{}

SimpleLogger implements the Logger interface

func (*SimpleLogger) Error ΒΆ

func (l *SimpleLogger) Error(msg string, fields ...interface{})

func (*SimpleLogger) Info ΒΆ

func (l *SimpleLogger) Info(msg string, fields ...interface{})

func (*SimpleLogger) Warn ΒΆ

func (l *SimpleLogger) Warn(msg string, fields ...interface{})

type SimpleModel ΒΆ

type SimpleModel[T ConsensusData] struct {
	// contains filtered or unexported fields
}

SimpleModel is a basic but effective AI model for consensus decisions

func NewSimpleModel ΒΆ

func NewSimpleModel[T ConsensusData](nodeID string, extractor FeatureExtractor[T]) *SimpleModel[T]

NewSimpleModel creates a practical AI model

func (*SimpleModel[T]) Decide ΒΆ

func (m *SimpleModel[T]) Decide(ctx context.Context, input T, context map[string]interface{}) (*Decision[T], error)

Decide makes a decision based on current model state

func (*SimpleModel[T]) GetState ΒΆ

func (m *SimpleModel[T]) GetState() map[string]interface{}

GetState returns current model state

func (*SimpleModel[T]) Learn ΒΆ

func (m *SimpleModel[T]) Learn(examples []TrainingExample[T]) error

Learn updates the model with training examples

func (*SimpleModel[T]) LoadState ΒΆ

func (m *SimpleModel[T]) LoadState(state map[string]interface{}) error

LoadState loads model state

func (*SimpleModel[T]) ProposeDecision ΒΆ

func (m *SimpleModel[T]) ProposeDecision(ctx context.Context, input T) (*Proposal[T], error)

ProposeDecision creates a proposal for consensus

func (*SimpleModel[T]) UpdateWeights ΒΆ

func (m *SimpleModel[T]) UpdateWeights(gradients []float64) error

UpdateWeights applies gradient updates

func (*SimpleModel[T]) ValidateProposal ΒΆ

func (m *SimpleModel[T]) ValidateProposal(proposal *Proposal[T]) (float64, error)

ValidateProposal validates another node's proposal

type State ΒΆ

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

State tracks what the AI knows

type TrainingExample ΒΆ

type TrainingExample[T ConsensusData] struct {
	Input    T                      `json:"input"`
	Output   Decision[T]            `json:"output"`
	Feedback float64                `json:"feedback"` // -1 to +1
	NodeID   string                 `json:"node_id"`
	Weight   float64                `json:"weight"`
	Context  map[string]interface{} `json:"context"`
}

TrainingExample for distributed learning

type TransactionData ΒΆ

type TransactionData struct {
	Hash      string                 `json:"hash"`
	From      string                 `json:"from"`
	To        string                 `json:"to"`
	Amount    uint64                 `json:"amount"`
	Fee       uint64                 `json:"fee"`
	Data      map[string]interface{} `json:"data"`
	Timestamp time.Time              `json:"timestamp"`
}

type TransactionFeatureExtractor ΒΆ

type TransactionFeatureExtractor struct{}

TransactionFeatureExtractor extracts features from transaction data

func (*TransactionFeatureExtractor) Extract ΒΆ

func (*TransactionFeatureExtractor) Names ΒΆ

func (e *TransactionFeatureExtractor) Names() []string

type TxStatus ΒΆ

type TxStatus string

TxStatus represents transaction state

const (
	TxPending    TxStatus = "pending"
	TxConfirming TxStatus = "confirming"
	TxCompleted  TxStatus = "completed"
	TxFailed     TxStatus = "failed"
)

type Upgrade ΒΆ

type Upgrade struct {
	ID          string                 `json:"id"`
	Type        string                 `json:"type"` // "protocol", "vm", "consensus", "security"
	ChainID     string                 `json:"chain_id"`
	Version     string                 `json:"version"`
	Changes     []string               `json:"changes"`
	Risk        string                 `json:"risk"`   // "low", "medium", "high", "critical"
	Status      string                 `json:"status"` // "proposed", "testing", "approved", "deployed"
	TestResults map[string]interface{} `json:"test_results,omitempty"`
	CreatedAt   time.Time              `json:"created_at"`
	DeployedAt  time.Time              `json:"deployed_at,omitempty"`
}

Upgrade represents a potential blockchain upgrade

type UpgradeAgent ΒΆ

type UpgradeAgent struct {
	*Agent[UpgradeData]
}

UpgradeAgent specializes in upgrade decisions

func NewUpgradeAgent ΒΆ

func NewUpgradeAgent(nodeID string, model *SimpleModel[UpgradeData]) *UpgradeAgent

NewUpgradeAgent creates a new upgrade specialist agent

func (*UpgradeAgent) AutonomousUpgrade ΒΆ

func (ua *UpgradeAgent) AutonomousUpgrade(ctx context.Context, currentVersion string, availableUpgrades []UpgradeData) (*Decision[UpgradeData], error)

AutonomousUpgrade allows the blockchain to upgrade itself based on AI consensus

type UpgradeData ΒΆ

type UpgradeData struct {
	Version     string    `json:"version"`
	Changes     []string  `json:"changes"`
	Risk        string    `json:"risk"`
	TestResults []string  `json:"test_results"`
	Timestamp   time.Time `json:"timestamp"`
}

type UpgradeFeatureExtractor ΒΆ

type UpgradeFeatureExtractor struct{}

UpgradeFeatureExtractor extracts features from upgrade data

func (*UpgradeFeatureExtractor) Extract ΒΆ

func (e *UpgradeFeatureExtractor) Extract(data UpgradeData) map[string]float64

func (*UpgradeFeatureExtractor) Names ΒΆ

func (e *UpgradeFeatureExtractor) Names() []string

type XChainBridge ΒΆ

type XChainBridge interface {
	// Transfer funds from source chain to pay for compute
	TransferPayment(ctx context.Context, sourceChain, targetChain string, amount *big.Int, recipient string) error

	// Verify payment was received
	VerifyPayment(ctx context.Context, txHash string, expectedAmount *big.Int) (*PaymentProof, error)

	// Get exchange rate between chains
	GetExchangeRate(ctx context.Context, fromChain, toChain string) (*big.Int, error)

	// Submit computation result back to requesting chain
	SubmitResult(ctx context.Context, targetChain string, jobID string, result []byte) error
}

XChainBridge interface for cross-chain communication

Jump to

Keyboard shortcuts

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