diff --git a/DELIVERY_REPORT.md b/DELIVERY_REPORT.md index 1d7af98..622f9d2 100644 --- a/DELIVERY_REPORT.md +++ b/DELIVERY_REPORT.md @@ -40,7 +40,7 @@ | **宪法层** | 6 | nac-cee, nac-constitution-state等 | | **钱包系统** | 4 | nac-wallet-core, nac-wallet-cli等 | | **工具链** | 6 | charter-compiler, cnnl-compiler等 | -| **NAC Lens** | 1 | nac-nrpc4 | +| **NAC Lens** | 1 | nac-lens | | **VISION钱包** | 2 | nac-vision-wallet, nac-vision-cli | ### 2.2 技术栈 @@ -93,7 +93,7 @@ ### 3.2 NAC Lens协议升级 -**模块**: `nac-nrpc4/` +**模块**: `nac-lens/` **版本**: 4.0.0-alpha **实现状态**: Phase 1完成(L1-L3层) @@ -422,7 +422,7 @@ NAC_Clean_Dev/ ├── nac-bridge-ethereum/ # 以太坊桥接 ├── nac-contract-deployer/ # 合约部署器 ├── xtzh-ai/ # XTZH AI -├── nac-nrpc4/ # NAC Lens ⭐ 新增 +├── nac-lens/ # NAC Lens ⭐ 新增 ├── nac-vision-wallet/ # VISION钱包核心 ⭐ 新增 └── nac-vision-cli/ # VISION钱包CLI ⭐ 新增 ``` diff --git a/ISSUE_025_COMPLETION_REPORT.md b/ISSUE_025_COMPLETION_REPORT.md index 0aded45..37a286d 100644 --- a/ISSUE_025_COMPLETION_REPORT.md +++ b/ISSUE_025_COMPLETION_REPORT.md @@ -139,7 +139,7 @@ nac-upgrade-framework/ - nac-deploy, nac-ftan - nac-integration-tests - nac-ma-rcm, nac-monitor -- nac-nrpc, nac-nrpc4, nac-nvm +- nac-nrpc, nac-lens, nac-nvm - nac-rwa-exchange - nac-sdk, nac-serde, nac-test - nac-uca, nac-udm @@ -287,7 +287,7 @@ match module.upgrade(target, upgrade_data) { - nac-nvm - nac-cbpp - nac-csnp - - nac-nrpc4 + - nac-lens 2. ✅ 添加升级监控和日志 3. ✅ 实现升级回滚测试 diff --git a/ISSUE_025_MODULE_UPGRADE_ANALYSIS.md b/ISSUE_025_MODULE_UPGRADE_ANALYSIS.md index 21ad555..669b6c5 100644 --- a/ISSUE_025_MODULE_UPGRADE_ANALYSIS.md +++ b/ISSUE_025_MODULE_UPGRADE_ANALYSIS.md @@ -210,7 +210,7 @@ pub struct UpgradeRecord { - [ ] nac-nvm (虚拟机) - [ ] nac-cbpp (共识) - [ ] nac-csnp (网络) -- [ ] nac-nrpc4 (RPC) +- [ ] nac-lens (RPC) - [ ] nac-constitution-state (宪法状态) ### Phase 3: 集成到ACC协议模块(3天) diff --git a/NAC_Development_Work_Log_20260217.md b/NAC_Development_Work_Log_20260217.md index 449e352..2656da9 100644 --- a/NAC_Development_Work_Log_20260217.md +++ b/NAC_Development_Work_Log_20260217.md @@ -35,7 +35,7 @@ NAC公链是一套完全自主开发的RWA(Real World Assets)专用区块链 ### 2.1 核心协议层 -#### ✅ nac-nrpc4 - NAC Lens元协议 +#### ✅ nac-lens - NAC Lens元协议 **功能描述:** NRPC(NAC Remote Procedure Call)4.0是NAC公链的核心通信协议,实现了六层协议栈(L1-L6),支持高效的节点间通信、数据传输和协议升级。 @@ -56,7 +56,7 @@ NAC公链是一套完全自主开发的RWA(Real World Assets)专用区块链 **编译产物:** -- 库文件:`target/release/libnac_nrpc4.rlib` +- 库文件:`target/release/libnac_lens.rlib` - 文档:完整的API文档和使用示例 --- @@ -558,7 +558,7 @@ done ``` NAC_Clean_Dev/ -├── nac-nrpc4/ # NAC Lens元协议 +├── nac-lens/ # NAC Lens元协议 ├── nac-vision-wallet/ # VISION钱包核心库 ├── nac-vision-cli/ # VISION CLI工具 ├── nac-acc-1410/ # ACC-1410部分同质化资产协议 @@ -661,7 +661,7 @@ ACC协议族 | 模块 | 单元测试 | 集成测试 | 总计 | 通过率 | |------|---------|---------|------|-------| -| nac-nrpc4 | 10 | 0 | 10 | 100% | +| nac-lens | 10 | 0 | 10 | 100% | | nac-vision-wallet | 4 | 0 | 4 | 100% | | nac-vision-cli | 0 | 0 | 0 | N/A | | nac-acc-1410 | 12 | 1 | 13 | 100% | diff --git a/NAC开发总结_2026-02-18.md b/NAC开发总结_2026-02-18.md index 297bf99..317bbce 100644 --- a/NAC开发总结_2026-02-18.md +++ b/NAC开发总结_2026-02-18.md @@ -24,7 +24,7 @@ NAC公链系统已完成核心开发,共计**48个模块**已完成并通过 6. **nac-csnp-l0** - CSNP L0层(3个Rust文件) 7. **nac-csnp-l1** - CSNP L1层(1个Rust文件) 8. **nac-nrpc** - NAC RPC协议(2个Rust文件) -9. **nac-nrpc4** - NAC RPC 4.0(9个Rust文件) +9. **nac-lens** - NAC RPC 4.0(9个Rust文件) ### AI智能系统(2个) 10. **nac-ai-valuation** - AI资产估值系统(8个Rust文件,11个测试通过) diff --git a/NAC系统完整清单_最终版.md b/NAC系统完整清单_最终版.md index b0723c7..2c01442 100644 --- a/NAC系统完整清单_最终版.md +++ b/NAC系统完整清单_最终版.md @@ -29,7 +29,7 @@ ### 5. RPC协议 - ✅ **nac-nrpc** - NAC远程过程调用协议 -- ✅ **nac-nrpc4** - NAC Lens版本 +- ✅ **nac-lens** - NAC Lens版本 ### 6. AI系统 - ✅ **nac-ai-valuation** - AI资产估值系统(11个测试通过) diff --git a/README.md b/README.md index d724a51..a966497 100644 --- a/README.md +++ b/README.md @@ -372,7 +372,7 @@ NAC_Clean_Dev/ ├── ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │ ├── nac-nrpc/ # NRPC 1.0 -├── nac-nrpc4/ # NAC Lens +├── nac-lens/ # NAC Lens ├── nac-api-server/ # API服务器 │ ├── ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ diff --git a/_archive/v1_legacy_nrpc3/README.md b/_archive/v1_legacy_nrpc3/README.md index 4bc416b..0799641 100644 --- a/_archive/v1_legacy_nrpc3/README.md +++ b/_archive/v1_legacy_nrpc3/README.md @@ -15,6 +15,6 @@ ## 当前最新版本 -- **协议**: `nac-lens/` (NAC Lens, 原 NRPC4.0) +- **协议**: `nac-lens/` (NAC Lens, 原 NAC Lens) - **SDK 客户端**: `nac-sdk/src/client/` (使用 nac-lens 依赖) - **版本**: nac-lens v0.1.0, nac-sdk v2.0.0 diff --git a/backups/mongodb/20260228_030001/BACKUP_MANIFEST.txt b/backups/mongodb/20260228_030001/BACKUP_MANIFEST.txt new file mode 100644 index 0000000..6d07a2b --- /dev/null +++ b/backups/mongodb/20260228_030001/BACKUP_MANIFEST.txt @@ -0,0 +1,20 @@ +NAC Knowledge Engine MongoDB备份清单 v2 +======================================== +备份时间: 2026-02-28 03:00:01 +数据库名: nac_knowledge_engine +备份大小: 64K +备份工具: mongodump 100.9.0 +备份内容: +total 64 +drwxr-xr-x 2 root root 4096 Feb 28 03:00 . +drwxr-xr-x 3 root root 4096 Feb 28 03:00 .. +-rw-r--r-- 1 root root 23 Feb 28 03:00 agent_conversations.bson.gz +-rw-r--r-- 1 root root 200 Feb 28 03:00 agent_conversations.metadata.json.gz +-rw-r--r-- 1 root root 460 Feb 28 03:00 audit_logs.bson.gz +-rw-r--r-- 1 root root 156 Feb 28 03:00 audit_logs.metadata.json.gz +-rw-r--r-- 1 root root 19679 Feb 28 03:00 compliance_rules.bson.gz +-rw-r--r-- 1 root root 247 Feb 28 03:00 compliance_rules.metadata.json.gz +-rw-r--r-- 1 root root 563 Feb 28 03:00 crawlers.bson.gz +-rw-r--r-- 1 root root 155 Feb 28 03:00 crawlers.metadata.json.gz +-rw-r--r-- 1 root root 388 Feb 28 03:00 protocol_registry.bson.gz +-rw-r--r-- 1 root root 160 Feb 28 03:00 protocol_registry.metadata.json.gz diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.bson.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.bson.gz new file mode 100644 index 0000000..1f0aab1 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.bson.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.metadata.json.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.metadata.json.gz new file mode 100644 index 0000000..0536c0c Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/agent_conversations.metadata.json.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.bson.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.bson.gz new file mode 100644 index 0000000..5d5e94a Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.bson.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.metadata.json.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.metadata.json.gz new file mode 100644 index 0000000..21fe9b8 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/audit_logs.metadata.json.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.bson.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.bson.gz new file mode 100644 index 0000000..5b61a71 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.bson.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.metadata.json.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.metadata.json.gz new file mode 100644 index 0000000..4ea927d Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/compliance_rules.metadata.json.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.bson.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.bson.gz new file mode 100644 index 0000000..af259ef Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.bson.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.metadata.json.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.metadata.json.gz new file mode 100644 index 0000000..c675fd5 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/crawlers.metadata.json.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.bson.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.bson.gz new file mode 100644 index 0000000..ceff474 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.bson.gz differ diff --git a/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.metadata.json.gz b/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.metadata.json.gz new file mode 100644 index 0000000..90f8115 Binary files /dev/null and b/backups/mongodb/20260228_030001/nac_knowledge_engine/protocol_registry.metadata.json.gz differ diff --git a/docs/ISSUE_026_PROGRESS.md b/docs/ISSUE_026_PROGRESS.md index 43f9305..e3e77b8 100644 --- a/docs/ISSUE_026_PROGRESS.md +++ b/docs/ISSUE_026_PROGRESS.md @@ -138,8 +138,8 @@ cd /home/ubuntu/NAC_Clean_Dev/nac-onboarding-system/src/services grep -n "adapter\." *.rs ``` -### 2. 使用NRPC4.0协议 -不使用JSON-RPC,使用NAC原生的NRPC4.0协议。 +### 2. 使用NAC Lens协议 +不使用JSON-RPC,使用NAC原生的NAC Lens协议。 ### 3. 无MANUS依赖 所有代码都在NAC_Clean_Dev开发文件夹中,无任何MANUS内联。 @@ -201,7 +201,7 @@ grep -n "adapter\." *.rs ### 已验证 - ✅ 所有服务模块都调用SDK适配器API -- ✅ 使用NRPC4.0协议 +- ✅ 使用NAC Lens协议 - ✅ 无MANUS依赖 - ✅ 完整的错误处理 - ✅ 完整的数据模型 diff --git a/docs/ISSUE_036_COMPLETE_SUMMARY.md b/docs/ISSUE_036_COMPLETE_SUMMARY.md index a025e51..d787b42 100644 --- a/docs/ISSUE_036_COMPLETE_SUMMARY.md +++ b/docs/ISSUE_036_COMPLETE_SUMMARY.md @@ -263,7 +263,7 @@ ```toml nac-nvm = { path = "../nac-nvm" } nac-cbpp = { path = "../nac-cbpp" } -nac-nrpc4 = { path = "../nac-nrpc4" } +nac-lens = { path = "../nac-lens" } hex = "0.4" ``` diff --git a/docs/ISSUE_038_VERIFICATION_REPORT.md b/docs/ISSUE_038_VERIFICATION_REPORT.md index a80911e..14321f1 100644 --- a/docs/ISSUE_038_VERIFICATION_REPORT.md +++ b/docs/ISSUE_038_VERIFICATION_REPORT.md @@ -117,7 +117,7 @@ NAC SDK的适配器部分实现状态: - 这些功能为CNNL编译器提供了完整的底层API支持 **关联Issue**: -- Issue #40: NAC SDK CSNP网络客户端与NRPC4.0协议客户端实现(紧急) +- Issue #40: NAC SDK CSNP网络客户端与NAC Lens协议客户端实现(紧急) - 该Issue引用了#38,表明SDK实现工作正在持续推进 --- diff --git a/docs/MAINNET_MONITOR_CHECK_REPORT.md b/docs/MAINNET_MONITOR_CHECK_REPORT.md index 8ff8e59..e4892fe 100644 --- a/docs/MAINNET_MONITOR_CHECK_REPORT.md +++ b/docs/MAINNET_MONITOR_CHECK_REPORT.md @@ -25,7 +25,7 @@ |--------|------|------| | 当前区块高度 | ❌ 获取失败 | 无法获取区块链高度数据 | | CBPP共识状态 | ✅ 运行中 | 宪政区块生产协议正常运行 | -| 网络协议 | NRPC4.0 | 显示使用NRPC4.0协议 | +| 网络协议 | NAC Lens | 显示使用NAC Lens协议 | | 共识机制 | CBPP | 宪政区块生产协议 | ### 2.2 系统状态消息 @@ -36,37 +36,37 @@ NAC主网正常运行中... --- -## 三、NRPC4.0部署状态分析 +## 三、NAC Lens部署状态分析 -### 3.1 监控系统中的NRPC4.0 +### 3.1 监控系统中的NAC Lens -✅ **NRPC4.0已在监控系统中显示** +✅ **NAC Lens已在监控系统中显示** 监控面板明确显示: -- 网络协议卡片:**NRPC4.0** -- 说明监控系统已配置NRPC4.0相关监控项 +- 网络协议卡片:**NAC Lens** +- 说明监控系统已配置NAC Lens相关监控项 ### 3.2 问题分析 ❌ **当前区块高度获取失败** **可能原因**: -1. **NRPC4.0 API端点未完全部署** - 监控系统配置了NRPC4.0,但实际的RPC服务未启动 -2. **API端点配置错误** - 监控系统连接的NRPC4.0端点地址不正确 -3. **NRPC4.0服务未运行** - 虽然代码已编译,但服务进程未启动 -4. **网络连接问题** - 监控系统无法访问NRPC4.0服务端口 +1. **NAC Lens API端点未完全部署** - 监控系统配置了NAC Lens,但实际的RPC服务未启动 +2. **API端点配置错误** - 监控系统连接的NAC Lens端点地址不正确 +3. **NAC Lens服务未运行** - 虽然代码已编译,但服务进程未启动 +4. **网络连接问题** - 监控系统无法访问NAC Lens服务端口 ### 3.3 代码库状态 根据之前的检查: -**NRPC4.0代码**: -- 位置:`/root/NAC_Blockchain/nac-nrpc4/` +**NAC Lens代码**: +- 位置:`/root/NAC_Blockchain/nac-lens/` - 版本:v1.0.0 - 编译状态:✅ 已成功编译(release版本) -- 编译产物:`/root/NAC_Blockchain/nac-nrpc4/target/release/libnac_nrpc4.rlib` (887KB) +- 编译产物:`/root/NAC_Blockchain/nac-lens/target/release/libnac_lens.rlib` (887KB) -**NRPC4.0架构**: +**NAC Lens架构**: - L1层:Cell Layer (细胞层) - L2层:Civilization Layer (文明层) - L3层:Aggregation Layer (聚合层) @@ -80,29 +80,29 @@ NAC主网正常运行中... ### 4.1 立即行动 -1. **检查NRPC4.0服务进程** +1. **检查NAC Lens服务进程** ```bash ps aux | grep nrpc ``` 2. **检查主网节点配置** - 查看`/root/NAC_Blockchain/mainnet_config.toml` - - 确认NRPC4.0端点配置 + - 确认NAC Lens端点配置 3. **检查监控系统配置** - 查看监控系统的API配置文件 - - 确认NRPC4.0 API端点地址 + - 确认NAC Lens API端点地址 -4. **启动NRPC4.0服务** - - 如果服务未运行,需要启动NRPC4.0服务进程 +4. **启动NAC Lens服务** + - 如果服务未运行,需要启动NAC Lens服务进程 - 确保服务监听正确的端口 ### 4.2 部署验证 需要验证的关键点: -- [ ] NRPC4.0服务进程是否运行 -- [ ] NRPC4.0 API端点是否可访问 -- [ ] 监控系统能否成功调用NRPC4.0 API +- [ ] NAC Lens服务进程是否运行 +- [ ] NAC Lens API端点是否可访问 +- [ ] 监控系统能否成功调用NAC Lens API - [ ] 区块高度数据能否正常获取 --- @@ -111,25 +111,25 @@ NAC主网正常运行中... ### 5.1 当前状态 -**NRPC4.0处于"半部署"状态**: +**NAC Lens处于"半部署"状态**: - ✅ 代码已完成并编译 -- ✅ 监控系统已配置NRPC4.0监控项 -- ❌ NRPC4.0服务可能未运行或配置不正确 +- ✅ 监控系统已配置NAC Lens监控项 +- ❌ NAC Lens服务可能未运行或配置不正确 - ❌ 监控系统无法获取区块链数据 ### 5.2 核心问题 -**NRPC4.0的库文件已编译,但可能缺少以下部分**: -1. **独立的NRPC4.0服务进程** - 需要一个运行的RPC服务器 -2. **与NAC节点的集成** - NRPC4.0需要集成到NAC主网节点程序中 +**NAC Lens的库文件已编译,但可能缺少以下部分**: +1. **独立的NAC Lens服务进程** - 需要一个运行的RPC服务器 +2. **与NAC节点的集成** - NAC Lens需要集成到NAC主网节点程序中 3. **API端点暴露** - 需要暴露HTTP/WebSocket端点供监控系统调用 ### 5.3 建议 **不应该使用以太坊的JSON-RPC方式部署**,而应该: -1. 将NRPC4.0作为库集成到NAC核心节点 -2. 通过CSNP网络层提供原生的NRPC4.0协议支持 -3. 为监控系统提供专门的NRPC4.0查询接口 +1. 将NAC Lens作为库集成到NAC核心节点 +2. 通过CSNP网络层提供原生的NAC Lens协议支持 +3. 为监控系统提供专门的NAC Lens查询接口 --- diff --git a/docs/VISION_Wallet_核心要点.md b/docs/VISION_Wallet_核心要点.md index 51a0b30..47fe76e 100644 --- a/docs/VISION_Wallet_核心要点.md +++ b/docs/VISION_Wallet_核心要点.md @@ -237,7 +237,7 @@ VISION内置宪政免疫系统客户端: | nac-cee | 宪法收据获取与验证 | | nac-udm | GNACS解析 | | nac-nrpc | RPC通信 | -| nac-nrpc4 | 跨链与多宇宙功能 | +| nac-lens | 跨链与多宇宙功能 | --- diff --git a/docs/assets/nac_blockview_logo.png b/docs/assets/nac_blockview_logo.png new file mode 100644 index 0000000..cd2c7d3 Binary files /dev/null and b/docs/assets/nac_blockview_logo.png differ diff --git a/docs/daily-logs/2026-02-22.md b/docs/daily-logs/2026-02-22.md new file mode 100644 index 0000000..cc335ae --- /dev/null +++ b/docs/daily-logs/2026-02-22.md @@ -0,0 +1,49 @@ +# NAC 主网日志 2026-02-22 + +## Issue #49: CBPP 共识修复 ✅ + +**问题**:CBPP 共识使用定时出块(每1.5秒),不符合"参与即是共识"原则。 + +**修复内容**: +- 移除定时出块循环 +- 新增交易驱动出块(有交易立即出块) +- 新增心跳块(60秒无交易时产生空块) +- → +- 移除投票机制 + +**验证结果**: + + +**部署**:,systemd 服务正常运行 + +--- + +## Issue #50: 量子浏览器多语言自适应 ✅ + +**功能**:根据用户系统语言(Accept-Language)自动切换中文/英文界面 + +**实现**:PHP i18n 系统,翻译字典覆盖全部界面文字 + +**部署**:,v2.2.0 + +--- + +## Issue #51: 全局词语替换 ✅ + +**问题**:"贫民"一词存在阶级歧视风险 + +**替换规则**: +- 贫民能玩的区块链 → 谁都可以玩得起的区块链 +- 贫民区块链 → 全民区块链 +- 贫民参与 → 全民参与 + +**涉及文件**:量子浏览器 index.php,共 9 处,0 处残留 + +--- + +## 节点状态 + +- 服务: active (running) +- RPC:(NAC Lens) +- P2P:(CSNP) +- 共识:CBPP,参与即是共识 diff --git a/docs/issues/ISSUE-009_nac-cli.md b/docs/issues/ISSUE-009_nac-cli.md index 9ef8740..e5c5735 100644 --- a/docs/issues/ISSUE-009_nac-cli.md +++ b/docs/issues/ISSUE-009_nac-cli.md @@ -39,7 +39,7 @@ **状态**: ✅ 已完成 **完成时间**: 2026-02-18 14:00:00 **完成人**: NAC开发团队 -**备注**: 已实现60+个NAC原生RPC方法,完全符合NRPC 4.0规范 +**备注**: 已实现60+个NAC原生RPC方法,完全符合NAC Lens规范 --- @@ -117,7 +117,7 @@ **完成任务**: ISSUE-009 nac-cli模块100%完成 **完成情况**: -- ✅ 实现60+个NAC原生RPC方法(NRPC 4.0) +- ✅ 实现60+个NAC原生RPC方法(NAC Lens) - ✅ 使用NAC原生加密算法(SHA3-384、32字节地址) - ✅ Keystore管理(AES-256-GCM加密) - ✅ 账户管理(6个子命令) diff --git a/docs/issues/ISSUE-012_nac-nrpc4.md b/docs/issues/ISSUE-012_nac-nrpc4.md index fd36b2b..30029c9 100644 --- a/docs/issues/ISSUE-012_nac-nrpc4.md +++ b/docs/issues/ISSUE-012_nac-nrpc4.md @@ -1,7 +1,7 @@ -# ISSUE-012: nac-nrpc4 模块完善工单 +# ISSUE-012: nac-lens 模块完善工单 **工单编号**: ISSUE-012 -**模块名称**: nac-nrpc4 +**模块名称**: nac-lens **当前完成度**: 65% **目标完成度**: 100% **优先级**: P2-中 @@ -74,8 +74,8 @@ _暂无记录,请在完成任务后在此处添加记录_ ## 🔗 相关链接 -- 模块分析报告: [docs/modules/nac-nrpc4分析报告.md](../modules/nac-nrpc4分析报告.md) -- 模块源代码: [nac-nrpc4/](../../nac-nrpc4/) +- 模块分析报告: [docs/modules/nac-lens分析报告.md](../modules/nac-lens分析报告.md) +- 模块源代码: [nac-lens/](../../nac-lens/) --- diff --git a/docs/issues/README.md b/docs/issues/README.md index 2562e00..de7f88e 100644 --- a/docs/issues/README.md +++ b/docs/issues/README.md @@ -52,7 +52,7 @@ #### P2-中 - [ISSUE-011](ISSUE-011_nac-constitution-macros.md) - **nac-constitution-macros** (50%) 🔴 待处理 -- [ISSUE-012](ISSUE-012_nac-nrpc4.md) - **nac-nrpc4** (65%) 🔴 待处理 +- [ISSUE-012](ISSUE-012_nac-lens.md) - **nac-lens** (65%) 🔴 待处理 - [ISSUE-013](ISSUE-013_nac-cbpp.md) - **nac-cbpp** (65%) 🔴 待处理 - [ISSUE-014](ISSUE-014_nac-cbpp-l1.md) - **nac-cbpp-l1** (70%) 🔴 待处理 - [ISSUE-015](ISSUE-015_nac-cbpp-l0.md) - **nac-cbpp-l0** (75%) 🔴 待处理 diff --git a/docs/issues/工单系统部署日志.md b/docs/issues/工单系统部署日志.md index 86e549e..64fd4aa 100644 --- a/docs/issues/工单系统部署日志.md +++ b/docs/issues/工单系统部署日志.md @@ -36,7 +36,7 @@ |--------|------|---------| | **P0-紧急** (0-20%) | 5个 | nac-cross-chain-bridge, charter-std-zh, nac-rwa-exchange, nac-integration-tests, nac-cee | | **P1-高** (20-50%) | 5个 | nac-api-server, nac-constitution-clauses, nac-constitution-state, nac-cli, nac-serde | -| **P2-中** (50-80%) | 3个 | nac-constitution-macros, nac-nrpc4, nac-cbpp | +| **P2-中** (50-80%) | 3个 | nac-constitution-macros, nac-lens, nac-cbpp | | **P3-低** (80-100%) | 10个 | nac-cbpp-l1, nac-cbpp-l0, charter-std, charter-compiler, nac-wallet-core, nac-csnp-l0, nac-csnp-l1, nac-nvm, nac-udm, nac-sdk | ### 按完成度分类 @@ -67,7 +67,7 @@ docs/ │ ├── ISSUE-009_nac-cli.md │ ├── ISSUE-010_nac-serde.md │ ├── ISSUE-011_nac-constitution-macros.md -│ ├── ISSUE-012_nac-nrpc4.md +│ ├── ISSUE-012_nac-lens.md │ ├── ISSUE-013_nac-cbpp.md │ ├── ISSUE-014_nac-cbpp-l1.md │ ├── ISSUE-015_nac-cbpp-l0.md diff --git a/docs/modules/nac-nrpc4分析报告.md b/docs/modules/nac-nrpc4分析报告.md index fce8b4a..b4a87b2 100644 --- a/docs/modules/nac-nrpc4分析报告.md +++ b/docs/modules/nac-nrpc4分析报告.md @@ -1,14 +1,14 @@ -# nac-nrpc4 模块深度分析报告 +# nac-lens 模块深度分析报告 **分析日期**: 2026-02-18 **分析人**: NAC开发团队 -**模块路径**: `/home/ubuntu/NAC_Clean_Dev/nac-nrpc4` +**模块路径**: `/home/ubuntu/NAC_Clean_Dev/nac-lens` --- ## 📊 模块概览 -**模块名称**: nac-nrpc4 +**模块名称**: nac-lens **全称**: NAC Lens: Meta-Protocol Civilization Network Stack(元协议文明网络栈) **模块类型**: 库(lib) **版本**: 0.1.0 @@ -23,7 +23,7 @@ NAC Lens是NAC公链的网络协议,将网络从"通信管道"提升为"多文 ## 📁 目录结构 ``` -nac-nrpc4/ +nac-lens/ ├── Cargo.toml ├── Cargo.lock ├── README.md @@ -813,7 +813,7 @@ nac-constitution-state = { path = "../nac-constitution-state" } ## 🔄 与其他模块的关系 ``` -nac-nrpc4 (NAC Lens协议) +nac-lens (NAC Lens协议) ├── 依赖 nac-udm (核心类型定义) ├── 依赖 nac-csnp-l0 (CSNP L0层) ├── 依赖 nac-csnp-l1 (CSNP L1层) @@ -889,7 +889,7 @@ nac-nrpc4 (NAC Lens协议) ## 📝 总结 -nac-nrpc4是NAC公链的网络协议,采用创新的六层架构,支持元胞自动机路由、灵魂签名、意识分叉、宪法全息化等特性。当前代码1,146行,完成度65%,框架完整但核心算法需要完善。 +nac-lens是NAC公链的网络协议,采用创新的六层架构,支持元胞自动机路由、灵魂签名、意识分叉、宪法全息化等特性。当前代码1,146行,完成度65%,框架完整但核心算法需要完善。 **核心价值**: - 🌟 六层架构清晰 diff --git a/docs/modules/完整分析总结报告.md b/docs/modules/完整分析总结报告.md index 568ce08..aa8f091 100644 --- a/docs/modules/完整分析总结报告.md +++ b/docs/modules/完整分析总结报告.md @@ -33,7 +33,7 @@ | nac-cbpp-l1 | 181 | 70% | CBPP节点管理 | | nac-csnp-l0 | 619 | 85% | CSNP网络层 | | nac-csnp-l1 | 426 | 80% | CSNP应用层 | -| nac-nrpc4 | 1,068 | 65% | NAC Lens协议 | +| nac-lens | 1,068 | 65% | NAC Lens协议 | ### 宪法系统模块(4个) diff --git a/docs/modules/完整模块统计报告.md b/docs/modules/完整模块统计报告.md index ba6d510..41c94cf 100644 --- a/docs/modules/完整模块统计报告.md +++ b/docs/modules/完整模块统计报告.md @@ -20,7 +20,7 @@ | nac-csnp-l0 | - | - | ⏳ 待查 | CSNP L0层 | | nac-csnp-l1 | - | - | ⏳ 待查 | CSNP L1层 | | nac-nrpc | - | - | ⏳ 待查 | NRPC协议 | -| nac-nrpc4 | 9 | 1146 | ✅ 完整 | NAC Lens六层架构 | +| nac-lens | 9 | 1146 | ✅ 完整 | NAC Lens六层架构 | **小计**: 2843行代码(已统计部分) @@ -146,7 +146,7 @@ 1. ✅ nac-nvm - 虚拟机核心 2. ✅ nac-cbpp - 共识协议 3. ✅ nac-cbpp-l0/l1 - 共识分层 -4. ✅ nac-nrpc4 - RPC 4.0协议 +4. ✅ nac-lens - RPC 4.0协议 5. ✅ nac-ai-valuation - AI估值(90%) 6. ✅ nac-acc-* (5个) - ACC资产协议 7. ✅ charter-compiler - Charter编译器 diff --git a/docs/modules/最终分析总结报告.md b/docs/modules/最终分析总结报告.md index c80ed31..0c64901 100644 --- a/docs/modules/最终分析总结报告.md +++ b/docs/modules/最终分析总结报告.md @@ -29,7 +29,7 @@ | 模块 | 行数 | 完成度 | 核心功能 | |------|------|--------|---------| | nac-cbpp | 766 | 65% | CBPP共识引擎 | -| nac-nrpc4 | 1,068 | 65% | NAC Lens协议 | +| nac-lens | 1,068 | 65% | NAC Lens协议 | | nac-nvm | 1,234 | 60% | NAC虚拟机 | | nac-constitution-macros | 470 | 50% | 宪法过程宏 | | nac-serde | 164 | 40% | GNACS序列化 | diff --git a/docs/modules/模块分析索引.md b/docs/modules/模块分析索引.md index 6bf836b..e290012 100644 --- a/docs/modules/模块分析索引.md +++ b/docs/modules/模块分析索引.md @@ -19,7 +19,7 @@ | 6 | nac-sdk | 5,490行 | 80% | [查看报告](./nac-sdk分析报告.md) | | 7 | nac-wallet-core | 2,241行 | 70% | [查看报告](./nac-wallet-core分析报告.md) | | 8 | nac-cee | 53行 | 10% | [查看报告](./nac-cee分析报告.md) | -| 9 | nac-nrpc4 | 1,146行 | 65% | [查看报告](./nac-nrpc4分析报告.md) | +| 9 | nac-lens | 1,146行 | 65% | [查看报告](./nac-lens分析报告.md) | | 10 | nac-csnp-l0 | 619行 | 85% | [查看报告](./nac-csnp-l0分析报告.md) | | 11 | nac-csnp-l1 | 756行 | 80% | [查看报告](./nac-csnp-l1分析报告.md) | | 12 | nac-cbpp-l0 | 900行 | 75% | [查看报告](./nac-cbpp-l0分析报告.md) | @@ -74,7 +74,7 @@ |-----------|---------|---------| | 90%+ | 2 | charter-std, nac-udm | | 70-89% | 7 | charter-compiler, nac-ai-valuation, nac-sdk, nac-wallet-core, nac-csnp-l0, nac-csnp-l1, nac-cbpp-l0 | -| 50-69% | 4 | nac-nvm, nac-nrpc4, nac-cbpp-l1, nac-cbpp | +| 50-69% | 4 | nac-nvm, nac-lens, nac-cbpp-l1, nac-cbpp | | 30-49% | 1 | nac-serde | | <30% | 2 | nac-cee, nac-constitution-state | @@ -83,7 +83,7 @@ | 行数范围 | 模块数量 | 模块列表 | |---------|---------|---------| | 10000+ | 2 | charter-std (11,364), nac-udm (28,777) | -| 1000-9999 | 6 | charter-compiler (3,246), nac-ai-valuation (2,508), nac-sdk (5,490), nac-wallet-core (2,241), nac-nrpc4 (1,146) | +| 1000-9999 | 6 | charter-compiler (3,246), nac-ai-valuation (2,508), nac-sdk (5,490), nac-wallet-core (2,241), nac-lens (1,146) | | 100-999 | 7 | nac-nvm (977), nac-csnp-l0 (619), nac-csnp-l1 (756), nac-cbpp-l0 (900), nac-cbpp-l1 (181), nac-cbpp (766), nac-serde (164) | | <100 | 1 | nac-cee (53), nac-constitution-state (40) | diff --git a/docs/modules/模块真实状态核查报告.md b/docs/modules/模块真实状态核查报告.md index a29334a..8839273 100644 --- a/docs/modules/模块真实状态核查报告.md +++ b/docs/modules/模块真实状态核查报告.md @@ -82,7 +82,7 @@ - ⏳ nac-cbpp - 待分析 - ⏳ nac-nvm - 待分析 - ⏳ nac-csnp - 待分析 -- ⏳ nac-nrpc4 - 待分析 +- ⏳ nac-lens - 待分析 - ⏳ 其他43个模块 - 待分析 --- diff --git a/docs/modules/阶段性分析总结.md b/docs/modules/阶段性分析总结.md index f0e498a..51fcfb2 100644 --- a/docs/modules/阶段性分析总结.md +++ b/docs/modules/阶段性分析总结.md @@ -14,7 +14,7 @@ |-----------|---------|---------| | 90%+ | 2 | charter-std (90%), nac-udm (95%) | | 70-89% | 7 | charter-compiler (85%), nac-ai-valuation (75%), nac-sdk (80%), nac-wallet-core (70%), nac-csnp-l0 (85%), nac-csnp-l1 (80%), nac-cbpp-l0 (75%) | -| 50-69% | 5 | nac-nvm (60%), nac-nrpc4 (65%), nac-cbpp-l1 (70%), nac-cbpp (65%), nac-constitution-macros (50%) | +| 50-69% | 5 | nac-nvm (60%), nac-lens (65%), nac-cbpp-l1 (70%), nac-cbpp (65%), nac-constitution-macros (50%) | | 30-49% | 1 | nac-serde (40%) | | 10-29% | 4 | nac-cee (10%), nac-constitution-state (30%), nac-constitution-clauses (25%), nac-api-server (20%) | | <10% | 1 | charter-std-zh (5%) | diff --git a/docs/nac-docs b/docs/nac-docs index 595f600..fb70795 160000 --- a/docs/nac-docs +++ b/docs/nac-docs @@ -1 +1 @@ -Subproject commit 595f600da8b2e436becc3620ca42ce288202ab3c +Subproject commit fb70795f26920df71f2a298c428ed29645e3452e diff --git a/docs/standards/port_standard_v1.0.0.md b/docs/standards/port_standard_v1.0.0.md index 70da315..7d14a92 100644 --- a/docs/standards/port_standard_v1.0.0.md +++ b/docs/standards/port_standard_v1.0.0.md @@ -27,7 +27,7 @@ |------|----------|------|------|------| | 9545 | CBPP 节点 RPC | HTTP | Constitutional Block Production Protocol | ✅ 运行中 | | 9546 | CBPP WebSocket | WebSocket | CBPP 实时通信 | 🟢 规划 | -| 9547 | NAC Lens HTTP | HTTP | NAC Lens 协议(原 NRPC4.0) | 🟢 规划 | +| 9547 | NAC Lens HTTP | HTTP | NAC Lens 协议(原 NAC Lens) | 🟢 规划 | | 9548 | NAC Lens WebSocket | WebSocket | NAC Lens 实时通信 | 🟢 规划 | | 9549 | NVM RPC | HTTP | NAC Virtual Machine RPC 接口 | 🟢 规划 | diff --git a/docs/工单管理.md b/docs/工单管理.md index 0d537e1..e312809 100644 --- a/docs/工单管理.md +++ b/docs/工单管理.md @@ -73,7 +73,7 @@ - nac-rpc - nac-node - nac-csnp -- nac-nrpc4 +- nac-lens - ... (其余33个) **备注**: diff --git a/logs/issue51_fix_log.md b/logs/issue51_fix_log.md new file mode 100644 index 0000000..bff0d2c --- /dev/null +++ b/logs/issue51_fix_log.md @@ -0,0 +1,75 @@ +# Issue #51 修复日志 + +## 工单信息 +- **工单编号**: Issue #51 (Gitea #68) +- **标题**: nac-sdk 编译错误修复:298个编译错误完全消除 +- **状态**: 已关闭 +- **完成时间**: 2026-02-28 + +## 问题描述 +nac-sdk 存在约298个编译错误,主要原因是 nac_udm 依赖库中的 l2_governance、acc 子模块尚未实现。 + +## 修复内容 + +### 1. 删除重复方法定义(mod.rs) +- optimize_reserves +- predict_sdr_rate +- manage_liquidity +- call_contract_method +- subscribe_event +- batch_call +- get_chain_stats + +### 2. 修复枚举重复变体 +- AmendmentStatus: 删除重复的 Voting, Rejected 变体 +- CollateralType: 删除重复的 derive 宏 + +### 3. 修复方法签名不匹配 +- vote_on_amendment: vote: &Vote -> vote: Vote +- vote_on_proposal: vote: &Vote -> vote: Vote +- get_transaction_receipt: 删除多余的 chain_id 参数 +- search_address: &Address -> query: &str +- submit_cross_shard_transaction: 返回类型 Hash -> CrossShardStatus + +### 4. 为 CSNPNetwork 添加缺失方法 +- broadcast_transaction +- broadcast_block +- sync_blocks +- get_peers +- connect_to_peer + +### 5. 修复 GNACSCode 调用方式 +- generate -> from_hex +- parse -> 手动构建 GNACSCode 结构体 +- validate -> verify_checksum + +### 6. 修复类型不匹配 +- get_balance: Decimal -> BalanceInfo +- get_transaction_history: Vec -> Vec +- list_token: 参数 &str -> &TokenMetadata,返回 bool -> ListingId +- cancel_order: 返回 bool -> () +- TransactionReceipt.tx_hash: *Hash -> Vec + +### 7. 其他修复 +- 添加 ListingId 类型别名到 mod.rs +- 修复 l4_ai.rs 中的 NRPC4Client 导入 +- 修复 l5_application.rs 中的 WalletInfo -> Wallet 类型 +- 修复 l1_protocol.rs 中的 CrossShardStatus 重复导入 + +## 验证结果 + +cargo check 输出: +- warning: nac-cbpp generated 8 warnings +- Finished dev profile [unoptimized + debuginfo] target(s) in 0.27s + +**编译错误:0个(完全消除)** + +## 关联提交 +- 269482a fix(nac-sdk): 修复所有编译错误,Issue #51 完全解决 + +## 后台管理员信息 +- 服务器 IP: 103.96.148.7:22000 +- 服务器用户名: root +- 服务器密码: XKUigTFMJXhH +- Gitea 地址: https://git.newassetchain.io/ +- Gitea 用户名: nacadmin diff --git a/nac-api-server/ISSUE_007_NRPC4_UPGRADE.md b/nac-api-server/ISSUE_007_NRPC4_UPGRADE.md index fe2e01e..7789d88 100644 --- a/nac-api-server/ISSUE_007_NRPC4_UPGRADE.md +++ b/nac-api-server/ISSUE_007_NRPC4_UPGRADE.md @@ -1,4 +1,4 @@ -# Issue #007 NRPC4.0升级完成报告 +# Issue #007 NAC Lens升级完成报告 ## 📋 工单信息 @@ -6,29 +6,29 @@ - **工单标题**: nac-api-server API服务器完善 (P1-高) - **完成日期**: 2026-02-19 - **完成人**: NAC Team -- **升级内容**: NRPC4.0协议集成(5%) +- **升级内容**: NAC Lens协议集成(5%) ## ✅ 升级内容 -### 1. NRPC4.0协议集成 +### 1. NAC Lens协议集成 #### 1.1 依赖更新 - **文件**: `Cargo.toml` -- **变更**: 添加nac-nrpc4依赖 +- **变更**: 添加nac-lens依赖 ```toml -# NAC NRPC4.0协议 -nac-nrpc4 = { path = "../nac-nrpc4" } +# NAC NAC Lens协议 +nac-lens = { path = "../nac-lens" } ``` #### 1.2 客户端重写 - **文件**: `src/blockchain/client.rs` -- **变更**: 从JSON-RPC升级到NRPC4.0 +- **变更**: 从JSON-RPC升级到NAC Lens - **代码行数**: 208行 → 422行 (增长103%) **主要改进**: 1. **连接管理** - - 使用NRPC4.0连接池 + - 使用NAC Lens连接池 - 配置连接超时、空闲超时 - 心跳机制(10秒间隔,5秒超时) - 连接复用支持 @@ -43,7 +43,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } - 错误追踪 - 性能监控 -4. **NRPC4.0协议** +4. **NAC Lens协议** - 自定义请求/响应格式 - 时间戳支持 - 错误详情(code + message + data) @@ -52,7 +52,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } #### 1.3 API方法升级 -所有RPC方法已升级到NRPC4.0格式: +所有RPC方法已升级到NAC Lens格式: 1. **get_balance** - 获取账户余额 - 请求方法: `nac_getBalance` @@ -81,7 +81,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } #### 1.4 测试更新 -所有测试已更新以适配NRPC4.0: +所有测试已更新以适配NAC Lens: 1. **test_client_creation** - 客户端创建测试 2. **test_nrpc_request_serialization** - 请求序列化测试 @@ -96,7 +96,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } **升级后**: - blockchain/client.rs: 422行 -- 使用NRPC4.0协议 +- 使用NAC Lens协议 - 集成连接池、重试、日志 **增长**: +214行 (+103%) @@ -123,13 +123,13 @@ nac-nrpc4 = { path = "../nac-nrpc4" } ## 🔗 依赖工单 -- **工单#19**: nac-nrpc4 NRPC4.0协议完善 ✅ (已完成) - - 提供了完整的NRPC4.0协议实现 +- **工单#19**: nac-lens NAC Lens协议完善 ✅ (已完成) + - 提供了完整的NAC Lens协议实现 - 连接管理、性能优化、安全加固、重试机制 ## 📝 技术细节 -### NRPC4.0请求格式 +### NAC Lens请求格式 ```json { "id": "uuid-v4", @@ -139,7 +139,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } } ``` -### NRPC4.0响应格式 +### NAC Lens响应格式 ```json { "id": "uuid-v4", @@ -149,7 +149,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } } ``` -### NRPC4.0错误格式 +### NAC Lens错误格式 ```json { "id": "uuid-v4", @@ -165,7 +165,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } ## 🎯 下一步计划 -1. ✅ 完成NRPC4.0协议集成 +1. ✅ 完成NAC Lens协议集成 2. ⏭️ 部署到测试环境 3. ⏭️ 性能测试和优化 4. ⏭️ 生产环境部署 @@ -173,7 +173,7 @@ nac-nrpc4 = { path = "../nac-nrpc4" } ## 📦 Git提交 - **提交哈希**: 待生成 -- **提交信息**: "完成Issue #007: nac-api-server升级到NRPC4.0协议 (95% → 100%)" +- **提交信息**: "完成Issue #007: nac-api-server升级到NAC Lens协议 (95% → 100%)" - **远程仓库**: ssh://root@103.96.148.7:22000/root/nac-api-server.git ## ✅ 工单状态 @@ -185,8 +185,8 @@ nac-nrpc4 = { path = "../nac-nrpc4" } --- **备注**: -- NRPC4.0协议已完全集成到nac-api-server -- 所有RPC调用已升级到NRPC4.0格式 +- NAC Lens协议已完全集成到nac-api-server +- 所有RPC调用已升级到NAC Lens格式 - 连接管理、重试机制、日志记录已集成 - 测试通过,编译成功 - 工单#7已100%完成! diff --git a/nac-cbpp/Cargo.lock b/nac-cbpp/Cargo.lock index 31e5cb5..39cd2ac 100644 --- a/nac-cbpp/Cargo.lock +++ b/nac-cbpp/Cargo.lock @@ -252,6 +252,7 @@ dependencies = [ "anyhow", "chrono", "hex", + "nac-upgrade-framework", "rand", "serde", "serde_json", @@ -261,6 +262,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "nac-upgrade-framework" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "hex", + "log", + "serde", + "serde_json", + "sha3", + "thiserror", +] + [[package]] name = "num-traits" version = "0.2.19" diff --git a/nac-cli/README.md b/nac-cli/README.md index bc655a2..ae5208d 100644 --- a/nac-cli/README.md +++ b/nac-cli/README.md @@ -10,7 +10,7 @@ NAC CLI是专为NAC原生公链设计的命令行工具,**不继承任何以 - **智能合约语言**: Charter(非Solidity) - **虚拟机**: NVM(非EVM) -- **RPC协议**: NRPC 4.0(非JSON-RPC) +- **RPC协议**: NAC Lens(非JSON-RPC) - **共识机制**: CBPP(宪政区块生产协议) - **网络协议**: CSNP(非传统P2P) - **地址格式**: 32字节(非以太坊的20字节) diff --git a/nac-cli/docs/TICKET_9_COMPLETION_LOG.md b/nac-cli/docs/TICKET_9_COMPLETION_LOG.md index 92318e1..4cdaa08 100644 --- a/nac-cli/docs/TICKET_9_COMPLETION_LOG.md +++ b/nac-cli/docs/TICKET_9_COMPLETION_LOG.md @@ -16,7 +16,7 @@ ### 1. NRPC客户端实现(100%) -实现了60+个NAC原生RPC方法,完全符合NRPC 4.0规范: +实现了60+个NAC原生RPC方法,完全符合NAC Lens规范: **账户相关** (12个方法) - `nac_account_getBalance` - 获取账户余额 @@ -204,7 +204,7 @@ - **智能合约语言**: Charter(非Solidity) - **虚拟机**: NVM(非EVM) -- **RPC协议**: NRPC 4.0(非JSON-RPC) +- **RPC协议**: NAC Lens(非JSON-RPC) - **共识机制**: CBPP(宪政区块生产协议) - **网络协议**: CSNP(非传统P2P) - **地址格式**: 32字节(非以太坊的20字节) diff --git a/nac-explorer-api.backup-20260227_141339/package.json b/nac-explorer-api.backup-20260227_141339/package.json new file mode 100644 index 0000000..e73755f --- /dev/null +++ b/nac-explorer-api.backup-20260227_141339/package.json @@ -0,0 +1,25 @@ +{ + "name": "nac-explorer-backend", + "version": "2.0.0", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "dev": "ts-node src/index.ts", + "watch": "nodemon --watch src --ext ts --exec ts-node src/index.ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "NAC区块链浏览器API服务器 - 完整功能实现", + "dependencies": { + "@types/cors": "^2.8.19", + "@types/express": "^5.0.6", + "@types/node": "^25.3.0", + "cors": "^2.8.6", + "express": "^5.2.1", + "nodemon": "^3.0.0", + "ts-node": "^10.9.2", + "typescript": "^5.9.3" + } +} diff --git a/nac-explorer-api.backup-20260227_141339/src/index.ts b/nac-explorer-api.backup-20260227_141339/src/index.ts new file mode 100644 index 0000000..9fadb95 --- /dev/null +++ b/nac-explorer-api.backup-20260227_141339/src/index.ts @@ -0,0 +1,504 @@ +/** + * NAC 区块链浏览器 API 服务器 + * 版本: 2.0.0 + * 协议: NAC Lens (原 NRPC4.0) + * + * 工单 #042: 统一更名 NRPC4.0 → NAC Lens + * 工单 #043: 统一 API 数据源,对接真实链上数据 + * + * 数据源架构: + * - 主数据源: nac-cbpp-node systemd 日志 (journalctl) → 真实区块高度 + * - 链状态: /opt/nac/bin/nac-api-server /health (9550) → 真实链状态 + * - 区块/交易: 基于真实区块高度生成确定性数据(阶段一) + */ + +import express, { Request, Response } from 'express'; +import cors from 'cors'; +import { execSync } from 'child_process'; + +const app = express(); +const PORT = process.env.PORT ? parseInt(process.env.PORT) : 9551; + +// NAC Lens 协议标识(工单 #042 更名) +const PROTOCOL = 'NAC Lens'; + +// 中间件 +app.use(cors()); +app.use(express.json()); + +// ==================== 真实数据获取层 ==================== + +/** + * 从 nac-api-server (9550) 获取真实链状态 + */ +function getRealChainStatus(): { + height: number; + chainId: number; + network: string; + cbppConsensus: string; + csnpNetwork: string; + nvmVersion: string; + constitutionLayer: boolean; + fluidBlockMode: boolean; +} { + try { + const result = execSync( + 'curl -s --max-time 2 http://localhost:9550/health', + { encoding: 'utf8', timeout: 3000 } + ); + const data = JSON.parse(result); + if (data && data.data) { + return { + height: data.data.block?.height || 0, + chainId: data.chain_id || 20260131, + network: data.network || 'mainnet', + cbppConsensus: data.data.cbpp_consensus || 'active', + csnpNetwork: data.data.csnp_network || 'connected', + nvmVersion: data.data.nvm_version || '2.0', + constitutionLayer: data.data.constitution_layer !== false, + fluidBlockMode: data.data.fluid_block_mode !== false, + }; + } + } catch (e) { + // 降级:从 CBPP 日志获取区块高度 + try { + const logResult = execSync( + 'journalctl -u nac-cbpp-node -n 5 --no-pager 2>/dev/null | grep "生产区块" | tail -1', + { encoding: 'utf8', timeout: 3000 } + ); + const match = logResult.match(/#(\d+)/); + if (match) { + return { + height: parseInt(match[1]), + chainId: 20260131, + network: 'mainnet', + cbppConsensus: 'active', + csnpNetwork: 'connected', + nvmVersion: '2.0', + constitutionLayer: true, + fluidBlockMode: true, + }; + } + } catch (e2) { /* ignore */ } + } + // 最终降级默认值 + return { + height: 0, + chainId: 20260131, + network: 'mainnet', + cbppConsensus: 'unknown', + csnpNetwork: 'unknown', + nvmVersion: '2.0', + constitutionLayer: true, + fluidBlockMode: true, + }; +} + +/** + * 基于真实区块高度生成确定性区块数据 + * 注:阶段一使用确定性算法;阶段二将对接 CBPP 节点原生存储 + */ +function buildBlock(blockNumber: number, chainHeight: number) { + // 确定性哈希(基于区块号,非随机) + const hashHex = blockNumber.toString(16).padStart(96, '0'); + const parentHashHex = blockNumber > 0 + ? (blockNumber - 1).toString(16).padStart(96, '0') + : '0'.repeat(96); + + // 基于区块号的确定性时间戳(每3秒一个区块) + const now = Math.floor(Date.now() / 1000); + const timestamp = now - (chainHeight - blockNumber) * 3; + + // 确定性矿工地址(基于区块号) + const minerSeed = (blockNumber * 1000003).toString(36).toUpperCase().padEnd(29, '0').substring(0, 29); + const miner = `NAC${minerSeed}`; + + // 确定性交易数量(基于区块号的哈希) + const txCount = ((blockNumber * 7 + 13) % 20) + 1; + + return { + number: blockNumber, + hash: `0x${hashHex}`, + parentHash: `0x${parentHashHex}`, + timestamp, + miner, + transactionCount: txCount, + size: ((blockNumber * 1009) % 40000) + 10000, + gasUsed: ((blockNumber * 997) % 7000000) + 1000000, + gasLimit: 10000000, + cbppConsensus: 'active', + constitutionLayer: true, + isFluid: true, + protocol: PROTOCOL, + }; +} + +/** + * 基于真实区块高度生成确定性交易数据 + */ +function buildTransactions(count: number, blockNumber: number) { + const txs = []; + for (let i = 0; i < count; i++) { + const seed = blockNumber * 1000 + i; + const hashHex = (seed * 999983).toString(16).padStart(96, '0'); + const fromSeed = (seed * 1000003).toString(36).toUpperCase().padEnd(29, '0').substring(0, 29); + const toSeed = (seed * 1000033).toString(36).toUpperCase().padEnd(29, '0').substring(0, 29); + txs.push({ + hash: `0x${hashHex}`, + from: `NAC${fromSeed}`, + to: `NAC${toSeed}`, + value: ((seed * 137) % 100000 / 100).toFixed(6), + gas: 21000 + (seed % 100000), + gasPrice: '1000000000', + nonce: i, + blockNumber, + blockHash: `0x${blockNumber.toString(16).padStart(96, '0')}`, + transactionIndex: i, + status: 'success', + protocol: PROTOCOL, + }); + } + return txs; +} + +// ==================== API 路由 ==================== + +/** + * 健康检查 + */ +app.get('/health', (_req: Request, res: Response) => { + const chain = getRealChainStatus(); + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + status: 'ok', + version: '2.0.0', + block: { + height: chain.height, + is_fluid: chain.fluidBlockMode, + }, + cbpp_consensus: chain.cbppConsensus, + csnp_network: chain.csnpNetwork, + nvm_version: chain.nvmVersion, + constitution_layer: chain.constitutionLayer, + fluid_block_mode: chain.fluidBlockMode, + }, + }); +}); + +/** + * 获取最新区块 + */ +app.get('/api/v1/blocks/latest', (_req: Request, res: Response) => { + const chain = getRealChainStatus(); + const block = buildBlock(chain.height, chain.height); + const txCount = block.transactionCount; + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + ...block, + transactions: buildTransactions(txCount, chain.height), + }, + }); +}); + +/** + * 获取区块列表(最新N个) + */ +app.get('/api/v1/blocks', (req: Request, res: Response) => { + const chain = getRealChainStatus(); + const limit = Math.min(parseInt(req.query.limit as string) || 20, 100); + const page = parseInt(req.query.page as string) || 1; + const start = chain.height - (page - 1) * limit; + + const blocks = []; + for (let i = 0; i < limit && start - i >= 0; i++) { + blocks.push(buildBlock(start - i, chain.height)); + } + + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + blocks, + total: chain.height + 1, + page, + limit, + currentHeight: chain.height, + }, + }); +}); + +/** + * 获取区块详情(按区块号或哈希) + */ +app.get('/api/v1/blocks/:numberOrHash', (req: Request, res: Response) => { + const chain = getRealChainStatus(); + const param = req.params.numberOrHash; + let blockNumber: number; + + if (/^\d+$/.test(param)) { + blockNumber = parseInt(param); + } else if (param.startsWith('0x')) { + // 从哈希反推区块号(确定性哈希格式) + blockNumber = parseInt(param.slice(2), 16); + } else { + return res.status(400).json({ error: '无效的区块号或哈希' }); + } + + if (blockNumber < 0 || blockNumber > chain.height) { + return res.status(404).json({ error: '区块不存在' }); + } + + const block = buildBlock(blockNumber, chain.height); + const txCount = block.transactionCount; + + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + ...block, + transactions: buildTransactions(txCount, blockNumber), + }, + }); +}); + +/** + * 获取最新交易列表 + */ +app.get('/api/v1/transactions/latest', (req: Request, res: Response) => { + const chain = getRealChainStatus(); + const limit = Math.min(parseInt(req.query.limit as string) || 20, 100); + const txs = buildTransactions(limit, chain.height); + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: txs, + }); +}); + +/** + * 获取交易详情 + */ +app.get('/api/v1/transactions/:hash', (req: Request, res: Response) => { + const hash = req.params.hash; + if (!hash.startsWith('0x') || hash.length !== 98) { + return res.status(400).json({ error: '无效的交易哈希' }); + } + const chain = getRealChainStatus(); + const tx = buildTransactions(1, chain.height)[0]; + tx.hash = hash; + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: tx, + }); +}); + +/** + * 获取地址信息 + */ +app.get('/api/v1/addresses/:address', (req: Request, res: Response) => { + const address = req.params.address as string; + if (!address.startsWith('NAC') && !address.startsWith('0x')) { + return res.status(400).json({ error: '无效的地址格式' }); + } + const seed = address.split('').reduce((a, c) => a + c.charCodeAt(0), 0); + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + address, + balance: ((seed * 137) % 1000000 / 100).toFixed(6), + transactionCount: seed % 1000, + contractCode: null, + isContract: false, + tokens: [], + lastActivity: Math.floor(Date.now() / 1000), + }, + }); +}); + +/** + * 获取地址交易历史 + */ +app.get('/api/v1/addresses/:address/transactions', (req: Request, res: Response) => { + const address = req.params.address as string; + const chain = getRealChainStatus(); + const limit = Math.min(parseInt(req.query.limit as string) || 20, 100); + const txs = buildTransactions(limit, chain.height); + txs.forEach((tx, i) => { + if (i % 2 === 0) tx.from = address; + else tx.to = address; + }); + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: txs, + }); +}); + +/** + * 获取智能合约信息 + */ +app.get('/api/v1/contracts/:address', (req: Request, res: Response) => { + const address = req.params.address as string; + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + address, + name: `Contract_${address.substring(0, 8)}`, + compiler: 'charter-1.0.0', + sourceCode: '// Charter 智能合约\ncontract Example {\n // ...\n}', + abi: [], + bytecode: '0x' + '60'.repeat(100), + isVerified: false, + transactionCount: 0, + balance: '0.000000', + }, + }); +}); + +/** + * 获取 RWA 资产列表 + */ +app.get('/api/v1/assets', (req: Request, res: Response) => { + const limit = Math.min(parseInt(req.query.limit as string) || 20, 100); + const assets = []; + for (let i = 0; i < limit; i++) { + assets.push({ + id: `RWA-${(i + 1).toString().padStart(6, '0')}`, + name: `RWA Asset #${i + 1}`, + type: ['real_estate', 'bond', 'commodity', 'equity'][i % 4], + value: ((i + 1) * 10000).toFixed(2), + currency: 'USD', + issuer: `NAC${'0'.repeat(29)}`, + status: 'active', + protocol: PROTOCOL, + }); + } + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: assets, + }); +}); + +/** + * 获取 RWA 资产详情 + */ +app.get('/api/v1/assets/:id', (req: Request, res: Response) => { + const id = req.params.id as string; + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + id, + name: `RWA Asset ${id}`, + type: 'real_estate', + value: '100000.00', + currency: 'USD', + issuer: `NAC${'0'.repeat(29)}`, + status: 'active', + protocol: PROTOCOL, + }, + }); +}); + +/** + * 获取网络统计数据(真实数据) + */ +app.get('/api/v1/network/stats', (_req: Request, res: Response) => { + const chain = getRealChainStatus(); + res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + data: { + currentBlock: chain.height, + totalTransactions: chain.height * 8, // 估算:平均每块8笔交易 + totalAddresses: Math.floor(chain.height * 0.3), + totalContracts: Math.floor(chain.height * 0.02), + totalAssets: Math.floor(chain.height * 0.01), + avgBlockTime: 3.0, + tps: 150, + cbppConsensus: chain.cbppConsensus, + csnpNetwork: chain.csnpNetwork, + constitutionLayer: chain.constitutionLayer, + fluidBlockMode: chain.fluidBlockMode, + chainId: chain.chainId, + network: chain.network, + }, + }); +}); + +/** + * 全局搜索 + */ +app.get('/api/v1/search', (req: Request, res: Response) => { + const query = (req.query.q as string) || ''; + if (!query) { + return res.status(400).json({ error: '搜索关键词不能为空' }); + } + const chain = getRealChainStatus(); + + if (/^\d+$/.test(query)) { + const blockNumber = parseInt(query); + if (blockNumber >= 0 && blockNumber <= chain.height) { + return res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + type: 'block', + data: buildBlock(blockNumber, chain.height), + }); + } + } else if (query.startsWith('0x') && query.length === 98) { + const tx = buildTransactions(1, chain.height)[0]; + tx.hash = query; + return res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + type: 'transaction', + data: tx, + }); + } else if (query.startsWith('NAC') || (query.startsWith('0x') && query.length === 66)) { + const seed = query.split('').reduce((a: number, c: string) => a + c.charCodeAt(0), 0); + return res.json({ + protocol: PROTOCOL, + timestamp: Math.floor(Date.now() / 1000), + type: 'address', + data: { + address: query, + balance: ((seed * 137) % 1000000 / 100).toFixed(6), + transactionCount: seed % 1000, + }, + }); + } + + res.status(404).json({ error: '未找到匹配的结果' }); +}); + +// 启动服务器 +app.listen(PORT, '0.0.0.0', () => { + console.log(`🚀 NAC 区块链浏览器 API 服务器启动成功`); + console.log(`📡 监听端口: ${PORT}`); + console.log(`🌐 协议: ${PROTOCOL}`); + console.log(`⛓️ 网络: NAC 主网`); + console.log(`📊 数据源: nac-cbpp-node (真实区块高度) + nac-api-server (链状态)`); + console.log(`\n可用端点:`); + console.log(` GET /health - 健康检查(真实数据)`); + console.log(` GET /api/v1/blocks/latest - 最新区块(真实高度)`); + console.log(` GET /api/v1/blocks?limit=20&page=1 - 区块列表`); + console.log(` GET /api/v1/blocks/:numberOrHash - 区块详情`); + console.log(` GET /api/v1/transactions/latest?limit=20 - 最新交易`); + console.log(` GET /api/v1/transactions/:hash - 交易详情`); + console.log(` GET /api/v1/addresses/:address - 地址信息`); + console.log(` GET /api/v1/addresses/:address/transactions - 地址交易历史`); + console.log(` GET /api/v1/contracts/:address - 智能合约`); + console.log(` GET /api/v1/assets?limit=20 - RWA 资产列表`); + console.log(` GET /api/v1/assets/:id - RWA 资产详情`); + console.log(` GET /api/v1/network/stats - 网络统计(真实数据)`); + console.log(` GET /api/v1/search?q=xxx - 全局搜索`); +}); diff --git a/nac-explorer-api.backup-20260227_141339/tsconfig.json b/nac-explorer-api.backup-20260227_141339/tsconfig.json new file mode 100644 index 0000000..bd56517 --- /dev/null +++ b/nac-explorer-api.backup-20260227_141339/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["ES2020"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "moduleResolution": "node" + }, + "include": ["src/**/*"], + "exclude": ["node_modules"] +} diff --git a/nac-explorer-api/src/index.ts b/nac-explorer-api/src/index.ts index 0079c00..49506f1 100644 --- a/nac-explorer-api/src/index.ts +++ b/nac-explorer-api/src/index.ts @@ -1,8 +1,17 @@ /** +<<<<<<< HEAD * NAC 区块链浏览器 API 服务器 v3.0 * * 数据源:CBPP 节点 RPC(localhost:9545) * 协议:NRPC/4.0 +======= + * NAC 区块链浏览器 API 服务器 + * 版本: 2.0.0 + * 协议: NAC Lens (原 NAC Lens) + * + * 工单 #042: 统一更名 NAC Lens → NAC Lens + * 工单 #043: 统一 API 数据源,对接真实链上数据 +>>>>>>> 22f21ea62b443708c5714ceddb1bd9d185f21e57 * * 所有区块、交易、状态数据均从真实 CBPP 节点读取,不使用任何模拟数据。 * 心跳块(txs=[])是 CBPP 协议的正当行为(宪法原则四),正确标注展示。 diff --git a/nac-lens/Cargo.lock b/nac-lens/Cargo.lock index 7116e50..02f93bb 100644 --- a/nac-lens/Cargo.lock +++ b/nac-lens/Cargo.lock @@ -1541,6 +1541,7 @@ name = "nac-constitution-state" version = "0.1.0" dependencies = [ "nac-udm", + "nac-upgrade-framework", "serde", "serde_json", ] @@ -1554,6 +1555,7 @@ dependencies = [ "libp2p", "lru", "nac-udm", + "nac-upgrade-framework", "serde", "serde_json", "thiserror 1.0.69", @@ -1566,13 +1568,14 @@ name = "nac-csnp-l1" version = "0.1.0" dependencies = [ "nac-udm", + "nac-upgrade-framework", "serde", "serde_json", "thiserror 1.0.69", ] [[package]] -name = "nac-nrpc4" +name = "nac-lens" version = "0.1.0" dependencies = [ "anyhow", @@ -1585,6 +1588,7 @@ dependencies = [ "nac-csnp-l0", "nac-csnp-l1", "nac-udm", + "nac-upgrade-framework", "serde", "serde_json", "sha2", @@ -1603,6 +1607,7 @@ dependencies = [ "chrono", "hex", "log", + "nac-upgrade-framework", "primitive-types", "serde", "serde_json", @@ -1611,6 +1616,20 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "nac-upgrade-framework" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "hex", + "log", + "serde", + "serde_json", + "sha3", + "thiserror 1.0.69", +] + [[package]] name = "netlink-packet-core" version = "0.7.0" diff --git a/nac-lens/Cargo.toml b/nac-lens/Cargo.toml index d66365a..e9e44f0 100644 --- a/nac-lens/Cargo.toml +++ b/nac-lens/Cargo.toml @@ -37,5 +37,5 @@ nac-constitution-state = { path = "../nac-constitution-state" } tokio-test = "0.4" [lib] -name = "nac_nrpc4" +name = "nac_lens" path = "src/lib.rs" diff --git a/nac-lens/ISSUE_019_COMPLETION.md b/nac-lens/ISSUE_019_COMPLETION.md index 835112c..327da0f 100644 --- a/nac-lens/ISSUE_019_COMPLETION.md +++ b/nac-lens/ISSUE_019_COMPLETION.md @@ -3,8 +3,8 @@ ## 📋 基本信息 - **Issue编号**: #019 -- **模块名称**: nac-nrpc4 -- **任务**: NRPC4.0协议完善 +- **模块名称**: nac-lens +- **任务**: NAC Lens协议完善 - **优先级**: P3-低 - **完成日期**: 2026-02-19 - **完成人**: Manus AI @@ -114,7 +114,7 @@ ## 📈 代码结构 ``` -nac-nrpc4/ +nac-lens/ ├── src/ │ ├── lib.rs (57行) - 主模块 │ ├── error.rs (46行) - 错误类型 @@ -172,12 +172,12 @@ nac-nrpc4/ **工单#7**: nac-api-server API服务器完善 - **当前状态**: 已关闭(95%完成) -- **未完成部分**: NRPC4.0协议集成(5%) +- **未完成部分**: NAC Lens协议集成(5%) - **后续任务**: 1. 重新打开工单#7 - 2. 升级nac-api-server使用NRPC4.0 + 2. 升级nac-api-server使用NAC Lens 3. 更新blockchain/client.rs - 4. 测试与NRPC4.0节点的通信 + 4. 测试与NAC Lens节点的通信 5. 更新工单#7完成度: 95% → 100% ## 🎯 质量保证 @@ -201,6 +201,6 @@ nac-nrpc4/ ## 🎉 总结 -Issue #019已100%完成!NRPC4.0协议已完善,新增了连接管理、性能优化、安全加固和重试日志四大系统,代码行数从1,146行增长到3,575行,增长212%。所有功能都经过测试验证,可以投入使用。 +Issue #019已100%完成!NAC Lens协议已完善,新增了连接管理、性能优化、安全加固和重试日志四大系统,代码行数从1,146行增长到3,575行,增长212%。所有功能都经过测试验证,可以投入使用。 -下一步需要回到工单#7,将nac-api-server升级到NRPC4.0协议。 +下一步需要回到工单#7,将nac-api-server升级到NAC Lens协议。 diff --git a/nac-lens/README.md b/nac-lens/README.md index 9b4d1be..a60c1be 100644 --- a/nac-lens/README.md +++ b/nac-lens/README.md @@ -1,6 +1,6 @@ -# nac_nrpc4 +# nac_lens -**模块名称**: nac_nrpc4 +**模块名称**: nac_lens **描述**: NAC Lens: Meta-Protocol Civilization Network Stack **最后更新**: 2026-02-18 @@ -9,7 +9,7 @@ ## 目录结构 ``` -nac-nrpc4/ +nac-lens/ ├── Cargo.toml ├── README.md (本文件) └── src/ diff --git a/nac-lens/src/lib.rs b/nac-lens/src/lib.rs index 71f1045..9532bb9 100644 --- a/nac-lens/src/lib.rs +++ b/nac-lens/src/lib.rs @@ -36,10 +36,10 @@ pub use error::{Nrpc4Error, Result}; pub use types::*; /// NAC Lens版本号 -pub const NAC Lens_VERSION: &str = "4.0.0-alpha"; +pub const NAC_LENS_VERSION: &str = "4.0.0-alpha"; /// NAC Lens协议魔数 -pub const NAC Lens_MAGIC: u32 = 0x4E525034; // "NRP4" +pub const NAC_LENS_MAGIC: u32 = 0x4E525034; // "NRP4" #[cfg(test)] mod tests { @@ -47,11 +47,11 @@ mod tests { #[test] fn test_version() { - assert_eq!(NAC Lens_VERSION, "4.0.0-alpha"); + assert_eq!(NAC_LENS_VERSION, "4.0.0-alpha"); } #[test] fn test_magic() { - assert_eq!(NAC Lens_MAGIC, 0x4E525034); + assert_eq!(NAC_LENS_MAGIC, 0x4E525034); } } diff --git a/nac-lens/src/lib.rs.bak.20260222 b/nac-lens/src/lib.rs.bak.20260222 new file mode 100644 index 0000000..71f1045 --- /dev/null +++ b/nac-lens/src/lib.rs.bak.20260222 @@ -0,0 +1,57 @@ +//! NAC Lens: 元协议文明网络栈 +//! +//! NAC Lens将网络从"通信管道"提升为"多文明共生进化的数字宇宙" +//! +//! # 六层架构 +//! +//! - **L1 元胞层**: 元胞自动机路由(CAR) +//! - **L2 文明层**: 文明特征向量、灵魂签名 +//! - **L3 聚合层**: 文明间路由(ICR)、意识分叉 +//! - **L4 宪法层**: 全息编码、分片存储 +//! - **L5 价值层**: XIC/XTZH跨文明价值交换 +//! - **L6 应用层**: AA-PE、FTAN、UCA +//! +//! # 核心特性 +//! +//! - **元胞自动机路由**: 无中央路由表,梯度下降路由 +//! - **文明间路由**: 基于DHT的文明发现,支持多文明共存 +//! - **灵魂签名**: 文明级集体签名,抗量子 +//! - **意识分叉**: 支持文明内分歧的和平分叉 +//! - **宪法全息化**: 分片存储宪法,零知识证明验证 + +pub mod l1_cell; +pub mod l2_civilization; +pub mod l3_aggregation; +pub mod l4_constitution; +pub mod l5_value; +pub mod l6_application; +pub mod types; +pub mod error; +pub mod connection; +pub mod performance; +pub mod security; +pub mod retry; + +pub use error::{Nrpc4Error, Result}; +pub use types::*; + +/// NAC Lens版本号 +pub const NAC Lens_VERSION: &str = "4.0.0-alpha"; + +/// NAC Lens协议魔数 +pub const NAC Lens_MAGIC: u32 = 0x4E525034; // "NRP4" + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_version() { + assert_eq!(NAC Lens_VERSION, "4.0.0-alpha"); + } + + #[test] + fn test_magic() { + assert_eq!(NAC Lens_MAGIC, 0x4E525034); + } +} diff --git a/nac-onboarding-system/TODO.md b/nac-onboarding-system/TODO.md index ba9c8dd..a4d9101 100644 --- a/nac-onboarding-system/TODO.md +++ b/nac-onboarding-system/TODO.md @@ -192,7 +192,7 @@ - [ ] 审计日志功能正常 ### 技术要求 -- [ ] 使用NRPC4.0协议(不是JSON-RPC) +- [ ] 使用NAC Lens协议(不是JSON-RPC) - [ ] 无MANUS依赖 - [ ] HTTPS + SSL证书 - [ ] 独立域名访问 diff --git a/nac-sdk/Cargo.lock b/nac-sdk/Cargo.lock index 215673b..eb6a7eb 100644 --- a/nac-sdk/Cargo.lock +++ b/nac-sdk/Cargo.lock @@ -2,6 +2,41 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -11,6 +46,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "android_system_properties" version = "0.1.5" @@ -20,56 +61,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" - -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.101" @@ -98,6 +89,48 @@ dependencies = [ "serde_json", ] +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "asynchronous-codec" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" +dependencies = [ + "bytes", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -110,6 +143,22 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "base-x" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" + +[[package]] +name = "base256emoji" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e9430d9a245a77c92176e649af6e275f20839a48389859d1661e9a128d077c" +dependencies = [ + "const-str", + "match-lookup", +] + [[package]] name = "base64" version = "0.21.7" @@ -155,6 +204,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "blake3" version = "1.8.3" @@ -178,6 +236,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.19.1" @@ -218,6 +285,30 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.43" @@ -233,10 +324,15 @@ dependencies = [ ] [[package]] -name = "colorchoice" -version = "1.0.4" +name = "cipher" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] [[package]] name = "colored" @@ -247,12 +343,27 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "const-oid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-str" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f421161cb492475f1661ddc9815a745a1c894592070661180fdec3d4872e9c3" + [[package]] name = "const_format" version = "0.2.35" @@ -295,6 +406,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505" +dependencies = [ + "memchr", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -304,6 +424,12 @@ dependencies = [ "libc", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + [[package]] name = "crunchy" version = "0.2.4" @@ -317,9 +443,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core 0.6.4", "typenum", ] +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -347,12 +483,45 @@ dependencies = [ "syn", ] +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "data-encoding" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" +[[package]] +name = "data-encoding-macro" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8142a83c17aa9461d637e649271eae18bf2edd00e91f2e105df36c3c16355bdb" +dependencies = [ + "data-encoding", + "data-encoding-macro-internal", +] + +[[package]] +name = "data-encoding-macro-internal" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ab67060fc6b8ef687992d439ca0fa36e7ed17e9a0b16b25b601e8757df720de" +dependencies = [ + "data-encoding", + "syn", +] + [[package]] name = "der" version = "0.7.10" @@ -371,6 +540,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -384,6 +554,12 @@ dependencies = [ "syn", ] +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + [[package]] name = "ed25519" version = "2.2.3" @@ -408,6 +584,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -418,26 +600,15 @@ dependencies = [ ] [[package]] -name = "env_filter" -version = "0.1.4" +name = "enum-as-inner" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "jiff", - "log", + "heck", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -486,6 +657,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -501,6 +678,31 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-bounded" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91f328e7fb845fc832912fb6a34f40cf6d1888c92f974d1893a54e97b5ff542e" +dependencies = [ + "futures-timer", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.31" @@ -508,6 +710,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -516,6 +719,45 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", + "num_cpus", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.31" @@ -528,15 +770,36 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" +[[package]] +name = "futures-ticker" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9763058047f713632a52e916cc7f6a4b3fc6e9fc1ff8c5b1dc49e5a89041682e" +dependencies = [ + "futures", + "futures-timer", + "instant", +] + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + [[package]] name = "futures-util" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "pin-utils", "slab", @@ -575,6 +838,16 @@ dependencies = [ "wasip2", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + [[package]] name = "h2" version = "0.3.27" @@ -613,18 +886,95 @@ dependencies = [ "tracing", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + [[package]] name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + [[package]] name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hex_fmt" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b07f60793ff0a4d9cef0f18e63b5357e06209987153a64648c972c1e5aff336f" + +[[package]] +name = "hickory-proto" +version = "0.24.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92652067c9ce6f66ce53cc38d1169daa36e6e7eb7dd3b63b5103bd9d97117248" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "enum-as-inner", + "futures-channel", + "futures-io", + "futures-util", + "idna", + "ipnet", + "once_cell", + "rand 0.8.5", + "socket2 0.5.10", + "thiserror 1.0.69", + "tinyvec", + "tracing", + "url", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "0.2.12" @@ -747,9 +1097,9 @@ dependencies = [ "futures-util", "http 0.2.12", "hyper 0.14.32", - "rustls 0.21.12", + "rustls", "tokio", - "tokio-rustls 0.24.1", + "tokio-rustls", ] [[package]] @@ -778,7 +1128,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -892,6 +1242,38 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "if-addrs" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabb0019d51a643781ff15c9c8a3e5dedc365c47211270f4e8f82812fedd8f0a" +dependencies = [ + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "if-watch" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdf9d64cfcf380606e64f9a0bcf493616b65331199f984151a6fa11a7b3cde38" +dependencies = [ + "async-io", + "core-foundation", + "fnv", + "futures", + "if-addrs", + "ipnet", + "log", + "netlink-packet-core", + "netlink-packet-route", + "netlink-proto", + "netlink-sys", + "rtnetlink", + "system-configuration 0.6.1", + "windows", +] + [[package]] name = "impl-codec" version = "0.6.0" @@ -919,7 +1301,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.16.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", ] [[package]] @@ -928,42 +1328,12 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itoa" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" -[[package]] -name = "jiff" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89a5b5e10d5a9ad6e5d1f4bd58225f655d6fe9767575a5e8ac5a6fe64e04495" -dependencies = [ - "jiff-static", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff-static" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff7a39c8862fc1369215ccf0a8f12dd4598c7f6484704359f0351bd617034dbf" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "js-sys" version = "0.3.85" @@ -983,12 +1353,300 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "libc" version = "0.2.180" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" +[[package]] +name = "libp2p" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "681fb3f183edfbedd7a57d32ebe5dcdc0b9f94061185acf3c30249349cc6fc99" +dependencies = [ + "bytes", + "either", + "futures", + "futures-timer", + "getrandom 0.2.17", + "instant", + "libp2p-allow-block-list", + "libp2p-connection-limits", + "libp2p-core", + "libp2p-gossipsub", + "libp2p-identity", + "libp2p-kad", + "libp2p-mdns", + "libp2p-metrics", + "libp2p-noise", + "libp2p-swarm", + "libp2p-tcp", + "libp2p-yamux", + "multiaddr", + "pin-project", + "rw-stream-sink", + "thiserror 1.0.69", +] + +[[package]] +name = "libp2p-allow-block-list" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107b238b794cb83ab53b74ad5dcf7cca3200899b72fe662840cfb52f5b0a32e6" +dependencies = [ + "libp2p-core", + "libp2p-identity", + "libp2p-swarm", + "void", +] + +[[package]] +name = "libp2p-connection-limits" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7cd50a78ccfada14de94cbacd3ce4b0138157f376870f13d3a8422cd075b4fd" +dependencies = [ + "libp2p-core", + "libp2p-identity", + "libp2p-swarm", + "void", +] + +[[package]] +name = "libp2p-core" +version = "0.41.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a8920cbd8540059a01950c1e5c96ea8d89eb50c51cd366fc18bdf540a6e48f" +dependencies = [ + "either", + "fnv", + "futures", + "futures-timer", + "libp2p-identity", + "multiaddr", + "multihash", + "multistream-select", + "once_cell", + "parking_lot", + "pin-project", + "quick-protobuf", + "rand 0.8.5", + "rw-stream-sink", + "smallvec", + "thiserror 1.0.69", + "tracing", + "unsigned-varint 0.8.0", + "void", + "web-time", +] + +[[package]] +name = "libp2p-gossipsub" +version = "0.46.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d665144a616dadebdc5fff186b1233488cdcd8bfb1223218ff084b6d052c94f7" +dependencies = [ + "asynchronous-codec", + "base64", + "byteorder", + "bytes", + "either", + "fnv", + "futures", + "futures-ticker", + "getrandom 0.2.17", + "hex_fmt", + "instant", + "libp2p-core", + "libp2p-identity", + "libp2p-swarm", + "prometheus-client", + "quick-protobuf", + "quick-protobuf-codec", + "rand 0.8.5", + "regex", + "sha2", + "smallvec", + "tracing", + "void", +] + +[[package]] +name = "libp2p-identity" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c7892c221730ba55f7196e98b0b8ba5e04b4155651736036628e9f73ed6fc3" +dependencies = [ + "bs58", + "ed25519-dalek", + "hkdf", + "multihash", + "quick-protobuf", + "rand 0.8.5", + "sha2", + "thiserror 2.0.18", + "tracing", + "zeroize", +] + +[[package]] +name = "libp2p-kad" +version = "0.45.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc5767727d062c4eac74dd812c998f0e488008e82cce9c33b463d38423f9ad2" +dependencies = [ + "arrayvec", + "asynchronous-codec", + "bytes", + "either", + "fnv", + "futures", + "futures-bounded", + "futures-timer", + "instant", + "libp2p-core", + "libp2p-identity", + "libp2p-swarm", + "quick-protobuf", + "quick-protobuf-codec", + "rand 0.8.5", + "sha2", + "smallvec", + "thiserror 1.0.69", + "tracing", + "uint", + "void", +] + +[[package]] +name = "libp2p-mdns" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49007d9a339b3e1d7eeebc4d67c05dbf23d300b7d091193ec2d3f26802d7faf2" +dependencies = [ + "data-encoding", + "futures", + "hickory-proto", + "if-watch", + "libp2p-core", + "libp2p-identity", + "libp2p-swarm", + "rand 0.8.5", + "smallvec", + "socket2 0.5.10", + "tracing", + "void", +] + +[[package]] +name = "libp2p-metrics" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdac91ae4f291046a3b2660c039a2830c931f84df2ee227989af92f7692d3357" +dependencies = [ + "futures", + "instant", + "libp2p-core", + "libp2p-gossipsub", + "libp2p-identity", + "libp2p-kad", + "libp2p-swarm", + "pin-project", + "prometheus-client", +] + +[[package]] +name = "libp2p-noise" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecd0545ce077f6ea5434bcb76e8d0fe942693b4380aaad0d34a358c2bd05793" +dependencies = [ + "asynchronous-codec", + "bytes", + "curve25519-dalek", + "futures", + "libp2p-core", + "libp2p-identity", + "multiaddr", + "multihash", + "once_cell", + "quick-protobuf", + "rand 0.8.5", + "sha2", + "snow", + "static_assertions", + "thiserror 1.0.69", + "tracing", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "libp2p-swarm" +version = "0.44.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80cae6cb75f89dbca53862f9ebe0b9f463aa7b302762fcfaafb9e51dcc9b0f7e" +dependencies = [ + "either", + "fnv", + "futures", + "futures-timer", + "instant", + "libp2p-core", + "libp2p-identity", + "lru", + "multistream-select", + "once_cell", + "rand 0.8.5", + "smallvec", + "tracing", + "void", +] + +[[package]] +name = "libp2p-tcp" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2460fc2748919adff99ecbc1aab296e4579e41f374fb164149bd2c9e529d4c" +dependencies = [ + "futures", + "futures-timer", + "if-watch", + "libc", + "libp2p-core", + "libp2p-identity", + "socket2 0.5.10", + "tracing", +] + +[[package]] +name = "libp2p-yamux" +version = "0.45.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd5265f6b80f94d48a3963541aad183cc598a645755d2f1805a373e41e0716b" +dependencies = [ + "either", + "futures", + "libp2p-core", + "thiserror 1.0.69", + "tracing", + "yamux 0.12.1", + "yamux 0.13.9", +] + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + [[package]] name = "litemap" version = "0.8.1" @@ -1010,6 +1668,26 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "match-lookup" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "757aee279b8bdbb9f9e676796fd459e4207a1f986e87886700abf589f5abf771" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "memchr" version = "2.8.0" @@ -1059,22 +1737,170 @@ dependencies = [ ] [[package]] -name = "nac-sdk" -version = "2.0.0" +name = "multiaddr" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6351f60b488e04c1d21bc69e56b89cb3f5e8f5d22557d6e8031bdfd79b6961" +dependencies = [ + "arrayref", + "byteorder", + "data-encoding", + "libp2p-identity", + "multibase", + "multihash", + "percent-encoding", + "serde", + "static_assertions", + "unsigned-varint 0.8.0", + "url", +] + +[[package]] +name = "multibase" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8694bb4835f452b0e3bb06dbebb1d6fc5385b6ca1caf2e55fd165c042390ec77" +dependencies = [ + "base-x", + "base256emoji", + "data-encoding", + "data-encoding-macro", +] + +[[package]] +name = "multihash" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b430e7953c29dd6a09afc29ff0bb69c6e306329ee6794700aee27b76a1aea8d" +dependencies = [ + "core2", + "unsigned-varint 0.8.0", +] + +[[package]] +name = "multistream-select" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0df8e5eec2298a62b326ee4f0d7fe1a6b90a09dfcf9df37b38f947a8c42f19" +dependencies = [ + "bytes", + "futures", + "log", + "pin-project", + "smallvec", + "unsigned-varint 0.7.2", +] + +[[package]] +name = "nac-cbpp" +version = "1.0.0" +dependencies = [ + "anyhow", + "chrono", + "hex", + "nac-upgrade-framework", + "rand 0.8.5", + "serde", + "serde_json", + "sha2", + "sha3", + "thiserror 1.0.69", + "tokio", +] + +[[package]] +name = "nac-constitution-state" +version = "0.1.0" +dependencies = [ + "nac-udm", + "nac-upgrade-framework", + "serde", + "serde_json", +] + +[[package]] +name = "nac-csnp-l0" +version = "0.1.0" +dependencies = [ + "blake3", + "dashmap", + "libp2p", + "lru", + "nac-udm", + "nac-upgrade-framework", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tracing", +] + +[[package]] +name = "nac-csnp-l1" +version = "0.1.0" +dependencies = [ + "nac-udm", + "nac-upgrade-framework", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "nac-lens" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "blake3", + "bytes", + "ed25519-dalek", + "futures", + "nac-constitution-state", + "nac-csnp-l0", + "nac-csnp-l1", + "nac-udm", + "nac-upgrade-framework", + "serde", + "serde_json", + "sha2", + "thiserror 1.0.69", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "nac-nvm" +version = "1.0.0" +dependencies = [ + "anyhow", + "hex", + "nac-upgrade-framework", + "serde", + "serde_json", + "sha3", + "thiserror 1.0.69", +] + +[[package]] +name = "nac-sdk" +version = "2.1.0" dependencies = [ "anyhow", - "base64", "bincode", "blake3", - "chrono", "ed25519-dalek", - "env_logger", "hex", "js-sys", "log", "mockito", + "nac-cbpp", + "nac-lens", + "nac-nvm", "nac-udm", "nac-upgrade-framework", + "rand 0.8.5", "reqwest", "serde", "serde_json", @@ -1083,6 +1909,8 @@ dependencies = [ "tokio", "tokio-test", "tokio-tungstenite", + "tracing", + "tungstenite", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -1120,6 +1948,94 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "netlink-packet-core" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72724faf704479d67b388da142b186f916188505e7e0b26719019c525882eda4" +dependencies = [ + "anyhow", + "byteorder", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-route" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053998cea5a306971f88580d0829e90f270f940befd7cf928da179d4187a5a66" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "byteorder", + "libc", + "netlink-packet-core", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-utils" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ede8a08c71ad5a95cdd0e4e52facd37190977039a4704eb82a283f713747d34" +dependencies = [ + "anyhow", + "byteorder", + "paste", + "thiserror 1.0.69", +] + +[[package]] +name = "netlink-proto" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72452e012c2f8d612410d89eea01e2d9b56205274abb35d53f60200b2ec41d60" +dependencies = [ + "bytes", + "futures", + "log", + "netlink-packet-core", + "netlink-sys", + "thiserror 2.0.18", +] + +[[package]] +name = "netlink-sys" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6c30ed10fa69cc491d491b85cc971f6bdeb8e7367b7cde2ee6cc878d583fae" +dependencies = [ + "bytes", + "libc", + "log", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1129,6 +2045,16 @@ dependencies = [ "autocfg", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "once_cell" version = "1.21.3" @@ -1136,10 +2062,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] -name = "once_cell_polyfill" -version = "1.70.2" +name = "opaque-debug" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "parity-scale-codec" @@ -1169,6 +2095,12 @@ dependencies = [ "syn", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1192,12 +2124,38 @@ dependencies = [ "windows-link", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -1221,18 +2179,40 @@ dependencies = [ ] [[package]] -name = "portable-atomic" -version = "1.13.1" +name = "polling" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] [[package]] -name = "portable-atomic-util" -version = "0.2.5" +name = "poly1305" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ - "portable-atomic", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", ] [[package]] @@ -1282,6 +2262,51 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prometheus-client" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "504ee9ff529add891127c4827eb481bd69dc0ebc72e9a682e187db4caa60c3ca" +dependencies = [ + "dtoa", + "itoa", + "parking_lot", + "prometheus-client-derive-encode", +] + +[[package]] +name = "prometheus-client-derive-encode" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quick-protobuf" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" +dependencies = [ + "byteorder", +] + +[[package]] +name = "quick-protobuf-codec" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15a0580ab32b169745d7a39db2ba969226ca16738931be152a3209b409de2474" +dependencies = [ + "asynchronous-codec", + "bytes", + "quick-protobuf", + "thiserror 1.0.69", + "unsigned-varint 0.8.0", +] + [[package]] name = "quote" version = "1.0.44" @@ -1423,21 +2448,21 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls 0.21.12", + "rustls", "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", - "system-configuration", + "system-configuration 0.5.1", "tokio", - "tokio-rustls 0.24.1", + "tokio-rustls", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots 0.25.4", + "webpki-roots", "winreg", ] @@ -1455,6 +2480,23 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rtnetlink" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a552eb82d19f38c3beed3f786bd23aa434ceb9ac43ab44419ca6d67a7e186c0" +dependencies = [ + "futures", + "log", + "netlink-packet-core", + "netlink-packet-route", + "netlink-packet-utils", + "netlink-proto", + "netlink-sys", + "nix", + "thiserror 1.0.69", +] + [[package]] name = "rustc-hex" version = "2.1.0" @@ -1470,6 +2512,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.21.12" @@ -1478,24 +2533,10 @@ checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", "ring", - "rustls-webpki 0.101.7", + "rustls-webpki", "sct", ] -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring", - "rustls-pki-types", - "rustls-webpki 0.102.8", - "subtle", - "zeroize", -] - [[package]] name = "rustls-pemfile" version = "1.0.4" @@ -1505,15 +2546,6 @@ dependencies = [ "base64", ] -[[package]] -name = "rustls-pki-types" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" -dependencies = [ - "zeroize", -] - [[package]] name = "rustls-webpki" version = "0.101.7" @@ -1524,23 +2556,23 @@ dependencies = [ "untrusted", ] -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rw-stream-sink" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8c9026ff5d2f23da5e45bbc283f156383001bfb09c4e44256d02c1a685fe9a1" +dependencies = [ + "futures", + "pin-project", + "static_assertions", +] + [[package]] name = "ryu" version = "1.0.22" @@ -1656,6 +2688,15 @@ dependencies = [ "keccak", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -1699,6 +2740,23 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +[[package]] +name = "snow" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "850948bee068e713b8ab860fe1adc4d109676ab4c3b621fd8147f06b261f2f85" +dependencies = [ + "aes-gcm", + "blake2", + "chacha20poly1305", + "curve25519-dalek", + "rand_core 0.6.4", + "ring", + "rustc_version", + "sha2", + "subtle", +] + [[package]] name = "socket2" version = "0.5.10" @@ -1783,7 +2841,18 @@ checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" dependencies = [ "bitflags 1.3.2", "core-foundation", - "system-configuration-sys", + "system-configuration-sys 0.5.0", +] + +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags 2.10.0", + "core-foundation", + "system-configuration-sys 0.6.0", ] [[package]] @@ -1796,6 +2865,16 @@ dependencies = [ "libc", ] +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -1842,6 +2921,15 @@ dependencies = [ "syn", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "tinystr" version = "0.8.2" @@ -1852,6 +2940,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.49.0" @@ -1886,18 +2989,7 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.12", - "tokio", -] - -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls 0.22.4", - "rustls-pki-types", + "rustls", "tokio", ] @@ -1931,12 +3023,8 @@ checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38" dependencies = [ "futures-util", "log", - "rustls 0.22.4", - "rustls-pki-types", "tokio", - "tokio-rustls 0.25.0", "tungstenite", - "webpki-roots 0.26.11", ] [[package]] @@ -1995,9 +3083,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -2005,6 +3105,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", ] [[package]] @@ -2026,8 +3152,6 @@ dependencies = [ "httparse", "log", "rand 0.8.5", - "rustls 0.22.4", - "rustls-pki-types", "sha1", "thiserror 1.0.69", "url", @@ -2064,6 +3188,28 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "unsigned-varint" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6889a77d49f1f013504cec6bf97a2c730394adedaeb1deb5ea08949a50541105" + +[[package]] +name = "unsigned-varint" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb066959b24b5196ae73cb057f45598450d2c5f71460e98c49b738086eff9c06" + [[package]] name = "untrusted" version = "0.9.0" @@ -2095,10 +3241,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] -name = "utf8parse" -version = "0.2.2" +name = "valuable" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "version_check" @@ -2106,6 +3252,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + [[package]] name = "want" version = "0.3.1" @@ -2199,6 +3351,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-roots" version = "0.25.4" @@ -2206,21 +3368,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" [[package]] -name = "webpki-roots" -version = "0.26.11" +name = "windows" +version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +checksum = "efc5cf48f83140dcaab716eeaea345f9e93d0018fb81162753a3f76c3397b538" dependencies = [ - "webpki-roots 1.0.6", + "windows-core 0.53.0", + "windows-targets 0.52.6", ] [[package]] -name = "webpki-roots" -version = "1.0.6" +name = "windows-core" +version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed" +checksum = "9dcc5b895a6377f1ab9fa55acedab1fd5ac0db66ad1e6c7f47e28a22e446a5dd" dependencies = [ - "rustls-pki-types", + "windows-result 0.1.2", + "windows-targets 0.52.6", ] [[package]] @@ -2232,7 +3396,7 @@ dependencies = [ "windows-implement", "windows-interface", "windows-link", - "windows-result", + "windows-result 0.4.1", "windows-strings", ] @@ -2264,6 +3428,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -2556,6 +3729,37 @@ dependencies = [ "zeroize", ] +[[package]] +name = "yamux" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed0164ae619f2dc144909a9f082187ebb5893693d8c0196e8085283ccd4b776" +dependencies = [ + "futures", + "log", + "nohash-hasher", + "parking_lot", + "pin-project", + "rand 0.8.5", + "static_assertions", +] + +[[package]] +name = "yamux" +version = "0.13.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c650efd29044140aa63caaf80129996a9e2659a2ab7045a7e061807d02fc8549" +dependencies = [ + "futures", + "log", + "nohash-hasher", + "parking_lot", + "pin-project", + "rand 0.9.2", + "static_assertions", + "web-time", +] + [[package]] name = "yoke" version = "0.8.1" diff --git a/nac-sdk/Cargo.toml b/nac-sdk/Cargo.toml index 76d552a..d431882 100644 --- a/nac-sdk/Cargo.toml +++ b/nac-sdk/Cargo.toml @@ -40,7 +40,6 @@ tokio-tungstenite = "0.21" hex = "0.4" thiserror = "1.0" anyhow = "1.0" -rand = "0.8" log = "0.4" tracing = "0.1" diff --git a/nac-sdk/Cargo.toml.bak.20260222 b/nac-sdk/Cargo.toml.bak.20260222 new file mode 100644 index 0000000..76d552a --- /dev/null +++ b/nac-sdk/Cargo.toml.bak.20260222 @@ -0,0 +1,83 @@ +[package] +name = "nac-sdk" +version = "2.1.0" +edition = "2021" +authors = ["NAC Team"] +description = "NAC (NewAssetChain) SDK - Native Rust Implementation for RWA Blockchain" +license = "MIT" +repository = "https://github.com/nac/nac-sdk" +keywords = ["blockchain", "nac", "rwa", "sdk"] +categories = ["cryptography", "blockchain"] + +[dependencies] +nac-upgrade-framework = { path = "../nac-upgrade-framework" } +nac-udm = { path = "../nac-udm" } +nac-nvm = { path = "../nac-nvm" } +nac-cbpp = { path = "../nac-cbpp" } +nac-lens = { path = "../nac-lens" } + +# Cryptography +blake3 = "1.5" +sha3 = "0.10" +ed25519-dalek = "2.1" +rand = "0.8" +x25519-dalek = "2.0" + +# Serialization +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +bincode = "1.3" + +# HTTP Client +reqwest = { version = "0.11", features = ["json", "rustls-tls"], default-features = false } +tokio = { version = "1.35", features = ["full"] } + +# WebSocket +tungstenite = "0.21" +tokio-tungstenite = "0.21" + +# Utilities +hex = "0.4" +thiserror = "1.0" +anyhow = "1.0" +rand = "0.8" +log = "0.4" +tracing = "0.1" + +# WASM support (optional) +wasm-bindgen = { version = "0.2", optional = true } +wasm-bindgen-futures = { version = "0.4", optional = true } +js-sys = { version = "0.3", optional = true } +web-sys = { version = "0.3", features = ["Window", "Document", "console"], optional = true } + +[dev-dependencies] +tokio-test = "0.4" +mockito = "1.2" + +[features] +default = ["native"] +native = [] +wasm = ["wasm-bindgen", "wasm-bindgen-futures", "js-sys", "web-sys"] + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +strip = true + +[profile.release-wasm] +inherits = "release" +opt-level = "z" +lto = true +codegen-units = 1 + +[lints.rust] +missing_docs = "allow" +unused_doc_comments = "allow" +non_camel_case_types = "allow" +dead_code = "allow" +unused_imports = "allow" +unused_variables = "allow" + +[lints.rustdoc] +all = "allow" diff --git a/nac-sdk/ISSUE_036_LAYER_ADAPTERS.md b/nac-sdk/ISSUE_036_LAYER_ADAPTERS.md index 8a4c480..6674e4f 100644 --- a/nac-sdk/ISSUE_036_LAYER_ADAPTERS.md +++ b/nac-sdk/ISSUE_036_LAYER_ADAPTERS.md @@ -51,9 +51,9 @@ L0: 原生层 (l0_native) 3. ❌ 缺少L0-L5各层的完整接口定义 4. ❌ 缺少统一的适配器调用方式 -### 2.2 nac-nrpc4 (NRPC 4.0协议) +### 2.2 nac-lens (NAC Lens协议) -**位置**: `/home/ubuntu/NAC_Clean_Dev/nac-nrpc4` +**位置**: `/home/ubuntu/NAC_Clean_Dev/nac-lens` **六层架构**: - L1: 元胞层 (l1_cell) - 元胞自动机路由 @@ -1048,7 +1048,7 @@ pub struct L5Config { - **工单链接**: https://git.newassetchain.io/nacadmin/NAC_Blockchain/issues/36 - **nac-sdk**: `/home/ubuntu/NAC_Clean_Dev/nac-sdk` - **nac-udm**: `/home/ubuntu/NAC_Clean_Dev/nac-udm` -- **nac-nrpc4**: `/home/ubuntu/NAC_Clean_Dev/nac-nrpc4` +- **nac-lens**: `/home/ubuntu/NAC_Clean_Dev/nac-lens` - **nac-ai-compliance**: `/home/ubuntu/NAC_Clean_Dev/nac-ai-compliance` - **nac-ai-valuation**: `/home/ubuntu/NAC_Clean_Dev/nac-ai-valuation` diff --git a/nac-sdk/README.md b/nac-sdk/README.md index 10cbbfe..f63cab4 100644 --- a/nac-sdk/README.md +++ b/nac-sdk/README.md @@ -16,7 +16,7 @@ NAC SDK是为RWA(真实世界资产)区块链设计的原生Rust SDK,提 - ✅ **统一接口** - 通过`NACAdapter`统一访问所有功能 - ✅ **高性能** - Rust实现,零成本抽象 - ✅ **类型安全** - 强类型系统,编译时错误检查 -- ✅ **NRPC4.0协议** - 支持NAC原生RPC协议 +- ✅ **NAC Lens协议** - 支持NAC原生RPC协议 - ✅ **完整文档** - 每个API都有详细的文档和示例 - ✅ **测试覆盖** - 完整的单元测试和集成测试 @@ -533,7 +533,7 @@ nac-sdk/ - `nac-udm` - NAC统一数据模型 - `nac-nvm` - NAC虚拟机 - `nac-cbpp` - CBPP共识协议 -- `nac-nrpc4` - NRPC4.0协议 +- `nac-lens` - NAC Lens协议 ### 第三方依赖 - `tokio` - 异步运行时 diff --git a/nac-sdk/src/adapters/config.rs b/nac-sdk/src/adapters/config.rs index 2fcadee..4e65100 100644 --- a/nac-sdk/src/adapters/config.rs +++ b/nac-sdk/src/adapters/config.rs @@ -149,6 +149,10 @@ impl Default for L4Config { /// L5层配置 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct L5Config { + /// 钱包服务 URL + pub wallet_url: String, + /// DApp 服务 URL + pub dapp_url: String, /// 钱包数据库路径 pub wallet_db_path: String, /// 浏览器API URL @@ -163,6 +167,8 @@ pub struct L5Config { impl Default for L5Config { fn default() -> Self { Self { + wallet_url: "http://localhost:9552".to_string(), + dapp_url: "http://localhost:9553".to_string(), wallet_db_path: "./data/wallet".to_string(), explorer_url: "http://localhost:9554".to_string(), exchange_url: "http://localhost:9555".to_string(), diff --git a/nac-sdk/src/adapters/l1_protocol.rs b/nac-sdk/src/adapters/l1_protocol.rs index f4d2507..8444f0e 100644 --- a/nac-sdk/src/adapters/l1_protocol.rs +++ b/nac-sdk/src/adapters/l1_protocol.rs @@ -30,13 +30,14 @@ use crate::error::{NACError, Result}; use super::config::L1Config; -use nac_udm::primitives::{Address, Hash, Decimal}; -use nac_udm::types::{ +use nac_udm::primitives::{Address, Hash}; +use super::{ Block, Transaction, SignedTransaction, TransactionReceipt, - GNACSCode, GNACSMetadata, ACC20Metadata, ACC1400Metadata, - CollateralProof, CrossShardStatus, + GNACSMetadata, ACC20Metadata, ACC1400Metadata, CrossShardStatus, + CollateralProof, Decimal, }; -use nac_nrpc4::client::NRPC4Client; +use nac_udm::l1_protocol::gnacs::GNACSCode; +use super::NRPC4Client; use std::time::Duration; /// L1协议层适配器 @@ -155,7 +156,7 @@ impl L1ProtocolAdapter { /// 返回预估的Gas消耗量 pub async fn estimate_gas( &self, - tx: &Transaction, + tx: &SignedTransaction, ) -> Result { self.client .estimate_gas(tx, self.chain_id) @@ -248,7 +249,7 @@ impl L1ProtocolAdapter { tx_hash: &Hash, ) -> Result { self.client - .get_transaction_receipt(tx_hash, self.chain_id) + .get_transaction_receipt(tx_hash) .await .map_err(|e| NACError::NetworkError(format!("Failed to get transaction receipt: {}", e))) } @@ -293,7 +294,8 @@ impl L1ProtocolAdapter { jurisdiction: &str, sub_category: Option<&str>, ) -> Result { - GNACSCode::generate(asset_type, jurisdiction, sub_category) + // 使用 GNACSCode::from_hex 创建编码(存根实现) + GNACSCode::from_hex(asset_type) .map_err(|e| NACError::ValidationError(format!("Failed to generate GNACS code: {}", e))) } @@ -310,8 +312,11 @@ impl L1ProtocolAdapter { &self, code: &GNACSCode, ) -> Result { - code.parse() - .map_err(|e| NACError::ValidationError(format!("Failed to parse GNACS code: {}", e))) + Ok(GNACSMetadata { + code: code.to_hex(), + category: format!("{:?}", code.category()), + jurisdiction: format!("{:?}", code.jurisdiction()), + }) } /// 验证GNACS编码 @@ -327,7 +332,7 @@ impl L1ProtocolAdapter { &self, code: &GNACSCode, ) -> bool { - code.validate() + code.verify_checksum() } // ===== ACC协议族 ===== @@ -515,7 +520,7 @@ impl L1ProtocolAdapter { &self, tx: &SignedTransaction, target_shard: u32, - ) -> Result { + ) -> Result { self.client .submit_cross_shard_tx(tx, target_shard, self.chain_id) .await diff --git a/nac-sdk/src/adapters/l2_layer.rs b/nac-sdk/src/adapters/l2_layer.rs index 68aaae1..b5132f3 100644 --- a/nac-sdk/src/adapters/l2_layer.rs +++ b/nac-sdk/src/adapters/l2_layer.rs @@ -29,14 +29,16 @@ use crate::error::{NACError, Result}; use super::config::L2Config; -use nac_udm::primitives::{Address, Hash, Decimal}; -use nac_udm::types::{ +use nac_udm::primitives::{Address, Hash}; +use super::{ Transaction, SignedTransaction, Block, Amendment, AmendmentStatus, Proposal, ProposalDetails, Vote, ComplianceResult, PeerInfo, }; -use nac_nrpc4::client::NRPC4Client; -use nac_csnp::network::CSNPNetwork; +use super::NRPC4Client; +use super::CSNPNetwork; +use super::Decimal; + use std::sync::Arc; /// 提案ID类型 diff --git a/nac-sdk/src/adapters/l3_storage.rs b/nac-sdk/src/adapters/l3_storage.rs index 41b2aaf..04d60c9 100644 --- a/nac-sdk/src/adapters/l3_storage.rs +++ b/nac-sdk/src/adapters/l3_storage.rs @@ -30,7 +30,7 @@ use crate::error::{NACError, Result}; use super::config::L3Config; use nac_udm::primitives::{Address, Hash}; -use nac_udm::types::{ +use super::{ Block, Transaction, TransactionReceipt, AccountState, }; use std::path::PathBuf; @@ -52,7 +52,7 @@ impl StateDatabase { async fn get_account_state(&self, _address: &Address) -> Result { // 实际实现应该从数据库读取 - Ok(AccountState::default()) + Ok(AccountState { address: [0u8; 32], balance: 0, nonce: 0, code_hash: None }) } async fn set_account_state(&self, _address: &Address, _state: &AccountState) -> Result<()> { diff --git a/nac-sdk/src/adapters/l4_ai.rs b/nac-sdk/src/adapters/l4_ai.rs index 88419bb..ca51696 100644 --- a/nac-sdk/src/adapters/l4_ai.rs +++ b/nac-sdk/src/adapters/l4_ai.rs @@ -31,15 +31,15 @@ use crate::error::{NACError, Result}; use super::config::L4Config; -use nac_udm::primitives::{Address, Decimal}; -use nac_udm::types::{ +use nac_udm::primitives::Address; + +use super::{NacLensClient as NRPC4Client, Transaction, ComplianceData, ComplianceResult, ComplianceReport, ZKProof, Asset, ValuationResult, MarketData, RiskScore, UserBehavior, AnomalyReport, RiskReport, Reserves, ReserveStrategy, - SDRForecast, LiquidityState, LiquidityStrategy, Jurisdiction, + Decimal, SDRForecast, LiquidityState, LiquidityStrategy, Jurisdiction, InternationalAgreement, }; -use nac_nrpc4::client::NRPC4Client; use std::time::Duration; /// L4 AI层适配器 diff --git a/nac-sdk/src/adapters/l5_application.rs b/nac-sdk/src/adapters/l5_application.rs index bc17220..8887f59 100644 --- a/nac-sdk/src/adapters/l5_application.rs +++ b/nac-sdk/src/adapters/l5_application.rs @@ -31,13 +31,14 @@ use crate::error::{NACError, Result}; use super::config::L5Config; -use nac_udm::primitives::{Address, Hash, Decimal}; -use nac_udm::types::{ - Wallet, BalanceInfo, TransactionInfo, TransactionReceipt, +use nac_udm::primitives::{Address, Hash}; +use super::{ + Wallet, BalanceInfo, TransactionInfo, TransactionReceipt, NacLensClient as NRPC4Client, Decimal, ChainStatistics, AddressInfo, TokenMetadata, TradingPair, OrderBook, Value, ContractCall, }; -use nac_nrpc4::client::NRPC4Client; + + use std::time::Duration; /// 列表ID类型 diff --git a/nac-sdk/src/adapters/mod.rs b/nac-sdk/src/adapters/mod.rs index 5b32b33..43e63b7 100644 --- a/nac-sdk/src/adapters/mod.rs +++ b/nac-sdk/src/adapters/mod.rs @@ -49,7 +49,9 @@ //! } //! ``` +use nac_udm::primitives::{Address, Hash}; use crate::error::Result; +use crate::error::NACError; use std::time::Duration; // 子模块声明 @@ -205,3 +207,1314 @@ mod tests { assert!(result.is_ok() || result.is_err()); } } + + +// ============================================================ +// 类型存根:这些类型将在对应的 nac-udm 子模块实现后替换 +// 目前用于让 nac-sdk 可以编译 +// ============================================================ + +/// NAC 区块结构 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Block { + pub height: u64, + pub hash: Vec, + pub parent_hash: Vec, + pub timestamp: u64, + pub transactions: Vec, + pub producer: [u8; 32], + pub size_bytes: u64, +} + +/// NAC 交易结构 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Transaction { + pub hash: Vec, + pub from: [u8; 32], + pub to: [u8; 32], + pub amount: u128, + pub nonce: u64, + pub data: Vec, +} + +/// 已签名交易 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SignedTransaction { + pub transaction: Transaction, + pub signature: Vec, +} + +/// 交易收据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TransactionReceipt { + pub tx_hash: Vec, + pub block_height: u64, + pub status: bool, + pub gas_used: u64, +} + +/// GNACS 元数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct GNACSMetadata { + pub code: String, + pub category: String, + pub jurisdiction: String, +} + +/// ACC-20 代币元数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ACC20Metadata { + pub name: String, + pub symbol: String, + pub total_supply: u128, + pub decimals: u8, +} + +/// ACC-1400 证券型代币元数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ACC1400Metadata { + pub name: String, + pub symbol: String, + pub total_supply: u128, + pub jurisdiction: String, + pub compliance_level: u8, +} + +/// 抵押证明 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum CollateralType { + Gold, + SDR, + RWA, + Other(String), +} + +pub struct CollateralProof { + pub collateral_type: CollateralType, + pub collateral_amount: u128, + pub asset_id: String, + pub value_usd: u128, + pub proof_hash: Vec, +} + +/// 跨分片交易状态 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum CrossShardStatus { + Pending, + Locked, + Committed, + Aborted, +} + +/// 合规数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ComplianceData { + pub asset_id: String, + pub jurisdiction: String, + pub compliance_type: String, + pub data: Vec, +} + +/// 合规结果 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ComplianceResult { + pub passed: bool, + pub score: f64, + pub issues: Vec, +} + +/// 合规报告 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ComplianceReport { + pub asset_id: String, + pub result: ComplianceResult, + pub timestamp: u64, +} + +/// 零知识证明 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ZKProof { + pub proof_type: String, + pub proof_data: Vec, + pub public_inputs: Vec, +} + +/// 资产信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Asset { + pub id: String, + pub gnacs_code: String, + pub owner: [u8; 32], + pub value_usd: u128, +} + +/// 估值结果 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ValuationResult { + pub asset_id: String, + pub value_usd: u128, + pub confidence: f64, + pub timestamp: u64, +} + +/// 市场数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MarketData { + pub symbol: String, + pub price_usd: f64, + pub volume_24h: f64, + pub timestamp: u64, +} + +/// 风险评分 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RiskScore { + pub score: f64, + pub level: String, + pub factors: Vec, +} + +/// 用户行为 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct UserBehavior { + pub address: [u8; 32], + pub action: String, + pub timestamp: u64, +} + +/// 异常报告 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct AnomalyReport { + pub address: [u8; 32], + pub anomaly_type: String, + pub severity: f64, + pub timestamp: u64, +} + +/// 风险报告 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RiskReport { + pub asset_id: String, + pub risk_score: RiskScore, + pub timestamp: u64, +} + +/// 储备信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Reserves { + pub total_usd: u128, + pub gold_oz: f64, + pub sdr_units: f64, +} + +/// 储备策略 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ReserveStrategy { + pub target_ratio: f64, + pub rebalance_threshold: f64, +} + +/// SDR 预测 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SDRForecast { + pub predicted_rate: f64, + pub confidence: f64, + pub horizon_days: u32, +} + +/// 流动性状态 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LiquidityState { + pub available: u128, + pub locked: u128, + pub ratio: f64, +} + +/// 流动性策略 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LiquidityStrategy { + pub min_ratio: f64, + pub target_ratio: f64, +} + +/// 国际协议 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct InternationalAgreement { + pub id: String, + pub parties: Vec, + pub terms: String, +} + +/// 节点信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PeerInfo { + pub node_id: String, + pub address: String, + pub status: String, +} + +/// 修正案 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Amendment { + pub id: u64, + pub title: String, + pub content: String, + pub proposer: [u8; 32], +} + +/// 修正案状态 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum AmendmentStatus { + Proposed, + Approved, + Rejected, + Voting, + Passed, +} + +/// 提案 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Proposal { + pub id: u64, + pub title: String, + pub proposer: [u8; 32], + pub status: String, +} + +/// 提案详情 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ProposalDetails { + pub proposal: Proposal, + pub votes_for: u64, + pub votes_against: u64, + pub description: String, +} + +/// 投票 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Vote { + pub proposal_id: u64, + pub voter: [u8; 32], + pub approve: bool, + pub timestamp: u64, +} + +/// 钱包 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Wallet { + pub address: [u8; 32], + pub balance: u128, +} +/// 钱包信息(含助记词) +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct WalletInfo { + pub address: nac_udm::primitives::Address, + pub mnemonic: Option, + pub created_at: u64, +} + +/// 余额信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BalanceInfo { + pub address: [u8; 32], + pub nac_balance: u128, + pub xtzh_balance: u128, +} + +/// 交易信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TransactionInfo { + pub hash: Vec, + pub from: [u8; 32], + pub to: [u8; 32], + pub amount: u128, + pub timestamp: u64, + pub status: String, +} + +/// 链统计 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ChainStatistics { + pub block_height: u64, + pub total_transactions: u64, + pub active_nodes: u32, + pub tps: f64, +} + +/// 地址信息 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct AddressInfo { + pub address: [u8; 32], + pub balance: u128, + pub transaction_count: u64, + pub node_status: Option, +} + +/// 代币元数据 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TokenMetadata { + pub name: String, + pub symbol: String, + pub total_supply: u128, + pub decimals: u8, + pub contract_address: [u8; 32], +} + +/// 交易对 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TradingPair { + pub base: String, + pub quote: String, + pub price: f64, +} + +/// 订单簿 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct OrderBook { + pub pair: TradingPair, + pub bids: Vec<(f64, f64)>, + pub asks: Vec<(f64, f64)>, +} + +/// 价值 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Value { + pub amount: u128, + pub currency: String, +} + +/// 合约调用 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ContractCall { + pub contract_address: [u8; 32], + pub method: String, + pub args: Vec, +} + +/// NAC Lens 客户端(NAC 原生协议客户端,NRPC4.0 已更名为 NAC Lens) +#[derive(Debug, Clone)] +pub struct NacLensClient { + pub endpoint: String, + pub timeout: std::time::Duration, + pub(crate) http_client: reqwest::Client, +} + +impl NacLensClient { + /// 创建新的 NAC Lens 客户端 + pub fn new(endpoint: &str, timeout: std::time::Duration) -> std::result::Result { + Ok(Self { + endpoint: endpoint.to_string(), + timeout, + http_client: reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| e.to_string())?, + }) + } + + /// 底层 NAC Lens 调用 + pub async fn call(&self, method: &str, params: serde_json::Value) -> Result { + let body = serde_json::json!({ + "jsonrpc": "2.0", + "method": method, + "params": params, + "id": 1 + }); + let resp = self.http_client + .post(&self.endpoint) + .json(&body) + .send() + .await + .map_err(|e| NACError::NetworkError(e.to_string()))?; + let json: serde_json::Value = resp.json().await + .map_err(|e| NACError::NetworkError(e.to_string()))?; + if let Some(err) = json.get("error") { + return Err(NACError::NetworkError(err.to_string())); + } + Ok(json["result"].clone()) + } + + /// 批量调用 + pub async fn batch_call(&self, calls: &[ContractCall]) -> Result> { + let _response = self.call("dapp_batchCall", serde_json::json!({ + "call_count": calls.len() + })).await?; + Ok(calls.iter().map(|_| Value { amount: 0, currency: "NAC".to_string() }).collect()) + } + + // ===== NVM 虚拟机 ===== + + /// 部署 Charter 智能合约 + pub async fn deploy_contract(&self, bytecode: &[u8], constructor_args: &[u8], deployer: &Address, chain_id: u32) -> Result
{ + let response = self.call("nvm_deployContract", serde_json::json!({ + "bytecode": hex::encode(bytecode), + "constructor_args": hex::encode(constructor_args), + "deployer": hex::encode(deployer.as_bytes()), + "chain_id": chain_id + })).await?; + let addr_hex = response["contract_address"].as_str().unwrap_or("").to_string(); + let addr_bytes = hex::decode(&addr_hex).map_err(|e| NACError::ContractError(e.to_string()))?; + { let mut a = [0u8; 32]; let l = addr_bytes.len().min(32); a[..l].copy_from_slice(&addr_bytes[..l]); Ok(Address::new(a)) } + } + + /// 调用 Charter 合约方法 + pub async fn call_contract(&self, contract_addr: &Address, method: &str, args: &[u8], caller: &Address, chain_id: u32) -> Result> { + let response = self.call("nvm_callContract", serde_json::json!({ + "contract": hex::encode(contract_addr.as_bytes()), + "method": method, + "args": hex::encode(args), + "caller": hex::encode(caller.as_bytes()), + "chain_id": chain_id + })).await?; + let data_hex = response["result"].as_str().unwrap_or("").to_string(); + hex::decode(&data_hex).map_err(|e| NACError::ContractError(e.to_string())) + } + + /// call_contract_method 别名 + pub async fn call_contract_method(&self, contract: &Address, method: &str, params: &[Value], caller: &Address) -> Result { + let response = self.call("dapp_callContractMethod", serde_json::json!({ + "contract": hex::encode(contract.as_bytes()), + "method": method, + "caller": hex::encode(caller.as_bytes()) + })).await?; + Ok(Value { + amount: response["amount"].as_u64().unwrap_or(0) as u128, + currency: response["currency"].as_str().unwrap_or("NAC").to_string(), + }) + } + + /// 查询合约状态 + pub async fn query_state(&self, contract_addr: &Address, key: &[u8], chain_id: u32) -> Result> { + let response = self.call("nvm_queryState", serde_json::json!({ + "contract": hex::encode(contract_addr.as_bytes()), + "key": hex::encode(key), + "chain_id": chain_id + })).await?; + let data_hex = response["data"].as_str().unwrap_or("").to_string(); + hex::decode(&data_hex).map_err(|e| NACError::ContractError(e.to_string())) + } + + /// 估算 Gas + pub async fn estimate_gas(&self, tx: &SignedTransaction, chain_id: u32) -> Result { + let tx_bytes = serde_json::to_vec(tx).unwrap_or_default(); + let response = self.call("cbpp_estimateGas", serde_json::json!({ + "tx": hex::encode(&tx_bytes), + "chain_id": chain_id + })).await?; + Ok(response["gas"].as_u64().unwrap_or(21000)) + } + + // ===== CBPP 共识 ===== + + /// 提交交易 + pub async fn submit_transaction(&self, tx: &SignedTransaction, chain_id: u32) -> Result { + let tx_bytes = serde_json::to_vec(tx).unwrap_or_default(); + let response = self.call("cbpp_submitTransaction", serde_json::json!({ + "tx": hex::encode(&tx_bytes), + "chain_id": chain_id + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).map_err(|e| NACError::NetworkError(e.to_string()))?; + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 广播交易(CSNP 网络) + pub async fn broadcast_transaction(&self, tx: &[u8]) -> Result { + self.call("csnp_broadcastTransaction", serde_json::json!({ + "tx": hex::encode(tx) + })).await + } + + /// 广播区块 + pub async fn broadcast_block(&self, block: &[u8]) -> Result { + self.call("csnp_broadcastBlock", serde_json::json!({ + "block": hex::encode(block) + })).await + } + + /// 按高度获取区块 + pub async fn get_block_by_number(&self, block_number: u64, chain_id: u32) -> Result { + let response = self.call("cbpp_getBlockByNumber", serde_json::json!({ + "block_number": block_number, + "chain_id": chain_id + })).await?; + let hash_bytes = hex::decode(response["hash"].as_str().unwrap_or("")).unwrap_or_default(); + let parent_bytes = hex::decode(response["prev_hash"].as_str().unwrap_or("")).unwrap_or_default(); + let producer_bytes = hex::decode(response["producer"].as_str().unwrap_or("")).unwrap_or_default(); + let mut producer_arr = [0u8; 32]; + if producer_bytes.len() >= 32 { + producer_arr.copy_from_slice(&producer_bytes[..32]); + } + Ok(Block { + height: response["height"].as_u64().unwrap_or(block_number), + hash: hash_bytes, + parent_hash: parent_bytes, + timestamp: response["timestamp"].as_u64().unwrap_or(0), + transactions: vec![], + producer: producer_arr, + size_bytes: response["size"].as_u64().unwrap_or(10240), + }) + } + + /// 按哈希获取区块 + pub async fn get_block_by_hash(&self, block_hash: &Hash, chain_id: u32) -> Result { + let response = self.call("cbpp_getBlockByHash", serde_json::json!({ + "block_hash": hex::encode(block_hash.as_bytes()), + "chain_id": chain_id + })).await?; + let parent_bytes2 = hex::decode(response["prev_hash"].as_str().unwrap_or("")).unwrap_or_default(); + let producer_bytes2 = hex::decode(response["producer"].as_str().unwrap_or("")).unwrap_or_default(); + let mut producer_arr2 = [0u8; 32]; + if producer_bytes2.len() >= 32 { + producer_arr2.copy_from_slice(&producer_bytes2[..32]); + } + Ok(Block { + height: response["height"].as_u64().unwrap_or(0), + hash: block_hash.as_bytes().to_vec(), + parent_hash: parent_bytes2, + timestamp: response["timestamp"].as_u64().unwrap_or(0), + transactions: vec![], + producer: producer_arr2, + size_bytes: response["size"].as_u64().unwrap_or(10240), + }) + } + + /// 获取最新区块高度 + pub async fn get_latest_block_number(&self, chain_id: u32) -> Result { + let response = self.call("cbpp_getLatestBlockNumber", serde_json::json!({ + "chain_id": chain_id + })).await?; + Ok(response["block_number"].as_u64().unwrap_or(0)) + } + + /// 获取交易收据 + pub async fn get_transaction_receipt(&self, tx_hash: &Hash) -> Result { + let response = self.call("cbpp_getTransactionReceipt", serde_json::json!({ + "tx_hash": hex::encode(tx_hash.as_bytes()) + })).await?; + Ok(TransactionReceipt { + tx_hash: tx_hash.as_bytes().to_vec(), + block_height: response["block_height"].as_u64().unwrap_or(0), + status: response["status"].as_bool().unwrap_or(false), + gas_used: response["gas_used"].as_u64().unwrap_or(0), + }) + } + + /// 等待交易确认 + pub async fn wait_for_confirmation(&self, tx_hash: &Hash, confirmations: u32, chain_id: u32, timeout: std::time::Duration) -> Result { + let response = self.call("cbpp_waitForConfirmation", serde_json::json!({ + "tx_hash": hex::encode(tx_hash.as_bytes()), + "confirmations": confirmations, + "chain_id": chain_id, + "timeout_ms": timeout.as_millis() + })).await?; + Ok(TransactionReceipt { + tx_hash: tx_hash.as_bytes().to_vec(), + block_height: response["block_height"].as_u64().unwrap_or(0), + status: response["status"].as_bool().unwrap_or(true), + gas_used: response["gas_used"].as_u64().unwrap_or(0), + }) + } + + /// 获取链统计 + pub async fn get_chain_stats(&self) -> Result { + let response = self.call("lens_getChainStats", serde_json::json!({})).await?; + Ok(ChainStatistics { + block_height: response["block_height"].as_u64().unwrap_or(0), + total_transactions: response["total_transactions"].as_u64().unwrap_or(0), + active_nodes: response["active_nodes"].as_u64().unwrap_or(0) as u32, + tps: response["tps"].as_f64().unwrap_or(0.0), + }) + } + + // ===== CSNP 网络 ===== + + /// 获取对等节点列表 + pub async fn get_peers(&self) -> Result> { + let response = self.call("csnp_getPeers", serde_json::json!({})).await?; + Ok(response.as_array().unwrap_or(&vec![]).iter() + .filter_map(|p| p.as_str().map(|s| s.to_string())) + .collect()) + } + + /// 连接到对等节点 + pub async fn connect_to_peer(&self, peer: &str) -> Result { + self.call("csnp_connectToPeer", serde_json::json!({ + "peer": peer + })).await + } + + /// 同步区块 + pub async fn sync_blocks(&self, from: u64, to: u64) -> Result { + self.call("csnp_syncBlocks", serde_json::json!({ + "from": from, + "to": to + })).await + } + + /// 订阅事件 + pub async fn subscribe_event(&self, contract: &Address, event_name: &str) -> Result<()> { + self.call("dapp_subscribeEvent", serde_json::json!({ + "contract": hex::encode(contract.as_bytes()), + "event_name": event_name + })).await?; + Ok(()) + } + + // ===== ACC-20 代币协议 ===== + + /// 部署 ACC-20 代币合约 + pub async fn deploy_acc20(&self, metadata: &ACC20Metadata, deployer: &Address, chain_id: u32) -> Result
{ + let response = self.call("acc20_deploy", serde_json::json!({ + "name": metadata.name, + "symbol": metadata.symbol, + "total_supply": metadata.total_supply, + "deployer": hex::encode(deployer.as_bytes()), + "chain_id": chain_id + })).await?; + let addr_hex = response["contract_address"].as_str().unwrap_or("").to_string(); + let addr_bytes = hex::decode(&addr_hex).map_err(|e| NACError::ContractError(e.to_string()))?; + { let mut a = [0u8; 32]; let l = addr_bytes.len().min(32); a[..l].copy_from_slice(&addr_bytes[..l]); Ok(Address::new(a)) } + } + + /// 铸造 ACC-20 代币 + pub async fn mint_acc20(&self, token_addr: &Address, to: &Address, amount: Decimal, minter: &Address, chain_id: u32) -> Result { + let response = self.call("acc20_mint", serde_json::json!({ + "token_addr": hex::encode(token_addr.as_bytes()), + "to": hex::encode(to.as_bytes()), + "amount": amount, + "minter": hex::encode(minter.as_bytes()), + "chain_id": chain_id + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).map_err(|e| NACError::NetworkError(e.to_string()))?; + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 转账 ACC-20 代币 + pub async fn transfer_acc20(&self, token_addr: &Address, from: &Address, to: &Address, amount: Decimal, chain_id: u32) -> Result { + let response = self.call("acc20_transfer", serde_json::json!({ + "token_addr": hex::encode(token_addr.as_bytes()), + "from": hex::encode(from.as_bytes()), + "to": hex::encode(to.as_bytes()), + "amount": amount, + "chain_id": chain_id + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).map_err(|e| NACError::NetworkError(e.to_string()))?; + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 查询 ACC-20 余额 + pub async fn balance_of_acc20(&self, token_addr: &Address, owner: &Address, chain_id: u32) -> Result { + let response = self.call("acc20_balanceOf", serde_json::json!({ + "token_addr": hex::encode(token_addr.as_bytes()), + "holder": hex::encode(owner.as_bytes()), + "chain_id": chain_id + })).await?; + Ok(response["balance"].as_u64().unwrap_or(0) as u128) + } + + // ===== ACC-1400 证券化资产协议 ===== + + /// 部署 ACC-1400 合约 + pub async fn deploy_acc1400(&self, metadata: &ACC1400Metadata, deployer: &Address, chain_id: u32) -> Result
{ + let response = self.call("acc1400_deploy", serde_json::json!({ + "name": metadata.name, + "symbol": metadata.symbol, + "deployer": hex::encode(deployer.as_bytes()), + "chain_id": chain_id + })).await?; + let addr_hex = response["contract_address"].as_str().unwrap_or("").to_string(); + let addr_bytes = hex::decode(&addr_hex).map_err(|e| NACError::ContractError(e.to_string()))?; + { let mut a = [0u8; 32]; let l = addr_bytes.len().min(32); a[..l].copy_from_slice(&addr_bytes[..l]); Ok(Address::new(a)) } + } + + // ===== XTZH 稳定币 ===== + + /// 铸造 XTZH 稳定币 + pub async fn mint_xtzh(&self, amount: Decimal, collateral_proof: &CollateralProof, minter: &Address, chain_id: u32) -> Result { + let response = self.call("xtzh_mint", serde_json::json!({ + "amount": amount, + "collateral_type": format!("{:?}", collateral_proof.collateral_type), + "collateral_amount": collateral_proof.collateral_amount, + "minter": hex::encode(minter.as_bytes()), + "chain_id": chain_id + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).map_err(|e| NACError::NetworkError(e.to_string()))?; + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 查询 XTZH 余额 + pub async fn balance_of_xtzh(&self, owner: &Address, chain_id: u32) -> Result { + let response = self.call("xtzh_balanceOf", serde_json::json!({ + "holder": hex::encode(owner.as_bytes()), + "chain_id": chain_id + })).await?; + Ok(response["balance"].as_u64().unwrap_or(0) as u128) + } + + /// 获取 SDR 汇率 + pub async fn get_sdr_rate(&self, chain_id: u32) -> Result { + let response = self.call("xtzh_getSdrRate", serde_json::json!({ + "chain_id": chain_id + })).await?; + Ok(response["rate"].as_u64().unwrap_or(1) as u128) + } + + /// 预测 SDR 汇率 + pub async fn predict_sdr_rate(&self, _horizon: std::time::Duration) -> Result { + let response = self.call("xtzh_predictSdrRate", serde_json::json!({})).await?; + Ok(SDRForecast { + predicted_rate: response["rate"].as_f64().unwrap_or(1.0), + confidence: response["confidence"].as_f64().unwrap_or(0.9), + horizon_days: 30, + }) + } + + /// 优化储备 + pub async fn optimize_reserves(&self, current_reserves: &Reserves) -> Result { + let response = self.call("xtzh_optimizeReserves", serde_json::json!({ + "total_usd": current_reserves.total_usd, + "gold_oz": current_reserves.gold_oz + })).await?; + Ok(ReserveStrategy { + target_ratio: response["target_ratio"].as_f64().unwrap_or(0.3), + rebalance_threshold: response["rebalance_threshold"].as_f64().unwrap_or(0.05), + }) + } + + /// 管理流动性 + pub async fn manage_liquidity(&self, current_liquidity: &LiquidityState) -> Result { + let response = self.call("xtzh_manageLiquidity", serde_json::json!({ + "available": current_liquidity.available, + "locked": current_liquidity.locked + })).await?; + Ok(LiquidityStrategy { + min_ratio: response["min_ratio"].as_f64().unwrap_or(0.2), + target_ratio: response["target_ratio"].as_f64().unwrap_or(0.3), + }) + } + + // ===== 跨分片交易 ===== + + /// 提交跨分片交易 + pub async fn submit_cross_shard_tx(&self, tx: &SignedTransaction, target_shard: u32, chain_id: u32) -> Result { + let tx_bytes = serde_json::to_vec(tx).unwrap_or_default(); + let response = self.call("cbpp_submitCrossShardTx", serde_json::json!({ + "tx": hex::encode(&tx_bytes), + "target_shard": target_shard, + "chain_id": chain_id + })).await?; + let status_str = response["status"].as_str().unwrap_or("pending"); + Ok(match status_str { + "locked" => CrossShardStatus::Locked, + "committed" => CrossShardStatus::Committed, + "aborted" => CrossShardStatus::Aborted, + _ => CrossShardStatus::Pending, + }) + } + + /// 获取跨分片状态 + pub async fn get_cross_shard_status(&self, tx_hash: &Hash, chain_id: u32) -> Result { + let response = self.call("cbpp_getCrossShardStatus", serde_json::json!({ + "tx_hash": hex::encode(tx_hash.as_bytes()), + "chain_id": chain_id + })).await?; + let status_str2 = response["status"].as_str().unwrap_or("pending"); + Ok(match status_str2 { + "locked" => CrossShardStatus::Locked, + "committed" => CrossShardStatus::Committed, + "aborted" => CrossShardStatus::Aborted, + _ => CrossShardStatus::Pending, + }) + } + // ===== 宪政层方法 ===== + + /// 检查宪政合规性 + pub async fn check_compliance(&self, tx: &Transaction) -> Result { + let tx_bytes = serde_json::to_vec(tx).unwrap_or_default(); + let response = self.call("constitutional_checkCompliance", serde_json::json!({ + "tx": hex::encode(&tx_bytes) + })).await?; + Ok(ComplianceResult { + passed: response["passed"].as_bool().unwrap_or(true), + score: response["score"].as_f64().unwrap_or(1.0), + issues: response["issues"].as_array() + .map(|a| a.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()) + .unwrap_or_default(), + }) + } + + /// 提出宪法修正案 + pub async fn propose_amendment(&self, amendment: &Amendment, _proposer: &Address) -> Result { + let response = self.call("constitutional_proposeAmendment", serde_json::json!({ + "title": amendment.title, + "content": amendment.content, + "proposer": hex::encode(&amendment.proposer) + })).await?; + Ok(response["proposal_id"].as_u64().unwrap_or(0)) + } + + /// 对修正案投票 + pub async fn vote_on_amendment(&self, proposal_id: u64, vote: Vote, _voter: &Address) -> Result { + let response = self.call("constitutional_voteOnAmendment", serde_json::json!({ + "proposal_id": proposal_id, + "approve": vote.approve, + "voter": hex::encode(&vote.voter) + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).unwrap_or_default(); + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 查询修正案状态 + pub async fn get_amendment_status(&self, proposal_id: u64) -> Result { + let response = self.call("constitutional_getAmendmentStatus", serde_json::json!({ + "proposal_id": proposal_id + })).await?; + let status = response["status"].as_str().unwrap_or("proposed"); + Ok(match status { + "approved" => AmendmentStatus::Approved, + "rejected" => AmendmentStatus::Rejected, + "voting" => AmendmentStatus::Voting, + _ => AmendmentStatus::Proposed, + }) + } + + // ===== 治理层方法 ===== + + /// 创建治理提案 + pub async fn create_proposal(&self, proposal: &Proposal, _proposer: &Address) -> Result { + let response = self.call("governance_createProposal", serde_json::json!({ + "title": proposal.title, + "proposer": hex::encode(&proposal.proposer), + "status": proposal.status + })).await?; + Ok(response["proposal_id"].as_u64().unwrap_or(0)) + } + + /// 对提案投票 + pub async fn vote_on_proposal(&self, proposal_id: u64, vote: Vote, _voter: &Address) -> Result { + let response = self.call("governance_voteOnProposal", serde_json::json!({ + "proposal_id": proposal_id, + "approve": vote.approve, + "voter": hex::encode(&vote.voter) + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).unwrap_or_default(); + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 执行通过的提案 + pub async fn execute_proposal(&self, proposal_id: u64, executor: &Address) -> Result { + let response = self.call("governance_executeProposal", serde_json::json!({ + "proposal_id": proposal_id, + "executor": hex::encode(executor.as_bytes()) + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).unwrap_or_default(); + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 查询提案详情 + pub async fn get_proposal(&self, proposal_id: u64) -> Result { + let response = self.call("governance_getProposal", serde_json::json!({ + "proposal_id": proposal_id + })).await?; + Ok(ProposalDetails { + proposal: Proposal { + id: proposal_id, + title: response["title"].as_str().unwrap_or("").to_string(), + proposer: [0u8; 32], + status: response["status"].as_str().unwrap_or("pending").to_string(), + }, + votes_for: response["votes_for"].as_u64().unwrap_or(0), + votes_against: response["votes_against"].as_u64().unwrap_or(0), + description: response["description"].as_str().unwrap_or("").to_string(), + }) + } + + /// 查询投票权重 + pub async fn get_voting_power(&self, voter: &Address) -> Result { + let response = self.call("governance_getVotingPower", serde_json::json!({ + "voter": hex::encode(voter.as_bytes()) + })).await?; + Ok(response["voting_power"].as_u64().unwrap_or(0) as u128) + } + + // ===== AI 合规层方法 ===== + + /// AI 合规验证 + pub async fn verify_compliance(&self, data: &ComplianceData) -> Result { + let response = self.call("ai_verifyCompliance", serde_json::json!({ + "asset_id": data.asset_id, + "jurisdiction": data.jurisdiction, + "compliance_type": data.compliance_type, + "data": hex::encode(&data.data) + })).await?; + Ok(ComplianceResult { + passed: response["passed"].as_bool().unwrap_or(true), + score: response["score"].as_f64().unwrap_or(1.0), + issues: response["issues"].as_array() + .map(|a| a.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()) + .unwrap_or_default(), + }) + } + + /// 生成零知识证明 + pub async fn generate_zk_proof(&self, result: &ComplianceResult) -> Result { + let response = self.call("ai_generateZKProof", serde_json::json!({ + "passed": result.passed, + "score": result.score + })).await?; + Ok(ZKProof { + proof_type: response["proof_type"].as_str().unwrap_or("groth16").to_string(), + proof_data: hex::decode(response["proof_data"].as_str().unwrap_or("")).unwrap_or_default(), + public_inputs: hex::decode(response["public_inputs"].as_str().unwrap_or("")).unwrap_or_default(), + }) + } + + /// 生成合规报告 + pub async fn generate_compliance_report(&self, results: &[ComplianceResult]) -> Result { + let passed = results.iter().filter(|r| r.passed).count(); + let response = self.call("ai_generateComplianceReport", serde_json::json!({ + "result_count": results.len(), + "passed_count": passed + })).await?; + Ok(ComplianceReport { + asset_id: response["asset_id"].as_str().unwrap_or("").to_string(), + result: results.first().cloned().unwrap_or(ComplianceResult { + passed: passed == results.len(), + score: 1.0, + issues: vec![], + }), + timestamp: response["timestamp"].as_u64().unwrap_or(0), + }) + } + + // ===== AI 估值层方法 ===== + + /// 评估资产价值 + pub async fn appraise_asset(&self, asset: &Asset, jurisdiction: Jurisdiction, _agreement: InternationalAgreement) -> Result { + let response = self.call("ai_appraiseAsset", serde_json::json!({ + "asset_id": asset.id, + "gnacs_code": asset.gnacs_code, + "jurisdiction": jurisdiction.code + })).await?; + Ok(ValuationResult { + asset_id: asset.id.clone(), + value_usd: response["value_usd"].as_u64().unwrap_or(0) as u128, + confidence: response["confidence"].as_f64().unwrap_or(0.95), + timestamp: response["timestamp"].as_u64().unwrap_or(0), + }) + } + + /// 获取市场数据 + pub async fn get_market_data(&self, asset_type: &str) -> Result { + let response = self.call("ai_getMarketData", serde_json::json!({ + "asset_type": asset_type + })).await?; + Ok(MarketData { + symbol: asset_type.to_string(), + price_usd: response["price_usd"].as_f64().unwrap_or(0.0), + volume_24h: response["volume_24h"].as_f64().unwrap_or(0.0), + timestamp: response["timestamp"].as_u64().unwrap_or(0), + }) + } + + /// 批量估值 + pub async fn batch_appraise(&self, assets: &[Asset]) -> Result> { + let _response = self.call("ai_batchAppraise", serde_json::json!({ + "asset_count": assets.len() + })).await?; + Ok(assets.iter().map(|a| ValuationResult { + asset_id: a.id.clone(), + value_usd: a.value_usd, + confidence: 0.95, + timestamp: 0, + }).collect()) + } + + // ===== AI 风控层方法 ===== + + /// 评估交易风险 + pub async fn assess_transaction_risk(&self, tx: &Transaction) -> Result { + let response = self.call("ai_assessTransactionRisk", serde_json::json!({ + "tx_hash": hex::encode(&tx.hash), + "amount": tx.amount + })).await?; + Ok(RiskScore { + score: response["score"].as_f64().unwrap_or(0.0), + level: response["level"].as_str().unwrap_or("low").to_string(), + factors: response["factors"].as_array() + .map(|a| a.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()) + .unwrap_or_default(), + }) + } + + /// 检测异常行为 + pub async fn detect_anomaly(&self, behavior: &UserBehavior) -> Result { + let response = self.call("ai_detectAnomaly", serde_json::json!({ + "address": hex::encode(&behavior.address), + "action": behavior.action + })).await?; + Ok(AnomalyReport { + address: behavior.address, + anomaly_type: response["anomaly_type"].as_str().unwrap_or("none").to_string(), + severity: response["severity"].as_f64().unwrap_or(0.0), + timestamp: response["timestamp"].as_u64().unwrap_or(0), + }) + } + + /// 生成风险报告 + pub async fn generate_risk_report(&self, address: &Address, _period: std::time::Duration) -> Result { + let response = self.call("ai_generateRiskReport", serde_json::json!({ + "address": hex::encode(address.as_bytes()) + })).await?; + Ok(RiskReport { + asset_id: hex::encode(address.as_bytes()), + risk_score: RiskScore { + score: response["overall_risk"].as_f64().unwrap_or(0.0), + level: response["level"].as_str().unwrap_or("low").to_string(), + factors: vec![], + }, + timestamp: response["timestamp"].as_u64().unwrap_or(0), + }) + } + + // ===== 钱包方法 ===== + + /// 创建钱包 + pub async fn create_wallet(&self, _password: &str) -> Result { + let response = self.call("wallet_create", serde_json::json!({})).await?; + let addr_bytes = hex::decode(response["address"].as_str().unwrap_or("")).unwrap_or_default(); + let mut addr_arr = [0u8; 32]; + let alen = addr_bytes.len().min(32); + addr_arr[..alen].copy_from_slice(&addr_bytes[..alen]); + Ok(Wallet { + address: addr_arr, + balance: 0, + }) + } + + /// 导入钱包 + pub async fn import_wallet(&self, mnemonic: &str, _password: &str) -> Result { + let response = self.call("wallet_import", serde_json::json!({ + "mnemonic": mnemonic + })).await?; + let addr_bytes = hex::decode(response["address"].as_str().unwrap_or("")).unwrap_or_default(); + let mut addr_arr = [0u8; 32]; + let alen = addr_bytes.len().min(32); + addr_arr[..alen].copy_from_slice(&addr_bytes[..alen]); + Ok(Wallet { + address: addr_arr, + balance: 0, + }) + } + + /// 发送交易 + pub async fn send_transaction(&self, from: &Address, to: &Address, amount: Decimal, _asset: Option<&Address>) -> Result { + let response = self.call("wallet_sendTransaction", serde_json::json!({ + "from": hex::encode(from.as_bytes()), + "to": hex::encode(to.as_bytes()), + "amount": amount + })).await?; + let hash_hex = response["tx_hash"].as_str().unwrap_or("").to_string(); + let hash_bytes = hex::decode(&hash_hex).unwrap_or_default(); + let mut hash_arr = [0u8; 48]; + let hlen = hash_bytes.len().min(48); + hash_arr[..hlen].copy_from_slice(&hash_bytes[..hlen]); + Ok(Hash::new(hash_arr)) + } + + /// 获取余额 + pub async fn get_balance(&self, address: &Address) -> Result { + let response = self.call("wallet_getBalance", serde_json::json!({ + "address": hex::encode(address.as_bytes()) + })).await?; + Ok(BalanceInfo { + address: *address.as_bytes(), + nac_balance: response["nac_balance"].as_u64().unwrap_or(0) as u128, + xtzh_balance: response["xtzh_balance"].as_u64().unwrap_or(0) as u128, + }) + } + + /// 获取交易历史 + pub async fn get_transaction_history(&self, address: &Address, limit: u32) -> Result> { + let _response = self.call("wallet_getTransactionHistory", serde_json::json!({ + "address": hex::encode(address.as_bytes()), + "limit": limit + })).await?; + Ok(vec![]) + } + + /// 搜索地址 + pub async fn search_address(&self, query: &str) -> Result> { + let _response = self.call("lens_searchAddress", serde_json::json!({ + "query": query + })).await?; + Ok(vec![]) + } + + // ===== 交易所方法 ===== + + /// 上架代币 + pub async fn list_token(&self, token: &Address, _metadata: &TokenMetadata) -> Result { + let response = self.call("exchange_listToken", serde_json::json!({ + "token": hex::encode(token.as_bytes()) + })).await?; + Ok(response["listing_id"].as_u64().unwrap_or(0)) + } + + /// 创建交易对 + pub async fn create_trading_pair(&self, base_token: &Address, quote_token: &Address) -> Result { + let response = self.call("exchange_createTradingPair", serde_json::json!({ + "base_token": hex::encode(base_token.as_bytes()), + "quote_token": hex::encode(quote_token.as_bytes()) + })).await?; + Ok(TradingPair { + base: response["base"].as_str().unwrap_or("NAC").to_string(), + quote: response["quote"].as_str().unwrap_or("XTZH").to_string(), + price: response["price"].as_f64().unwrap_or(0.0), + }) + } + + /// 获取订单簿 + pub async fn get_order_book(&self, pair_id: u64) -> Result { + let response = self.call("exchange_getOrderBook", serde_json::json!({ + "pair_id": pair_id + })).await?; + Ok(OrderBook { + pair: TradingPair { + base: response["base"].as_str().unwrap_or("NAC").to_string(), + quote: response["quote"].as_str().unwrap_or("XTZH").to_string(), + price: response["price"].as_f64().unwrap_or(0.0), + }, + bids: response["bids"].as_array() + .map(|a| a.iter().map(|v| (v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0))).collect()) + .unwrap_or_default(), + asks: response["asks"].as_array() + .map(|a| a.iter().map(|v| (v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0))).collect()) + .unwrap_or_default(), + }) + } + + /// 下单 + pub async fn place_order(&self, pair_id: u64, is_buy: bool, price: Decimal, amount: Decimal, trader: &Address) -> Result { + let response = self.call("exchange_placeOrder", serde_json::json!({ + "pair_id": pair_id, + "is_buy": is_buy, + "price": price, + "amount": amount, + "trader": hex::encode(trader.as_bytes()) + })).await?; + Ok(response["order_id"].as_u64().unwrap_or(0)) + } + + /// 取消订单 + pub async fn cancel_order(&self, order_id: u64, trader: &Address) -> Result<()> { + self.call("exchange_cancelOrder", serde_json::json!({ + "order_id": order_id, + "trader": hex::encode(trader.as_bytes()) + })).await?; + Ok(()) + } + +} +/// NRPC4Client 类型别名(向后兼容) +pub type NRPC4Client = NacLensClient; +/// NRPC3Client 类型别名(向后兼容,已更名为 NAC Lens) +pub type NRPC3Client = NacLensClient; + +/// Decimal 类型(代币数量,精度由协议层处理) +/// 使用 u128 表示,最小单位为 1e-18 +pub type Decimal = u128; +pub type ListingId = u64; + + +/// 账户状态 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct AccountState { + pub address: [u8; 32], + pub balance: u128, + pub nonce: u64, + pub code_hash: Option>, +} + +/// 司法辖区 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Jurisdiction { + pub code: String, + pub name: String, + pub region: String, +} + +/// CSNPNetwork 存根(CSNP 网络,NAC 原生网络协议) +#[derive(Debug, Clone)] +pub struct CSNPNetwork { + pub peers: Vec, +} + +impl CSNPNetwork { + pub async fn new(peers: &[String]) -> std::result::Result { + Ok(Self { + peers: peers.to_vec(), + }) + } + + /// 广播交易到网络 + pub async fn broadcast_transaction(&self, _tx: &SignedTransaction) -> crate::error::Result<()> { + // CSNP 网络广播交易(存根实现) + Ok(()) + } + + /// 广播区块到网络 + pub async fn broadcast_block(&self, _block: &Block) -> crate::error::Result<()> { + // CSNP 网络广播区块(存根实现) + Ok(()) + } + + /// 同步区块 + pub async fn sync_blocks(&self, _from_height: u64, _to_height: u64) -> crate::error::Result> { + // CSNP 网络同步区块(存根实现) + Ok(vec![]) + } + + /// 获取网络节点列表 + pub async fn get_peers(&self) -> crate::error::Result> { + Ok(self.peers.iter().map(|addr| PeerInfo { + node_id: addr.clone(), + address: addr.clone(), + status: "active".to_string(), + }).collect()) + } + + /// 连接到节点 + pub async fn connect_to_peer(&self, _peer_addr: &str) -> crate::error::Result<()> { + // CSNP 网络连接节点(存根实现) + Ok(()) + } +} diff --git a/nac-sdk/src/client/mod.rs b/nac-sdk/src/client/mod.rs index 0aebb0b..c70bace 100644 --- a/nac-sdk/src/client/mod.rs +++ b/nac-sdk/src/client/mod.rs @@ -4,7 +4,7 @@ NAC SDK 的客户端模块,提供 NAC Lens 协议客户端。 ## 核心组件 -- NacLensClient - NAC Lens 协议 RPC 客户端(原 NRPC4.0,工单 #042 更名) +- NacLensClient - NAC Lens 协议 RPC 客户端(原 NAC Lens,工单 #042 更名) ## 版本历史 - v1.x: NRPC3.0 客户端(已归档至 _archive/v1_legacy_nrpc3/) diff --git a/nac-sdk/src/error/mod.rs b/nac-sdk/src/error/mod.rs index 0ac395d..89a2f02 100644 --- a/nac-sdk/src/error/mod.rs +++ b/nac-sdk/src/error/mod.rs @@ -130,6 +130,30 @@ pub enum NACError { /// 其他错误 #[error("Other error: {0}")] Other(String), + /// 合约错误 + #[error("Contract error: {0}")] + ContractError(String), + /// 验证错误 + #[error("Validation error: {0}")] + ValidationError(String), + /// 未找到错误 + #[error("Not found: {0}")] + NotFound(String), + /// 配置错误 + #[error("Configuration error: {0}")] + ConfigError(String), + /// 钱包错误 + #[error("Wallet error: {0}")] + WalletError(String), + /// 区块链错误 + #[error("Blockchain error: {0}")] + BlockchainError(String), + /// 存储错误 + #[error("Storage error: {0}")] + StorageError(String), + /// AI服务错误 + #[error("AI service error: {0}")] + AIServiceError(String), } /// NAC SDK Result类型别名 diff --git a/nac-sdk/src/genesis_config.rs b/nac-sdk/src/genesis_config.rs new file mode 100644 index 0000000..a585754 --- /dev/null +++ b/nac-sdk/src/genesis_config.rs @@ -0,0 +1,144 @@ +//! NAC 公链创世配置 +//! +//! 定义 NAC 公链的核心参数,包括代币发行总量、区块参数等。 +//! +//! # NAC 代币经济模型 +//! - $NAC 原生代币发行总量:10 亿枚(1,000,000,000),固定总量,永不增发 +//! - XTZH 稳定币:锚定 SDR + 黄金储备,按需发行 +//! - XIC 治理代币:已在 BSC 发行(BEP-20),通过跨链桥与 NAC 主网互通 + +/// NAC 公链创世配置 +pub struct GenesisConfig { + /// 链 ID(NAC 主网:0x4E4143 = "NAC" ASCII) + pub chain_id: u64, + /// 链名称 + pub chain_name: &'static str, + /// 链符号 + pub chain_symbol: &'static str, +} + +/// NAC 原生代币配置 +pub struct NacTokenConfig { + /// 代币名称 + pub name: &'static str, + /// 代币符号 + pub symbol: &'static str, + /// 精度(小数位数) + pub decimals: u8, + /// 发行总量(固定,永不增发) + pub total_supply: u64, + /// 发行总量(带精度的完整表示,18位小数) + pub total_supply_wei: &'static str, +} + +/// XTZH 稳定币配置 +pub struct XtzhConfig { + /// 代币名称 + pub name: &'static str, + /// 代币符号 + pub symbol: &'static str, + /// 精度 + pub decimals: u8, + /// 锚定机制:SDR + 黄金储备 + pub peg_mechanism: &'static str, +} + +/// XIC 治理代币配置 +pub struct XicConfig { + /// 代币名称 + pub name: &'static str, + /// 代币符号 + pub symbol: &'static str, + /// BSC 合约地址(BEP-20) + pub bsc_contract: &'static str, + /// 跨链桥锚定机制:1:1 永久锚定 + pub bridge_mechanism: &'static str, +} + +/// NAC 主网创世配置(单例) +pub const MAINNET_GENESIS: GenesisConfig = GenesisConfig { + chain_id: 0x4E4143, // "NAC" in ASCII + chain_name: "New Asset Chain Mainnet", + chain_symbol: "NAC", +}; + +/// $NAC 原生代币配置 +/// 发行总量:10 亿枚,固定总量,永不增发 +pub const NAC_TOKEN: NacTokenConfig = NacTokenConfig { + name: "NAC Token", + symbol: "NAC", + decimals: 18, + total_supply: 1_000_000_000, // 10 亿枚,固定总量,永不增发 + total_supply_wei: "1000000000000000000000000000", // 1e27 (10亿 × 10^18) +}; + +/// XTZH 稳定币配置 +pub const XTZH_TOKEN: XtzhConfig = XtzhConfig { + name: "XTZH Stable Token", + symbol: "XTZH", + decimals: 18, + peg_mechanism: "SDR + Gold Reserve (黄金储备锚定 SDR 模型)", +}; + +/// XIC 治理代币配置 +pub const XIC_TOKEN: XicConfig = XicConfig { + name: "XIC Governance Token", + symbol: "XIC", + bsc_contract: "0x59ff34dd59680a7125782b1f6df2a86ed46f5a24", + bridge_mechanism: "BSC-XIC to NAC-XIC 1:1 永久锚定(5/7 多签验证)", +}; + +/// CBPP 区块参数 +pub struct CbppParams { + /// 空块最小大小(字节) + pub min_block_size_bytes: u64, + /// 空块最小大小(KB) + pub min_block_size_kb: u64, + /// 出块间隔(秒,每节点) + pub block_interval_per_node_secs: u64, + /// 共识协议 + pub consensus: &'static str, + /// 网络协议 + pub network: &'static str, + /// 虚拟机 + pub vm: &'static str, + /// 数据透镜协议 + pub lens: &'static str, +} + +/// CBPP 主网参数 +pub const CBPP_MAINNET: CbppParams = CbppParams { + min_block_size_bytes: 10240, // 10 KB + min_block_size_kb: 10, + block_interval_per_node_secs: 60, + consensus: "CBPP (Constitutional Block Production Protocol)", + network: "CSNP (Constitutional Secure Network Protocol)", + vm: "NVM (NAC Virtual Machine)", + lens: "NAC Lens (NAC Chain Data Lens)", +}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_nac_token_total_supply() { + // $NAC 发行总量:10 亿枚,固定总量,永不增发 + assert_eq!(NAC_TOKEN.total_supply, 1_000_000_000); + assert_eq!(NAC_TOKEN.symbol, "NAC"); + assert_eq!(NAC_TOKEN.decimals, 18); + } + + #[test] + fn test_chain_id() { + // NAC 主网链 ID:0x4E4143("NAC" ASCII) + assert_eq!(MAINNET_GENESIS.chain_id, 0x4E4143); + } + + #[test] + fn test_cbpp_block_params() { + // 空块最小 10KB + assert_eq!(CBPP_MAINNET.min_block_size_kb, 10); + assert_eq!(CBPP_MAINNET.min_block_size_bytes, 10240); + } +} diff --git a/nac-sdk/src/lib.rs b/nac-sdk/src/lib.rs index d975cab..d0d65bc 100644 --- a/nac-sdk/src/lib.rs +++ b/nac-sdk/src/lib.rs @@ -33,7 +33,7 @@ pub mod adapters; // pub mod advanced; // Phase 10高级功能,待与NRPC3Client集成 // 重新导出常用类型和函数 -pub use client::NRPC3Client; +// pub use client::NRPC3Client; // NAC Lens 客户端通过 client 模块重新导出 pub use crypto::{Blake3Hasher, AssetDNA, GNACSEncoder}; pub use protocols::ACC20; // 待实现的协议(将在Phase 7完成) @@ -65,4 +65,6 @@ mod tests { } // 导出适配器模块 -pub mod adapters; + +/// NAC 公链创世配置(代币发行、区块参数) +pub mod genesis_config; diff --git a/nac-sdk/src/protocols/acc1155.rs b/nac-sdk/src/protocols/acc1155.rs index faec830..5a591f2 100644 --- a/nac-sdk/src/protocols/acc1155.rs +++ b/nac-sdk/src/protocols/acc1155.rs @@ -2,16 +2,17 @@ //! //! 提供与NAC区块链上ACC-1155证书交互的客户端接口 -use crate::client::NRPC3Client; +// NRPC3Client 已更名为 NAC Lens 客户端 use crate::error::{NACError, Result}; +use crate::adapters::NRPC3Client; use nac_udm::primitives::{Address, Hash, Timestamp}; use nac_udm::l1_protocol::gnacs::GNACSCode; use nac_udm::l1_protocol::acc::acc1155::{ TokenId, TokenType, TokenTypeDNA, TokenTypeMetadata, BatchTransfer, BatchMint, BatchBurn, TokenCustodyInfo, TokenInsuranceInfo, - TokenTypeValuation, ApprovalInfo, TokenBalance, HybridAssetPool, TokenTypeConfig, + TokenTypeValuation, }; -use nac_udm::l2_governance::SovereigntyRight; +use nac_udm::l2_governance::sovereignty::SovereigntyRight; use serde_json::json; /// ACC-1155多代币证书接口 diff --git a/nac-sdk/src/protocols/acc20.rs b/nac-sdk/src/protocols/acc20.rs index b78427a..643db68 100644 --- a/nac-sdk/src/protocols/acc20.rs +++ b/nac-sdk/src/protocols/acc20.rs @@ -24,8 +24,9 @@ ACC-20可替代代币协议接口,完全替代以太坊的ERC-20。 */ use crate::error::{NACError, Result}; +use crate::adapters::NRPC3Client; use nac_udm::primitives::{Address, Hash, Timestamp}; -use crate::client::NRPC3Client; +// NRPC3Client 已更名为 NAC Lens 客户端 use serde::{Deserialize, Serialize}; /// ACC-20代币信息 diff --git a/nac-sdk/src/protocols/acc20c.rs b/nac-sdk/src/protocols/acc20c.rs index cdbc2b9..69d0b76 100644 --- a/nac-sdk/src/protocols/acc20c.rs +++ b/nac-sdk/src/protocols/acc20c.rs @@ -2,8 +2,9 @@ //! //! 提供与NAC区块链上ACC-20C兼容层交互的客户端接口 -use crate::client::NRPC3Client; +// NRPC3Client 已更名为 NAC Lens 客户端 use crate::error::{NACError, Result}; +use crate::adapters::NRPC3Client; use nac_udm::primitives::{Address, Hash, Timestamp}; use nac_udm::l1_protocol::gnacs::GNACSCode; use nac_udm::l1_protocol::acc20c::{ diff --git a/nac-sdk/src/protocols/acc721.rs b/nac-sdk/src/protocols/acc721.rs index 479a344..ae43802 100644 --- a/nac-sdk/src/protocols/acc721.rs +++ b/nac-sdk/src/protocols/acc721.rs @@ -2,16 +2,17 @@ //! //! 提供与NAC区块链上ACC-721证书交互的客户端接口 -use crate::client::NRPC3Client; +// NRPC3Client 已更名为 NAC Lens 客户端 use crate::error::{NACError, Result}; +use crate::adapters::NRPC3Client; use crate::types::*; use nac_udm::primitives::{Address, Hash, Timestamp}; use nac_udm::l1_protocol::gnacs::GNACSCode; use nac_udm::l1_protocol::acc::acc721::{ AssetId, AssetDNA, AssetValuation, - CustodyInfo, InsuranceInfo, CollateralInfo, ACC721FragmentationPool, + CustodyInfo, InsuranceInfo, ACC721FragmentationPool, }; -use nac_udm::l2_governance::SovereigntyRight; +use nac_udm::l2_governance::sovereignty::SovereigntyRight; use serde_json::json; /// ACC-721唯一资产证书接口 diff --git a/nac-sdk/src/types/mod.rs b/nac-sdk/src/types/mod.rs index a322914..a71417e 100644 --- a/nac-sdk/src/types/mod.rs +++ b/nac-sdk/src/types/mod.rs @@ -299,3 +299,29 @@ mod tests { assert_eq!(coords.branch, 0); } } + +/// 自定义 serde 支持 [u8; 48] 的序列化/反序列化 +mod hex_serde_48 { + use serde::{Deserializer, Serializer, Deserialize}; + + pub fn serialize(bytes: &[u8; 48], serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&hex::encode(bytes)) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 48], D::Error> + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + let bytes = hex::decode(&s).map_err(serde::de::Error::custom)?; + if bytes.len() != 48 { + return Err(serde::de::Error::custom(format!("Expected 48 bytes, got {}", bytes.len()))); + } + let mut arr = [0u8; 48]; + arr.copy_from_slice(&bytes); + Ok(arr) + } +} diff --git a/nac-udm/src/l1_protocol/layer_router.rs b/nac-udm/src/l1_protocol/layer_router.rs index 1ab48fc..911678b 100644 --- a/nac-udm/src/l1_protocol/layer_router.rs +++ b/nac-udm/src/l1_protocol/layer_router.rs @@ -437,8 +437,8 @@ mod tests { #[test] fn test_layer_message_creation() { - let sender = Address::from_slice(&[1u8; 20]).unwrap(); - let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); + let receiver = Address::from_slice(&[2u8; 32]).unwrap(); let message = LayerMessage::new( LayerMessageType::Request, @@ -476,7 +476,7 @@ mod tests { #[test] fn test_message_queue() { let mut queue = LayerMessageQueue::new(); - let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); // 添加低优先级消息 let message1 = LayerMessage::new( @@ -512,8 +512,8 @@ mod tests { #[test] fn test_layer_router_send() { let mut router = LayerRouter::new(Layer::L1); - let sender = Address::from_slice(&[1u8; 20]).unwrap(); - let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); + let receiver = Address::from_slice(&[2u8; 32]).unwrap(); let result = router.send_message( LayerMessageType::Request, @@ -533,8 +533,8 @@ mod tests { #[test] fn test_layer_router_receive() { let mut router = LayerRouter::new(Layer::L2); - let sender = Address::from_slice(&[1u8; 20]).unwrap(); - let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); + let receiver = Address::from_slice(&[2u8; 32]).unwrap(); // 创建从L1发往L2的消息 let message = LayerMessage::new( @@ -557,8 +557,8 @@ mod tests { #[test] fn test_layer_router_forward() { let mut router = LayerRouter::new(Layer::L1); - let sender = Address::from_slice(&[1u8; 20]).unwrap(); - let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); + let receiver = Address::from_slice(&[2u8; 32]).unwrap(); // 创建从L0发往L2的消息(需要经过L1转发) let message = LayerMessage::new( @@ -594,8 +594,8 @@ mod tests { #[test] fn test_process_messages() { let mut router = LayerRouter::new(Layer::L1); - let sender = Address::from_slice(&[1u8; 20]).unwrap(); - let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + let sender = Address::from_slice(&[1u8; 32]).unwrap(); + let receiver = Address::from_slice(&[2u8; 32]).unwrap(); // 发送2条消息 router.send_message( diff --git a/nac-udm/src/l1_protocol/layer_router.rs.bak.20260227 b/nac-udm/src/l1_protocol/layer_router.rs.bak.20260227 new file mode 100644 index 0000000..1ab48fc --- /dev/null +++ b/nac-udm/src/l1_protocol/layer_router.rs.bak.20260227 @@ -0,0 +1,626 @@ +///! NAC层间路由器 +///! +///! 管理L0-L1-L2-L3层间的通信和路由 +///! +///! **NAC四层架构**: +///! - L0: 基础层(DAG + CBPP共识 + OPN) +///! - L1: 协议层(NVM + ACC + GNACS + 碎片化) +///! - L2: 宪法层(宪法收据 + CEE + 合规验证) +///! - L3: 应用层(业务应用 + UI + API) + +use crate::primitives::{Address, Hash}; +use std::collections::{HashMap, VecDeque}; +use serde::{Deserialize, Serialize}; + +/// NAC层级 +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +/// Layer +pub enum Layer { + /// L0: 基础层 + L0, + /// L1: 协议层 + L1, + /// L2: 宪法层 + L2, + /// L3: 应用层 + L3, +} + +impl Layer { + /// 获取层级编号 + pub fn level(&self) -> u8 { + match self { + Layer::L0 => 0, + Layer::L1 => 1, + Layer::L2 => 2, + Layer::L3 => 3, + } + } + + /// 从层级编号创建 + pub fn from_level(level: u8) -> Option { + match level { + 0 => Some(Layer::L0), + 1 => Some(Layer::L1), + 2 => Some(Layer::L2), + 3 => Some(Layer::L3), + _ => None, + } + } + + /// 是否可以直接通信 + pub fn can_communicate_with(&self, other: &Layer) -> bool { + // 相邻层可以直接通信 + let diff = (self.level() as i8 - other.level() as i8).abs(); + diff <= 1 + } +} + +/// 层间消息类型 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +/// LayerMessageType +pub enum LayerMessageType { + /// 请求 + Request, + /// 响应 + Response, + /// 通知 + Notification, + /// 事件 + Event, +} + +/// 层间消息 +#[derive(Debug, Clone, Serialize, Deserialize)] +/// LayerMessage +pub struct LayerMessage { + /// 消息ID + pub message_id: Hash, + /// 消息类型 + pub message_type: LayerMessageType, + /// 源层 + pub source_layer: Layer, + /// 目标层 + pub target_layer: Layer, + /// 发送者地址 + pub sender: Address, + /// 接收者地址(None表示广播) + pub receiver: Option
, + /// 消息负载 + pub payload: Vec, + /// 时间戳 + pub timestamp: u64, + /// 优先级(0-255,数字越大优先级越高) + pub priority: u8, + /// 路由路径(经过的层) + pub route_path: Vec, +} + +impl LayerMessage { + /// 创建新的层间消息 + pub fn new( + message_type: LayerMessageType, + source_layer: Layer, + target_layer: Layer, + sender: Address, + receiver: Option
, + payload: Vec, + timestamp: u64, + priority: u8, + ) -> Self { + // 计算消息ID + let mut data = Vec::new(); + data.push(source_layer.level()); + data.push(target_layer.level()); + data.extend_from_slice(sender.as_bytes()); + if let Some(ref r) = receiver { + data.extend_from_slice(r.as_bytes()); + } + data.extend_from_slice(&payload); + data.extend_from_slice(×tamp.to_le_bytes()); + + let message_id = Hash::sha3_384(&data); + + Self { + message_id, + message_type, + source_layer, + target_layer, + sender, + receiver, + payload, + timestamp, + priority, + route_path: vec![source_layer], + } + } + + /// 添加路由路径 + pub fn add_to_route(&mut self, layer: Layer) { + self.route_path.push(layer); + } + + /// 是否到达目标层 + pub fn has_reached_target(&self) -> bool { + self.route_path.last() == Some(&self.target_layer) + } +} + +/// 层间路由表 +struct RoutingTable { + /// 路由规则(source_layer, target_layer) => next_layer + routes: HashMap<(Layer, Layer), Layer>, +} + +impl RoutingTable { + /// 创建新的路由表 + fn new() -> Self { + let mut routes = HashMap::new(); + + // 初始化默认路由规则 + // L0 <-> L1 直接通信 + routes.insert((Layer::L0, Layer::L1), Layer::L1); + routes.insert((Layer::L1, Layer::L0), Layer::L0); + + // L1 <-> L2 直接通信 + routes.insert((Layer::L1, Layer::L2), Layer::L2); + routes.insert((Layer::L2, Layer::L1), Layer::L1); + + // L2 <-> L3 直接通信 + routes.insert((Layer::L2, Layer::L3), Layer::L3); + routes.insert((Layer::L3, Layer::L2), Layer::L2); + + // L0 -> L2 经过 L1 + routes.insert((Layer::L0, Layer::L2), Layer::L1); + + // L0 -> L3 经过 L1 + routes.insert((Layer::L0, Layer::L3), Layer::L1); + + // L1 -> L3 经过 L2 + routes.insert((Layer::L1, Layer::L3), Layer::L2); + + // L3 -> L1 经过 L2 + routes.insert((Layer::L3, Layer::L1), Layer::L2); + + // L3 -> L0 经过 L2 + routes.insert((Layer::L3, Layer::L0), Layer::L2); + + // L2 -> L0 经过 L1 + routes.insert((Layer::L2, Layer::L0), Layer::L1); + + Self { routes } + } + + /// 获取下一跳层级 + fn get_next_hop(&self, current_layer: Layer, target_layer: Layer) -> Option { + if current_layer == target_layer { + return Some(target_layer); + } + + self.routes.get(&(current_layer, target_layer)).copied() + } +} + +/// 层间消息队列 +struct LayerMessageQueue { + /// 消息队列(按优先级排序) + queue: VecDeque, +} + +impl LayerMessageQueue { + /// 创建新的消息队列 + fn new() -> Self { + Self { + queue: VecDeque::new(), + } + } + + /// 添加消息 + fn enqueue(&mut self, message: LayerMessage) { + // 按优先级插入(优先级高的在前) + let pos = self.queue + .iter() + .position(|m| m.priority < message.priority) + .unwrap_or(self.queue.len()); + + self.queue.insert(pos, message); + } + + /// 取出消息 + fn dequeue(&mut self) -> Option { + self.queue.pop_front() + } + + /// 获取队列长度 + fn len(&self) -> usize { + self.queue.len() + } + + /// 是否为空 + #[allow(dead_code)] + fn is_empty(&self) -> bool { + self.queue.is_empty() + } +} + +/// 层间路由器 +pub struct LayerRouter { + /// 当前层级 + current_layer: Layer, + /// 路由表 + routing_table: RoutingTable, + /// 待发送消息队列 + outbound_queue: LayerMessageQueue, + /// 已接收消息队列 + inbound_queue: LayerMessageQueue, + /// 消息处理器(message_type => handler_id) + message_handlers: HashMap>, + /// 统计信息 + stats: RouterStats, +} + +impl LayerRouter { + /// 创建新的层间路由器 + pub fn new(current_layer: Layer) -> Self { + Self { + current_layer, + routing_table: RoutingTable::new(), + outbound_queue: LayerMessageQueue::new(), + inbound_queue: LayerMessageQueue::new(), + message_handlers: HashMap::new(), + stats: RouterStats::default(), + } + } + + /// 发送消息 + pub fn send_message( + &mut self, + message_type: LayerMessageType, + target_layer: Layer, + sender: Address, + receiver: Option
, + payload: Vec, + timestamp: u64, + priority: u8, + ) -> Result { + // 创建消息 + let message = LayerMessage::new( + message_type, + self.current_layer, + target_layer, + sender, + receiver, + payload, + timestamp, + priority, + ); + + let message_id = message.message_id.clone(); + + // 加入发送队列 + self.outbound_queue.enqueue(message); + self.stats.messages_sent += 1; + + Ok(message_id) + } + + /// 接收消息 + pub fn receive_message(&mut self, mut message: LayerMessage) -> Result<(), String> { + // 验证消息是否应该到达当前层 + let next_hop = self.routing_table + .get_next_hop( + *message.route_path.last().unwrap(), + message.target_layer, + ) + .ok_or("No route found")?; + + if next_hop != self.current_layer { + return Err(format!( + "Message should be routed to {:?}, not {:?}", + next_hop, self.current_layer + )); + } + + // 添加到路由路径 + message.add_to_route(self.current_layer); + + // 如果到达目标层,加入接收队列 + if message.has_reached_target() { + self.inbound_queue.enqueue(message); + self.stats.messages_received += 1; + } else { + // 否则继续转发 + self.outbound_queue.enqueue(message); + self.stats.messages_forwarded += 1; + } + + Ok(()) + } + + /// 处理待发送消息 + pub fn process_outbound_messages(&mut self) -> Vec { + let mut processed = Vec::new(); + + while let Some(message) = self.outbound_queue.dequeue() { + processed.push(message); + } + + processed + } + + /// 处理已接收消息 + pub fn process_inbound_messages(&mut self) -> Vec { + let mut processed = Vec::new(); + + while let Some(message) = self.inbound_queue.dequeue() { + processed.push(message); + } + + processed + } + + /// 注册消息处理器 + pub fn register_handler(&mut self, message_type: LayerMessageType, handler_id: String) { + self.message_handlers + .entry(message_type) + .or_insert_with(Vec::new) + .push(handler_id); + } + + /// 获取消息处理器 + pub fn get_handlers(&self, message_type: &LayerMessageType) -> Option<&Vec> { + self.message_handlers.get(message_type) + } + + /// 获取统计信息 + pub fn get_stats(&self) -> &RouterStats { + &self.stats + } + + /// 获取待发送消息数量 + pub fn outbound_count(&self) -> usize { + self.outbound_queue.len() + } + + /// 获取已接收消息数量 + pub fn inbound_count(&self) -> usize { + self.inbound_queue.len() + } +} + +/// 路由器统计信息 +#[derive(Debug, Clone, Default)] +/// RouterStats +pub struct RouterStats { + /// 已发送消息数 + pub messages_sent: u64, + /// 已接收消息数 + pub messages_received: u64, + /// 已转发消息数 + pub messages_forwarded: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_layer_level() { + assert_eq!(Layer::L0.level(), 0); + assert_eq!(Layer::L1.level(), 1); + assert_eq!(Layer::L2.level(), 2); + assert_eq!(Layer::L3.level(), 3); + } + + #[test] + fn test_layer_from_level() { + assert_eq!(Layer::from_level(0), Some(Layer::L0)); + assert_eq!(Layer::from_level(1), Some(Layer::L1)); + assert_eq!(Layer::from_level(2), Some(Layer::L2)); + assert_eq!(Layer::from_level(3), Some(Layer::L3)); + assert_eq!(Layer::from_level(4), None); + } + + #[test] + fn test_layer_communication() { + // 相邻层可以直接通信 + assert!(Layer::L0.can_communicate_with(&Layer::L1)); + assert!(Layer::L1.can_communicate_with(&Layer::L0)); + assert!(Layer::L1.can_communicate_with(&Layer::L2)); + assert!(Layer::L2.can_communicate_with(&Layer::L3)); + + // 非相邻层不能直接通信 + assert!(!Layer::L0.can_communicate_with(&Layer::L2)); + assert!(!Layer::L0.can_communicate_with(&Layer::L3)); + assert!(!Layer::L1.can_communicate_with(&Layer::L3)); + } + + #[test] + fn test_layer_message_creation() { + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + + let message = LayerMessage::new( + LayerMessageType::Request, + Layer::L1, + Layer::L2, + sender, + Some(receiver), + vec![1, 2, 3], + 1000, + 10, + ); + + assert_eq!(message.source_layer, Layer::L1); + assert_eq!(message.target_layer, Layer::L2); + assert_eq!(message.priority, 10); + assert_eq!(message.route_path, vec![Layer::L1]); + assert!(!message.has_reached_target()); + } + + #[test] + fn test_routing_table() { + let table = RoutingTable::new(); + + // 直接通信 + assert_eq!(table.get_next_hop(Layer::L0, Layer::L1), Some(Layer::L1)); + assert_eq!(table.get_next_hop(Layer::L1, Layer::L2), Some(Layer::L2)); + + // 间接通信(L0 -> L2 经过 L1) + assert_eq!(table.get_next_hop(Layer::L0, Layer::L2), Some(Layer::L1)); + + // 间接通信(L0 -> L3 经过 L1) + assert_eq!(table.get_next_hop(Layer::L0, Layer::L3), Some(Layer::L1)); + } + + #[test] + fn test_message_queue() { + let mut queue = LayerMessageQueue::new(); + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + + // 添加低优先级消息 + let message1 = LayerMessage::new( + LayerMessageType::Request, + Layer::L1, + Layer::L2, + sender.clone(), + None, + vec![1], + 1000, + 5, // 低优先级 + ); + queue.enqueue(message1); + + // 添加高优先级消息 + let message2 = LayerMessage::new( + LayerMessageType::Request, + Layer::L1, + Layer::L2, + sender, + None, + vec![2], + 1001, + 10, // 高优先级 + ); + queue.enqueue(message2.clone()); + + // 高优先级消息应该先出队 + let dequeued = queue.dequeue().unwrap(); + assert_eq!(dequeued.message_id, message2.message_id); + } + + #[test] + fn test_layer_router_send() { + let mut router = LayerRouter::new(Layer::L1); + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + + let result = router.send_message( + LayerMessageType::Request, + Layer::L2, + sender, + Some(receiver), + vec![1, 2, 3], + 1000, + 10, + ); + + assert!(result.is_ok()); + assert_eq!(router.outbound_count(), 1); + assert_eq!(router.get_stats().messages_sent, 1); + } + + #[test] + fn test_layer_router_receive() { + let mut router = LayerRouter::new(Layer::L2); + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + + // 创建从L1发往L2的消息 + let message = LayerMessage::new( + LayerMessageType::Request, + Layer::L1, + Layer::L2, + sender, + Some(receiver), + vec![1, 2, 3], + 1000, + 10, + ); + + let result = router.receive_message(message); + assert!(result.is_ok()); + assert_eq!(router.inbound_count(), 1); + assert_eq!(router.get_stats().messages_received, 1); + } + + #[test] + fn test_layer_router_forward() { + let mut router = LayerRouter::new(Layer::L1); + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + + // 创建从L0发往L2的消息(需要经过L1转发) + let message = LayerMessage::new( + LayerMessageType::Request, + Layer::L0, + Layer::L2, + sender, + Some(receiver), + vec![1, 2, 3], + 1000, + 10, + ); + + let result = router.receive_message(message); + assert!(result.is_ok()); + assert_eq!(router.outbound_count(), 1); // 转发到发送队列 + assert_eq!(router.get_stats().messages_forwarded, 1); + } + + #[test] + fn test_message_handler_registration() { + let mut router = LayerRouter::new(Layer::L1); + + router.register_handler(LayerMessageType::Request, "handler1".to_string()); + router.register_handler(LayerMessageType::Request, "handler2".to_string()); + + let handlers = router.get_handlers(&LayerMessageType::Request).unwrap(); + assert_eq!(handlers.len(), 2); + assert!(handlers.contains(&"handler1".to_string())); + assert!(handlers.contains(&"handler2".to_string())); + } + + #[test] + fn test_process_messages() { + let mut router = LayerRouter::new(Layer::L1); + let sender = Address::from_slice(&[1u8; 20]).unwrap(); + let receiver = Address::from_slice(&[2u8; 20]).unwrap(); + + // 发送2条消息 + router.send_message( + LayerMessageType::Request, + Layer::L2, + sender.clone(), + Some(receiver.clone()), + vec![1], + 1000, + 10, + ).unwrap(); + + router.send_message( + LayerMessageType::Request, + Layer::L2, + sender, + Some(receiver), + vec![2], + 1001, + 5, + ).unwrap(); + + // 处理待发送消息 + let processed = router.process_outbound_messages(); + assert_eq!(processed.len(), 2); + assert_eq!(router.outbound_count(), 0); + } +} diff --git a/nac-udm/src/l1_protocol/state_shard_optimization.rs b/nac-udm/src/l1_protocol/state_shard_optimization.rs index 8159a6f..8674816 100644 --- a/nac-udm/src/l1_protocol/state_shard_optimization.rs +++ b/nac-udm/src/l1_protocol/state_shard_optimization.rs @@ -490,7 +490,7 @@ mod tests { #[test] fn test_optimizer_hot_account_tracking() { let mut optimizer = StateShardOptimizer::new(1, 3600, 1024 * 1024); - let address = Address::from_slice(&[1u8; 20]).unwrap(); + let address = Address::from_slice(&[1u8; 32]).unwrap(); // 记录大量活动 for i in 0..1001 { diff --git a/nac-udm/src/l1_protocol/state_shard_optimization.rs.bak.20260227 b/nac-udm/src/l1_protocol/state_shard_optimization.rs.bak.20260227 new file mode 100644 index 0000000..8159a6f --- /dev/null +++ b/nac-udm/src/l1_protocol/state_shard_optimization.rs.bak.20260227 @@ -0,0 +1,561 @@ +///! 状态分片优化模块 +///! +///! 优化分片状态存储和访问性能 +///! +///! **NAC原生设计原则**: +///! - 使用Asset(资产),不是Token +///! - 使用Certificate(证书),不是Contract +///! - 使用SHA3-384哈希,不是SHA256/Keccak256 +///! - 通过CBPP共识协调 + +use crate::primitives::{Address, Hash}; +use std::collections::HashMap; +use serde::{Deserialize, Serialize}; + +/// 状态分片优化器 +#[derive(Debug, Clone)] +/// StateShardOptimizer +pub struct StateShardOptimizer { + /// 分片ID + shard_id: u64, + /// 状态缓存 + state_cache: HashMap, + /// 热点账户追踪 + hot_accounts: HashMap, + /// 冷数据归档阈值(秒) + cold_threshold: u64, + /// 缓存大小限制(字节) + max_cache_size: u64, + /// 当前缓存大小 + current_cache_size: u64, + /// 优化统计 + stats: OptimizationStats, +} + +/// 状态条目 +#[derive(Debug, Clone, Serialize, Deserialize)] +/// StateEntry +pub struct StateEntry { + /// 状态键 + pub key: Hash, + /// 状态值 + pub value: Vec, + /// 最后访问时间 + pub last_access: u64, + /// 访问次数 + pub access_count: u64, + /// 是否为热点数据 + pub is_hot: bool, + /// 数据大小(字节) + pub size: u64, +} + +impl StateEntry { + /// 创建新的状态条目 + pub fn new(key: Hash, value: Vec, timestamp: u64) -> Self { + let size = value.len() as u64; + Self { + key, + value, + last_access: timestamp, + access_count: 1, + is_hot: false, + size, + } + } + + /// 更新访问信息 + pub fn update_access(&mut self, timestamp: u64) { + self.last_access = timestamp; + self.access_count += 1; + + // 访问次数超过阈值标记为热点 + if self.access_count > 100 { + self.is_hot = true; + } + } + + /// 检查是否为冷数据 + pub fn is_cold(&self, current_time: u64, threshold: u64) -> bool { + current_time - self.last_access > threshold + } +} + +/// 热点账户统计 +#[derive(Debug, Clone, Serialize, Deserialize)] +/// HotAccountStats +pub struct HotAccountStats { + /// 账户地址 + pub address: Address, + /// 读取次数 + pub read_count: u64, + /// 写入次数 + pub write_count: u64, + /// 最后活动时间 + pub last_activity: u64, + /// 平均交易大小 + pub avg_tx_size: u64, + /// 是否为高频账户 + pub is_high_frequency: bool, +} + +impl HotAccountStats { + /// 创建新的热点账户统计 + pub fn new(address: Address, timestamp: u64) -> Self { + Self { + address, + read_count: 0, + write_count: 0, + last_activity: timestamp, + avg_tx_size: 0, + is_high_frequency: false, + } + } + + /// 记录读取操作 + pub fn record_read(&mut self, timestamp: u64) { + self.read_count += 1; + self.last_activity = timestamp; + self.update_frequency(); + } + + /// 记录写入操作 + pub fn record_write(&mut self, timestamp: u64, tx_size: u64) { + self.write_count += 1; + self.last_activity = timestamp; + + // 更新平均交易大小 + let total_count = self.read_count + self.write_count; + self.avg_tx_size = (self.avg_tx_size * (total_count - 1) + tx_size) / total_count; + + self.update_frequency(); + } + + /// 更新频率标记 + fn update_frequency(&mut self) { + // 读写总次数超过1000标记为高频 + if self.read_count + self.write_count > 1000 { + self.is_high_frequency = true; + } + } +} + +/// 优化统计 +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +/// OptimizationStats +pub struct OptimizationStats { + /// 缓存命中次数 + pub cache_hits: u64, + /// 缓存未命中次数 + pub cache_misses: u64, + /// 冷数据归档次数 + pub cold_data_archived: u64, + /// 热点数据提升次数 + pub hot_data_promoted: u64, + /// 缓存驱逐次数 + pub cache_evictions: u64, + /// 总状态访问次数 + pub total_accesses: u64, +} + +impl OptimizationStats { + /// 计算缓存命中率 + pub fn cache_hit_rate(&self) -> f64 { + if self.total_accesses == 0 { + return 0.0; + } + self.cache_hits as f64 / self.total_accesses as f64 + } +} + +impl StateShardOptimizer { + /// 创建新的状态分片优化器 + pub fn new(shard_id: u64, cold_threshold: u64, max_cache_size: u64) -> Self { + Self { + shard_id, + state_cache: HashMap::new(), + hot_accounts: HashMap::new(), + cold_threshold, + max_cache_size, + current_cache_size: 0, + stats: OptimizationStats::default(), + } + } + + /// 读取状态 + pub fn read_state(&mut self, key: &Hash, current_time: u64) -> Option> { + self.stats.total_accesses += 1; + + if let Some(entry) = self.state_cache.get_mut(key) { + // 缓存命中 + self.stats.cache_hits += 1; + entry.update_access(current_time); + Some(entry.value.clone()) + } else { + // 缓存未命中 + self.stats.cache_misses += 1; + None + } + } + + /// 写入状态 + pub fn write_state(&mut self, key: Hash, value: Vec, current_time: u64) -> Result<(), String> { + let entry_size = value.len() as u64; + + // 检查缓存大小限制 + if self.current_cache_size + entry_size > self.max_cache_size { + // 驱逐冷数据 + self.evict_cold_data(current_time)?; + } + + // 创建或更新状态条目 + if let Some(existing) = self.state_cache.get_mut(&key) { + self.current_cache_size -= existing.size; + existing.value = value; + existing.size = entry_size; + existing.update_access(current_time); + self.current_cache_size += entry_size; + } else { + let entry = StateEntry::new(key.clone(), value, current_time); + self.state_cache.insert(key, entry); + self.current_cache_size += entry_size; + } + + Ok(()) + } + + /// 驱逐冷数据 + pub fn evict_cold_data(&mut self, current_time: u64) -> Result<(), String> { + let mut cold_keys = Vec::new(); + + // 查找冷数据 + for (key, entry) in &self.state_cache { + if entry.is_cold(current_time, self.cold_threshold) && !entry.is_hot { + cold_keys.push(key.clone()); + } + } + + if cold_keys.is_empty() { + return Err("No cold data to evict".to_string()); + } + + // 驱逐冷数据 + for key in cold_keys { + if let Some(entry) = self.state_cache.remove(&key) { + self.current_cache_size -= entry.size; + self.stats.cache_evictions += 1; + self.stats.cold_data_archived += 1; + } + } + + Ok(()) + } + + /// 提升热点数据 + pub fn promote_hot_data(&mut self, key: &Hash) -> Result<(), String> { + if let Some(entry) = self.state_cache.get_mut(key) { + if !entry.is_hot { + entry.is_hot = true; + self.stats.hot_data_promoted += 1; + } + Ok(()) + } else { + Err("State entry not found".to_string()) + } + } + + /// 记录账户活动 + pub fn record_account_activity( + &mut self, + address: Address, + is_write: bool, + tx_size: u64, + timestamp: u64, + ) { + let stats = self.hot_accounts + .entry(address.clone()) + .or_insert_with(|| HotAccountStats::new(address, timestamp)); + + if is_write { + stats.record_write(timestamp, tx_size); + } else { + stats.record_read(timestamp); + } + } + + /// 获取热点账户列表 + pub fn get_hot_accounts(&self) -> Vec
{ + self.hot_accounts + .values() + .filter(|stats| stats.is_high_frequency) + .map(|stats| stats.address.clone()) + .collect() + } + + /// 获取优化统计 + pub fn get_stats(&self) -> OptimizationStats { + self.stats.clone() + } + + /// 获取缓存使用率 + pub fn get_cache_usage(&self) -> f64 { + if self.max_cache_size == 0 { + return 0.0; + } + self.current_cache_size as f64 / self.max_cache_size as f64 + } + + /// 清理过期数据 + pub fn cleanup_expired(&mut self, current_time: u64) -> usize { + let mut expired_keys = Vec::new(); + + // 查找过期数据(超过冷数据阈值的2倍) + let expiry_threshold = self.cold_threshold * 2; + for (key, entry) in &self.state_cache { + if current_time - entry.last_access > expiry_threshold { + expired_keys.push(key.clone()); + } + } + + let count = expired_keys.len(); + + // 删除过期数据 + for key in expired_keys { + if let Some(entry) = self.state_cache.remove(&key) { + self.current_cache_size -= entry.size; + } + } + + count + } + + /// 优化分片状态 + pub fn optimize(&mut self, current_time: u64) -> Result { + let initial_cache_size = self.current_cache_size; + let initial_entry_count = self.state_cache.len(); + + // 1. 清理过期数据 + let expired_count = self.cleanup_expired(current_time); + + // 2. 驱逐冷数据(如果缓存使用率超过80%) + let evicted_count = if self.get_cache_usage() > 0.8 { + let before = self.state_cache.len(); + self.evict_cold_data(current_time)?; + before - self.state_cache.len() + } else { + 0 + }; + + // 3. 提升热点数据 + let hot_keys: Vec = self.state_cache + .iter() + .filter(|(_, entry)| entry.access_count > 50 && !entry.is_hot) + .map(|(key, _)| key.clone()) + .collect(); + + for key in &hot_keys { + let _ = self.promote_hot_data(key); + } + + Ok(OptimizationReport { + shard_id: self.shard_id, + expired_count, + evicted_count, + promoted_count: hot_keys.len(), + space_freed: initial_cache_size - self.current_cache_size, + entries_before: initial_entry_count, + entries_after: self.state_cache.len(), + cache_hit_rate: self.stats.cache_hit_rate(), + }) + } +} + +/// 优化报告 +#[derive(Debug, Clone, Serialize, Deserialize)] +/// OptimizationReport +pub struct OptimizationReport { + /// 分片ID + pub shard_id: u64, + /// 清理的过期数据数量 + pub expired_count: usize, + /// 驱逐的冷数据数量 + pub evicted_count: usize, + /// 提升的热点数据数量 + pub promoted_count: usize, + /// 释放的空间(字节) + pub space_freed: u64, + /// 优化前条目数 + pub entries_before: usize, + /// 优化后条目数 + pub entries_after: usize, + /// 缓存命中率 + pub cache_hit_rate: f64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_state_entry_creation() { + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + let value = vec![1, 2, 3, 4]; + let entry = StateEntry::new(key, value.clone(), 1000); + + assert_eq!(entry.value, value); + assert_eq!(entry.last_access, 1000); + assert_eq!(entry.access_count, 1); + assert!(!entry.is_hot); + assert_eq!(entry.size, 4); + } + + #[test] + fn test_state_entry_hot_promotion() { + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + let value = vec![1, 2, 3]; + let mut entry = StateEntry::new(key, value, 1000); + + // 访问101次应该变为热点 + for i in 0..101 { + entry.update_access(1000 + i); + } + + assert!(entry.is_hot); + assert_eq!(entry.access_count, 102); // 初始1次 + 101次 + } + + #[test] + fn test_state_entry_cold_detection() { + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + let value = vec![1, 2, 3]; + let entry = StateEntry::new(key, value, 1000); + + // 在阈值内不是冷数据 + assert!(!entry.is_cold(1500, 1000)); + + // 超过阈值是冷数据 + assert!(entry.is_cold(2001, 1000)); + } + + #[test] + fn test_optimizer_read_write() { + let mut optimizer = StateShardOptimizer::new(1, 3600, 1024 * 1024); + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + let value = vec![1, 2, 3, 4]; + + // 写入状态 + assert!(optimizer.write_state(key.clone(), value.clone(), 1000).is_ok()); + + // 读取状态 + let read_value = optimizer.read_state(&key, 1001); + assert_eq!(read_value, Some(value)); + + // 验证统计 + assert_eq!(optimizer.stats.cache_hits, 1); + assert_eq!(optimizer.stats.total_accesses, 1); + } + + #[test] + fn test_optimizer_cache_miss() { + let mut optimizer = StateShardOptimizer::new(1, 3600, 1024 * 1024); + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + + // 读取不存在的状态 + let result = optimizer.read_state(&key, 1000); + assert!(result.is_none()); + + // 验证统计 + assert_eq!(optimizer.stats.cache_misses, 1); + assert_eq!(optimizer.stats.total_accesses, 1); + } + + #[test] + fn test_optimizer_evict_cold_data() { + let mut optimizer = StateShardOptimizer::new(1, 1000, 1024); + + // 写入一些数据 + for i in 0..5 { + let key = Hash::from_slice(&[i; 32]).unwrap(); + let value = vec![i; 100]; + optimizer.write_state(key, value, 1000 + i as u64).unwrap(); + } + + // 等待一段时间后驱逐冷数据 + assert!(optimizer.evict_cold_data(3000).is_ok()); + + // 验证统计 + assert!(optimizer.stats.cold_data_archived > 0); + } + + #[test] + fn test_optimizer_hot_account_tracking() { + let mut optimizer = StateShardOptimizer::new(1, 3600, 1024 * 1024); + let address = Address::from_slice(&[1u8; 20]).unwrap(); + + // 记录大量活动 + for i in 0..1001 { + optimizer.record_account_activity(address.clone(), i % 2 == 0, 100, 1000 + i); + } + + // 验证热点账户 + let hot_accounts = optimizer.get_hot_accounts(); + assert_eq!(hot_accounts.len(), 1); + assert_eq!(hot_accounts[0], address); + } + + #[test] + fn test_optimizer_cache_usage() { + let mut optimizer = StateShardOptimizer::new(1, 3600, 1000); + + // 写入500字节数据 + let key = Hash::from_slice(&[1u8; 32]).unwrap(); + let value = vec![1u8; 500]; + optimizer.write_state(key, value, 1000).unwrap(); + + // 验证缓存使用率 + assert_eq!(optimizer.get_cache_usage(), 0.5); + } + + #[test] + fn test_optimizer_cleanup_expired() { + let mut optimizer = StateShardOptimizer::new(1, 1000, 1024 * 1024); + + // 写入一些数据 + for i in 0..5 { + let key = Hash::from_slice(&[i; 32]).unwrap(); + let value = vec![i; 10]; + optimizer.write_state(key, value, 1000).unwrap(); + } + + // 清理过期数据(超过2000秒) + let expired = optimizer.cleanup_expired(4000); + assert_eq!(expired, 5); + } + + #[test] + fn test_optimizer_full_optimization() { + let mut optimizer = StateShardOptimizer::new(1, 1000, 1024 * 1024); + + // 写入一些数据 + for i in 0..10 { + let key = Hash::from_slice(&[i; 32]).unwrap(); + let value = vec![i; 100]; + optimizer.write_state(key, value, 1000 + i as u64).unwrap(); + } + + // 访问部分数据使其成为热点(但不超过100次,避免自动标记为hot) + for i in 0..3 { + let key = Hash::from_slice(&[i; 32]).unwrap(); + for _ in 0..50 { + optimizer.read_state(&key, 2000); + } + } + + // 执行优化 + let report = optimizer.optimize(4000).unwrap(); + + assert_eq!(report.shard_id, 1); + assert!(report.promoted_count > 0); + assert!(report.cache_hit_rate > 0.0); + } +} diff --git a/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/chunks/000001 b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/chunks/000001 new file mode 100644 index 0000000..ea6a280 Binary files /dev/null and b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/chunks/000001 differ diff --git a/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/index b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/index new file mode 100644 index 0000000..c4d7b0a Binary files /dev/null and b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/index differ diff --git a/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/meta.json b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/meta.json new file mode 100644 index 0000000..c9f575d --- /dev/null +++ b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/meta.json @@ -0,0 +1,36 @@ +{ + "ulid": "01KJFC2WB0KTPPNZRT33KJ9KF5", + "minTime": 1772150403067, + "maxTime": 1772172000000, + "stats": { + "numSamples": 1314720, + "numSeries": 913, + "numChunks": 10956 + }, + "compaction": { + "level": 2, + "sources": [ + "01KJEGKZH8GKNPMQ4CSY6Q2NH6", + "01KJEQFPS5PDAPHBZERMK243HE", + "01KJEYBE16DN0293TC8C9KH6X0" + ], + "parents": [ + { + "ulid": "01KJEGKZH8GKNPMQ4CSY6Q2NH6", + "minTime": 1772150403067, + "maxTime": 1772157600000 + }, + { + "ulid": "01KJEQFPS5PDAPHBZERMK243HE", + "minTime": 1772157603067, + "maxTime": 1772164800000 + }, + { + "ulid": "01KJEYBE16DN0293TC8C9KH6X0", + "minTime": 1772164803067, + "maxTime": 1772172000000 + } + ] + }, + "version": 1 +} \ No newline at end of file diff --git a/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/tombstones b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/tombstones new file mode 100644 index 0000000..95fb832 Binary files /dev/null and b/prometheus/data/01KJFC2WB0KTPPNZRT33KJ9KF5/tombstones differ diff --git a/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/chunks/000001 b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/chunks/000001 new file mode 100644 index 0000000..3dc3a0a Binary files /dev/null and b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/chunks/000001 differ diff --git a/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/index b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/index new file mode 100644 index 0000000..c27d6da Binary files /dev/null and b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/index differ diff --git a/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/meta.json b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/meta.json new file mode 100644 index 0000000..73e6264 --- /dev/null +++ b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/meta.json @@ -0,0 +1,17 @@ +{ + "ulid": "01KJFSTABWA081QJMMVEC6NSED", + "minTime": 1772193603066, + "maxTime": 1772200800000, + "stats": { + "numSamples": 438240, + "numSeries": 913, + "numChunks": 3652 + }, + "compaction": { + "level": 1, + "sources": [ + "01KJFSTABWA081QJMMVEC6NSED" + ] + }, + "version": 1 +} \ No newline at end of file diff --git a/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/tombstones b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/tombstones new file mode 100644 index 0000000..95fb832 Binary files /dev/null and b/prometheus/data/01KJFSTABWA081QJMMVEC6NSED/tombstones differ diff --git a/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/chunks/000001 b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/chunks/000001 new file mode 100644 index 0000000..78c9def Binary files /dev/null and b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/chunks/000001 differ diff --git a/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/index b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/index new file mode 100644 index 0000000..c50f797 Binary files /dev/null and b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/index differ diff --git a/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/meta.json b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/meta.json new file mode 100644 index 0000000..b422a6d --- /dev/null +++ b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/meta.json @@ -0,0 +1,17 @@ +{ + "ulid": "01KJG0P296Z19XC0BS2FSXFFNR", + "minTime": 1772200803067, + "maxTime": 1772208000000, + "stats": { + "numSamples": 438240, + "numSeries": 913, + "numChunks": 3652 + }, + "compaction": { + "level": 1, + "sources": [ + "01KJG0P296Z19XC0BS2FSXFFNR" + ] + }, + "version": 1 +} \ No newline at end of file diff --git a/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/tombstones b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/tombstones new file mode 100644 index 0000000..95fb832 Binary files /dev/null and b/prometheus/data/01KJG0P296Z19XC0BS2FSXFFNR/tombstones differ diff --git a/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/chunks/000001 b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/chunks/000001 new file mode 100644 index 0000000..c1b2fb7 Binary files /dev/null and b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/chunks/000001 differ diff --git a/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/index b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/index new file mode 100644 index 0000000..3d3eec8 Binary files /dev/null and b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/index differ diff --git a/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/meta.json b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/meta.json new file mode 100644 index 0000000..5c75be7 --- /dev/null +++ b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/meta.json @@ -0,0 +1,36 @@ +{ + "ulid": "01KJG0P2EMDYT9KR830HPNA65K", + "minTime": 1772172003065, + "maxTime": 1772193600000, + "stats": { + "numSamples": 1314720, + "numSeries": 913, + "numChunks": 10956 + }, + "compaction": { + "level": 2, + "sources": [ + "01KJF574KWX9GSQ800QYSSFJXV", + "01KJFC2VVVR8666R8YWWGFMA0Y", + "01KJFJYK3W114RCCDVD93N7DMK" + ], + "parents": [ + { + "ulid": "01KJF574KWX9GSQ800QYSSFJXV", + "minTime": 1772172003065, + "maxTime": 1772179200000 + }, + { + "ulid": "01KJFC2VVVR8666R8YWWGFMA0Y", + "minTime": 1772179203063, + "maxTime": 1772186400000 + }, + { + "ulid": "01KJFJYK3W114RCCDVD93N7DMK", + "minTime": 1772186403066, + "maxTime": 1772193600000 + } + ] + }, + "version": 1 +} \ No newline at end of file diff --git a/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/tombstones b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/tombstones new file mode 100644 index 0000000..95fb832 Binary files /dev/null and b/prometheus/data/01KJG0P2EMDYT9KR830HPNA65K/tombstones differ diff --git a/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/chunks/000001 b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/chunks/000001 new file mode 100644 index 0000000..0fbad61 Binary files /dev/null and b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/chunks/000001 differ diff --git a/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/index b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/index new file mode 100644 index 0000000..874ae82 Binary files /dev/null and b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/index differ diff --git a/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/meta.json b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/meta.json new file mode 100644 index 0000000..100b3ee --- /dev/null +++ b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/meta.json @@ -0,0 +1,17 @@ +{ + "ulid": "01KJG7HSH64RHXEXRGJ1ZPAEKZ", + "minTime": 1772208003067, + "maxTime": 1772215200000, + "stats": { + "numSamples": 438240, + "numSeries": 913, + "numChunks": 3652 + }, + "compaction": { + "level": 1, + "sources": [ + "01KJG7HSH64RHXEXRGJ1ZPAEKZ" + ] + }, + "version": 1 +} \ No newline at end of file diff --git a/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/tombstones b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/tombstones new file mode 100644 index 0000000..95fb832 Binary files /dev/null and b/prometheus/data/01KJG7HSH64RHXEXRGJ1ZPAEKZ/tombstones differ diff --git a/prometheus/data/chunks_head/000091 b/prometheus/data/chunks_head/000091 new file mode 100644 index 0000000..1f5c601 Binary files /dev/null and b/prometheus/data/chunks_head/000091 differ diff --git a/prometheus/data/chunks_head/000092 b/prometheus/data/chunks_head/000092 new file mode 100644 index 0000000..d9ba869 Binary files /dev/null and b/prometheus/data/chunks_head/000092 differ diff --git a/prometheus/data/wal/00000088 b/prometheus/data/wal/00000088 new file mode 100644 index 0000000..efc4d22 Binary files /dev/null and b/prometheus/data/wal/00000088 differ diff --git a/prometheus/data/wal/00000089 b/prometheus/data/wal/00000089 new file mode 100644 index 0000000..28e7575 Binary files /dev/null and b/prometheus/data/wal/00000089 differ diff --git a/prometheus/data/wal/00000090 b/prometheus/data/wal/00000090 new file mode 100644 index 0000000..576b278 Binary files /dev/null and b/prometheus/data/wal/00000090 differ diff --git a/prometheus/data/wal/00000091 b/prometheus/data/wal/00000091 new file mode 100644 index 0000000..726dd26 Binary files /dev/null and b/prometheus/data/wal/00000091 differ diff --git a/prometheus/data/wal/checkpoint.00000087/00000000 b/prometheus/data/wal/checkpoint.00000087/00000000 new file mode 100644 index 0000000..784976f Binary files /dev/null and b/prometheus/data/wal/checkpoint.00000087/00000000 differ diff --git a/开发状态追踪_每日更新.md b/开发状态追踪_每日更新.md index bec6382..52e90ff 100644 --- a/开发状态追踪_每日更新.md +++ b/开发状态追踪_每日更新.md @@ -59,7 +59,7 @@ - ✅ **nac-nrpc** (2个Rust文件) - 基础版本 - **状态**: 已完成 -- ✅ **nac-nrpc4** (9个Rust文件) - 4.0版本 +- ✅ **nac-lens** (9个Rust文件) - 4.0版本 - **状态**: 已完成,最新版本 ### 5. AI系统 diff --git a/模块真实状态核查报告.md b/模块真实状态核查报告.md index a29334a..8839273 100644 --- a/模块真实状态核查报告.md +++ b/模块真实状态核查报告.md @@ -82,7 +82,7 @@ - ⏳ nac-cbpp - 待分析 - ⏳ nac-nvm - 待分析 - ⏳ nac-csnp - 待分析 -- ⏳ nac-nrpc4 - 待分析 +- ⏳ nac-lens - 待分析 - ⏳ 其他43个模块 - 待分析 ---