ai

package
v1.22.45 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: BSD-3-Clause Imports: 9 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 ΒΆ

This section is empty.

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.QuasarCore,
	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 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"`
	ParentHash   string    `json:"parent_hash"`
	Transactions []string  `json:"transactions"`
	TxCount      int       `json:"tx_count"`
	Timestamp    time.Time `json:"timestamp"`
	Validator    string    `json:"validator"`
	Size         uint64    `json:"size"`
	GasUsed      uint64    `json:"gas_used"`
}

type BlockFeatureExtractor ΒΆ

type BlockFeatureExtractor struct{}

BlockFeatureExtractor extracts features from block data

func NewBlockFeatures ΒΆ added in v1.21.0

func NewBlockFeatures() *BlockFeatureExtractor

Factory functions for feature extractors

func (*BlockFeatureExtractor) Extract ΒΆ

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

func (*BlockFeatureExtractor) Names ΒΆ

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

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 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 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 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 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 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 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 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 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 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]) GetWeights ΒΆ added in v1.21.0

func (m *SimpleModel[T]) GetWeights() map[string]float64

GetWeights returns the current model weights

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]) SetWeights ΒΆ added in v1.21.0

func (m *SimpleModel[T]) SetWeights(weights map[string]float64)

SetWeights updates the model weights

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"`
	GasPrice  uint64                 `json:"gas_price"`
	GasLimit  uint64                 `json:"gas_limit"`
	Nonce     uint64                 `json:"nonce"`
	Data      map[string]interface{} `json:"data"`
	Timestamp time.Time              `json:"timestamp"`
}

type TransactionFeatureExtractor ΒΆ

type TransactionFeatureExtractor struct{}

TransactionFeatureExtractor extracts features from transaction data

func NewTransactionFeatures ΒΆ added in v1.21.0

func NewTransactionFeatures() *TransactionFeatureExtractor

func (*TransactionFeatureExtractor) Extract ΒΆ

func (*TransactionFeatureExtractor) Names ΒΆ

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

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 NewUpgradeFeatures ΒΆ added in v1.21.0

func NewUpgradeFeatures() *UpgradeFeatureExtractor

func (*UpgradeFeatureExtractor) Extract ΒΆ

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

func (*UpgradeFeatureExtractor) Names ΒΆ

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

Jump to

Keyboard shortcuts

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