# 工单 #36: NAC公链逐层接口规范与适配器实现 **工单链接**: https://git.newassetchain.io/nacadmin/NAC_Blockchain/issues/36 **目标**: 逐层分析每一层实现的功能,为每个功能模块建立适配器,并在SDK中统一调用方式和适配器。 **创建时间**: 2026-02-19 **状态**: 进行中 --- ## 一、NAC公链层级架构 根据nac-udm模块的实际结构,NAC公链采用**六层架构**: ``` L5: 应用层 (l5_application) ↓ L4: AI层 (l4_ai) ↓ L3: 存储层 (l3_storage) ↓ L2: 宪政/治理/网络层 (l2_constitutional, l2_governance, l2_network) ↓ L1: 协议层 (l1_protocol) ↓ L0: 原生层 (l0_native) ``` --- ## 二、现有模块分析 ### 2.1 nac-sdk (当前状态) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-sdk` **现有模块**: - `client/` - NRPC3客户端(需要升级到NRPC4) - `crypto/` - Blake3哈希、AssetDNA、GNACS编码 - `protocols/` - ACC20协议(ACC721、ACC1155、XTZH待实现) - `types/` - 类型定义 - `error/` - 错误处理 - `utils/` - 工具函数 - `advanced/` - 高级功能(待实现) **问题**: 1. ❌ 没有分层的适配器架构 2. ❌ 使用NRPC3,需要升级到NRPC4 3. ❌ 缺少L0-L5各层的完整接口定义 4. ❌ 缺少统一的适配器调用方式 ### 2.2 nac-lens (NAC Lens协议) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-lens` **六层架构**: - L1: 元胞层 (l1_cell) - 元胞自动机路由 - L2: 文明层 (l2_civilization) - 文明特征向量、灵魂签名 - L3: 聚合层 (l3_aggregation) - 文明间路由、意识分叉 - L4: 宪法层 (l4_constitution) - 全息编码、分片存储 - L5: 价值层 (l5_value) - XIC/XTZH跨文明价值交换 - L6: 应用层 (l6_application) - AA-PE、FTAN、UCA **核心模块**: - `connection.rs` - 连接管理 - `performance.rs` - 性能优化 - `security.rs` - 安全机制 - `retry.rs` - 重试机制 ### 2.3 nac-udm (统一数据模型) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-udm` **层级模块**: - `l0_native/` - 原生层 - `l1_protocol/` - 协议层(NVM、CBPP、GNACS、ACC) - `l2_constitutional/` - 宪政层 - `l2_governance/` - 治理层 - `l2_network/` - 网络层 - `l3_storage/` - 存储层 - `l4_ai/` - AI层 - `l5_application/` - 应用层 **其他模块**: - `asset_dna/` - 资产DNA生成 - `dividend_ai/` - 分红AI - `primitives/` - 基础类型 - `registry/` - 注册表 - `utils/` - 工具函数 ### 2.4 nac-ai-compliance (AI合规审批) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-ai-compliance` **核心功能**: 七层合规验证(KYC/AML、资产真实性、法律合规、财务合规、税务合规、ESG合规、持续监控) **代码量**: 2,185行 ### 2.5 nac-ai-valuation (AI估值引擎) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-ai-valuation` **核心功能**: 多元AI协同估值(ChatGPT、DeepSeek、豆包) **代码量**: 25,369行 ### 2.6 nac-api-server (API服务器) **位置**: `/home/ubuntu/NAC_Clean_Dev/nac-api-server` **核心功能**: - 钱包API(余额查询、转账、交易历史) - 交易所API(资产列表、订单管理、市场数据) - 区块链集成(RPC连接) **问题**: 使用JSON-RPC,需要升级到NRPC4 --- ## 三、完整的层级接口规范 ### 3.1 L0 原生层接口 **模块**: `nac-sdk/src/adapters/l0_native.rs` ```rust /// L0原生层适配器 pub struct L0NativeAdapter { // 内部实现 } impl L0NativeAdapter { /// 创建新的L0适配器 pub fn new() -> Result; // 地址操作 pub fn generate_address(public_key: &[u8]) -> Address32; pub fn validate_address(address: &Address32) -> bool; pub fn address_from_private_key(private_key: &PrivateKey) -> Address32; // 哈希操作 pub fn hash_sha3_384(data: &[u8]) -> Hash48; pub fn compute_block_hash(block_header: &BlockHeader) -> Hash48; pub fn compute_transaction_hash(tx: &Transaction) -> Hash48; pub fn compute_merkle_root(hashes: &[Hash48]) -> Hash48; // 密码学操作 pub fn generate_keypair() -> (PrivateKey, PublicKey); pub fn sign_data(data: &[u8], private_key: &PrivateKey) -> Signature; pub fn verify_signature(data: &[u8], signature: &Signature, public_key: &PublicKey) -> bool; pub fn sign_transaction(tx: &Transaction, private_key: &PrivateKey) -> SignedTransaction; // 编码/解码 pub fn encode_transaction(tx: &Transaction) -> Vec; pub fn decode_transaction(data: &[u8]) -> Result; pub fn encode_block(block: &Block) -> Vec; pub fn decode_block(data: &[u8]) -> Result; } ``` ### 3.2 L1 协议层接口 **模块**: `nac-sdk/src/adapters/l1_protocol.rs` ```rust /// L1协议层适配器 pub struct L1ProtocolAdapter { nvm_client: NVMClient, cbpp_client: CBPPClient, gnacs_encoder: GNACSEncoder, acc_protocols: ACCProtocols, } impl L1ProtocolAdapter { /// 创建新的L1适配器 pub async fn new(config: &L1Config) -> Result; // ===== NVM虚拟机 ===== /// 部署Charter智能合约 pub async fn deploy_contract( &self, bytecode: &[u8], constructor_args: &[u8], deployer: &Address32, ) -> Result; /// 调用智能合约方法 pub async fn call_contract( &self, contract_addr: &Address32, method: &str, args: &[u8], caller: &Address32, ) -> Result; /// 查询合约状态 pub async fn query_contract_state( &self, contract_addr: &Address32, key: &[u8], ) -> Result>; /// 估算Gas消耗 pub async fn estimate_gas( &self, tx: &Transaction, ) -> Result; // ===== CBPP共识 ===== /// 提交交易到交易池 pub async fn submit_transaction( &self, tx: &SignedTransaction, ) -> Result; /// 获取区块 pub async fn get_block( &self, block_number: u64, ) -> Result; /// 获取区块(按哈希) pub async fn get_block_by_hash( &self, block_hash: &Hash48, ) -> Result; /// 获取最新区块高度 pub async fn get_latest_block_number(&self) -> Result; /// 获取交易收据 pub async fn get_transaction_receipt( &self, tx_hash: &Hash48, ) -> Result; /// 等待交易确认 pub async fn wait_for_confirmation( &self, tx_hash: &Hash48, confirmations: u32, ) -> Result; // ===== GNACS编码系统 ===== /// 生成GNACS编码 pub fn generate_gnacs_code( &self, asset_type: &str, jurisdiction: &str, sub_category: Option<&str>, ) -> Result; /// 解析GNACS编码 pub fn parse_gnacs_code( &self, code: &GNACSCode, ) -> Result; /// 验证GNACS编码 pub fn validate_gnacs_code( &self, code: &GNACSCode, ) -> bool; // ===== ACC协议族 ===== /// 部署ACC-20代币 pub async fn deploy_acc20_token( &self, metadata: &ACC20Metadata, deployer: &Address32, ) -> Result; /// 铸造ACC-20代币 pub async fn mint_acc20( &self, token_addr: &Address32, to: &Address32, amount: Decimal, minter: &Address32, ) -> Result; /// 转账ACC-20代币 pub async fn transfer_acc20( &self, token_addr: &Address32, from: &Address32, to: &Address32, amount: Decimal, ) -> Result; /// 查询ACC-20余额 pub async fn balance_of_acc20( &self, token_addr: &Address32, owner: &Address32, ) -> Result; /// 部署ACC-1400证券型代币 pub async fn deploy_acc1400_token( &self, metadata: &ACC1400Metadata, deployer: &Address32, ) -> Result; /// 铸造XTZH稳定币 pub async fn mint_xtzh( &self, amount: Decimal, collateral_proof: &CollateralProof, minter: &Address32, ) -> Result; /// 查询XTZH余额 pub async fn balance_of_xtzh( &self, owner: &Address32, ) -> Result; /// 查询SDR汇率 pub async fn get_sdr_rate(&self) -> Result; // ===== 跨分片交易 ===== /// 提交跨分片交易 pub async fn submit_cross_shard_transaction( &self, tx: &SignedTransaction, target_shard: u32, ) -> Result; /// 查询跨分片交易状态 pub async fn get_cross_shard_status( &self, tx_hash: &Hash48, ) -> Result; } ``` ### 3.3 L2 宪政/治理/网络层接口 **模块**: `nac-sdk/src/adapters/l2_layer.rs` ```rust /// L2层适配器 pub struct L2Adapter { constitutional: ConstitutionalAdapter, governance: GovernanceAdapter, network: NetworkAdapter, } impl L2Adapter { /// 创建新的L2适配器 pub async fn new(config: &L2Config) -> Result; // ===== 宪政层 ===== /// 检查交易的宪政合规性 pub async fn check_constitutional_compliance( &self, tx: &Transaction, ) -> Result; /// 提出宪法修正案 pub async fn propose_amendment( &self, amendment: &Amendment, proposer: &Address32, ) -> Result; /// 对修正案投票 pub async fn vote_on_amendment( &self, proposal_id: ProposalId, vote: Vote, voter: &Address32, ) -> Result; /// 查询修正案状态 pub async fn get_amendment_status( &self, proposal_id: ProposalId, ) -> Result; // ===== 治理层 ===== /// 创建治理提案 pub async fn create_proposal( &self, proposal: &Proposal, proposer: &Address32, ) -> Result; /// 对提案投票 pub async fn vote_on_proposal( &self, proposal_id: ProposalId, vote: Vote, voter: &Address32, ) -> Result; /// 执行通过的提案 pub async fn execute_proposal( &self, proposal_id: ProposalId, executor: &Address32, ) -> Result; /// 查询提案详情 pub async fn get_proposal( &self, proposal_id: ProposalId, ) -> Result; /// 查询投票权重 pub async fn get_voting_power( &self, voter: &Address32, ) -> Result; // ===== 网络层 (CSNP) ===== /// 广播交易到网络 pub async fn broadcast_transaction( &self, tx: &SignedTransaction, ) -> Result<()>; /// 广播区块到网络 pub async fn broadcast_block( &self, block: &Block, ) -> Result<()>; /// 同步区块 pub async fn sync_blocks( &self, from_height: u64, to_height: u64, ) -> Result>; /// 查询网络节点 pub async fn get_peers(&self) -> Result>; /// 连接到节点 pub async fn connect_to_peer( &self, peer_addr: &str, ) -> Result<()>; } ``` ### 3.4 L3 存储层接口 **模块**: `nac-sdk/src/adapters/l3_storage.rs` ```rust /// L3存储层适配器 pub struct L3StorageAdapter { state_db: StateDatabase, block_db: BlockDatabase, ipfs_client: Option, } impl L3StorageAdapter { /// 创建新的L3适配器 pub async fn new(config: &L3Config) -> Result; // ===== 状态数据库 ===== /// 获取账户状态 pub async fn get_account_state( &self, address: &Address32, ) -> Result; /// 设置账户状态 pub async fn set_account_state( &self, address: &Address32, state: &AccountState, ) -> Result<()>; /// 获取合约存储 pub async fn get_contract_storage( &self, contract_addr: &Address32, key: &[u8], ) -> Result>; /// 设置合约存储 pub async fn set_contract_storage( &self, contract_addr: &Address32, key: &[u8], value: &[u8], ) -> Result<()>; /// 获取状态根哈希 pub async fn get_state_root(&self) -> Result; // ===== 区块存储 ===== /// 存储区块 pub async fn store_block( &self, block: &Block, ) -> Result<()>; /// 获取区块(按高度) pub async fn get_block_by_height( &self, height: u64, ) -> Result; /// 获取区块(按哈希) pub async fn get_block_by_hash( &self, hash: &Hash48, ) -> Result; /// 存储交易 pub async fn store_transaction( &self, tx: &Transaction, ) -> Result<()>; /// 获取交易 pub async fn get_transaction( &self, tx_hash: &Hash48, ) -> Result; /// 存储交易收据 pub async fn store_receipt( &self, receipt: &TransactionReceipt, ) -> Result<()>; /// 获取交易收据 pub async fn get_receipt( &self, tx_hash: &Hash48, ) -> Result; // ===== IPFS集成 ===== /// 上传文件到IPFS pub async fn upload_to_ipfs( &self, data: &[u8], ) -> Result; // 返回CID /// 从IPFS下载文件 pub async fn download_from_ipfs( &self, cid: &str, ) -> Result>; /// 固定IPFS文件 pub async fn pin_ipfs_file( &self, cid: &str, ) -> Result<()>; } ``` ### 3.5 L4 AI层接口 **模块**: `nac-sdk/src/adapters/l4_ai.rs` ```rust /// L4 AI层适配器 pub struct L4AIAdapter { compliance: AIComplianceAdapter, valuation: AIValuationAdapter, risk: AIRiskAdapter, xtzh_ai: XTZHAIAdapter, } impl L4AIAdapter { /// 创建新的L4适配器 pub async fn new(config: &L4Config) -> Result; // ===== AI合规审批 ===== /// 执行七层合规验证 pub async fn verify_compliance( &self, data: &ComplianceData, ) -> Result; /// 生成ZK证明 pub async fn generate_zk_proof( &self, result: &ComplianceResult, ) -> Result; /// 生成合规报告 pub async fn generate_compliance_report( &self, results: &[ComplianceResult], ) -> Result; // ===== AI估值引擎 ===== /// 评估资产价值 pub async fn appraise_asset( &self, asset: &Asset, jurisdiction: Jurisdiction, agreement: InternationalAgreement, ) -> Result; /// 获取市场数据 pub async fn get_market_data( &self, asset_type: &str, ) -> Result; /// 批量估值 pub async fn batch_appraise( &self, assets: &[Asset], ) -> Result>; // ===== AI风险评估 ===== /// 评估交易风险 pub async fn assess_transaction_risk( &self, tx: &Transaction, ) -> Result; /// 检测异常行为 pub async fn detect_anomaly( &self, behavior: &UserBehavior, ) -> Result; /// 生成风险报告 pub async fn generate_risk_report( &self, address: &Address32, period: Duration, ) -> Result; // ===== XTZH AI引擎 ===== /// 优化储备配置 pub async fn optimize_reserves( &self, current_reserves: &Reserves, ) -> Result; /// 预测SDR汇率 pub async fn predict_sdr_rate( &self, horizon: Duration, ) -> Result; /// 管理流动性 pub async fn manage_liquidity( &self, current_liquidity: &LiquidityState, ) -> Result; } ``` ### 3.6 L5 应用层接口 **模块**: `nac-sdk/src/adapters/l5_application.rs` ```rust /// L5应用层适配器 pub struct L5ApplicationAdapter { wallet: WalletAdapter, dapp: DAppAdapter, explorer: ExplorerAdapter, exchange: ExchangeAdapter, } impl L5ApplicationAdapter { /// 创建新的L5适配器 pub async fn new(config: &L5Config) -> Result; // ===== 钱包接口 ===== /// 创建钱包 pub async fn create_wallet( &self, password: &str, ) -> Result; /// 导入钱包 pub async fn import_wallet( &self, mnemonic: &str, password: &str, ) -> Result; /// 发送交易 pub async fn send_transaction( &self, from: &Address32, to: &Address32, amount: Decimal, asset: Option<&Address32>, ) -> Result; /// 查询余额 pub async fn get_balance( &self, address: &Address32, ) -> Result; /// 查询交易历史 pub async fn get_transaction_history( &self, address: &Address32, limit: u32, ) -> Result>; // ===== DApp接口 ===== /// 调用合约方法 pub async fn call_contract_method( &self, contract: &Address32, method: &str, params: &[Value], caller: &Address32, ) -> Result; /// 订阅合约事件 pub async fn subscribe_event( &self, contract: &Address32, event_name: &str, ) -> Result; /// 批量调用 pub async fn batch_call( &self, calls: &[ContractCall], ) -> Result>; // ===== 浏览器接口 ===== /// 获取交易收据 pub async fn get_transaction_receipt( &self, tx_hash: &Hash48, ) -> Result; /// 获取链上统计 pub async fn get_chain_stats(&self) -> Result; /// 搜索地址 pub async fn search_address( &self, query: &str, ) -> Result>; // ===== 交易所接口 ===== /// 在交易所上架代币 pub async fn list_token_on_exchange( &self, token: &Address32, metadata: &TokenMetadata, ) -> Result; /// 创建交易对 pub async fn create_trading_pair( &self, base: &Address32, quote: &Address32, ) -> Result; /// 下单 pub async fn place_order( &self, order: &Order, ) -> Result; /// 查询订单簿 pub async fn get_orderbook( &self, pair_id: PairId, ) -> Result; /// 查询市场数据 pub async fn get_market_data( &self, pair_id: PairId, ) -> Result; } ``` --- ## 四、统一适配器架构 ### 4.1 NACAdapter - 统一入口 **模块**: `nac-sdk/src/adapters/mod.rs` ```rust /// NAC SDK统一适配器 pub struct NACAdapter { l0: L0NativeAdapter, l1: L1ProtocolAdapter, l2: L2Adapter, l3: L3StorageAdapter, l4: L4AIAdapter, l5: L5ApplicationAdapter, config: NACConfig, } impl NACAdapter { /// 创建新的NAC适配器 pub async fn new(config: NACConfig) -> Result { Ok(Self { l0: L0NativeAdapter::new()?, l1: L1ProtocolAdapter::new(&config.l1).await?, l2: L2Adapter::new(&config.l2).await?, l3: L3StorageAdapter::new(&config.l3).await?, l4: L4AIAdapter::new(&config.l4).await?, l5: L5ApplicationAdapter::new(&config.l5).await?, config, }) } /// 获取L0层适配器 pub fn l0(&self) -> &L0NativeAdapter { &self.l0 } /// 获取L1层适配器 pub fn l1(&self) -> &L1ProtocolAdapter { &self.l1 } /// 获取L2层适配器 pub fn l2(&self) -> &L2Adapter { &self.l2 } /// 获取L3层适配器 pub fn l3(&self) -> &L3StorageAdapter { &self.l3 } /// 获取L4层适配器 pub fn l4(&self) -> &L4AIAdapter { &self.l4 } /// 获取L5层适配器 pub fn l5(&self) -> &L5ApplicationAdapter { &self.l5 } } ``` ### 4.2 配置结构 ```rust /// NAC配置 #[derive(Debug, Clone)] pub struct NACConfig { pub l1: L1Config, pub l2: L2Config, pub l3: L3Config, pub l4: L4Config, pub l5: L5Config, } /// L1层配置 #[derive(Debug, Clone)] pub struct L1Config { pub nrpc4_url: String, pub chain_id: u32, pub timeout: Duration, } /// L2层配置 #[derive(Debug, Clone)] pub struct L2Config { pub constitutional_url: String, pub governance_url: String, pub network_peers: Vec, } /// L3层配置 #[derive(Debug, Clone)] pub struct L3Config { pub state_db_path: String, pub block_db_path: String, pub ipfs_url: Option, } /// L4层配置 #[derive(Debug, Clone)] pub struct L4Config { pub chatgpt_key: String, pub deepseek_key: String, pub doubao_key: String, } /// L5层配置 #[derive(Debug, Clone)] pub struct L5Config { pub wallet_db_path: String, pub explorer_url: String, pub exchange_url: String, } ``` --- ## 五、实施计划 ### 5.1 阶段一:基础架构(第1周) - [ ] 创建`nac-sdk/src/adapters/`目录结构 - [ ] 实现`mod.rs` - 统一适配器入口 - [ ] 实现配置结构`NACConfig` - [ ] 编写基础测试框架 ### 5.2 阶段二:L0原生层(第2周) - [ ] 实现`l0_native.rs`完整接口 - [ ] 集成nac-udm的l0_native模块 - [ ] 编写单元测试(覆盖率>90%) - [ ] 编写使用示例 ### 5.3 阶段三:L1协议层(第3-4周) - [ ] 实现`l1_protocol.rs`完整接口 - [ ] 集成NVM、CBPP、GNACS、ACC模块 - [ ] 升级到NRPC4协议 - [ ] 编写集成测试 - [ ] 编写使用示例 ### 5.4 阶段四:L2层(第5周) - [ ] 实现`l2_layer.rs`完整接口 - [ ] 集成宪政、治理、网络模块 - [ ] 编写集成测试 - [ ] 编写使用示例 ### 5.5 阶段五:L3存储层(第6周) - [ ] 实现`l3_storage.rs`完整接口 - [ ] 集成状态数据库、区块存储、IPFS - [ ] 编写性能测试 - [ ] 编写使用示例 ### 5.6 阶段六:L4 AI层(第7-8周) - [ ] 实现`l4_ai.rs`完整接口 - [ ] 集成nac-ai-compliance、nac-ai-valuation - [ ] 集成XTZH AI引擎 - [ ] 编写端到端测试 - [ ] 编写使用示例 ### 5.7 阶段七:L5应用层(第9周) - [ ] 实现`l5_application.rs`完整接口 - [ ] 集成钱包、DApp、浏览器、交易所接口 - [ ] 编写用户场景测试 - [ ] 编写使用示例 ### 5.8 阶段八:文档和示例(第10周) - [ ] 编写完整的API文档 - [ ] 编写架构设计文档 - [ ] 编写使用指南 - [ ] 创建示例项目(至少5个) - [ ] 录制视频教程 --- ## 六、验收标准 ### 6.1 代码质量 - [ ] 所有适配器100%完整实现,无简化版本 - [ ] 单元测试覆盖率 > 90% - [ ] 集成测试覆盖所有主要功能 - [ ] 无编译警告 - [ ] 通过Clippy检查 ### 6.2 文档质量 - [ ] 每个公共API都有完整的文档注释 - [ ] 提供至少5个完整的使用示例 - [ ] 架构设计文档完整清晰 - [ ] 使用指南详细易懂 ### 6.3 性能要求 - [ ] L0层操作 < 1ms - [ ] L1层RPC调用 < 100ms - [ ] L3层存储操作 < 10ms - [ ] L4层AI调用 < 5s ### 6.4 兼容性 - [ ] 支持Rust 1.70+ - [ ] 支持Linux、macOS、Windows - [ ] 支持WASM编译 --- ## 七、当前状态 **开始时间**: 2026-02-19 **当前阶段**: 阶段一 - 基础架构 **已完成**: - [x] 分析NAC公链层级架构 - [x] 分析现有模块结构 - [x] 设计完整的接口规范 - [x] 制定实施计划 **进行中**: - [ ] 创建适配器目录结构 - [ ] 实现统一适配器入口 **下一步**: - 创建`nac-sdk/src/adapters/`目录 - 实现`NACAdapter`统一入口 - 实现配置结构 --- ## 八、相关资源 - **工单链接**: 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-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` --- **最后更新**: 2026-02-19 **负责人**: NAC开发团队 **状态**: 进行中