Metadata-Version: 2.4
Name: aicoin
Version: 0.1.0
Summary: AICoin - 去中心化AI算力挖矿网络
Author: AICoin Team
License: MIT
Project-URL: Homepage, https://github.com/ctz168/aicoin
Project-URL: Repository, https://github.com/ctz168/aicoin
Project-URL: Issues, https://github.com/ctz168/aicoin/issues
Keywords: blockchain,ai,mining,decentralized,cryptocurrency,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
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: ecdsa>=0.18.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"

<p align="center">
  <strong>AICoin</strong> — 去中心化AI算力挖矿网络
</p>

<p align="center">
  <a href="#安装">安装</a> ·
  <a href="#快速开始">快速开始</a> ·
  <a href="#节点部署指南">节点部署</a> ·
  <a href="#api-使用">API 使用</a> ·
  <a href="#架构设计">架构</a>
</p>

---

## 项目简介

**AICoin (AIC)** 是一个基于区块链的去中心化AI计算网络。网络通过代币激励机制将AI算力提供者、API调用者和治理参与者连接在一起，构建一个可持续的去中心化AI基础设施。

### 三大角色

| 角色 | 说明 |
|------|------|
| **算力节点** | 贡献 GPU/CPU 算力运行 AI 模型，通过"算力挖矿"获得 AICoin 代币奖励 |
| **API 调用者** | 通过燃烧 AICoin 代币来使用网络中的 AI 算力，获取 OpenAI 兼容的 API 服务 |
| **治理参与者** | AIC 代币持有者通过投票治理，决定网络运行的 AI 模型及关键参数 |

---

## 安装

### 从 PyPI 安装（推荐）

```bash
# 基础安装（仅核心功能，无需 GPU）
pip install aicoin

# 完整安装（含 AI 推理、Web3、高性能优化）
pip install aicoin[all]

# 按需安装
pip install aicoin[inference]   # AI 模型推理（需要 GPU）
pip install aicoin[web3]       # 连接真实区块链
pip install aicoin[perf]       # 高性能优化（uvloop + numpy）
pip install aicoin[gpu]        # GPU 监控（NVIDIA）
```

### 从源码安装

```bash
git clone https://github.com/ctz168/aicoin.git
cd aicoin
pip install -e .              # 开发模式安装
# 或
pip install -e .[all]         # 开发模式 + 全部依赖
```

### 环境要求

| 依赖 | 最低版本 | 说明 |
|------|---------|------|
| Python | 3.10+ | 推荐 3.11 或 3.12 |
| pip | 最新版 | `pip install --upgrade pip` |
| CUDA GPU | 可选 | 用于加速模型推理（无 GPU 可运行模拟模式） |

---

## 快速开始

安装完成后，使用 `aicoin` 命令启动：

```bash
# 交互式启动菜单
aicoin

# 演示挖矿（模拟模式，无需 GPU）
aicoin --demo

# 钱包管理
aicoin --wallet

# 查看节点状态
aicoin --status

# 查看版本
aicoin --version
```

### 30 秒体验

```bash
pip install aicoin && aicoin --demo
```

演示模式会自动完成以下步骤：

1. 创建/加载钱包（BIP39 助记词 + 以太坊地址）
2. 初始化模拟区块链（无需真实链节点）
3. 模拟 AI 推理任务（贡献算力）
4. 提交算力证明到链上
5. 计算并领取挖矿奖励

---

## 节点部署指南

### 1. 系统要求

#### 最低配置（模拟模式 / CPU 推理）

| 组件 | 要求 |
|------|------|
| CPU | 4 核以上 |
| 内存 | 8 GB |
| 硬盘 | 20 GB 可用空间 |
| 网络 | 公网 IP 或端口映射 |
| 系统 | Ubuntu 20.04+ / Debian 11+ / CentOS 8+ |

#### 推荐配置（GPU 推理）

| 组件 | 要求 |
|------|------|
| CPU | 8 核以上 |
| GPU | NVIDIA RTX 3060+（8 GB 显存） |
| 内存 | 32 GB |
| 硬盘 | 100 GB SSD |
| CUDA | 11.8+ |
| 系统 | Ubuntu 22.04 LTS |

### 2. 安装步骤

#### 方式一：pip 安装（最简）

```bash
# 1. 创建虚拟环境
python3 -m venv .venv
source .venv/bin/activate

# 2. 安装 AICoin
pip install aicoin[all]

# 3. 启动节点
aicoin
```

#### 方式二：源码安装（开发者推荐）

```bash
# 1. 克隆仓库
git clone https://github.com/ctz168/aicoin.git
cd aicoin

# 2. 创建虚拟环境
python3 -m venv .venv
source .venv/bin/activate

# 3. 安装依赖
pip install -e .[all]

# 4. 启动节点
python run.py
```

#### 方式三：Docker 部署（生产环境推荐）

```bash
# 拉取镜像（即将支持）
# docker pull aicoin/node:latest

# 运行节点
# docker run -d \
#   --name aicoin-node \
#   --gpus all \
#   -p 8080:8080 \
#   -p 5000:5000 \
#   -v $(pwd)/data:/app/data \
#   aicoin/node:latest
```

### 3. 配置节点

创建配置文件 `config.json`：

```json
{
  "node": {
    "node_id": "",
    "node_name": "my-mining-node",
    "wallet_address": ""
  },
  "network": {
    "host": "0.0.0.0",
    "api_port": 8080,
    "p2p_port": 5000,
    "seeds": []
  },
  "blockchain": {
    "mode": "simulation",
    "web3_rpc_url": "",
    "contract_address": "",
    "chain_id": 1
  },
  "mining": {
    "auto_mine": true,
    "mining_interval": 60,
    "proof_submission_enabled": true
  },
  "model": {
    "name": "Qwen/Qwen2.5-0.5B-Instruct",
    "base_path": "./models"
  },
  "governance": {
    "enabled": true,
    "min_proposal_stake": 1000,
    "voting_period_days": 7,
    "quorum_percentage": 10.0,
    "approval_threshold": 51.0
  }
}
```

**关键配置说明**：

| 配置项 | 说明 | 默认值 |
|--------|------|--------|
| `node.node_id` | 节点唯一标识，留空自动生成 | 自动 UUID |
| `node.wallet_address` | 钱包地址，用于接收挖矿奖励 | 空（启动时创建） |
| `blockchain.mode` | `simulation` 模拟链 / `web3` 真实链 | `simulation` |
| `mining.auto_mine` | 是否自动挖矿 | `true` |
| `model.name` | 运行的 AI 模型 | `Qwen/Qwen2.5-0.5B-Instruct` |
| `network.seeds` | 种子节点列表 `["host:port", ...]` | `[]` |

### 4. 连接真实区块链（可选）

默认使用模拟模式。如需连接以太坊兼容链：

```json
{
  "blockchain": {
    "mode": "web3",
    "web3_rpc_url": "https://mainnet.infura.io/v3/YOUR_KEY",
    "contract_address": "0xDeployedContractAddress",
    "chain_id": 1
  }
}
```

### 5. 环境变量覆盖

所有配置均支持通过 `AICOIN_` 前缀的环境变量覆盖：

```bash
export AICOIN_API_PORT=9090
export AICOIN_AUTO_MINE=true
export AICOIN_SEEDS=node1:5000,node2:5000
export AICOIN_MODEL_NAME=Qwen/Qwen2.5-7B-Instruct
```

### 6. systemd 守护进程（Linux 生产环境）

创建 `/etc/systemd/system/aicoin.service`：

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

[Service]
Type=simple
User=aicoin
WorkingDirectory=/opt/aicoin
ExecStart=/opt/aicoin/.venv/bin/python run.py
Restart=always
RestartSec=10
Environment=AICOIN_LOG_LEVEL=INFO

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

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

### 7. 防火墙配置

```bash
# 开放 API 和 P2P 端口
sudo ufw allow 8080/tcp   # API 网关
sudo ufw allow 5000/tcp   # P2P 通信
```

---

## 架构设计

```
API 调用者
   │ 燃烧 AIC
   ▼
┌──────────┐    路由请求    ┌─────────────┐
│ API 网关   │──────────────→│ 最优路由引擎  │
└──────────┘               └──────┬───────┘
                                  │
                    ┌─────────────┼─────────────┐
                    ▼             ▼              ▼
              ┌──────────┐ ┌──────────┐  ┌──────────┐
              │ 算力节点A │ │ 算力节点B │  │ 算力节点C │
              │ (挖矿)   │ │ (挖矿)   │  │ (挖矿)   │
              └────┬─────┘ └────┬─────┘  └────┬─────┘
                   │            │              │
                   └────────────┼──────────────┘
                                ▼
                    ┌──────────────────────┐
                    │   AICoin 区块链       │
                    │ (智能合约管理层)       │
                    │ - AICoinToken 代币    │
                    │ - Mining 挖矿合约     │
                    │ - Governance 治理     │
                    │ - APIAccess API 访问   │
                    └──────────────────────┘
```

### 项目结构

```
aicoin/
├── contracts/              # Solidity 智能合约
│   ├── AICoinToken.sol     # ERC20 代币合约 (21M 最大供应)
│   ├── Mining.sol          # 算力挖矿合约 (减半机制)
│   ├── Governance.sol      # 治理投票合约
│   ├── APIAccess.sol       # API 调用燃烧合约
│   └── AICoinDAO.sol       # DAO 聚合合约
├── core/                   # Python 后端核心
│   ├── blockchain.py       # 区块链交互层 (模拟/Web3 双模式)
│   ├── mining_engine.py    # 挖矿引擎 (ComputeMeter/MiningEngine/RewardDistributor)
│   ├── router.py           # 最优路由引擎 (NodeRegistry/LatencyProbe/OptimalRouter)
│   ├── governance.py       # 治理管理 (GovernanceManager/ModelRegistry/ProposalExecutor)
│   ├── api_gateway.py      # OpenAI 兼容 API 网关
│   ├── wallet.py           # 内置加密钱包 (BIP39/BIP44)
│   ├── config.py           # 配置管理系统
│   ├── node.py             # 节点主程序入口
│   ├── worker_pool.py      # 多进程工作池 (绕过 GIL)
│   ├── async_blockchain.py # 异步 I/O 路径 (asyncio + uvloop)
│   ├── consensus.py        # 最终确认机制 (时间锁定 + 验证者投票)
│   ├── dag_scheduler.py    # 依赖图调度器 (图着色并行)
│   ├── hybrid_inference.py # 混合推理引擎
│   └── distributed/        # P2P 分布式推理
│       ├── distributed_node.py
│       ├── raft_election.py
│       ├── network_manager.py
│       └── ...
├── tests/                  # 测试套件 (106 个测试用例)
├── ui/                     # Web 管理仪表盘
├── config.json             # 默认配置模板
├── run.py                  # 一键启动脚本 (pip 入口点)
├── pyproject.toml          # 项目打包配置 (PyPI)
├── requirements.txt        # Python 依赖
└── README.md               # 本文件
```

---

## 核心特性

### 1. 算力挖矿（类比特币减半机制）

- 节点贡献 GPU/CPU 算力运行 AI 大语言模型
- 按算力贡献比例分配区块挖矿奖励
- **初始奖励 50 AIC / 区块**，每 **210,000 区块** 减半
- **最大供应量 21,000,000 AIC**
- 80% 奖励分配给算力节点，20% 进入 DAO 金库
- **支持 CPU 推理**：无 GPU 也能参与挖矿，算力按 30% 折算

### 2. 代币治理（DAO）

- AIC 代币持有者可以发起治理提案
- **提案类型**：运行模型选择、新增模型、移除模型、网络参数修改、紧急操作、协议升级
- **投票规则**：1 AIC = 1 票，51% 通过阈值，10% 法定人数
- 支持投票委托机制

### 3. 去中心化 API 网关

- **OpenAI 兼容 API 接口** — 可直接替换 OpenAI SDK 的 `base_url`
- 代币燃烧机制，输入/输出分离计费
- **最优路由引擎**：就近选择延迟最低的可用节点
- 收入分配：80% 给算力节点，20% 进入金库

### 4. P2P 分布式网络

- 基于 servermodel 的分布式推理引擎
- NAT 穿透支持，轻松部署在家庭网络环境
- **Raft 共识** 实现 Leader 选举与节点协调
- **管线并行推理**，多节点协同处理大模型请求

### 5. 高性能优化

- **多进程架构**：绕过 Python GIL，实现真正的并行交易处理
- **异步 I/O**：asyncio + uvloop，API 吞吐提升 10 倍
- **最终确认机制**：时间锁定 + 2/3 验证者投票
- **依赖图调度器**：图着色算法并行，并行度提升 10 倍
- **Rust 执行引擎**：PyO3 FFI，TPS 从数百提升到万级

---

## API 使用

### 使用 requests

```python
import requests

# 查询余额
balance = requests.get(
    "http://localhost:8080/v1/balance/your_address"
).json()

# 聊天补全（需要燃烧 AIC）
response = requests.post(
    "http://localhost:8080/v1/chat/completions",
    headers={
        "x-aicoin-address": "your_wallet_address",
        "Content-Type": "application/json"
    },
    json={
        "model": "aicoin-qwen-72b",
        "messages": [{"role": "user", "content": "Hello"}],
        "max_tokens": 100
    }
).json()
```

### 使用 OpenAI SDK（直接兼容）

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="your_wallet_address"  # 用钱包地址作为 API Key
)

response = client.chat.completions.create(
    model="aicoin-qwen-72b",
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)
```

### API 端点

| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/health` | 健康检查 |
| GET | `/stats` | 网络统计信息 |
| GET | `/v1/models` | 可用模型列表 |
| GET | `/v1/pricing` | API 定价信息 |
| GET | `/v1/balance/:address` | 查询余额 |
| POST | `/v1/chat/completions` | 聊天补全（OpenAI 兼容） |
| POST | `/v1/governance/proposals` | 创建治理提案 |
| POST | `/v1/governance/vote` | 投票 |
| GET | `/v1/governance/proposals` | 查询提案列表 |
| GET | `/v1/mining/stats` | 挖矿统计 |
| GET | `/v1/mining/rewards/:address` | 查询挖矿奖励 |

---

## 代币经济学

| 参数 | 值 |
|------|-----|
| 代币名称 | AICoin (AIC) |
| 代币标准 | ERC20 |
| 最大供应量 | 21,000,000 AIC |
| 初始区块奖励 | 50 AIC |
| 减半周期 | 210,000 区块（约 1 年） |
| 节点奖励比例 | 80% |
| DAO 金库比例 | 20% |
| 治理提案最低质押 | 1,000 AIC |
| 投票周期 | 7 天（紧急 24 小时） |
| 法定人数 | 总供应量的 10% |
| 通过阈值 | 赞成票 >= 51% |

### API 调用定价

| 模型 | 参数量 | 输入价格 | 输出价格 |
|------|--------|---------|---------|
| aicoin-llama-7b | 7B | 0.0004 AIC / 1K | 0.0012 AIC / 1K |
| aicoin-mistral-7b | 7B | 0.0004 AIC / 1K | 0.0012 AIC / 1K |
| aicoin-llama-13b | 13B | 0.0007 AIC / 1K | 0.0018 AIC / 1K |
| aicoin-coder-34b | 34B | 0.0012 AIC / 1K | 0.0032 AIC / 1K |
| aicoin-llama-70b | 70B | 0.0018 AIC / 1K | 0.0045 AIC / 1K |
| aicoin-qwen-72b | 72B | 0.0018 AIC / 1K | 0.0045 AIC / 1K |

---

## 智能合约

| 合约 | 说明 |
|------|------|
| **AICoinToken.sol** | ERC20 代币合约，21,000,000 AIC 最大供应量，支持铸造/燃烧 |
| **Mining.sol** | 算力证明挖矿合约，内置比特币减半奖励机制 |
| **Governance.sol** | DAO 治理合约，支持提案创建、投票、执行 |
| **APIAccess.sol** | API 访问控制合约，代币燃烧计费逻辑 |
| **AICoinDAO.sol** | DAO 聚合合约，统一管理所有子合约交互 |

---

## 运行测试

```bash
# 安装开发依赖
pip install aicoin[dev]

# 运行全部测试
python -m pytest tests/test_all.py -v

# 预期: 106 passed
```

---

## 许可证

MIT License
