Metadata-Version: 2.4
Name: aicoin
Version: 0.4.0
Summary: AICoin - Decentralized AI computing network where nodes mine AIC tokens by contributing GPU/CPU compute power to run AI inference
Author-email: AICoin Team <aicoin@proton.me>
License: MIT
Project-URL: Homepage, https://github.com/ctz168/aicoin
Project-URL: Repository, https://github.com/ctz168/aicoin
Project-URL: Documentation, https://github.com/ctz168/aicoin#readme
Project-URL: Bug Tracker, https://github.com/ctz168/aicoin/issues
Project-URL: PyPI, https://pypi.org/project/aicoin/
Keywords: aicoin,blockchain,cryptocurrency,mining,ai,decentralized,compute,inference,erc20,web3,gpu-mining,distributed-computing,governance,dao
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: ecdsa>=0.18.0
Requires-Dist: pycryptodome>=3.19.0
Requires-Dist: psutil>=5.9.0
Requires-Dist: pydantic>=2.5.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: inference
Requires-Dist: torch>=2.0.0; extra == "inference"
Requires-Dist: transformers>=4.36.0; extra == "inference"
Requires-Dist: accelerate>=0.25.0; extra == "inference"
Requires-Dist: sentencepiece>=0.1.99; extra == "inference"
Requires-Dist: safetensors>=0.4.0; extra == "inference"
Provides-Extra: web3
Requires-Dist: web3>=6.15.0; extra == "web3"
Provides-Extra: perf
Requires-Dist: uvloop>=0.19.0; extra == "perf"
Requires-Dist: numpy>=1.24.0; extra == "perf"
Provides-Extra: rust
Requires-Dist: maturin>=1.3.0; extra == "rust"
Provides-Extra: gpu
Requires-Dist: nvidia-ml-py3>=7.352.0; extra == "gpu"
Provides-Extra: all
Requires-Dist: aicoin[gpu,inference,perf,web3]; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Dynamic: license-file

# AICoin - Decentralized AI Computing Network

<p align="center">
  <strong>Train the future, mine the intelligence.</strong>
</p>

<p align="center">
  <a href="https://pypi.org/project/aicoin/"><img src="https://img.shields.io/pypi/v/aicoin.svg" alt="PyPI"></a>
  <a href="https://github.com/ctz168/aicoin"><img src="https://img.shields.io/github/stars/ctz168/aicoin.svg" alt="GitHub"></a>
  <img src="https://img.shields.io/pypi/pyversions/aicoin.svg" alt="Python Version">
  <img src="https://img.shields.io/pypi/l/aicoin.svg" alt="License">
</p>

AICoin is a decentralized AI computing network where nodes earn AIC tokens by contributing GPU/CPU compute power to run AI inference tasks. Built with Python and Solidity, it combines blockchain mining economics with distributed AI model serving.

## Table of Contents

- [Key Features](#key-features)
- [Quick Start](#quick-start)
- [Adding AICoin to MetaMask](#adding-aicoin-to-metamask)
- [Mining Guide](#mining-guide)
- [API Reference](#api-reference)
- [Payment Integration](#payment-integration)
- [Multi-Node Deployment](#multi-node-deployment)
- [Token Economics](#token-economics)
- [Architecture](#architecture)
- [Project Structure](#project-structure)
- [Requirements](#requirements)
- [License](#license)

## Key Features

- **Proof-of-Compute Mining**: Nodes mine AIC by running AI model inference (not hash puzzles). Rewards scale with actual compute contribution — GPU hours, token throughput, and task completion rate.
- **Bitcoin-Style Tokenomics**: Fixed 21,000,000 AIC max supply. Initial block reward is 50 AIC, halving every 210,000 blocks (~1 year). 50% pre-allocated to genesis wallet, 50% released through mining.
- **Zero Transaction Fees**: AICoin charges zero gas fees for all transactions. Send AIC to anyone without paying any transaction cost.
- **EVM Compatible**: Fully compatible with Ethereum JSON-RPC standard. MetaMask and other Web3 wallets can connect directly.
- **Built-in Crypto Wallet**: BIP39 mnemonic generation, HD key derivation (BIP44 `m/44'/60'/0'/0/0`), secp256k1 ECDSA signing, and encrypted local storage. Compatible with Ethereum addresses.
- **Multi-Node High Availability**: Leader/Follower architecture with automatic failover. Deploy 2+ nodes for chain stability.
- **On-Chain Governance**: Token-weighted voting (1 AIC = 1 vote). Proposals for model selection, parameter changes, emergency actions, and protocol upgrades.
- **API Gateway**: RESTful API for AI inference with tiered pricing (Basic / Standard / Premium). Revenue shared 80/20 between compute nodes and treasury.

## Quick Start

### Installation

```bash
# Basic installation (required for running a node)
pip install aicoin

# With Web3 support (for production chains)
pip install aicoin[web3]

# With AI inference support (requires GPU)
pip install aicoin[inference]

# Everything
pip install aicoin[all]
```

### Run a Single Node

The simplest way to start an AICoin chain node:

```bash
python -m core.run_chain --host 0.0.0.0 --rpc-port 8546 --chain-id 2108 \
  --miner-address 0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C \
  --data-dir ./data --block-interval 3.0
```

This starts a Leader node that:
- Produces blocks every 3 seconds
- Awards 50 AIC per block to the miner address
- Serves JSON-RPC on port 8546
- Zero gas fees for all transactions

### Create a Wallet

```python
from core.wallet import AICoinWallet

# Create a new wallet with password
wallet = AICoinWallet("my_wallet.dat")
result = wallet.create_new("my_secure_password_123")

print(f"Mnemonic: {result['mnemonic']}")
print(f"Address:  {result['address']}")
# IMPORTANT: Write down your mnemonic! It can recover your wallet.

# Load existing wallet
wallet2 = AICoinWallet("my_wallet.dat")
wallet2.unlock("my_secure_password_123")
print(f"Address: {wallet2.address}")
print(f"Balance: {wallet2.get_balance()} AIC")
```

### Send AIC Tokens

```python
from core.wallet import AICoinWallet

wallet = AICoinWallet("my_wallet.dat")
wallet.unlock("my_password")

# Send 10 AIC to another address
tx_hash = wallet.send_transaction(
    to_address="0x758C45FfDFcba739Abb232e81814d3f5bf5A913b",
    amount=10.0,  # AIC amount (decimals handled automatically)
    rpc_url="https://aic.aicq.online"
)
print(f"Transaction sent: {tx_hash}")
```

## Adding AICoin to MetaMask

### Method 1: One-Click Add (Recommended)

Visit [https://aic.aicq.online/aicoin.html](https://aic.aicq.online/aicoin.html) and click "Add to MetaMask". The network will be automatically configured.

### Method 2: Manual Configuration

Open MetaMask → Settings → Networks → Add Network manually:

| Parameter | Value |
|-----------|-------|
| **Network Name** | AICoinChain |
| **RPC URL** | `https://aic.aicq.online` |
| **Chain ID** | `2108` |
| **Currency Symbol** | `AIC` |
| **Block Explorer** | (leave blank for now) |

### Method 3: Programmatic Add

You can add the AICoin network to MetaMask programmatically from your dApp:

```javascript
await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x83C',           // 2108 in hex
    chainName: 'AICoinChain',
    nativeCurrency: {
      name: 'AIC',
      symbol: 'AIC',
      decimals: 18
    },
    rpcUrls: ['https://aic.aicq.online'],
    blockExplorerUrls: null
  }]
});
```

### Verify Connection

After adding the network, verify it works:

```bash
# Using curl
curl -X POST https://aic.aicq.online \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'

# Expected response: {"jsonrpc":"2.0","id":1,"result":"0x83c"}
```

## Mining Guide

### What is Mining?

AICoin mining is **Proof-of-Compute** — instead of solving hash puzzles, nodes earn AIC by contributing GPU/CPU compute power to run AI inference tasks. The more compute you contribute, the more AIC you earn.

### Mining Rewards

| Parameter | Value |
|-----------|-------|
| Block Reward | 50 AIC (initial) |
| Block Interval | 3 seconds |
| Halving Interval | 210,000 blocks (~1 year) |
| Max Supply | 21,000,000 AIC |
| Gas Fees | 0 (zero transaction fees) |

### Supply Schedule

```
Year 1:  50 AIC/block  → ~10,500,000 AIC mined
Year 2:  25 AIC/block  → ~5,250,000 AIC mined
Year 3:  12.5 AIC/block → ~2,625,000 AIC mined
...continues halving until max supply reached
```

### Setting Up a Mining Node

#### Step 1: Install AICoin

```bash
pip install aicoin
```

#### Step 2: Create or Import a Wallet

```python
from core.wallet import AICoinWallet

# Create new wallet
wallet = AICoinWallet("miner_wallet.dat")
result = wallet.create_new("strong_password_here")
print(f"Miner Address: {result['address']}")
print(f"Mnemonic: {result['mnemonic']}")

# Or import from existing mnemonic
wallet_import = AICoinWallet("imported_wallet.dat")
result = wallet_import.import_mnemonic("your twelve word mnemonic phrase here", "password")
print(f"Imported Address: {result['address']}")
```

#### Step 3: Start Mining (Block Production)

Run the chain node with your miner address:

```bash
python -m core.run_chain \
  --host 0.0.0.0 \
  --rpc-port 8546 \
  --chain-id 2108 \
  --miner-address YOUR_MINER_ADDRESS \
  --data-dir ./data \
  --block-interval 3.0
```

Replace `YOUR_MINER_ADDRESS` with your wallet address (e.g., `0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C`).

The node will:
1. Start producing blocks every 3 seconds
2. Award 50 AIC per block to your miner address
3. Serve JSON-RPC for wallet connections

#### Step 4: Monitor Your Mining

```bash
# Check current block number
curl -X POST http://localhost:8546 \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'

# Check your balance
curl -X POST http://localhost:8546 \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_getBalance","params":["YOUR_MINER_ADDRESS","latest"],"id":1}'
```

Or in Python:

```python
from core.blockchain import BlockchainManager

bm = BlockchainManager({"mode": "independent", "state_file": "./data/blockchain_state.json"})
balance = bm.get_balance("YOUR_MINER_ADDRESS")
print(f"Balance: {balance / 10**18:.4f} AIC")
```

### Compute Scoring

Mining rewards are proportional to each node's compute score (0-10,000), calculated from four dimensions:

| Dimension | Weight | Metric |
|-----------|--------|--------|
| Compute Utilization | 30% | GPU VRAM usage or CPU inference time |
| Throughput | 30% | Tokens/second (model-adjusted) |
| Uptime | 20% | Node online duration (log-scaled, 30-day cap) |
| Completion Rate | 20% | Successful inference tasks / total tasks in 24h |

CPU nodes receive a fair power coefficient (default 0.3x) so they earn meaningful rewards even without GPU.

## API Reference

### JSON-RPC Endpoints

AICoin implements the standard Ethereum JSON-RPC API, making it compatible with MetaMask, ethers.js, web3.py, and other Web3 tools.

**RPC URL**: `https://aic.aicq.online`

#### eth_* Methods

| Method | Description | Example |
|--------|-------------|---------|
| `eth_chainId` | Get chain ID | Returns `0x83c` (2108) |
| `eth_blockNumber` | Get latest block number | Returns hex block number |
| `eth_getBalance` | Get address balance | `["0xAddress", "latest"]` |
| `eth_sendRawTransaction` | Send signed transaction | `["0xSignedTxHex"]` |
| `eth_getTransactionReceipt` | Get transaction receipt | `["0xTxHash"]` |
| `eth_getTransactionCount` | Get address nonce | `["0xAddress", "latest"]` |
| `eth_getBlockByNumber` | Get block by number | `["0x1", true]` |
| `eth_getBlockByHash` | Get block by hash | `["0xBlockHash", true]` |
| `eth_gasPrice` | Get gas price | Returns `0x0` (zero fees!) |
| `eth_estimateGas` | Estimate gas usage | `[{to, value, data}]` |
| `eth_call` | Read-only contract call | `[{to, data}, "latest"]` |
| `eth_getCode` | Get contract code | `["0xAddress", "latest"]` |
| `eth_syncing` | Check sync status | Returns `false` when synced |
| `eth_mining` | Check if mining | Returns `true` |
| `eth_coinbase` | Get miner address | Returns miner address |
| `eth_feeHistory` | Get fee history | Returns zero fees |

#### net_* Methods

| Method | Description |
|--------|-------------|
| `net_version` | Returns `2108` |
| `net_listening` | Returns `true` |
| `net_peerCount` | Returns number of connected peers |

#### web3_* Methods

| Method | Description |
|--------|-------------|
| `web3_clientVersion` | Returns `AICoin/v0.4.0/AICoinChain` |

### API Examples

#### Using curl

```bash
# Get chain ID
curl -X POST https://aic.aicq.online \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'

# Get balance
curl -X POST https://aic.aicq.online \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C","latest"],"id":2}'

# Get block number
curl -X POST https://aic.aicq.online \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":3}'
```

#### Using Python (web3.py)

```python
from web3 import Web3

# Connect to AICoin
w3 = Web3(Web3.HTTPProvider("https://aic.aicq.online"))

# Verify connection
print(f"Connected: {w3.is_connected()}")
print(f"Chain ID: {w3.eth.chain_id}")          # 2108
print(f"Block Number: {w3.eth.block_number}")
print(f"Gas Price: {w3.eth.gas_price}")         # 0 (zero fees!)

# Check balance (returns wei, 18 decimals)
address = "0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C"
balance_wei = w3.eth.get_balance(address)
balance_aic = w3.from_wei(balance_wei, 'ether')
print(f"Balance: {balance_aic} AIC")

# Send transaction (zero gas fees)
from eth_account import Account
account = Account.from_key("your_private_key")
tx = {
    'nonce': w3.eth.get_transaction_count(account.address),
    'to': '0x758C45FfDFcba739Abb232e81814d3f5bf5A913b',
    'value': w3.to_wei(1.0, 'ether'),  # 1 AIC
    'gas': 21000,
    'gasPrice': 0,  # Zero gas fee!
    'chainId': 2108,
}
signed = account.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
print(f"TX Hash: {tx_hash.hex()}")

# Wait for receipt
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(f"Status: {'Success' if receipt.status == 1 else 'Failed'}")
```

#### Using JavaScript (ethers.js)

```javascript
const { ethers } = require('ethers');

// Connect to AICoin
const provider = new ethers.JsonRpcProvider('https://aic.aicq.online');

async function main() {
  // Check connection
  const network = await provider.getNetwork();
  console.log(`Chain ID: ${network.chainId}`);  // 2108n

  // Get block number
  const blockNumber = await provider.getBlockNumber();
  console.log(`Block: ${blockNumber}`);

  // Get balance
  const balance = await provider.getBalance('0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C');
  console.log(`Balance: ${ethers.formatEther(balance)} AIC`);

  // Send transaction
  const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);
  const tx = await wallet.sendTransaction({
    to: '0x758C45FfDFcba739Abb232e81814d3f5bf5A913b',
    value: ethers.parseEther('1.0'),  // 1 AIC
    gasPrice: 0,  // Zero gas fee!
  });
  console.log(`TX: ${tx.hash}`);
  await tx.wait();
  console.log('Confirmed!');
}
main();
```

### Sync API (Internal Node-to-Node)

AICoin uses an internal sync protocol for multi-node communication:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/sync` | POST | Handle sync messages (heartbeat, state_sync, sync_request, tx_forward, leader_announce) |
| `/` | GET | Health check endpoint |

## Payment Integration

### Accepting AIC Payments

AICoin can be used as a payment method for goods, services, or API access. Here's how to integrate AIC payments into your application.

#### Method 1: Direct Transfer (Simplest)

The simplest way to accept AIC payments is to monitor your address for incoming transactions:

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider("https://aic.aicq.online"))

def check_payment(receiving_address, expected_amount_aic):
    """Check if a payment has been received."""
    balance_wei = w3.eth.get_balance(receiving_address)
    balance_aic = w3.from_wei(balance_wei, 'ether')
    return balance_aic >= expected_amount_aic

# Example: Check if at least 100 AIC has been received
if check_payment("0xYOUR_ADDRESS", 100.0):
    print("Payment confirmed!")
```

#### Method 2: Transaction Monitoring

Monitor specific transactions for payment confirmation:

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider("https://aic.aicq.online"))

def wait_for_payment(address, expected_amount_wei, poll_interval=3):
    """Wait for a payment of a specific amount to an address."""
    initial_balance = w3.eth.get_balance(address)
    target_balance = initial_balance + expected_amount_wei

    while True:
        current_balance = w3.eth.get_balance(address)
        if current_balance >= target_balance:
            received = current_balance - initial_balance
            return {
                "status": "confirmed",
                "received_wei": received,
                "received_aic": w3.from_wei(received, 'ether'),
            }
        import time
        time.sleep(poll_interval)

# Wait for 10 AIC payment
result = wait_for_payment(
    "0xYOUR_ADDRESS",
    w3.to_wei(10.0, 'ether')
)
print(f"Payment received: {result['received_aic']} AIC")
```

#### Method 3: API Access with AIC Payment

Use AIC to pay for API access tiers:

```python
from core.blockchain import BlockchainManager

bm = BlockchainManager({"mode": "independent"})

# Purchase API access (1 AIC = Basic tier, 5 AIC = Standard, 20 AIC = Premium)
user_address = "0xUser123..."
tier = "standard"
price = 5 * 10**18  # 5 AIC in wei

# Check if user has enough balance
balance = bm.get_balance(user_address)
if balance >= price:
    # Deduct payment and enable access
    bm.purchase_api_access(user_address, tier)
    print(f"API access enabled: {tier}")
else:
    print(f"Insufficient balance: {balance / 10**18:.2f} AIC, need {price / 10**18:.2f} AIC")
```

#### Method 4: E-Commerce Integration

Example of a simple payment gateway:

```python
from web3 import Web3
from eth_account import Account

w3 = Web3(Web3.HTTPProvider("https://aic.aicq.online"))

class AICPaymentGateway:
    """Simple AIC payment gateway for e-commerce."""

    def __init__(self, merchant_private_key):
        self.account = Account.from_key(merchant_private_key)
        self.w3 = w3

    def create_invoice(self, amount_aic, order_id):
        """Create a payment invoice."""
        return {
            "order_id": order_id,
            "amount": amount_aic,
            "currency": "AIC",
            "receive_address": self.account.address,
            "chain_id": 2108,
            "rpc_url": "https://aic.aicq.online",
            "status": "pending",
        }

    def check_payment(self, amount_aic, initial_balance=None):
        """Check if payment has been received."""
        current = self.w3.eth.get_balance(self.account.address)
        if initial_balance is None:
            return current >= w3.to_wei(amount_aic, 'ether')
        return (current - initial_balance) >= w3.to_wei(amount_aic, 'ether')

# Usage
gateway = AICPaymentGateway("your_merchant_private_key")
invoice = gateway.create_invoice(10.0, "ORDER-001")
print(f"Send {invoice['amount']} AIC to {invoice['receive_address']}")
```

### Payment Flow Diagram

```
Customer                    AICoin Network                  Merchant
   |                             |                             |
   |-- 1. Create Invoice ------->|                             |
   |                             |                    2. Generate Invoice
   |                             |                    (address, amount)
   |                             |                             |
   |-- 3. Send AIC Payment ----->|                             |
   |    (zero gas fee!)          |-- 4. Transaction Included -->|
   |                             |    in block                  |
   |                             |                             |
   |                             |<-- 5. Check Balance ---------|
   |                             |    (confirmed)               |
   |                             |                    6. Fulfill Order
   |                             |                             |
```

## Multi-Node Deployment

For production stability, deploy multiple nodes in a Leader/Follower architecture. The Leader produces blocks and broadcasts state; Followers sync state and forward transactions.

### Architecture

```
                  ┌─────────────────────┐
                  │   nginx (HTTPS)     │
                  │   aic.aicq.online   │
                  └──────────┬──────────┘
                             │
            ┌────────────────┼────────────────┐
            │                │                │
     ┌──────▼──────┐  ┌─────▼──────┐  ┌─────▼──────┐
     │  Node 1     │  │  Node 2    │  │  Node 3    │
     │  (Leader)   │  │  (Follower)│  │  (Follower)│
     │  :8546      │  │  :8547     │  │  :8548     │
     │  :9551(sync)│  │  :9552     │  │  :9553     │
     │  priority=1 │  │  priority=2│  │  priority=3│
     └──────┬──────┘  └─────┬──────┘  └─────┬──────┘
            │                │                │
            └────────────────┼────────────────┘
                             │
                    Internal Sync Network
              (heartbeat + state broadcast)
```

### Deploy Leader Node

```bash
# On server 1 (Leader)
python -m core.run_chain \
  --host 0.0.0.0 \
  --rpc-port 8546 \
  --chain-id 2108 \
  --miner-address 0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C \
  --data-dir /opt/aicoin/data \
  --block-interval 3.0 \
  --role leader \
  --sync-port 9551 \
  --node-id node-8546 \
  --priority 1 \
  --peers '[{"node_id":"node-8547","host":"acer.t.aicq.online","sync_port":9552,"rpc_port":8547,"role":"follower","priority":2}]'
```

### Deploy Follower Node

```bash
# On server 2 (Follower)
python -m core.run_chain \
  --host 0.0.0.0 \
  --rpc-port 8547 \
  --chain-id 2108 \
  --miner-address 0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C \
  --data-dir /opt/aicoin/data \
  --block-interval 3.0 \
  --role follower \
  --sync-port 9552 \
  --node-id node-8547 \
  --priority 2 \
  --peers '[{"node_id":"node-8546","host":"aic.aicq.online","sync_port":9551,"rpc_port":8546,"role":"leader","priority":1}]'
```

### Sync Protocol

| Message | Direction | Description |
|---------|-----------|-------------|
| `heartbeat` | Leader → Followers | Sent every 2 seconds |
| `state_sync` | Leader → Followers | Broadcast after each new block |
| `sync_request` | Follower → Leader | Request full state (on startup or when behind) |
| `tx_forward` | Follower → Leader | Forward transaction from follower's RPC |
| `leader_announce` | New Leader → All | Announce leadership after election |

### Automatic Failover

When the Leader node goes down:
1. Followers detect heartbeat timeout (after 10 seconds)
2. The highest-priority alive Follower becomes the new Leader
3. New Leader starts producing blocks
4. Other Followers sync from the new Leader
5. When the old Leader recovers, it joins as a Follower

### Systemd Service (Production)

Create `/etc/systemd/system/aicoin.service`:

```ini
[Unit]
Description=AICoin Chain Node
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/opt/aicoin
ExecStart=/usr/bin/python3 /opt/aicoin/run_chain.py \
  --host 0.0.0.0 --rpc-port 8546 --chain-id 2108 \
  --miner-address 0x83374239A87BcbA593E0775b3EDA5a1ce8bDAA0C \
  --data-dir /opt/aicoin/data --block-interval 3.0 \
  --role leader --sync-port 9551 --node-id node-8546 --priority 1 \
  --peers '[{"node_id":"node-8547","host":"follower-host","sync_port":9552,"rpc_port":8547,"role":"follower","priority":2}]'
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
```

Then enable and start:

```bash
sudo systemctl daemon-reload
sudo systemctl enable aicoin
sudo systemctl start aicoin
sudo systemctl status aicoin
```

### Nginx Configuration (HTTPS + CORS)

```nginx
server {
    listen 443 ssl;
    server_name aic.aicq.online;

    ssl_certificate /etc/letsencrypt/live/aic.aicq.online/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/aic.aicq.online/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8546;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 86400s;

        # CORS headers (MetaMask requires this)
        add_header Access-Control-Allow-Origin * always;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type" always;

        if ($request_method = OPTIONS) {
            return 200;
        }
    }
}
```

## Token Economics

| Parameter | Value |
|-----------|-------|
| Token Symbol | AIC |
| Max Supply | 21,000,000 AIC |
| Decimals | 18 (ERC20 compatible) |
| Genesis Allocation | 10,500,000 AIC (50%) |
| Mining Reserve | 10,500,000 AIC (50%) |
| Initial Block Reward | 50 AIC |
| Halving Interval | 210,000 blocks (~1 year) |
| Mining Reward Split | 80% node / 20% treasury |
| Transaction Fee | 0 AIC (zero gas fees) |

## Architecture

```
┌──────────────────────────────────────────────────────────┐
│                      AICoin Node                         │
├──────────┬──────────┬───────────┬──────────┬─────────────┤
│  Wallet  │ Mining   │ Blockchain│Governance│ API Gateway │
│ (BIP39)  │ Engine   │ Manager   │ Manager  │ (REST)      │
├──────────┴──────────┴───────────┴──────────┴─────────────┤
│           JSON-RPC Server (EVM Compatible)                │
│           (eth_*, net_*, web3_*)                          │
├──────────────────────────────────────────────────────────┤
│           Node Sync (Leader/Follower)                     │
│           (Heartbeat + State Broadcast + Election)        │
├──────────────────────────────────────────────────────────┤
│           Block Producer (3s interval, PoA)               │
├──────────────────────────────────────────────────────────┤
│              Distributed Inference Engine                 │
│         (Pipeline Parallelism + Model Sharding)           │
├──────────────────────────────────────────────────────────┤
│              P2P Network (TCP + Gossip)                   │
│              Raft Consensus + Routing                     │
└──────────────────────────────────────────────────────────┘
```

## Project Structure

```
aicoin/
├── run_chain.py           # Chain launcher (single/multi-node)
├── start_chain.py         # Alternative launcher (full AICoinNode)
├── core/
│   ├── blockchain.py      # Blockchain manager (simulation + Web3)
│   ├── wallet.py          # BIP39/HD wallet with ECDSA signing
│   ├── tx_processor.py    # EVM-compatible transaction processor
│   ├── block_producer.py  # Block producer (3s interval, PoA)
│   ├── json_rpc.py        # JSON-RPC server (MetaMask compatible)
│   ├── node_sync.py       # Multi-node sync (Leader/Follower)
│   ├── mining_engine.py   # Compute meter + mining engine
│   ├── governance.py      # Governance manager + model registry
│   ├── node.py            # Full node (P2P + mining + API)
│   ├── api_gateway.py     # REST API gateway
│   ├── config.py          # Configuration management
│   ├── router.py          # Intelligent request routing
│   ├── consensus.py       # Finality consensus mechanism
│   └── distributed/       # Distributed inference modules
├── contracts/             # Solidity smart contracts
├── deploy/                # Deployment tools
└── tests/                 # Test suite
```

## Requirements

- Python >= 3.10
- `aiohttp` >= 3.9.0 (JSON-RPC + sync server)
- `ecdsa` >= 0.18.0 (secp256k1 signing)
- `pycryptodome` >= 3.19.0 (Keccak-256 hashing)
- `psutil` >= 5.9.0 (system monitoring)
- `pydantic` >= 2.5.0 (data validation)

### Optional

- `torch` + `transformers` (AI model inference)
- `web3` (production blockchain connection)
- `uvloop` + `numpy` (performance optimization)

## Governance

Token holders govern the network through proposals and voting:

- **1 AIC = 1 Vote** — voting power equals token balance
- **Quorum**: 10% of total supply must participate
- **Approval**: 51%+ of cast votes required to pass
- **Standard voting period**: 7 days
- **Emergency voting period**: 24 hours
- **Proposal types**: Model selection, model addition/removal, parameter changes, emergency actions, protocol upgrades
- **Minimum stake**: 1,000 AIC required to create a proposal

## License

MIT License

## Links

- **PyPI**: https://pypi.org/project/aicoin/
- **GitHub**: https://github.com/ctz168/aicoin
- **RPC Endpoint**: https://aic.aicq.online
- **Chain ID**: 2108
