Skip to main content

Distributed AI-validated ledger system - Blockless blockchain with AI consensus

Project description

AI Ledger - AI-First Distributed Ledger System

Revolutionary ledger technology that replaces blockchain mining with AI-powered validation

Python 3.11+ License: MIT AI-Powered

๐Ÿš€ What This Is

NOT another blockchain! AI Ledger is a fundamentally different approach to distributed ledger technology:

  • Natural Language Transactions: "Alice pays Bob 50 LABS for design work"
  • AI Validators: Replace energy-hungry miners with intelligent AI validators
  • Instant Finality: Transactions finalize in ~1-2 seconds, not minutes or hours
  • Human-Readable: Every transaction, receipt, and decision is explainable
  • Zero Energy Waste: No proof-of-work, no mining, no environmental impact

๐ŸŽฏ Key Features

๐Ÿง  AI-Powered Consensus

  • Multiple AI Validators independently evaluate each transaction
  • Risk Assessment with explainable scoring (0.0 = safe, 1.0 = risky)
  • Quorum Decision requires 5 of 7 validators to approve with low risk
  • Human Judgment layer on top of deterministic rules

โšก Production Ready

  • Battle-Tested Security: Ed25519 signatures, domain separation, replay protection
  • Decimal Precision: No floating-point errors, proper financial math
  • Comprehensive Validation: Clock skew protection, rate limiting, nonce management
  • Durable Storage: Checksummed logs with fsync guarantees

๐Ÿ” Transparency & Verification

  • Tamper-Evident Receipts: Every transaction gets a cryptographic receipt
  • Merkle Trees: Account state integrity with inclusion proofs
  • Full Audit Trail: Every decision is logged and verifiable
  • Real-Time Monitoring: Health checks, metrics, and observability

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.11 or higher
  • 8GB RAM (for OpenAI mode)
  • 1GB disk space

Installation

# Clone the repository
git clone https://github.com/your-org/ai-ledger.git
cd ai-ledger

# Install dependencies
pip install -e .

# Run the interactive demo (no API keys needed!)
python -m ai_ledger.demo

Try with Real AI (OpenAI)

# Set your OpenAI API key
export OPENAI_API_KEY="your-key-here"

# Run demo with real AI validation
python -m ai_ledger.demo --mode openai

๐Ÿ“– Demo Walkthrough

The demo runs 5 realistic transactions and shows you exactly how AI validation works:

๐Ÿš€ AI Ledger Demo
Mode: STUB
============================================================

๐ŸŒ Initial State:
  alice       100.0 LABS (nonce=0, txs=0)
  bob           0.0 LABS (nonce=0, txs=0)
  treasury    900.0 LABS (nonce=0, txs=0)

๐Ÿ’ซ Demo Transactions
============================================================

Transaction 1: Normal Payment
  ๐Ÿ“ค Submitting: Alice pays Bob 25 LABS for web design work
    alice โ†’ bob: 25.0 LABS
    โœ“ Accepted: abc123def456...
    ๐Ÿค– Validator Opinions:
      โœ“ val001: Risk=0.15 โ–ˆโ–Œ Normal meal transaction  
      โœ“ val002: Risk=0.12 โ–ˆโ– Valid transaction
      โœ“ val003: Risk=0.18 โ–ˆโ–Š Normal payment pattern
    โœ… APPROVED (5/7 validators, risk=0.150, time=1.2s)

๐Ÿ“Š Final Results
============================================================
  alice          75.0 LABS (nonce=1, txs=1)
  bob            25.0 LABS (nonce=0, txs=1)

๐ŸŽ‰ Demo completed successfully!

๐Ÿ—๏ธ Architecture Overview

User submits "Pay Bob $50" โ†’ Node โ†’ AI Validators โ†’ Quorum โ†’ Receipt
                              โ†“        โ†“             โ†“        โ†“
                           Mempool  AI+Rules    Consensus   Chain

Core Components

  1. Transaction Layer: Natural language transactions with comprehensive validation
  2. Validator Network: AI-powered validators with fallback rule systems
  3. Quorum Manager: Collects opinions and determines consensus
  4. Storage Engine: Durable, checksummed append-only logs
  5. Account Manager: Balance tracking with atomic operations

Trust Model

Instead of proof-of-work:

  1. Transaction Submitted in natural language to any node
  2. Multiple AI Validators evaluate independently using rules + AI judgment
  3. Quorum Consensus requires 5/7 validators to approve with average risk โ‰ค0.25
  4. Tamper-Evident Receipt created with cryptographic proofs
  5. Account State Updated atomically with full audit trail

๐Ÿ› ๏ธ Usage Examples

Running a Node

# Start a node on port 8001
python -m ai_ledger.node --port 8001

# With custom log directory
python -m ai_ledger.node --port 8001 --log-dir ./my-logs

# Enable debug logging
python -m ai_ledger.node --port 8001 --log-level DEBUG

Submit Transactions via API

import httpx

async def send_payment():
    async with httpx.AsyncClient() as client:
        # Submit transaction
        response = await client.post("http://localhost:8001/submit", json={
            "nl_description": "Alice pays Bob 25 LABS for lunch",
            "from_acct": "alice", 
            "to_acct": "bob",
            "amount": "25.0",
            "nonce": 1
        })
        
        tx_id = response.json()["transaction_id"]
        print(f"Transaction submitted: {tx_id}")
        
        # Wait for finality
        while True:
            receipt = await client.get(f"http://localhost:8001/receipt/{tx_id}")
            if receipt.status_code == 200 and "receipt_id" in receipt.json():
                print("Transaction finalized!")
                break
            await asyncio.sleep(1)

Generate Validator Keys

# Generate 7 validators for production
python -m ai_ledger.keygen generate --count 7 --output-dir ./production-keys

# Verify generated keys
python -m ai_ledger.keygen verify --file ./production-keys/validators.json

Verify System Integrity

# Check specific receipt
python -m ai_ledger.verify receipt abc123def456...

# Verify account chain integrity  
python -m ai_ledger.verify account alice

# Full storage integrity check
python -m ai_ledger.verify storage-integrity

# Verify all recent receipts
python -m ai_ledger.verify all-receipts --limit 100

๐Ÿ”ง Configuration

Environment Variables

# Required for OpenAI mode
export OPENAI_API_KEY="your-openai-api-key"

# Optional configuration
export AI_LEDGER_LOG_LEVEL="INFO"
export AI_LEDGER_LOG_DIR="./logs"
export AI_LEDGER_PORT="8001"

Configuration Files

Edit ai_ledger/params.py to customize:

# Consensus parameters
N_VALIDATORS = 7          # Number of validators
QUORUM_K = 5             # Required approvals
MAX_RISK_AVG = 0.25      # Maximum average risk score

# LLM configuration  
LLM_MODE = "stub"        # "openai", "stub", or "rule_only"
OPENAI_MODEL = "gpt-4-turbo-preview"

# Security settings
MAX_CLOCK_SKEW_SECS = 120
RATE_LIMIT_TPS = 10

๐Ÿงช Testing

Run the comprehensive test suite:

# Run all tests
python -m pytest

# Run specific test categories
python -m pytest ai_ledger/tests/test_canonical.py   # Deterministic hashing
python -m pytest ai_ledger/tests/test_quorum.py      # Consensus mechanics
python -m pytest ai_ledger/tests/test_replay.py      # Replay protection
python -m pytest ai_ledger/tests/test_llm_safety.py  # AI safety

# Run with coverage
python -m pytest --cov=ai_ledger --cov-report=html

Test Coverage

  • Canonical JSON: Deterministic serialization and hashing
  • Quorum Consensus: Validator opinion collection and consensus rules
  • Replay Protection: Nonce management and duplicate prevention
  • LLM Safety: Prompt injection resistance and consistent behavior
  • Storage Integrity: Checksum verification and corruption detection

๐Ÿ“Š Monitoring & Observability

Health Checks

curl http://localhost:8001/health
{
  "status": "healthy",
  "uptime_seconds": 3600,
  "components": {
    "storage": {"status": "healthy", "stats": {...}},
    "validators": {"status": "healthy", "eligible_validators": 5},
    "accounts": {"status": "healthy", "account_count": 3}
  }
}

Metrics (Prometheus Compatible)

curl http://localhost:8001/metrics
# HELP transactions_submitted Total transactions submitted
# TYPE transactions_submitted counter
transactions_submitted 1250

# HELP avg_finality_time Average time to finality in seconds  
# TYPE avg_finality_time gauge
avg_finality_time 1.234

Debug Endpoints

# View mempool contents
curl http://localhost:8001/debug/mempool

# Get consensus parameters
curl http://localhost:8001/params

# Check account balances
curl http://localhost:8001/account/alice

๐Ÿ” Security Model

Cryptographic Security

  • Ed25519 Signatures for all validator opinions and receipts
  • Domain Separation prevents cross-protocol signature reuse
  • Blake3 Hashing for tamper-evident integrity
  • Merkle Trees for efficient state verification

Economic Security

  • Validator Reputation system with automatic stake adjustment
  • Rate Limiting prevents spam and DoS attacks
  • Nonce Management prevents replay attacks
  • Clock Skew Protection prevents timestamp manipulation

AI Safety

  • Fail-Closed Design: Errors result in transaction rejection
  • Prompt Injection Resistance: Multiple layers of input sanitization
  • Deterministic Fallbacks: Rule-only mode when AI unavailable
  • Multi-Validator Consensus: No single AI can approve transactions

๐ŸŽฏ Production Deployment

System Requirements

Minimum:

  • 2 CPU cores
  • 4GB RAM
  • 10GB SSD storage
  • 100 Mbps network

Recommended:

  • 4 CPU cores
  • 8GB RAM
  • 50GB SSD storage
  • 1 Gbps network

Docker Deployment

FROM python:3.11-slim

WORKDIR /app
COPY . .
RUN pip install -e .

EXPOSE 8001
CMD ["python", "-m", "ai_ledger.node", "--port", "8001", "--host", "0.0.0.0"]
# Build and run
docker build -t ai-ledger .
docker run -p 8001:8001 -v ./logs:/app/logs ai-ledger

Kubernetes Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ai-ledger-node
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ai-ledger
  template:
    metadata:
      labels:
        app: ai-ledger
    spec:
      containers:
      - name: ai-ledger
        image: ai-ledger:latest
        ports:
        - containerPort: 8001
        env:
        - name: OPENAI_API_KEY
          valueFrom:
            secretKeyRef:
              name: ai-ledger-secrets
              key: openai-api-key
        volumeMounts:
        - name: logs
          mountPath: /app/logs

๐Ÿ›ฃ๏ธ Roadmap

Phase 1: Core System โœ…

  • AI-powered transaction validation
  • Quorum consensus mechanism
  • Deterministic state management
  • Comprehensive test coverage
  • Production security features

Phase 2: Network Layer ๐Ÿšง

  • Multi-node consensus protocol
  • Network partition tolerance
  • Validator discovery and selection
  • Cross-node receipt verification

Phase 3: Advanced Features ๐Ÿ“‹

  • Multi-asset support (USD, EUR, BTC)
  • Smart contract equivalent (AI-validated programs)
  • Web dashboard and explorer
  • Mobile SDK and wallet apps
  • Enterprise integrations

Phase 4: Scale & Optimize ๐Ÿ“‹

  • Horizontal scaling (1000+ TPS)
  • Advanced AI models (GPT-5, Claude-4)
  • Zero-knowledge privacy features
  • Cross-ledger interoperability

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

# Clone and install in development mode
git clone https://github.com/your-org/ai-ledger.git
cd ai-ledger
pip install -e ".[dev]"

# Run tests
python -m pytest

# Format code  
black ai_ledger/
ruff ai_ledger/

# Type checking
mypy ai_ledger/

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • OpenAI for GPT models that power our AI validators
  • NaCl/libsodium for production-grade cryptography
  • Blake3 for high-performance hashing
  • FastAPI for the modern web framework
  • Pydantic for data validation and serialization

๐Ÿ“ž Support & Community


Built with โค๏ธ by the AI Ledger team

"The future of money is intelligent, transparent, and instant."

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

blockless_ai_ledger-0.1.0.tar.gz (67.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

blockless_ai_ledger-0.1.0-py3-none-any.whl (71.9 kB view details)

Uploaded Python 3

File details

Details for the file blockless_ai_ledger-0.1.0.tar.gz.

File metadata

  • Download URL: blockless_ai_ledger-0.1.0.tar.gz
  • Upload date:
  • Size: 67.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.6

File hashes

Hashes for blockless_ai_ledger-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cf0454608bd6b1886b9d0f8807dc87be4d90f9556f06b7c131ccda3fd1d57342
MD5 1e33429e2718a1b7aa1295fb526e1102
BLAKE2b-256 5ea0a83dd32761bcb5879a4cdd538754b278972d07e9660af17927af586fe4db

See more details on using hashes here.

File details

Details for the file blockless_ai_ledger-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for blockless_ai_ledger-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3f9bfce73f907dba7b84827c60896a4bc931767f4445f9cb08438761ad7357a5
MD5 f3fdee089e2a5c25365ff4ef18c9af39
BLAKE2b-256 7ff418f32fc68ee50c7ef3df97523390148be1da857b58db6f78e75a96da0d53

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page