485 lines
12 KiB
Markdown
485 lines
12 KiB
Markdown
# NAC钱包架构设计文档
|
||
|
||
**版本**: v2.0
|
||
**日期**: 2026年2月16日
|
||
**状态**: 生产级实现
|
||
|
||
---
|
||
|
||
## 一、总体架构
|
||
|
||
### 1.1 分层架构
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────┐
|
||
│ CLI / UI Layer │
|
||
│ (nac-wallet-cli, 未来Web/Mobile) │
|
||
├─────────────────────────────────────────────────────────┤
|
||
│ Application Layer │
|
||
│ (WalletManager, AccountManager, AssetManager) │
|
||
├─────────────────────────────────────────────────────────┤
|
||
│ Business Layer │
|
||
│ ┌──────────────┬──────────────┬──────────────────────┐ │
|
||
│ │ Transaction │ Asset │ Constitutional │ │
|
||
│ │ Builder │ Parser │ Receipt Manager │ │
|
||
│ └──────────────┴──────────────┴──────────────────────┘ │
|
||
├─────────────────────────────────────────────────────────┤
|
||
│ Infrastructure Layer │
|
||
│ ┌──────────────┬──────────────┬──────────────────────┐ │
|
||
│ │ RPC Client │ CEE Client │ Key Manager │ │
|
||
│ └──────────────┴──────────────┴──────────────────────┘ │
|
||
│ ┌──────────────┬──────────────┬──────────────────────┐ │
|
||
│ │ Storage │ Network │ Crypto │ │
|
||
│ └──────────────┴──────────────┴──────────────────────┘ │
|
||
└─────────────────────────────────────────────────────────┘
|
||
```
|
||
|
||
### 1.2 模块依赖关系
|
||
|
||
```
|
||
nac-wallet-cli
|
||
↓
|
||
nac-wallet-core
|
||
├── key_manager (密钥管理)
|
||
├── address (地址生成)
|
||
├── transaction (交易构造)
|
||
├── constitutional_receipt (CR管理)
|
||
├── gnacs_parser (资产解析)
|
||
├── network (网络通信)
|
||
│ ├── rpc_client (RPC客户端)
|
||
│ └── cee_client (CEE客户端)
|
||
├── storage (存储管理)
|
||
├── account (账户管理)
|
||
└── asset (资产管理)
|
||
```
|
||
|
||
---
|
||
|
||
## 二、核心模块设计
|
||
|
||
### 2.1 RPC通信层
|
||
|
||
**协议**: JSON-RPC 2.0
|
||
**传输**: HTTP/HTTPS
|
||
**库**: `reqwest` + `serde_json`
|
||
|
||
#### 接口设计
|
||
|
||
```rust
|
||
pub trait RpcClient {
|
||
async fn get_balance(&self, address: &Address) -> Result<Balance>;
|
||
async fn get_nonce(&self, address: &Address) -> Result<u64>;
|
||
async fn send_transaction(&self, tx: &SignedTransaction) -> Result<TxHash>;
|
||
async fn get_transaction(&self, hash: &TxHash) -> Result<Transaction>;
|
||
async fn get_transaction_receipt(&self, hash: &TxHash) -> Result<TxReceipt>;
|
||
async fn get_block(&self, number: u64) -> Result<Block>;
|
||
async fn call(&self, call_data: &CallData) -> Result<Bytes>;
|
||
}
|
||
```
|
||
|
||
#### RPC方法映射
|
||
|
||
| 功能 | RPC方法 | 参数 | 返回 |
|
||
|------|---------|------|------|
|
||
| 查询余额 | `nac_getBalance` | address, asset_id | balance |
|
||
| 查询nonce | `nac_getNonce` | address | nonce |
|
||
| 发送交易 | `nac_sendTransaction` | signed_tx | tx_hash |
|
||
| 查询交易 | `nac_getTransaction` | tx_hash | transaction |
|
||
| 查询收据 | `nac_getTransactionReceipt` | tx_hash | receipt |
|
||
| 查询区块 | `nac_getBlockByNumber` | block_number | block |
|
||
| 只读调用 | `nac_call` | call_data | result |
|
||
|
||
### 2.2 CEE通信层
|
||
|
||
**协议**: HTTP REST API
|
||
**格式**: JSON
|
||
**库**: `reqwest` + `serde_json`
|
||
|
||
#### 接口设计
|
||
|
||
```rust
|
||
pub trait CeeClient {
|
||
async fn request_cr(&self, request: &CrRequest) -> Result<ConstitutionalReceipt>;
|
||
async fn verify_cr(&self, cr: &ConstitutionalReceipt) -> Result<bool>;
|
||
async fn get_constitutional_hash(&self) -> Result<Hash>;
|
||
async fn health_check(&self) -> Result<bool>;
|
||
}
|
||
```
|
||
|
||
#### CEE API端点
|
||
|
||
| 功能 | 端点 | 方法 | 参数 | 返回 |
|
||
|------|------|------|------|------|
|
||
| 请求CR | `/api/v1/cr/request` | POST | tx_data, metadata | CR |
|
||
| 验证CR | `/api/v1/cr/verify` | POST | cr | valid |
|
||
| 宪法哈希 | `/api/v1/constitution/hash` | GET | - | hash |
|
||
| 健康检查 | `/api/v1/health` | GET | - | status |
|
||
|
||
### 2.3 交易构造流程
|
||
|
||
```
|
||
用户输入
|
||
↓
|
||
1. 构造交易体
|
||
├── 转账: TransferTx
|
||
├── 代币: TokenTransferTx
|
||
└── 合约: ContractCallTx
|
||
↓
|
||
2. 请求宪法收据
|
||
├── 向CEE发送请求
|
||
├── 包含交易数据和元数据
|
||
└── 获取签名的CR
|
||
↓
|
||
3. 验证CR
|
||
├── 验证CEE签名
|
||
├── 验证宪法哈希
|
||
└── 验证有效期
|
||
↓
|
||
4. 组装完整交易
|
||
├── Transaction = TxBody + CR
|
||
└── 计算交易哈希
|
||
↓
|
||
5. 签名交易
|
||
├── 使用私钥签名
|
||
└── 生成SignedTransaction
|
||
↓
|
||
6. 广播交易
|
||
├── 通过RPC发送
|
||
└── 获取tx_hash
|
||
↓
|
||
7. 等待确认
|
||
├── 轮询交易状态
|
||
└── 返回收据
|
||
```
|
||
|
||
### 2.4 资产管理
|
||
|
||
#### 资产类型
|
||
|
||
```rust
|
||
pub enum AssetType {
|
||
Native(NativeAsset), // XTZH, XIC
|
||
ACC20(ACC20Token), // 同质化代币
|
||
ACC721(ACC721Token), // NFT
|
||
ACC1155(ACC1155Token), // 多代币
|
||
ACC1400(ACC1400Token), // 证券型代币
|
||
}
|
||
```
|
||
|
||
#### 资产信息
|
||
|
||
```rust
|
||
pub struct AssetInfo {
|
||
pub asset_id: String,
|
||
pub name: String,
|
||
pub symbol: String,
|
||
pub decimals: u8,
|
||
pub gnacs_code: GNACSCode,
|
||
pub asset_type: AssetType,
|
||
pub contract_address: Option<Address>,
|
||
pub total_supply: Option<u128>,
|
||
pub metadata: HashMap<String, String>,
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 三、数据结构设计
|
||
|
||
### 3.1 地址结构
|
||
|
||
```rust
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub struct Address {
|
||
pub version: u8, // 1字节:版本
|
||
pub account_type: u8, // 1字节:账户类型
|
||
pub kyc_level: u8, // 1字节:KYC等级
|
||
pub region: u16, // 2字节:区域代码
|
||
pub pubkey_hash: [u8; 26], // 26字节:公钥哈希
|
||
}
|
||
```
|
||
|
||
### 3.2 交易结构
|
||
|
||
```rust
|
||
#[derive(Clone, Debug)]
|
||
pub struct Transaction {
|
||
pub nonce: u64,
|
||
pub from: Address,
|
||
pub to: Address,
|
||
pub value: u128,
|
||
pub asset_id: String,
|
||
pub data: Vec<u8>,
|
||
pub gas_limit: u64,
|
||
pub gas_price: u128,
|
||
pub constitutional_receipt: ConstitutionalReceipt,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
pub struct SignedTransaction {
|
||
pub transaction: Transaction,
|
||
pub signature: Signature,
|
||
pub public_key: PublicKey,
|
||
}
|
||
```
|
||
|
||
### 3.3 宪法收据结构
|
||
|
||
```rust
|
||
#[derive(Clone, Debug)]
|
||
pub struct ConstitutionalReceipt {
|
||
pub transaction_hash: [u8; 32],
|
||
pub constitutional_hash: [u8; 32],
|
||
pub clause_mask: u64,
|
||
pub execution_result_hash: [u8; 32],
|
||
pub timestamp: u64,
|
||
pub validity_window: u64,
|
||
pub signatures: Vec<Vec<u8>>,
|
||
pub receipt_id: [u8; 32],
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 四、存储设计
|
||
|
||
### 4.1 密钥库格式
|
||
|
||
```json
|
||
{
|
||
"version": 1,
|
||
"id": "uuid",
|
||
"address": "nac1...",
|
||
"crypto": {
|
||
"cipher": "aes-256-gcm",
|
||
"ciphertext": "...",
|
||
"cipherparams": {
|
||
"nonce": "..."
|
||
},
|
||
"kdf": "pbkdf2",
|
||
"kdfparams": {
|
||
"dklen": 32,
|
||
"salt": "...",
|
||
"c": 100000,
|
||
"prf": "hmac-sha256"
|
||
}
|
||
},
|
||
"metadata": {
|
||
"account_type": "personal",
|
||
"kyc_level": 2,
|
||
"region": 156,
|
||
"created_at": 1708099200
|
||
}
|
||
}
|
||
```
|
||
|
||
### 4.2 配置文件格式
|
||
|
||
```toml
|
||
[network]
|
||
chain_id = 626
|
||
network_name = "mainnet"
|
||
|
||
[[rpc_nodes]]
|
||
url = "https://rpc.newassetchain.com"
|
||
priority = 1
|
||
|
||
[[rpc_nodes]]
|
||
url = "https://rpc2.newassetchain.com"
|
||
priority = 2
|
||
|
||
[[cee_nodes]]
|
||
url = "https://cee.newassetchain.com"
|
||
priority = 1
|
||
|
||
[[cee_nodes]]
|
||
url = "https://cee2.newassetchain.com"
|
||
priority = 2
|
||
|
||
[wallet]
|
||
keystore_dir = "~/.nac/keystore"
|
||
cache_dir = "~/.nac/cache"
|
||
log_level = "info"
|
||
```
|
||
|
||
---
|
||
|
||
## 五、错误处理
|
||
|
||
### 5.1 错误类型
|
||
|
||
```rust
|
||
#[derive(Debug, thiserror::Error)]
|
||
pub enum WalletError {
|
||
#[error("密钥管理错误: {0}")]
|
||
KeyManagement(String),
|
||
|
||
#[error("网络通信错误: {0}")]
|
||
Network(String),
|
||
|
||
#[error("交易构造错误: {0}")]
|
||
Transaction(String),
|
||
|
||
#[error("宪法收据错误: {0}")]
|
||
ConstitutionalReceipt(String),
|
||
|
||
#[error("存储错误: {0}")]
|
||
Storage(String),
|
||
|
||
#[error("解析错误: {0}")]
|
||
Parse(String),
|
||
|
||
#[error("验证错误: {0}")]
|
||
Validation(String),
|
||
}
|
||
```
|
||
|
||
### 5.2 错误处理策略
|
||
|
||
1. **网络错误**: 自动重试(最多3次),切换备用节点
|
||
2. **CEE错误**: 尝试其他CEE节点,记录失败节点
|
||
3. **交易错误**: 返回详细错误信息,不自动重试
|
||
4. **存储错误**: 立即返回,不修改数据
|
||
5. **验证错误**: 拒绝操作,记录日志
|
||
|
||
---
|
||
|
||
## 六、安全设计
|
||
|
||
### 6.1 密钥安全
|
||
|
||
1. **内存清除**: 使用`zeroize`库清除敏感数据
|
||
2. **加密存储**: AES-256-GCM + PBKDF2
|
||
3. **密码强度**: 最少8位,建议12位以上
|
||
4. **助记词**: BIP39标准,支持12/24词
|
||
|
||
### 6.2 网络安全
|
||
|
||
1. **HTTPS**: 所有网络通信使用TLS
|
||
2. **证书验证**: 验证服务器证书
|
||
3. **超时设置**: 防止长时间阻塞
|
||
4. **重放攻击**: 使用nonce机制
|
||
|
||
### 6.3 交易安全
|
||
|
||
1. **CR验证**: 强制验证宪法收据
|
||
2. **签名验证**: 验证所有签名
|
||
3. **金额检查**: 防止溢出和负数
|
||
4. **Gas估算**: 防止Gas不足
|
||
|
||
---
|
||
|
||
## 七、性能优化
|
||
|
||
### 7.1 缓存策略
|
||
|
||
1. **余额缓存**: 5秒TTL
|
||
2. **Nonce缓存**: 实时更新
|
||
3. **资产信息缓存**: 1小时TTL
|
||
4. **宪法哈希缓存**: 10分钟TTL
|
||
|
||
### 7.2 并发处理
|
||
|
||
1. **异步I/O**: 使用tokio异步运行时
|
||
2. **连接池**: 复用HTTP连接
|
||
3. **批量查询**: 支持批量RPC请求
|
||
4. **并行验证**: 并行验证多个签名
|
||
|
||
### 7.3 资源管理
|
||
|
||
1. **内存限制**: 限制缓存大小
|
||
2. **连接限制**: 限制并发连接数
|
||
3. **日志轮转**: 防止日志文件过大
|
||
4. **数据库清理**: 定期清理过期数据
|
||
|
||
---
|
||
|
||
## 八、测试策略
|
||
|
||
### 8.1 单元测试
|
||
|
||
- 每个模块独立测试
|
||
- 覆盖率目标: 80%+
|
||
- Mock外部依赖
|
||
|
||
### 8.2 集成测试
|
||
|
||
- 完整流程测试
|
||
- 使用测试网
|
||
- 模拟各种场景
|
||
|
||
### 8.3 性能测试
|
||
|
||
- 并发交易测试
|
||
- 大数据量测试
|
||
- 长时间运行测试
|
||
|
||
---
|
||
|
||
## 九、技术选型
|
||
|
||
### 9.1 核心库
|
||
|
||
| 功能 | 库 | 版本 | 说明 |
|
||
|------|-----|------|------|
|
||
| 异步运行时 | tokio | 1.0 | 异步I/O |
|
||
| HTTP客户端 | reqwest | 0.11 | RPC/CEE通信 |
|
||
| 序列化 | serde | 1.0 | JSON处理 |
|
||
| 密码学 | ed25519-dalek | 2.0 | Ed25519签名 |
|
||
| 哈希 | sha3 | 0.10 | SHA3-384 |
|
||
| 加密 | aes-gcm | 0.10 | AES-256-GCM |
|
||
| 密钥派生 | pbkdf2 | 0.12 | PBKDF2 |
|
||
| 助记词 | bip39 | 2.0 | BIP39 |
|
||
| 错误处理 | thiserror | 1.0 | 错误类型 |
|
||
| 日志 | tracing | 0.1 | 结构化日志 |
|
||
| CLI | clap | 4.0 | 命令行解析 |
|
||
|
||
### 9.2 开发工具
|
||
|
||
- **构建**: Cargo
|
||
- **测试**: cargo test
|
||
- **文档**: cargo doc
|
||
- **格式化**: rustfmt
|
||
- **Lint**: clippy
|
||
|
||
---
|
||
|
||
## 十、实现计划
|
||
|
||
### Phase 1: 基础设施(2天)
|
||
- [x] 密钥管理
|
||
- [x] 地址生成
|
||
- [x] 存储模块
|
||
|
||
### Phase 2: 网络通信(2天)
|
||
- [ ] RPC客户端
|
||
- [ ] CEE客户端
|
||
- [ ] 错误处理
|
||
|
||
### Phase 3: 交易处理(2天)
|
||
- [ ] 交易构造
|
||
- [ ] CR集成
|
||
- [ ] 交易签名
|
||
|
||
### Phase 4: 资产管理(1天)
|
||
- [ ] 资产解析
|
||
- [ ] 余额查询
|
||
- [ ] 代币管理
|
||
|
||
### Phase 5: CLI工具(2天)
|
||
- [ ] 基础命令
|
||
- [ ] 交易命令
|
||
- [ ] 资产命令
|
||
|
||
### Phase 6: 测试(1天)
|
||
- [ ] 单元测试
|
||
- [ ] 集成测试
|
||
- [ ] 文档
|
||
|
||
**总计**: 10天完成生产级钱包
|
||
|
||
---
|
||
|
||
**架构设计完成**: ✅
|
||
**下一步**: 实现RPC通信层
|