NAC_Blockchain/nac-udm/API_SPECIFICATION.md

1875 lines
37 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# NAC UDM API规范文档
**版本**: 1.0.0
**作者**: NAC公链开发小组
**日期**: 2025-02-07
**状态**: 正式发布
---
## 📋 目录
1. [概述](#概述)
2. [架构设计](#架构设计)
3. [核心注册表系统API](#核心注册表系统api)
4. [基础原语类型API](#基础原语类型api)
5. [L2宪法治理层API](#l2宪法治理层api)
6. [L1多链协议层API](#l1多链协议层api)
7. [L0 CSNP网络层API](#l0-csnp网络层api)
8. [多语言绑定](#多语言绑定)
9. [错误处理](#错误处理)
10. [版本管理](#版本管理)
---
## 概述
NAC统一定义模块UDM是NewAssetChain区块链生态系统的**单一真理来源**Single Source of Truth统一管理所有类型定义、函数签名、常量、版本信息和协议规范。
### 核心特性
-**不使用任何ERC标准**ERC-20、ERC-721、ERC-1155等
-**不继承以太坊或其他链的实现**
-**不是P2P网络** - 使用CSNP宪政结构化网络协议
-**100% NAC原生设计**
-**专注于RWA真实世界资产应用场景**
-**基于CBPP宪政共识不需要投票治理**
-**支持Rust/Go/Charter多语言绑定**
### 设计哲学
> "宪法治下,节点产生区块,参与即是共识,交易扩张区块的大小和高度。"
---
## 架构设计
NAC采用**3层架构体系**
### L2: 宪法治理层 (Constitutional Governance Layer)
最高层级,定义整个系统的治理规则(**不是投票治理,而是规则定义层**
- **网络规则定义**: 连接规则、传播规则、惩罚条款(跨链适用)
- **跨链中继授权**: 授权跨链中继节点CCRN列表
- **宪法条款库**: 宪法收据CR验证规则
- **宪法执行引擎**: CEE管理与签发机制
### L1: 多链协议层 (Multi-Chain Protocol Layer)
核心协议层,实现"宪法即共识"
- **CBPP核心**: 宪法区块生产协议宪法收据CR、OPN、FBM、RVGP
- **ACC协议族**: 13个原生资产协议ACC-20, ACC-721, ACC-1155, ACC-RWA等
- **NVM 2.0**: 虚拟机层225个基础操作码 + 125个RWA专属指令
- **GNACS**: 全球资产分类系统48位编码
### L0: CSNP结构化网络层 (CSNP Structured Network Layer)
宪政结构化网络层提供5大核心组件**不是P2P网络**
- **GIDS**: 全域身份目录服务 - 多链DID解析与信誉聚合
- **MA-RCM**: 多链自适应连接管理器 - 跨链优化连接拓扑
- **AA-PE**: 资产感知传播引擎 - 基于GNACS的智能路由
- **FTAN**: 碎片化交易聚合网络 - 批量签名与传播
- **UCA**: 统一跨链审计器 - 跨链行为追踪与惩罚
---
## 核心注册表系统API
### UID (Unified Identifier)
统一标识符,用于唯一标识每个定义。
#### 数据结构
```rust
pub struct UID {
namespace: String, // 命名空间 (e.g., "nac.l1.cbpp.receipt")
}
```
#### 构造方法
```rust
// 创建新的UID
pub fn new(namespace: impl Into<String>) -> Self
// 从字符串解析UID
pub fn from_str(s: &str) -> Result<Self, String>
```
#### 查询方法
```rust
// 获取完整命名空间
pub fn namespace(&self) -> &str
// 获取层级l0, l1, l2
pub fn layer(&self) -> Option<&str>
// 获取模块名称
pub fn module(&self) -> Option<&str>
// 获取定义名称
pub fn definition(&self) -> Option<&str>
// 获取父UID
pub fn parent(&self) -> Option<UID>
// 获取子UID
pub fn child(&self, name: &str) -> UID
// 是否是另一个UID的祖先
pub fn is_ancestor_of(&self, other: &UID) -> bool
```
#### 示例
```rust
use nac_udm::registry::UID;
// 创建UID
let uid = UID::new("nac.l1.cbpp.receipt");
// 查询层级
assert_eq!(uid.layer(), Some("l1"));
assert_eq!(uid.module(), Some("cbpp"));
assert_eq!(uid.definition(), Some("receipt"));
// 父子关系
let parent = uid.parent().unwrap();
assert_eq!(parent.namespace(), "nac.l1.cbpp");
let child = uid.child("field1");
assert_eq!(child.namespace(), "nac.l1.cbpp.receipt.field1");
```
---
### Version (版本管理)
语义化版本管理遵循SemVer 2.0.0规范。
#### 数据结构
```rust
pub struct Version {
major: u32,
minor: u32,
patch: u32,
pre_release: Option<String>,
build_metadata: Option<String>,
}
```
#### 构造方法
```rust
// 创建新版本
pub fn new(major: u32, minor: u32, patch: u32) -> Self
// 从字符串解析版本
pub fn from_str(s: &str) -> Result<Self, String>
```
#### 版本操作
```rust
// 递增主版本号
pub fn bump_major(&mut self)
// 递增次版本号
pub fn bump_minor(&mut self)
// 递增补丁版本号
pub fn bump_patch(&mut self)
// 设置预发布标签
pub fn set_pre_release(&mut self, pre_release: impl Into<String>)
// 设置构建元数据
pub fn set_build_metadata(&mut self, metadata: impl Into<String>)
```
#### 版本比较
```rust
// 是否兼容(主版本号相同)
pub fn is_compatible_with(&self, other: &Version) -> bool
// 是否向后兼容(主版本号相同,次版本号>=
pub fn is_backward_compatible_with(&self, other: &Version) -> bool
```
#### 示例
```rust
use nac_udm::registry::Version;
// 创建版本
let mut v = Version::new(1, 2, 3);
assert_eq!(v.to_string(), "1.2.3");
// 递增版本
v.bump_minor();
assert_eq!(v.to_string(), "1.3.0");
// 版本比较
let v1 = Version::from_str("1.2.3").unwrap();
let v2 = Version::from_str("1.3.0").unwrap();
assert!(v1.is_compatible_with(&v2));
```
---
### Definition (定义抽象)
元定义系统,定义"什么是定义"。
#### 数据结构
```rust
pub struct Definition {
uid: UID,
version: Version,
name: String,
description: String,
definition_type: DefinitionType,
tags: Vec<String>,
dependencies: Vec<UID>,
deprecated: bool,
language_bindings: HashMap<Language, LanguageBinding>,
}
```
#### 定义类型
```rust
pub enum DefinitionType {
Type, // 类型定义
Function, // 函数定义
Constant, // 常量定义
Protocol, // 协议定义
Module, // 模块定义
Interface, // 接口定义
}
```
#### 构造方法
```rust
// 使用构建器模式创建定义
pub fn builder() -> DefinitionBuilder
// 构建器方法
impl DefinitionBuilder {
pub fn uid(mut self, uid: UID) -> Self
pub fn version(mut self, version: Version) -> Self
pub fn name(mut self, name: impl Into<String>) -> Self
pub fn description(mut self, description: impl Into<String>) -> Self
pub fn definition_type(mut self, dt: DefinitionType) -> Self
pub fn add_tag(mut self, tag: impl Into<String>) -> Self
pub fn add_dependency(mut self, dep: UID) -> Self
pub fn deprecated(mut self, deprecated: bool) -> Self
pub fn add_language_binding(mut self, lang: Language, binding: LanguageBinding) -> Self
pub fn build(self) -> Definition
}
```
#### 查询方法
```rust
// 获取UID
pub fn uid(&self) -> &UID
// 获取版本
pub fn version(&self) -> &Version
// 获取名称
pub fn name(&self) -> &str
// 获取描述
pub fn description(&self) -> &str
// 获取定义类型
pub fn definition_type(&self) -> &DefinitionType
// 获取标签
pub fn tags(&self) -> &[String]
// 获取依赖
pub fn dependencies(&self) -> &[UID]
// 是否已弃用
pub fn is_deprecated(&self) -> bool
// 获取语言绑定
pub fn language_binding(&self, lang: Language) -> Option<&LanguageBinding>
```
#### 示例
```rust
use nac_udm::registry::{Definition, DefinitionType, UID, Version, Language, LanguageBinding};
// 创建定义
let def = Definition::builder()
.uid(UID::new("nac.l1.cbpp.receipt"))
.version(Version::new(1, 0, 0))
.name("ConstitutionalReceipt")
.description("宪法收据,交易进入区块链的唯一门票")
.definition_type(DefinitionType::Type)
.add_tag("cbpp")
.add_tag("core")
.add_language_binding(
Language::Rust,
LanguageBinding::new("pub struct ConstitutionalReceipt { ... }")
)
.build();
// 查询定义
assert_eq!(def.name(), "ConstitutionalReceipt");
assert_eq!(def.version().to_string(), "1.0.0");
assert!(def.tags().contains(&"cbpp".to_string()));
```
---
### DefinitionRegistry (定义注册表)
线程安全的定义管理系统。
#### 数据结构
```rust
pub struct DefinitionRegistry {
// 内部使用Arc<RwLock<...>>实现线程安全
}
```
#### 注册方法
```rust
// 注册新定义
pub fn register(&self, definition: Definition) -> Result<(), String>
// 批量注册定义
pub fn register_batch(&self, definitions: Vec<Definition>) -> Result<(), String>
```
#### 查询方法
```rust
// 通过UID查询定义
pub fn get(&self, uid: &UID) -> Option<Definition>
// 通过UID和版本查询定义
pub fn get_version(&self, uid: &UID, version: &Version) -> Option<Definition>
// 获取最新版本
pub fn get_latest(&self, uid: &UID) -> Option<Definition>
// 获取所有版本
pub fn get_all_versions(&self, uid: &UID) -> Vec<Definition>
// 通过标签查询定义
pub fn find_by_tag(&self, tag: &str) -> Vec<Definition>
// 通过类型查询定义
pub fn find_by_type(&self, dt: &DefinitionType) -> Vec<Definition>
// 获取依赖关系
pub fn get_dependencies(&self, uid: &UID) -> Vec<UID>
// 获取反向依赖
pub fn get_dependents(&self, uid: &UID) -> Vec<UID>
```
#### 统计方法
```rust
// 获取定义总数
pub fn count(&self) -> usize
// 获取版本总数
pub fn version_count(&self) -> usize
// 按类型统计
pub fn count_by_type(&self, dt: &DefinitionType) -> usize
```
#### 示例
```rust
use nac_udm::registry::{DefinitionRegistry, Definition, UID};
// 创建注册表
let registry = DefinitionRegistry::new();
// 注册定义
registry.register(definition).unwrap();
// 查询定义
let uid = UID::new("nac.l1.cbpp.receipt");
let def = registry.get(&uid).unwrap();
println!("Found: {}", def.name());
// 按标签查询
let cbpp_defs = registry.find_by_tag("cbpp");
println!("Found {} CBPP definitions", cbpp_defs.len());
```
---
## 基础原语类型API
### Address (地址类型)
20字节地址类型用于标识账户、合约等实体。
#### 数据结构
```rust
pub struct Address([u8; 20]);
```
#### 构造方法
```rust
// 创建新地址
pub fn new(bytes: [u8; 20]) -> Self
// 从切片创建
pub fn from_slice(slice: &[u8]) -> Result<Self, String>
// 从十六进制字符串创建
pub fn from_hex(hex: &str) -> Result<Self, String>
// 零地址
pub fn zero() -> Self
```
#### 查询方法
```rust
// 获取字节数组
pub fn as_bytes(&self) -> &[u8; 20]
// 转换为十六进制字符串
pub fn to_hex(&self) -> String
// 是否为零地址
pub fn is_zero(&self) -> bool
```
#### 示例
```rust
use nac_udm::primitives::Address;
// 创建地址
let addr = Address::from_hex("0x1234567890123456789012345678901234567890").unwrap();
// 查询
assert!(!addr.is_zero());
assert_eq!(addr.to_hex(), "0x1234567890123456789012345678901234567890");
```
---
### Hash (哈希类型)
32字节哈希类型SHA256用于标识交易、区块等。
#### 数据结构
```rust
pub struct Hash([u8; 32]);
```
#### 构造方法
```rust
// 创建新哈希
pub fn new(bytes: [u8; 32]) -> Self
// 从切片创建
pub fn from_slice(slice: &[u8]) -> Result<Self, String>
// 从十六进制字符串创建
pub fn from_hex(hex: &str) -> Result<Self, String>
// 计算SHA256哈希
pub fn sha256(data: &[u8]) -> Self
// 零哈希
pub fn zero() -> Self
```
#### 查询方法
```rust
// 获取字节数组
pub fn as_bytes(&self) -> &[u8; 32]
// 转换为十六进制字符串
pub fn to_hex(&self) -> String
// 是否为零哈希
pub fn is_zero(&self) -> bool
```
#### 示例
```rust
use nac_udm::primitives::Hash;
// 计算哈希
let data = b"Hello, NAC!";
let hash = Hash::sha256(data);
// 查询
assert!(!hash.is_zero());
println!("Hash: {}", hash.to_hex());
```
---
### Timestamp (时间戳类型)
Unix时间戳类型u64秒级精度
#### 数据结构
```rust
pub struct Timestamp(u64);
```
#### 构造方法
```rust
// 当前时间
pub fn now() -> Self
// 从秒数创建
pub fn from_secs(secs: u64) -> Self
```
#### 查询方法
```rust
// 获取秒数
pub fn as_secs(&self) -> u64
// 是否过期
pub fn is_expired(&self, current: u64) -> bool
```
#### 时间操作
```rust
// 增加秒数
pub fn add_secs(&self, secs: u64) -> Self
// 减少秒数
pub fn sub_secs(&self, secs: u64) -> Self
```
#### 示例
```rust
use nac_udm::primitives::Timestamp;
// 当前时间
let now = Timestamp::now();
// 时间操作
let future = now.add_secs(3600); // 1小时后
let past = now.sub_secs(3600); // 1小时前
// 过期检查
assert!(!future.is_expired(now.as_secs()));
assert!(past.is_expired(now.as_secs()));
```
---
### Signature (签名类型)
数字签名类型(可变长度)。
#### 数据结构
```rust
pub struct Signature(Vec<u8>);
```
#### 构造方法
```rust
// 创建新签名
pub fn new(bytes: Vec<u8>) -> Self
// 从切片创建
pub fn from_slice(slice: &[u8]) -> Self
// 从十六进制字符串创建
pub fn from_hex(hex: &str) -> Result<Self, String>
// 空签名
pub fn empty() -> Self
```
#### 查询方法
```rust
// 获取字节数组
pub fn as_bytes(&self) -> &[u8]
// 转换为十六进制字符串
pub fn to_hex(&self) -> String
// 是否为空
pub fn is_empty(&self) -> bool
// 获取长度
pub fn len(&self) -> usize
```
#### 示例
```rust
use nac_udm::primitives::Signature;
// 创建签名
let sig = Signature::from_hex("0x1234...").unwrap();
// 查询
assert!(!sig.is_empty());
println!("Signature length: {}", sig.len());
```
---
## L2宪法治理层API
### ConstitutionalClause (宪法条款)
宪法条款定义。
#### 数据结构
```rust
pub struct ConstitutionalClause {
pub clause_id: u32,
pub title: String,
pub content: String,
pub version: String,
pub active: bool,
}
```
---
### NetworkRule (网络规则)
网络规则定义。
#### 数据结构
```rust
pub struct NetworkRule {
pub rule_id: u32,
pub rule_type: RuleType,
pub description: String,
pub parameters: Vec<(String, String)>,
}
pub enum RuleType {
Connection, // 连接规则
Propagation, // 传播规则
Validation, // 验证规则
Penalty, // 惩罚规则
}
```
---
### CrossChainRelayNode (跨链中继节点)
跨链中继节点授权。
#### 数据结构
```rust
pub struct CrossChainRelayNode {
pub node_address: Address,
pub authorized_chains: Vec<String>,
pub stake_amount: u128,
pub reputation_score: u8,
}
```
---
### PenaltyRecord (惩罚记录)
惩罚条款记录。
#### 数据结构
```rust
pub struct PenaltyRecord {
pub violator: Address,
pub violation_type: ViolationType,
pub penalty_amount: u128,
pub timestamp: u64,
}
pub enum ViolationType {
InvalidBlock, // 无效区块
DoubleSpend, // 双花攻击
MaliciousRelay, // 恶意中继
RuleViolation, // 规则违反
}
```
---
## L1多链协议层API
### CBPP模块
#### ConstitutionalReceipt (宪法收据)
宪法收据,交易进入区块链的唯一门票。
**数据结构**:
```rust
pub struct ConstitutionalReceipt {
pub receipt_id: Hash,
pub transaction_hash: Hash,
pub constitutional_hash: Hash,
pub clause_index: u32,
pub execution_result_hash: Hash,
pub timestamp: Timestamp,
pub validity_window: u64,
pub validator_signature: Signature,
pub validation_types: Vec<ValidationType>,
pub validation_results: Vec<ValidationResult>,
}
pub enum ValidationType {
KYC, // 身份验证
AML, // 反洗钱
AssetValuation, // 资产估值
Compliance, // 合规性
Custody, // 托管验证
Collateral, // 抵押验证
Insurance, // 保险验证
Governance, // 治理验证
}
pub struct ValidationResult {
pub validation_type: ValidationType,
pub passed: bool,
pub score: u8,
pub validator: Address,
pub timestamp: Timestamp,
}
```
**构造方法**:
```rust
pub fn new(
transaction_hash: Hash,
constitutional_hash: Hash,
clause_index: u32,
execution_result_hash: Hash,
timestamp: Timestamp,
validity_window: u64,
validator_signature: Signature,
) -> Self
```
**验证方法**:
```rust
// 验证收据是否有效
pub fn is_valid(&self, current_timestamp: u64) -> bool
// 验证收据是否过期
pub fn is_expired(&self, current_timestamp: u64) -> bool
// 计算收据ID
pub fn calculate_receipt_id(&self) -> Hash
// 添加验证结果
pub fn add_validation_result(&mut self, result: ValidationResult)
// 获取验证通过率
pub fn validation_pass_rate(&self) -> f64
// 计算收据权重
pub fn calculate_weight(&self) -> u64
```
**示例**:
```rust
use nac_udm::l1_protocol::cbpp::*;
use nac_udm::primitives::*;
// 创建宪法收据
let receipt = ConstitutionalReceipt::new(
tx_hash,
const_hash,
1,
result_hash,
Timestamp::now(),
3600,
signature,
);
// 添加验证结果
receipt.add_validation_result(ValidationResult {
validation_type: ValidationType::KYC,
passed: true,
score: 95,
validator: validator_addr,
timestamp: Timestamp::now(),
});
// 验证收据
if receipt.is_valid(Timestamp::now().as_secs()) {
println!("Receipt is valid!");
println!("Pass rate: {:.2}%", receipt.validation_pass_rate() * 100.0);
}
```
---
#### FluidBlock (流体区块)
流体区块支持DAG结构的三维坐标系统。
**数据结构**:
```rust
pub struct FluidBlock {
pub coordinates: BlockCoordinates,
pub parent_hashes: Vec<Hash>,
pub transactions: Vec<TransactionWithReceipt>,
pub timestamp: Timestamp,
pub producer: Address,
pub signature: Signature,
pub capacity: u64,
pub used_capacity: u64,
}
pub struct BlockCoordinates {
pub epoch: u64,
pub round: u64,
pub branch: u64,
}
pub struct TransactionWithReceipt {
pub transaction: Transaction,
pub receipt: ConstitutionalReceipt,
}
```
**构造方法**:
```rust
pub fn new(
coordinates: BlockCoordinates,
parent_hashes: Vec<Hash>,
producer: Address,
) -> Self
```
**区块操作**:
```rust
// 添加交易
pub fn add_transaction(&mut self, tx: TransactionWithReceipt) -> Result<(), String>
// 计算区块哈希
pub fn calculate_hash(&self) -> Hash
// 验证区块
pub fn validate(&self) -> Result<(), String>
// 是否已满
pub fn is_full(&self) -> bool
// 获取容量使用率
pub fn capacity_usage(&self) -> f64
```
---
#### OpenProductionNetwork (开放生产网络)
开放生产网络,管理区块生产者。
**数据结构**:
```rust
pub struct OpenProductionNetwork {
pub producers: Vec<BlockProducer>,
pub min_stake: u128,
pub reputation_threshold: u8,
}
pub struct BlockProducer {
pub address: Address,
pub stake: u128,
pub reputation: u8,
pub blocks_produced: u64,
pub last_active: Timestamp,
}
```
**生产者管理**:
```rust
// 添加生产者
pub fn add_producer(&mut self, producer: BlockProducer) -> Result<(), String>
// 移除生产者
pub fn remove_producer(&mut self, address: &Address) -> Result<(), String>
// 获取活跃生产者
pub fn get_active_producers(&self) -> Vec<&BlockProducer>
// 选择生产者
pub fn select_producer(&self, seed: u64) -> Option<&BlockProducer>
```
---
#### GossipProtocol (Gossip协议)
Gossip协议用于消息传播。
**数据结构**:
```rust
pub struct GossipProtocol {
pub peers: Vec<Address>,
pub message_cache: Vec<Hash>,
pub max_cache_size: usize,
}
pub struct GossipMessage {
pub message_id: Hash,
pub content: Vec<u8>,
pub timestamp: Timestamp,
pub sender: Address,
}
```
**消息传播**:
```rust
// 广播消息
pub fn broadcast(&self, message: &GossipMessage) -> Vec<Vec<u8>>
// 接收消息
pub fn receive(&mut self, message: GossipMessage) -> bool
// 是否已见过消息
pub fn has_seen(&self, message_id: &Hash) -> bool
```
---
### GNACS模块
#### GNACSCode (GNACS编码)
48位资产分类编码。
**数据结构**:
```rust
pub struct GNACSCode([u8; 6]);
```
**构造方法**:
```rust
// 创建新编码
pub fn new(bytes: [u8; 6]) -> Self
// 从十六进制创建
pub fn from_hex(hex: &str) -> Result<Self, String>
// 从组件创建
pub fn from_components(
jurisdiction: Jurisdiction,
asset_category: AssetCategory,
compliance_level: ComplianceLevel,
risk_level: RiskLevel,
) -> Self
```
**解析方法**:
```rust
// 获取司法辖区
pub fn jurisdiction(&self) -> Jurisdiction
// 获取资产类别
pub fn asset_category(&self) -> AssetCategory
// 获取合规级别
pub fn compliance_level(&self) -> ComplianceLevel
// 获取风险级别
pub fn risk_level(&self) -> RiskLevel
// 验证编码
pub fn validate(&self) -> bool
// 计算校验和
pub fn checksum(&self) -> u8
```
**格式转换**:
```rust
// 转换为十六进制
pub fn to_hex(&self) -> String
// 转换为人类可读格式
pub fn to_human_readable(&self) -> String
```
**示例**:
```rust
use nac_udm::l1_protocol::gnacs::*;
// 创建GNACS编码
let gnacs = GNACSCode::from_components(
Jurisdiction::US,
AssetCategory::RealEstate,
ComplianceLevel::High,
RiskLevel::Low,
);
// 解析编码
println!("Jurisdiction: {:?}", gnacs.jurisdiction());
println!("Category: {:?}", gnacs.asset_category());
println!("Compliance: {:?}", gnacs.compliance_level());
println!("Risk: {:?}", gnacs.risk_level());
// 验证
assert!(gnacs.validate());
```
---
#### AssetCategory (资产分类)
11种资产大类。
```rust
pub enum AssetCategory {
RealEstate, // 房地产
Equity, // 股权
Debt, // 债权
Commodity, // 商品
IntellectualProperty, // 知识产权
ArtCollectible, // 艺术收藏品
Vehicle, // 车辆
Machinery, // 机械设备
Inventory, // 存货
FinancialInstrument, // 金融工具
Other, // 其他
}
```
---
#### Jurisdiction (司法辖区)
17个司法辖区。
```rust
pub enum Jurisdiction {
US, // 美国
EU, // 欧盟
UK, // 英国
CN, // 中国
JP, // 日本
SG, // 新加坡
HK, // 香港
CH, // 瑞士
AE, // 阿联酋
AU, // 澳大利亚
CA, // 加拿大
KR, // 韩国
IN, // 印度
BR, // 巴西
ZA, // 南非
MX, // 墨西哥
Unknown, // 未知
}
```
---
#### ComplianceLevel (合规级别)
6个合规等级。
```rust
pub enum ComplianceLevel {
VeryHigh, // 极高 (100分)
High, // 高 (80分)
Medium, // 中 (60分)
Low, // 低 (40分)
VeryLow, // 极低 (20分)
Unknown, // 未知 (0分)
}
```
---
#### RiskLevel (风险等级)
6个风险等级。
```rust
pub enum RiskLevel {
VeryLow, // 极低 (20分)
Low, // 低 (40分)
Medium, // 中 (60分)
High, // 高 (80分)
VeryHigh, // 极高 (100分)
Unknown, // 未知 (0分)
}
```
---
### ACC协议族
#### ACC-20 (可替代代币)
**数据结构**:
```rust
pub struct ACC20Token {
pub name: String,
pub symbol: String,
pub decimals: u8,
pub total_supply: u128,
pub balances: HashMap<Address, u128>,
pub allowances: HashMap<Address, HashMap<Address, u128>>,
}
```
**核心方法**:
```rust
// 转账
pub fn transfer(&mut self, from: Address, to: Address, amount: u128) -> Result<(), String>
// 授权
pub fn approve(&mut self, owner: Address, spender: Address, amount: u128) -> Result<(), String>
// 授权转账
pub fn transfer_from(&mut self, spender: Address, from: Address, to: Address, amount: u128) -> Result<(), String>
// 铸造
pub fn mint(&mut self, to: Address, amount: u128) -> Result<(), String>
// 销毁
pub fn burn(&mut self, from: Address, amount: u128) -> Result<(), String>
// 查询余额
pub fn balance_of(&self, account: &Address) -> u128
// 查询授权额度
pub fn allowance(&self, owner: &Address, spender: &Address) -> u128
```
---
#### ACC-721 (不可替代代币)
**数据结构**:
```rust
pub struct ACC721Token {
pub name: String,
pub symbol: String,
pub owners: HashMap<u128, Address>,
pub balances: HashMap<Address, u128>,
pub token_approvals: HashMap<u128, Address>,
pub operator_approvals: HashMap<Address, HashMap<Address, bool>>,
}
```
**核心方法**:
```rust
// 铸造NFT
pub fn mint(&mut self, to: Address, token_id: u128) -> Result<(), String>
// 转移NFT
pub fn transfer(&mut self, from: Address, to: Address, token_id: u128) -> Result<(), String>
// 授权NFT
pub fn approve(&mut self, owner: Address, to: Address, token_id: u128) -> Result<(), String>
// 设置操作员
pub fn set_approval_for_all(&mut self, owner: Address, operator: Address, approved: bool)
// 查询所有者
pub fn owner_of(&self, token_id: u128) -> Option<Address>
// 查询余额
pub fn balance_of(&self, owner: &Address) -> u128
// 销毁NFT
pub fn burn(&mut self, token_id: u128) -> Result<(), String>
```
---
#### ACC-1155 (多代币标准)
**数据结构**:
```rust
pub struct ACC1155Token {
pub balances: HashMap<Address, HashMap<u128, u128>>,
pub operator_approvals: HashMap<Address, HashMap<Address, bool>>,
}
```
**核心方法**:
```rust
// 单个转账
pub fn safe_transfer_from(&mut self, from: Address, to: Address, id: u128, amount: u128) -> Result<(), String>
// 批量转账
pub fn safe_batch_transfer_from(&mut self, from: Address, to: Address, ids: Vec<u128>, amounts: Vec<u128>) -> Result<(), String>
// 查询余额
pub fn balance_of(&self, account: &Address, id: u128) -> u128
// 批量查询余额
pub fn balance_of_batch(&self, accounts: Vec<Address>, ids: Vec<u128>) -> Vec<u128>
// 设置操作员
pub fn set_approval_for_all(&mut self, owner: Address, operator: Address, approved: bool)
// 查询操作员
pub fn is_approved_for_all(&self, owner: &Address, operator: &Address) -> bool
```
---
#### ACC-RWA (RWA资产标准)
**数据结构**:
```rust
pub struct RWAAsset {
pub asset_id: Hash,
pub gnacs_code: GNACSCode,
pub owner: Address,
pub custodian: Address,
pub valuation: u128,
pub metadata_uri: String,
pub constitutional_receipt: Hash,
}
```
**核心方法**:
```rust
// 创建RWA资产
pub fn create(gnacs_code: GNACSCode, owner: Address, custodian: Address) -> Self
// 转移所有权
pub fn transfer_ownership(&mut self, new_owner: Address, receipt: Hash) -> Result<(), String>
// 更新估值
pub fn update_valuation(&mut self, new_valuation: u128, appraiser: Address) -> Result<(), String>
// 验证合规性
pub fn verify_compliance(&self) -> bool
```
---
#### ACC-Compliance (合规协议)
**数据结构**:
```rust
pub struct ComplianceRecord {
pub entity: Address,
pub jurisdiction: Jurisdiction,
pub compliance_level: ComplianceLevel,
pub kyc_verified: bool,
pub aml_verified: bool,
pub accreditation_verified: bool,
pub verification_date: Timestamp,
pub expiry_date: Timestamp,
pub verifier: Address,
pub document_hash: Hash,
}
```
---
#### ACC-Valuation (估值协议)
**数据结构**:
```rust
pub struct ValuationReport {
pub asset_id: Hash,
pub valuation_amount: u128,
pub currency: String,
pub valuation_method: String,
pub appraiser: Address,
pub report_date: Timestamp,
pub validity_period: u64,
pub confidence_score: u8,
pub report_hash: Hash,
}
```
---
#### ACC-Custody (托管协议)
**数据结构**:
```rust
pub struct CustodyRecord {
pub asset_id: Hash,
pub custodian: Address,
pub owner: Address,
pub custody_type: CustodyType,
pub start_date: Timestamp,
pub end_date: Option<Timestamp>,
pub terms_hash: Hash,
}
pub enum CustodyType {
Physical, // 实物托管
Digital, // 数字托管
Legal, // 法律托管
Escrow, // 第三方托管
}
```
---
#### ACC-Collateral (抵押协议)
**数据结构**:
```rust
pub struct CollateralRecord {
pub collateral_id: Hash,
pub asset_id: Hash,
pub borrower: Address,
pub lender: Address,
pub collateral_value: u128,
pub loan_amount: u128,
pub ltv_ratio: u8,
pub start_date: Timestamp,
pub maturity_date: Timestamp,
}
```
---
#### ACC-Redemption (赎回协议)
**数据结构**:
```rust
pub struct RedemptionRequest {
pub request_id: Hash,
pub asset_id: Hash,
pub requester: Address,
pub redemption_amount: u128,
pub request_date: Timestamp,
pub status: RedemptionStatus,
}
pub enum RedemptionStatus {
Pending,
Approved,
Rejected,
Completed,
}
```
---
#### ACC-Insurance (保险协议)
**数据结构**:
```rust
pub struct InsurancePolicy {
pub policy_id: Hash,
pub asset_id: Hash,
pub insured: Address,
pub insurer: Address,
pub coverage_amount: u128,
pub premium: u128,
pub start_date: Timestamp,
pub end_date: Timestamp,
pub policy_terms_hash: Hash,
}
```
---
#### ACC-Governance (治理协议)
**数据结构**:
```rust
pub struct GovernanceProposal {
pub proposal_id: Hash,
pub proposer: Address,
pub title: String,
pub description: String,
pub voting_start: Timestamp,
pub voting_end: Timestamp,
pub votes_for: u128,
pub votes_against: u128,
pub status: ProposalStatus,
}
pub enum ProposalStatus {
Pending,
Active,
Passed,
Rejected,
Executed,
}
```
---
#### ACC-XTZH (XTZH稳定币协议)
**数据结构**:
```rust
pub struct XTZHToken {
pub total_supply: u128,
pub reserve_assets: Vec<ReserveAsset>,
pub peg_rate: u128,
pub balances: HashMap<Address, u128>,
}
pub struct ReserveAsset {
pub asset_type: String,
pub amount: u128,
pub value_in_sdr: u128,
}
```
---
#### ACC-Reserve (储备协议)
**数据结构**:
```rust
pub struct ReservePool {
pub pool_id: Hash,
pub assets: Vec<ReserveAsset>,
pub total_value: u128,
pub manager: Address,
pub last_audit: Timestamp,
}
```
---
### NVM 2.0模块
#### OpCode (操作码)
350个操作码225个基础 + 125个RWA专属
**数据结构**:
```rust
pub enum OpCode {
// 基础操作码 (0x00-0xE0)
STOP = 0x00,
ADD = 0x01,
MUL = 0x02,
// ... 225个基础操作码
// RWA专属操作码 (0xE1-0xFF)
CR_CREATE = 0xE1, // 创建宪法收据
CR_VERIFY = 0xE2, // 验证宪法收据
CR_GET = 0xE3, // 获取宪法收据
CR_REVOKE = 0xE4, // 撤销宪法收据
CR_EXTEND = 0xE5, // 延长宪法收据
GNACS_ENCODE = 0xE6, // GNACS编码
GNACS_DECODE = 0xE7, // GNACS解码
GNACS_VALIDATE = 0xE8, // GNACS验证
GNACS_CATEGORY = 0xE9, // 获取资产类别
GNACS_JURISDICTION = 0xEA, // 获取司法辖区
ACC20_TRANSFER = 0xEB, // ACC-20转账
ACC20_APPROVE = 0xEC, // ACC-20授权
ACC20_MINT = 0xED, // ACC-20铸造
ACC20_BURN = 0xEE, // ACC-20销毁
ACC20_BALANCE = 0xEF, // ACC-20余额查询
ACC721_MINT = 0xF6, // ACC-721铸造
ACC721_TRANSFER = 0xF7, // ACC-721转移
ACC721_OWNER = 0xF8, // ACC-721所有者查询
ACC721_BURN = 0xF9, // ACC-721销毁
}
```
**方法**:
```rust
// 获取操作码名称
pub fn name(&self) -> &'static str
// 是否是RWA专属操作码
pub fn is_rwa_specific(&self) -> bool
// 从字节创建操作码
pub fn from_u8(byte: u8) -> Option<Self>
```
---
#### Instruction (指令)
**数据结构**:
```rust
pub struct Instruction {
pub opcode: OpCode,
pub operands: Vec<u8>,
pub gas_cost: u64,
}
```
**构造方法**:
```rust
// 创建新指令
pub fn new(opcode: OpCode) -> Self
// 创建带操作数的指令
pub fn with_operands(opcode: OpCode, operands: Vec<u8>) -> Self
```
---
#### GasCalculator (Gas计量)
**方法**:
```rust
// 计算操作码的Gas成本
pub fn calculate(opcode: &OpCode) -> u64
```
**Gas成本表**:
| 操作码类型 | Gas成本 |
|-----------|---------|
| STOP | 0 |
| ADD, SUB | 3 |
| MUL, DIV | 5 |
| SLOAD | 200 |
| SSTORE | 20,000 |
| CR_CREATE | 50,000 |
| CR_VERIFY | 10,000 |
| GNACS_ENCODE | 5,000 |
| ACC20_TRANSFER | 21,000 |
---
## L0 CSNP网络层API
### GIDS (全域身份目录服务)
**数据结构**:
```rust
pub struct GlobalIdentity {
pub address: Address,
pub identity_type: IdentityType,
pub verification_level: u8,
pub metadata: Vec<(String, String)>,
}
pub enum IdentityType {
Individual, // 个人
Organization, // 组织
SmartContract, // 智能合约
RelayNode, // 中继节点
}
```
---
### MA-RCM (多链自适应连接管理器)
**数据结构**:
```rust
pub struct ChainConnection {
pub chain_id: String,
pub connection_type: ConnectionType,
pub latency_ms: u32,
pub bandwidth_mbps: u32,
}
pub enum ConnectionType {
Direct, // 直连
Relay, // 中继
Bridge, // 桥接
}
```
---
### AA-PE (资产感知传播引擎)
**数据结构**:
```rust
pub struct AssetAwarePropagation {
pub asset_id: Hash,
pub priority: u8,
pub propagation_strategy: PropagationStrategy,
}
pub enum PropagationStrategy {
Broadcast, // 广播
Targeted, // 定向
Layered, // 分层
}
```
---
### FTAN (碎片化交易聚合网络)
**数据结构**:
```rust
pub struct FragmentedTransaction {
pub tx_id: Hash,
pub fragments: Vec<TransactionFragment>,
pub total_fragments: u32,
}
pub struct TransactionFragment {
pub fragment_id: u32,
pub data: Vec<u8>,
}
```
---
### UCA (统一跨链审计器)
**数据结构**:
```rust
pub struct CrossChainAuditRecord {
pub audit_id: Hash,
pub source_chain: String,
pub target_chain: String,
pub transaction_hash: Hash,
pub auditor: Address,
pub status: AuditStatus,
}
pub enum AuditStatus {
Pending, // 待审计
Verified, // 已验证
Rejected, // 已拒绝
}
```
---
## 多语言绑定
UDM支持Rust、Go、Charter三种语言的绑定。
### 语言枚举
```rust
pub enum Language {
Rust,
Go,
Charter,
}
```
### 语言绑定
```rust
pub struct LanguageBinding {
pub code: String,
pub imports: Vec<String>,
pub type_mappings: HashMap<String, String>,
}
```
### 类型映射表
| UDM类型 | Rust | Go | Charter |
|---------|------|----|---------|
| u8 | u8 | uint8 | u8 |
| u64 | u64 | uint64 | u64 |
| u128 | u128 | *big.Int | u128 |
| u256 | U256 | *big.Int | u256 |
| address | Address | [20]byte | address |
| hash | Hash | [32]byte | hash |
| bool | bool | bool | bool |
| string | String | string | string |
| bytes | Vec<u8> | []byte | bytes |
---
## 错误处理
所有可能失败的操作都返回`Result<T, String>`类型。
### 常见错误
| 错误类型 | 描述 |
|---------|------|
| `InvalidAddress` | 无效的地址格式 |
| `InvalidHash` | 无效的哈希格式 |
| `InvalidGNACSCode` | 无效的GNACS编码 |
| `ReceiptExpired` | 宪法收据已过期 |
| `InsufficientBalance` | 余额不足 |
| `UnauthorizedAccess` | 未授权访问 |
| `InvalidSignature` | 无效的签名 |
| `DuplicateDefinition` | 重复的定义 |
| `VersionConflict` | 版本冲突 |
### 错误处理示例
```rust
use nac_udm::primitives::Address;
match Address::from_hex("0xinvalid") {
Ok(addr) => println!("Address: {}", addr.to_hex()),
Err(e) => eprintln!("Error: {}", e),
}
```
---
## 版本管理
UDM遵循语义化版本管理SemVer 2.0.0)。
### 版本号格式
```
MAJOR.MINOR.PATCH[-PRE_RELEASE][+BUILD_METADATA]
```
### 版本兼容性规则
- **主版本号MAJOR**: 不兼容的API变更
- **次版本号MINOR**: 向后兼容的功能新增
- **补丁版本号PATCH**: 向后兼容的问题修复
### 版本查询
```rust
use nac_udm::VERSION;
println!("UDM Version: {}", VERSION);
```
---
## 附录
### A. 完整的模块清单
| 模块 | 描述 | UID前缀 |
|------|------|---------|
| registry | 核心注册表系统 | nac.registry |
| primitives | 基础原语类型 | nac.primitives |
| l2_governance | L2宪法治理层 | nac.l2 |
| l1_protocol | L1多链协议层 | nac.l1 |
| l0_native | L0 CSNP网络层 | nac.l0 |
### B. 完整的ACC协议清单
| 协议 | 描述 | UID |
|------|------|-----|
| ACC-20 | 可替代代币 | nac.l1.acc.acc20 |
| ACC-721 | 不可替代代币 | nac.l1.acc.acc721 |
| ACC-1155 | 多代币标准 | nac.l1.acc.acc1155 |
| ACC-RWA | RWA资产标准 | nac.l1.acc.rwa |
| ACC-Compliance | 合规协议 | nac.l1.acc.compliance |
| ACC-Valuation | 估值协议 | nac.l1.acc.valuation |
| ACC-Custody | 托管协议 | nac.l1.acc.custody |
| ACC-Collateral | 抵押协议 | nac.l1.acc.collateral |
| ACC-Redemption | 赎回协议 | nac.l1.acc.redemption |
| ACC-Insurance | 保险协议 | nac.l1.acc.insurance |
| ACC-Governance | 治理协议 | nac.l1.acc.governance |
| ACC-XTZH | XTZH稳定币协议 | nac.l1.acc.xtzh |
| ACC-Reserve | 储备协议 | nac.l1.acc.reserve |
### C. 完整的NVM操作码清单
详见[NVM 2.0模块](#nvm-20模块)章节。
### D. 参考资源
- NAC官方网站: https://newassetchain.io
- NAC技术白皮书: https://docs.newassetchain.io/whitepaper
- UDM GitHub仓库: https://github.com/newassetchain/nac-udm
- CSNP协议规范: https://docs.newassetchain.io/csnp
- CBPP共识协议: https://docs.newassetchain.io/cbpp
- GNACS编码标准: https://docs.newassetchain.io/gnacs
---
**文档结束**
**版本**: 1.0.0
**最后更新**: 2025-02-07
**维护者**: NAC公链开发小组
**许可证**: MIT License