simchain-go 是一个本地极简 PoW 区块链模拟器,用于学习和测试区块链核心概念:
- ⛏️ PoW 挖矿 - 可配置难度的工作量证明
- 🔗 链同步 - Headers-first 同步协议
- 🌐 P2P 网络 - 支持 TCP 多进程或 inproc 单进程模式
- 💾 持久化 - 主链数据落盘与重启恢复
- 🔒 身份绑定 - Ed25519 握手验证
⚠️ 声明: 本项目部分代码基于 AI 辅助生成,仅供学习测试使用,不适用于生产环境。
# 构建节点
go build -o simchain-node ./cmd/node
# 构建客户端
go build -o simchain-cli ./cmd/cli# 启动 2 节点仿真,运行 30 秒
./simchain-node --nodes=2 --difficulty=16 --duration=30s# 终端 1: Seed 节点
./simchain-node --transport=tcp --listen=127.0.0.1:50001 --duration=0
# 终端 2: 普通节点
./simchain-node --transport=tcp --listen=127.0.0.1:50002 --seeds=127.0.0.1:50001 --duration=0
# 终端 3: 普通节点
./simchain-node --transport=tcp --listen=127.0.0.1:50003 --seeds=127.0.0.1:50001 --duration=0┌─────────────────────────────────────────────────────┐
│ Node (编排者) │
│ ┌────────┐ ┌─────────┐ ┌───────┐ ┌───────────────┐ │
│ │ Miner │ │ Mempool │ │ Chain │ │ Syncer │ │
│ └────────┘ └─────────┘ └───────┘ └───────────────┘ │
│ │ │
│ ┌─────────────────────┴──────────────────────────┐ │
│ │ Transport (inproc/TCP) │ │
│ └────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────┴──────────────────────────┐ │
│ │ Store │ │
│ └────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
详细设计文档:
DESIGN.md- V1 基础设计DESIGN_V2.md- V2 Inv/Get 协议DESIGN_V3_UNIFIED.md- V3 TCP + 持久化 + 健壮性
| 参数 | 说明 | 默认值 |
|---|---|---|
--transport |
传输方式 inproc|tcp |
inproc |
--listen |
TCP 监听地址 | - |
--seeds |
Seed 节点列表(逗号分隔) | - |
--data-dir |
数据目录 | data/tcp-<port> |
--difficulty |
PoW 难度(前导零 bits) | 16 |
--duration |
运行时长(0 = 永久) |
30s |
--tx-interval |
交易注入间隔 | 1s |
--max-tx-per-block |
每块最大交易数 | 50 |
--miner-sleep |
挖矿间隔 | 10ms |
Windows (PowerShell)
.\scripts\run-tcp-demo.ps1 -BasePort 50001 -Nodes 3 -DurationSec 20 -Difficulty 16Linux/macOS (Bash)
BASE_PORT=50001 NODES=3 DURATION_SEC=20 ./scripts/run-tcp-demo.sh# 提交交易
./simchain-cli --connect=127.0.0.1:50001 --cmd=submit --data="hello world"go test ./...go test ./internal/integration -run TestTCPE2E -vMempool 容量测试 (testPool.ps1)
# 前置: 启动节点
./simchain-node --transport=tcp --listen=127.0.0.1:50001 --duration=0
# 运行测试 (另一终端)
./testPool.ps1预期: Mempool 增长至 5000 后稳定,拒绝后续交易。
TCP 连接限制测试 (verify_v3c.py)
# 连接数限制
python verify_v3c.py tcp-limit --port 50001 --count 10
# Slowloris 防护
python verify_v3c.py slowloris --port 50001simchain-go/
├── cmd/
│ ├── node/ # 节点主程序
│ └── cli/ # 命令行客户端
├── internal/
│ ├── blockchain/ # 链索引与 reorg
│ ├── mempool/ # 交易池
│ ├── syncer/ # 同步状态机
│ ├── transport/ # 网络传输 (inproc/TCP)
│ ├── store/ # 持久化
│ └── ...
├── scripts/ # 演示脚本
├── data/ # 运行时数据
└── *.md # 设计文档
完整结构见 FILE_TREE.md
TCP 消息编码与 framing 约定见 PROTOCOL.md
MIT