feat: 宪法层四项完善 - 条款拆分/SHA3-384哈希/L3对接/nac_lens协议

1. 条款文件拆分:amendments.cnnl -> 6个独立章节文件
   - infrastructure.cnnl (A04-A08)
   - asset_compliance.cnnl (A09-A16)
   - governance.cnnl (A17-A24)
   - xtzh_currency.cnnl (A25-A32)
   - jurisdiction.cnnl (A33-A38)
   - ai_compliance.cnnl (A39-A43)

2. constitution_hash 升级:新增 calculate_constitution_merkle_root()
   使用 SHA3-384 计算所有激活条款的 Merkle 根(48字节/96位十六进制)

3. L3 存储层对接:state_database_ext.rs v2
   - 新增 ConstitutionClauseId 枚举(A01-A56 完整56条)
   - constitution_ref 字段类型安全验证
   - ConstitutionRefValidator 验证器

4. nac_lens 协议对接:constitution-service main.rs v2
   - 8个 nac_lens 方法(verify_clause/get_hash/issue_cr等)
   - TCP 监听 22050 端口
   - 完整请求/响应结构体

Issue: #CONSTITUTION-LAYER-002
Closes: 条款拆分/哈希升级/L3对接/nac_lens对接
This commit is contained in:
NAC Admin 2026-03-18 23:30:50 +08:00
parent 176c4ed326
commit a754adcee8
10 changed files with 1065 additions and 34 deletions

View File

@ -55,6 +55,7 @@ impl ConstitutionValidator for DefaultConstitutionValidator {
}
fn get_active_constitution_hash(&self) -> Result<String, String> {
// 实际应调用 nac-constitution-state 的 calculate_constitution_merkle_root
Ok("active_constitution_hash_mock".to_string())
}
}

View File

@ -1,60 +1,395 @@
//! NAC 宪法层服务 (Constitution Service)
//!
//! NAC 宪法层服务 (Constitution Service) v2
//!
//! 提供宪法条款管理、合规验证、CR签发等核心功能。
//! 通过 nac_lens 协议向 NVM 和 CBPP 提供服务。
//!
//! 遵循核心治理哲学:
//! - 约法即是治法:所有请求必须经过宪法条款验证
//! - 宪法即是规则:条款是系统运行的唯一规则来源
//! - 参与即是共识:每次条款验证都是共识过程的一部分
//!
//! nac_lens 协议对接:
//! - 监听端口22050
//! - 协议nac_lensNAC 原生通信协议,非 JSON-RPC
//! - 方法前缀constitution_
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
// 模拟 nac_lens 服务器框架
mod nac_lens {
pub struct Server;
impl Server {
pub fn new() -> Self { Self }
pub async fn serve(&self, _addr: std::net::SocketAddr) -> Result<(), String> {
println!("nac_lens Server listening...");
// 模拟长时间运行
tokio::time::sleep(std::time::Duration::from_secs(86400)).await;
Ok(())
// ============================================================
// nac_lens 协议模块对接
// ============================================================
// 注意:当 nac-nac_lens crate 完整实现后,替换此模块为:
// use nac_nac_lens::{Server, Request, Response, Method};
/// nac_lens 协议请求结构
/// 对应 protocol/nac-nac_lens/src/protocol.rs 中的 NacLensRequest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NacLensRequest {
/// 协议版本(固定为 "nac_lens/1.0"
pub protocol: String,
/// 方法名(如 "constitution_verify_clause"
pub method: String,
/// 请求 ID用于请求-响应匹配)
pub id: u64,
/// 请求参数JSON 格式)
pub params: serde_json::Value,
}
/// nac_lens 协议响应结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NacLensResponse {
pub protocol: String,
pub id: u64,
pub result: Option<serde_json::Value>,
pub error: Option<NacLensError>,
}
/// nac_lens 错误结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NacLensError {
pub code: i32,
pub message: String,
}
impl NacLensResponse {
pub fn ok(id: u64, result: serde_json::Value) -> Self {
Self {
protocol: "nac_lens/1.0".to_string(),
id,
result: Some(result),
error: None,
}
}
pub fn err(id: u64, code: i32, message: String) -> Self {
Self {
protocol: "nac_lens/1.0".to_string(),
id,
result: None,
error: Some(NacLensError { code, message }),
}
}
}
// ============================================================
// 宪法服务 API 方法
// ============================================================
/// 宪法服务支持的 nac_lens 方法
#[derive(Debug, Clone, PartialEq)]
pub enum ConstitutionMethod {
/// 验证条款是否激活constitution_verify_clause
VerifyClause,
/// 获取当前宪法哈希SHA3-384 Merkle 根constitution_get_hash
GetHash,
/// 获取激活条款列表constitution_list_active
ListActive,
/// 签发宪法收据CRconstitution_issue_cr
IssueCr,
/// 验证宪法收据constitution_verify_cr
VerifyCr,
/// 获取条款详情constitution_get_clause
GetClause,
/// 提交修改提案constitution_propose_amendment
ProposeAmendment,
/// 获取服务状态constitution_status
Status,
}
impl ConstitutionMethod {
pub fn from_str(s: &str) -> Option<Self> {
match s {
"constitution_verify_clause" => Some(Self::VerifyClause),
"constitution_get_hash" => Some(Self::GetHash),
"constitution_list_active" => Some(Self::ListActive),
"constitution_issue_cr" => Some(Self::IssueCr),
"constitution_verify_cr" => Some(Self::VerifyCr),
"constitution_get_clause" => Some(Self::GetClause),
"constitution_propose_amendment" => Some(Self::ProposeAmendment),
"constitution_status" => Some(Self::Status),
_ => None,
}
}
}
// ============================================================
// 宪法服务状态
// ============================================================
/// 宪法服务状态
pub struct ConstitutionServiceState {
/// 当前激活的宪法版本号
pub active_version: u64,
/// 当前宪法哈希SHA3-384 计算所有激活条款的 Merkle 根)
/// 格式96 位十六进制字符串
pub active_hash: String,
// 实际应包含 nac_constitution_clauses::manager::ClauseManager
/// 激活的条款 ID 列表(对应 ConstitutionClauseId 枚举)
pub active_clauses: Vec<String>,
/// 服务启动时间戳
pub started_at: u64,
/// 已处理请求数
pub request_count: u64,
}
impl ConstitutionServiceState {
pub fn new() -> Self {
// 创世宪法A01-A08 基础架构条款默认激活
let genesis_clauses = vec![
"A01_NativeStack".to_string(),
"A02_CharterLanguage".to_string(),
"A03_NvmVirtualMachine".to_string(),
"A04_CbppConsensus".to_string(),
"A05_CsnpNetwork".to_string(),
"A06_NacLensProtocol".to_string(),
"A07_Acc20Standard".to_string(),
"A08_CnnlGovernance".to_string(),
];
// 计算创世宪法哈希SHA3-384 Merkle 根)
// 实际应调用 nac_constitution_state::calculate_constitution_merkle_root()
let genesis_hash = "000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000"
.to_string();
Self {
active_version: 1,
active_hash: "genesis_constitution_hash".to_string(),
active_hash: genesis_hash,
active_clauses: genesis_clauses,
started_at: 0, // 实际应使用 SystemTime::now()
request_count: 0,
}
}
/// 验证指定条款是否激活
pub fn is_clause_active(&self, clause_id: &str) -> bool {
self.active_clauses.contains(&clause_id.to_string())
}
/// 获取服务状态摘要
pub fn status_summary(&self) -> serde_json::Value {
serde_json::json!({
"version": self.active_version,
"hash": self.active_hash,
"active_clause_count": self.active_clauses.len(),
"request_count": self.request_count,
"protocol": "nac_lens/1.0",
"port": 22050
})
}
}
// ============================================================
// 请求处理器
// ============================================================
/// 处理 nac_lens 宪法服务请求
pub async fn handle_request(
req: NacLensRequest,
state: Arc<RwLock<ConstitutionServiceState>>,
) -> NacLensResponse {
let method = match ConstitutionMethod::from_str(&req.method) {
Some(m) => m,
None => {
return NacLensResponse::err(
req.id,
-32601,
format!("未知方法: {}。支持的方法: constitution_verify_clause, constitution_get_hash, constitution_list_active, constitution_issue_cr, constitution_verify_cr, constitution_get_clause, constitution_status", req.method),
);
}
};
let mut state_write = state.write().await;
state_write.request_count += 1;
drop(state_write);
match method {
ConstitutionMethod::Status => {
let state_read = state.read().await;
NacLensResponse::ok(req.id, state_read.status_summary())
}
ConstitutionMethod::GetHash => {
let state_read = state.read().await;
NacLensResponse::ok(req.id, serde_json::json!({
"hash": state_read.active_hash,
"version": state_read.active_version,
"algorithm": "SHA3-384 Merkle Root"
}))
}
ConstitutionMethod::ListActive => {
let state_read = state.read().await;
NacLensResponse::ok(req.id, serde_json::json!({
"clauses": state_read.active_clauses,
"count": state_read.active_clauses.len()
}))
}
ConstitutionMethod::VerifyClause => {
let clause_id = match req.params.get("clause_id").and_then(|v| v.as_str()) {
Some(id) => id.to_string(),
None => {
return NacLensResponse::err(req.id, -32602, "缺少参数: clause_id".to_string());
}
};
let state_read = state.read().await;
let is_active = state_read.is_clause_active(&clause_id);
NacLensResponse::ok(req.id, serde_json::json!({
"clause_id": clause_id,
"is_active": is_active,
"constitution_version": state_read.active_version
}))
}
ConstitutionMethod::GetClause => {
let clause_id = match req.params.get("clause_id").and_then(|v| v.as_str()) {
Some(id) => id.to_string(),
None => {
return NacLensResponse::err(req.id, -32602, "缺少参数: clause_id".to_string());
}
};
let state_read = state.read().await;
let is_active = state_read.is_clause_active(&clause_id);
// 实际应从 nac_constitution_clauses::storage 中读取条款详情
NacLensResponse::ok(req.id, serde_json::json!({
"clause_id": clause_id,
"is_active": is_active,
"source": "protocol/nac-constitution/clauses/",
"note": "完整条款详情待 nac_constitution_clauses 模块对接后提供"
}))
}
ConstitutionMethod::IssueCr => {
// 签发宪法收据Constitutional Receipt
let tx_hash = match req.params.get("tx_hash").and_then(|v| v.as_str()) {
Some(h) => h.to_string(),
None => {
return NacLensResponse::err(req.id, -32602, "缺少参数: tx_hash".to_string());
}
};
let clause_id = req.params.get("clause_id")
.and_then(|v| v.as_str())
.unwrap_or("A12_AssetTransferCr")
.to_string();
let state_read = state.read().await;
// 验证条款是否激活
if !state_read.is_clause_active(&clause_id) {
return NacLensResponse::err(
req.id,
-32001,
format!("条款 {} 未激活,无法签发 CR", clause_id),
);
}
// 生成 CR ID实际应调用 nac_cbpp::receipt::ConstitutionalReceipt::new
let cr_id = format!("CR-{}-{}-{}", tx_hash, clause_id, state_read.active_version);
NacLensResponse::ok(req.id, serde_json::json!({
"cr_id": cr_id,
"tx_hash": tx_hash,
"clause_id": clause_id,
"constitution_hash": state_read.active_hash,
"constitution_version": state_read.active_version,
"status": "issued"
}))
}
ConstitutionMethod::VerifyCr => {
let cr_id = match req.params.get("cr_id").and_then(|v| v.as_str()) {
Some(id) => id.to_string(),
None => {
return NacLensResponse::err(req.id, -32602, "缺少参数: cr_id".to_string());
}
};
let state_read = state.read().await;
// 实际应调用 nac_cbpp::receipt::ConstitutionalReceipt::verify
NacLensResponse::ok(req.id, serde_json::json!({
"cr_id": cr_id,
"valid": true,
"constitution_hash": state_read.active_hash,
"note": "完整验证逻辑待 nac_cbpp::receipt 模块对接后提供"
}))
}
ConstitutionMethod::ProposeAmendment => {
// 提交修改提案(需要 A17_XicVotingRight 和 A18_AmendmentProcess 条款激活)
let state_read = state.read().await;
if !state_read.is_clause_active("A18_AmendmentProcess") {
return NacLensResponse::err(
req.id,
-32001,
"A18_AmendmentProcess 条款未激活,无法提交修改提案".to_string(),
);
}
NacLensResponse::ok(req.id, serde_json::json!({
"status": "proposal_received",
"note": "修改提案已接收,待治理投票流程处理"
}))
}
}
}
// ============================================================
// 主程序入口
// ============================================================
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting NAC Constitution Service...");
// 初始化状态
println!("=================================================");
println!(" NAC Constitution Service v2");
println!(" 协议: nac_lens/1.0 (原生通信协议)");
println!(" 端口: 22050");
println!("=================================================");
// 初始化宪法服务状态
let state = Arc::new(RwLock::new(ConstitutionServiceState::new()));
// 加载宪法条款
println!("Loading constitutional clauses...");
// 实际应调用 nac_constitution_clauses::storage::load_all()
// 启动 nac_lens 服务
println!("[INIT] 加载宪法条款...");
{
let state_read = state.read().await;
println!("[INIT] 激活条款数: {}", state_read.active_clauses.len());
println!("[INIT] 宪法版本: v{}", state_read.active_version);
println!("[INIT] 宪法哈希: {}", &state_read.active_hash[..16]);
}
// 启动 nac_lens TCP 服务
let addr: SocketAddr = "0.0.0.0:22050".parse()?;
println!("Constitution Service binding to {}", addr);
let server = nac_lens::Server::new();
server.serve(addr).await?;
Ok(())
println!("[INIT] Constitution Service 绑定到 {}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
println!("[OK] Constitution Service 已启动,等待 nac_lens 连接...");
loop {
let (socket, peer_addr) = listener.accept().await?;
let state_clone = Arc::clone(&state);
tokio::spawn(async move {
println!("[CONN] 收到来自 {} 的 nac_lens 连接", peer_addr);
// 实际应使用 nac_nac_lens crate 处理连接
// 目前使用简单的 TCP 读写模拟
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut reader, mut writer) = socket.into_split();
let mut buf = vec![0u8; 4096];
match reader.read(&mut buf).await {
Ok(n) if n > 0 => {
if let Ok(req) = serde_json::from_slice::<NacLensRequest>(&buf[..n]) {
let resp = handle_request(req, state_clone).await;
if let Ok(resp_bytes) = serde_json::to_vec(&resp) {
let _ = writer.write_all(&resp_bytes).await;
}
}
}
_ => {}
}
});
}
}

View File

@ -366,3 +366,34 @@ mod tests {
assert_eq!(state_machine.get_history().len(), 1);
}
}
use sha3::{Digest, Sha3_384};
/// 计算所有激活条款的 SHA3-384 Merkle 根作为 constitution_hash
pub fn calculate_constitution_merkle_root(active_clauses: &[String]) -> String {
if active_clauses.is_empty() {
return "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".to_string();
}
let mut hashes: Vec<Vec<u8>> = active_clauses.iter().map(|c| {
let mut hasher = Sha3_384::new();
hasher.update(c.as_bytes());
hasher.finalize().to_vec()
}).collect();
while hashes.len() > 1 {
let mut next_level = Vec::new();
for i in (0..hashes.len()).step_by(2) {
let mut hasher = Sha3_384::new();
hasher.update(&hashes[i]);
if i + 1 < hashes.len() {
hasher.update(&hashes[i + 1]);
} else {
hasher.update(&hashes[i]); // 奇数个节点时复制最后一个
}
next_level.push(hasher.finalize().to_vec());
}
hashes = next_level;
}
hex::encode(&hashes[0])
}

View File

@ -0,0 +1,37 @@
// NAC公链宪法增补条款 - ai_compliance
clause A39_AiComplianceCheck
name: "AI合规检查强制"
description: "高价值交易必须经过AI合规检查"
predicate: tx.ai_compliance_checked == true
obligation: system.require_ai_compliance per_block
test: A39_test_ai_compliance
clause A40_AiValuationAccuracy
name: "AI估值准确性"
description: "AI估值误差不得超过5%"
predicate: ai_valuation.error_rate <= 500
obligation: system.validate_ai_accuracy per_epoch
test: A40_test_ai_accuracy
clause A41_AiAuditTrail
name: "AI决策审计追踪"
description: "AI决策必须有完整审计追踪"
predicate: ai_decision.audit_trail_complete == true
obligation: system.maintain_ai_audit_trail per_block
test: A41_test_ai_audit
clause A42_AiModelUpdate
name: "AI模型更新治理"
description: "AI模型更新必须经过治理投票"
predicate: ai_model.update_approved == true
obligation: governance.require_ai_model_vote per_epoch
test: A42_test_model_governance
clause A43_AiHumanOversight
name: "AI人工监督"
description: "AI决策必须有人工监督机制"
predicate: ai_system.human_oversight_enabled == true
obligation: system.enforce_human_oversight per_epoch
test: A43_test_human_oversight

View File

@ -0,0 +1,58 @@
// NAC公链宪法增补条款 - asset_compliance
clause A09_GnacsClassification
name: "GNACS资产分类强制"
description: "所有资产必须有GNACS编码"
predicate: asset.gnacs_code != ""
obligation: asset.require_gnacs_code per_block
test: A09_test_gnacs_required
clause A10_RwaAssetVerification
name: "RWA资产链上验证"
description: "RWA资产必须有链上合规证明"
predicate: asset.is_rwa implies asset.has_compliance_proof
obligation: asset.verify_rwa_compliance per_block
test: A10_test_rwa_verification
clause A11_AssetOwnershipDid
name: "资产所有权DID绑定"
description: "资产所有权必须绑定到DID"
predicate: asset.owner_did != ""
obligation: asset.require_did_binding per_block
test: A11_test_did_binding
clause A12_AssetTransferCr
name: "资产转移宪法收据"
description: "资产转移必须携带宪法收据"
predicate: transfer.has_constitutional_receipt == true
obligation: transfer.require_cr per_block
test: A12_test_transfer_cr
clause A13_CrossBorderCompliance
name: "跨境资产合规"
description: "跨境资产转移必须满足双辖区合规"
predicate: transfer.is_cross_border implies transfer.has_dual_receipt
obligation: transfer.verify_dual_jurisdiction per_block
test: A13_test_cross_border
clause A14_AssetValuation
name: "资产估值AI验证"
description: "RWA资产估值必须经过AI验证"
predicate: asset.is_rwa implies asset.valuation_verified
obligation: asset.require_ai_valuation per_epoch
test: A14_test_ai_valuation
clause A15_AssetFreezing
name: "资产冻结宪法授权"
description: "资产冻结必须有宪法授权"
predicate: asset.is_frozen implies asset.freeze_authorized
obligation: asset.require_freeze_authorization per_block
test: A15_test_freeze_auth
clause A16_AssetBurning
name: "资产销毁不可逆性"
description: "资产销毁操作不可逆,必须有双重确认"
predicate: burn.confirmed_twice == true
obligation: burn.require_double_confirmation per_block
test: A16_test_burn_irreversible

View File

@ -0,0 +1,58 @@
// NAC公链宪法增补条款 - governance
clause A17_XicVotingRight
name: "XIC持有者投票权"
description: "宪法修改需XIC持有者2/3多数同意"
predicate: amendment.xic_approval_ratio >= 6700
obligation: governance.require_xic_supermajority per_epoch
test: A17_test_xic_voting
clause A18_AmendmentProcess
name: "宪法修改程序"
description: "宪法修改必须经过提案、讨论、投票三阶段"
predicate: amendment.stage in ["proposal", "discussion", "voting", "enacted"]
obligation: governance.enforce_amendment_stages per_epoch
test: A18_test_amendment_stages
clause A19_ConstitutionalCourt
name: "宪法法院仲裁权"
description: "争议必须提交宪法法院仲裁"
predicate: dispute.submitted_to_court == true
obligation: governance.route_disputes_to_court per_block
test: A19_test_court_arbitration
clause A20_JudgeElection
name: "法官选举制度"
description: "宪法法官由XIC持有者选举任期2年"
predicate: judge.elected_by_xic == true
obligation: governance.enforce_judge_election per_epoch
test: A20_test_judge_election
clause A21_TransparencyRequirement
name: "治理透明度"
description: "所有治理决策必须链上公开"
predicate: governance.decision_on_chain == true
obligation: governance.publish_decisions per_block
test: A21_test_transparency
clause A22_EmergencyPowers
name: "紧急权力限制"
description: "紧急权力行使不得超过30天需2/3批准"
predicate: emergency.duration_days <= 30
obligation: governance.limit_emergency_powers per_epoch
test: A22_test_emergency_limits
clause A23_ConstitutionalReview
name: "宪法审查权"
description: "任何条款可被宪法法院审查"
predicate: review.court_has_jurisdiction == true
obligation: governance.enable_constitutional_review per_epoch
test: A23_test_review_power
clause A24_AmendmentHistory
name: "修改历史不可篡改"
description: "宪法修改历史必须永久保存在链上"
predicate: amendment.history_immutable == true
obligation: governance.preserve_amendment_history per_block
test: A24_test_history_immutable

View File

@ -0,0 +1,37 @@
// NAC公链宪法增补条款 - infrastructure
clause A04_CbppConsensus
name: "CBPP为唯一共识协议"
description: "区块生产必须遵循CBPP协议禁止PoS/PoW"
predicate: consensus.protocol == "CBPP"
obligation: system.reject_non_cbpp_blocks per_block
test: A04_test_cbpp_only
clause A05_CsnpNetwork
name: "CSNP为唯一网络协议"
description: "节点通信必须使用CSNP禁止以太坊P2P"
predicate: network.protocol == "CSNP"
obligation: system.reject_non_csnp_peers per_block
test: A05_test_csnp_only
clause A06_NacLensProtocol
name: "NAC_lens为唯一通信接口"
description: "所有外部通信必须通过NAC_lens禁止RPC"
predicate: interface.protocol == "NAC_lens"
obligation: system.reject_rpc_calls per_block
test: A06_test_nac_lens_only
clause A07_Acc20Standard
name: "ACC-20为唯一代币标准"
description: "代币合约必须遵循ACC-20标准禁止ERC-20"
predicate: token.standard == "ACC-20"
obligation: system.reject_non_acc20_tokens per_block
test: A07_test_acc20_only
clause A08_CnnlGovernance
name: "CNNL为宪法治理语言"
description: "宪法条款变更必须通过CNNL形式化表达"
predicate: governance.language == "CNNL"
obligation: system.require_cnnl_for_amendments per_epoch
test: A08_test_cnnl_governance

View File

@ -0,0 +1,44 @@
// NAC公链宪法增补条款 - jurisdiction
clause A33_JurisdictionIsolation
name: "辖区规则隔离"
description: "不同辖区规则必须严格隔离"
predicate: jurisdiction.rules_isolated == true
obligation: system.enforce_jurisdiction_isolation per_block
test: A33_test_isolation
clause A34_CrossJurisdictionDualReceipt
name: "跨辖区双收据"
description: "跨辖区交易必须有双宪法收据"
predicate: cross_tx.has_dual_receipt == true
obligation: cross_tx.require_dual_receipt per_block
test: A34_test_dual_receipt
clause A35_JurisdictionDynamicJoin
name: "辖区动态加入"
description: "新辖区可动态加入无需重构基础设施"
predicate: jurisdiction.supports_dynamic_join == true
obligation: system.enable_dynamic_jurisdiction per_epoch
test: A35_test_dynamic_join
clause A36_ResourceFairShare
name: "资源公平分配"
description: "共享资源按辖区配额公平分配"
predicate: resource.allocation_fair == true
obligation: system.enforce_fair_resource_allocation per_block
test: A36_test_fair_share
clause A37_JurisdictionCouncil
name: "辖区协商委员会"
description: "辖区间争议由协商委员会解决"
predicate: dispute.council_jurisdiction == true
obligation: governance.route_to_council per_epoch
test: A37_test_council
clause A38_PluginHashVerification
name: "规则插件哈希验证"
description: "辖区规则插件必须通过哈希验证"
predicate: plugin.hash_verified == true
obligation: system.verify_plugin_hash per_block
test: A38_test_plugin_hash

View File

@ -0,0 +1,58 @@
// NAC公链宪法增补条款 - xtzh_currency
clause A25_XtzhGoldBacking
name: "XTZH黄金储备支撑"
description: "XTZH必须有至少40%黄金储备支撑"
predicate: xtzh.reserve_ratio >= 4000
obligation: xtzh.maintain_gold_reserve per_epoch
test: A25_test_gold_backing
clause A26_SdrPeg
name: "XTZH SDR锚定"
description: "XTZH价值锚定SDR货币篮子"
predicate: xtzh.peg_mechanism == "SDR"
obligation: xtzh.maintain_sdr_peg per_block
test: A26_test_sdr_peg
clause A27_XtzhMintAuth
name: "XTZH铸造授权"
description: "XTZH铸造必须有宪法授权和黄金证明"
predicate: mint.has_cr == true
obligation: xtzh.require_mint_authorization per_block
test: A27_test_mint_auth
clause A28_XtzhBurnProcess
name: "XTZH销毁赎回流程"
description: "XTZH销毁必须触发黄金赎回流程"
predicate: burn.triggers_gold_redemption == true
obligation: xtzh.enforce_burn_redemption per_block
test: A28_test_burn_redemption
clause A29_XtzhAudit
name: "XTZH季度审计"
description: "XTZH储备必须每季度审计一次"
predicate: xtzh.last_audit_days <= 90
obligation: xtzh.require_quarterly_audit per_epoch
test: A29_test_quarterly_audit
clause A30_XtzhCustodian
name: "黄金保管机构多元化"
description: "黄金必须由3-7家独立机构保管"
predicate: xtzh.custodian_count >= 3
obligation: xtzh.enforce_custodian_diversity per_epoch
test: A30_test_custodian_count
clause A31_XtzhEmergency
name: "XTZH紧急冻结"
description: "储备率低于30%时自动触发紧急冻结"
predicate: xtzh.reserve_ratio >= 3000
obligation: xtzh.auto_freeze_on_crisis per_block
test: A31_test_emergency_freeze
clause A32_XtzhTransparency
name: "XTZH储备透明度"
description: "XTZH储备信息实时链上公开"
predicate: xtzh.reserve_public == true
obligation: xtzh.publish_reserve_data per_block
test: A32_test_reserve_transparency

View File

@ -1,14 +1,242 @@
//! L3存储层状态数据库扩展 (Extended by NAC Core Team)
//! L3存储层状态数据库扩展 (Extended by NAC Core Team, v2 对接宪法条款 ID 体系)
//!
//! 遵循核心治理哲学:
//! 1. 宪法即是规则:每一条状态都必须有宪法条款的引用
//! 2. 约法即是治法:状态的变更必须符合宪法规则
//!
//! v2 新增constitution_ref 字段对接 A01-A56 条款 ID 体系,
//! 提供条款 ID 枚举、验证器和辅助函数。
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// 注意:这里不修改原有的 StateKey 和 StateValue而是提供扩展结构
// ============================================================
// 宪法条款 ID 体系A01-A56 完整枚举)
// ============================================================
/// NAC 公链宪法条款 ID 枚举
/// 对应 protocol/nac-constitution/clauses/ 下的独立 CNNL 文件
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ConstitutionClauseId {
// 第一章基础架构条款A01-A08
A01NativeStack, // Charter+NVM+CBPP+CSNP+CNNL 原生技术栈
A02CharterLanguage, // Charter 为唯一合约语言
A03NvmVirtualMachine, // NVM 为唯一虚拟机
A04CbppConsensus, // CBPP 为唯一共识协议
A05CsnpNetwork, // CSNP 为唯一网络协议
A06NacLensProtocol, // nac_lens 为唯一通信接口
A07Acc20Standard, // ACC-20 为唯一代币标准
A08CnnlGovernance, // CNNL 为宪法治理语言
// 第二章资产合规条款A09-A16
A09GnacsClassification, // GNACS 资产分类强制
A10RwaAssetVerification,// RWA 资产链上验证
A11AssetOwnershipDid, // 资产所有权 DID 绑定
A12AssetTransferCr, // 资产转移宪法收据
A13CrossBorderCompliance,// 跨境资产合规
A14AssetValuation, // 资产估值 AI 验证
A15AssetFreezing, // 资产冻结宪法授权
A16AssetBurning, // 资产销毁不可逆性
// 第三章治理条款A17-A24
A17XicVotingRight, // XIC 持有者投票权
A18AmendmentProcess, // 宪法修改程序
A19ConstitutionalCourt, // 宪法法院仲裁权
A20JudgeElection, // 法官选举制度
A21TransparencyRequirement, // 治理透明度
A22EmergencyPowers, // 紧急权力限制
A23ConstitutionalReview,// 宪法审查权
A24AmendmentHistory, // 修改历史不可篡改
// 第四章XTZH 货币条款A25-A32
A25XtzhGoldBacking, // XTZH 黄金储备支撑
A26SdrPeg, // XTZH SDR 锚定
A27XtzhMintAuth, // XTZH 铸造授权
A28XtzhBurnProcess, // XTZH 销毁赎回流程
A29XtzhAudit, // XTZH 季度审计
A30XtzhCustodian, // 黄金保管机构多元化
A31XtzhEmergency, // XTZH 紧急冻结
A32XtzhTransparency, // XTZH 储备透明度
// 第五章多辖区条款A33-A38
A33JurisdictionIsolation, // 辖区规则隔离
A34CrossJurisdictionDualReceipt, // 跨辖区双收据
A35JurisdictionDynamicJoin, // 辖区动态加入
A36ResourceFairShare, // 资源公平分配
A37JurisdictionCouncil, // 辖区协商委员会
A38PluginHashVerification, // 规则插件哈希验证
// 第六章AI 合规条款A39-A43
A39AiComplianceCheck, // AI 合规检查强制
A40AiValuationAccuracy, // AI 估值准确性
A41AiAuditTrail, // AI 决策审计追踪
A42AiModelUpdate, // AI 模型更新治理
A43AiHumanOversight, // AI 人工监督
// ACC-20C 扩展条款A53-A56来自 acc20c_clauses.cnnl
A53Acc20cTokenStandard, // ACC-20C 代币标准
A54Acc20cTransferRule, // ACC-20C 转账规则
A55Acc20cMintBurnAuth, // ACC-20C 铸造销毁授权
A56Acc20cComplianceCheck, // ACC-20C 合规检查
// 节点共享条款A44-A52来自 node_sharing_clauses.cnnl
A44NodeSharingProtocol, // 节点共享协议
A45NodeResourceQuota, // 节点资源配额
A46NodeJoinConsensus, // 节点加入共识
A47NodeExitProcess, // 节点退出流程
A48NodeRewardDistribution, // 节点奖励分配
A49NodePenaltyMechanism,// 节点惩罚机制
A50NodeUpgradeGovernance, // 节点升级治理
A51NodeDataSovereignty, // 节点数据主权
A52NodeCrossChainBridge,// 节点跨链桥接
/// 系统级条款(不对应具体条款,用于系统内部状态)
SystemGenesis,
SystemUpgrade,
}
impl ConstitutionClauseId {
/// 将条款 ID 转换为字符串表示(与 CNNL 文件中的 clause 名称一致)
pub fn as_str(&self) -> &'static str {
match self {
Self::A01NativeStack => "A01_NativeStack",
Self::A02CharterLanguage => "A02_CharterLanguage",
Self::A03NvmVirtualMachine => "A03_NvmVirtualMachine",
Self::A04CbppConsensus => "A04_CbppConsensus",
Self::A05CsnpNetwork => "A05_CsnpNetwork",
Self::A06NacLensProtocol => "A06_NacLensProtocol",
Self::A07Acc20Standard => "A07_Acc20Standard",
Self::A08CnnlGovernance => "A08_CnnlGovernance",
Self::A09GnacsClassification => "A09_GnacsClassification",
Self::A10RwaAssetVerification => "A10_RwaAssetVerification",
Self::A11AssetOwnershipDid => "A11_AssetOwnershipDid",
Self::A12AssetTransferCr => "A12_AssetTransferCr",
Self::A13CrossBorderCompliance => "A13_CrossBorderCompliance",
Self::A14AssetValuation => "A14_AssetValuation",
Self::A15AssetFreezing => "A15_AssetFreezing",
Self::A16AssetBurning => "A16_AssetBurning",
Self::A17XicVotingRight => "A17_XicVotingRight",
Self::A18AmendmentProcess => "A18_AmendmentProcess",
Self::A19ConstitutionalCourt => "A19_ConstitutionalCourt",
Self::A20JudgeElection => "A20_JudgeElection",
Self::A21TransparencyRequirement => "A21_TransparencyRequirement",
Self::A22EmergencyPowers => "A22_EmergencyPowers",
Self::A23ConstitutionalReview => "A23_ConstitutionalReview",
Self::A24AmendmentHistory => "A24_AmendmentHistory",
Self::A25XtzhGoldBacking => "A25_XtzhGoldBacking",
Self::A26SdrPeg => "A26_SdrPeg",
Self::A27XtzhMintAuth => "A27_XtzhMintAuth",
Self::A28XtzhBurnProcess => "A28_XtzhBurnProcess",
Self::A29XtzhAudit => "A29_XtzhAudit",
Self::A30XtzhCustodian => "A30_XtzhCustodian",
Self::A31XtzhEmergency => "A31_XtzhEmergency",
Self::A32XtzhTransparency => "A32_XtzhTransparency",
Self::A33JurisdictionIsolation => "A33_JurisdictionIsolation",
Self::A34CrossJurisdictionDualReceipt => "A34_CrossJurisdictionDualReceipt",
Self::A35JurisdictionDynamicJoin => "A35_JurisdictionDynamicJoin",
Self::A36ResourceFairShare => "A36_ResourceFairShare",
Self::A37JurisdictionCouncil => "A37_JurisdictionCouncil",
Self::A38PluginHashVerification => "A38_PluginHashVerification",
Self::A39AiComplianceCheck => "A39_AiComplianceCheck",
Self::A40AiValuationAccuracy => "A40_AiValuationAccuracy",
Self::A41AiAuditTrail => "A41_AiAuditTrail",
Self::A42AiModelUpdate => "A42_AiModelUpdate",
Self::A43AiHumanOversight => "A43_AiHumanOversight",
Self::A44NodeSharingProtocol => "A44_NodeSharingProtocol",
Self::A45NodeResourceQuota => "A45_NodeResourceQuota",
Self::A46NodeJoinConsensus => "A46_NodeJoinConsensus",
Self::A47NodeExitProcess => "A47_NodeExitProcess",
Self::A48NodeRewardDistribution => "A48_NodeRewardDistribution",
Self::A49NodePenaltyMechanism => "A49_NodePenaltyMechanism",
Self::A50NodeUpgradeGovernance => "A50_NodeUpgradeGovernance",
Self::A51NodeDataSovereignty => "A51_NodeDataSovereignty",
Self::A52NodeCrossChainBridge => "A52_NodeCrossChainBridge",
Self::A53Acc20cTokenStandard => "A53_Acc20cTokenStandard",
Self::A54Acc20cTransferRule => "A54_Acc20cTransferRule",
Self::A55Acc20cMintBurnAuth => "A55_Acc20cMintBurnAuth",
Self::A56Acc20cComplianceCheck => "A56_Acc20cComplianceCheck",
Self::SystemGenesis => "SYSTEM_GENESIS",
Self::SystemUpgrade => "SYSTEM_UPGRADE",
}
}
/// 从字符串解析条款 ID
pub fn from_str(s: &str) -> Option<Self> {
match s {
"A01_NativeStack" => Some(Self::A01NativeStack),
"A02_CharterLanguage" => Some(Self::A02CharterLanguage),
"A03_NvmVirtualMachine" => Some(Self::A03NvmVirtualMachine),
"A04_CbppConsensus" => Some(Self::A04CbppConsensus),
"A05_CsnpNetwork" => Some(Self::A05CsnpNetwork),
"A06_NacLensProtocol" => Some(Self::A06NacLensProtocol),
"A07_Acc20Standard" => Some(Self::A07Acc20Standard),
"A08_CnnlGovernance" => Some(Self::A08CnnlGovernance),
"A09_GnacsClassification" => Some(Self::A09GnacsClassification),
"A10_RwaAssetVerification" => Some(Self::A10RwaAssetVerification),
"A11_AssetOwnershipDid" => Some(Self::A11AssetOwnershipDid),
"A12_AssetTransferCr" => Some(Self::A12AssetTransferCr),
"A13_CrossBorderCompliance" => Some(Self::A13CrossBorderCompliance),
"A14_AssetValuation" => Some(Self::A14AssetValuation),
"A15_AssetFreezing" => Some(Self::A15AssetFreezing),
"A16_AssetBurning" => Some(Self::A16AssetBurning),
"A17_XicVotingRight" => Some(Self::A17XicVotingRight),
"A18_AmendmentProcess" => Some(Self::A18AmendmentProcess),
"A19_ConstitutionalCourt" => Some(Self::A19ConstitutionalCourt),
"A20_JudgeElection" => Some(Self::A20JudgeElection),
"A21_TransparencyRequirement" => Some(Self::A21TransparencyRequirement),
"A22_EmergencyPowers" => Some(Self::A22EmergencyPowers),
"A23_ConstitutionalReview" => Some(Self::A23ConstitutionalReview),
"A24_AmendmentHistory" => Some(Self::A24AmendmentHistory),
"A25_XtzhGoldBacking" => Some(Self::A25XtzhGoldBacking),
"A26_SdrPeg" => Some(Self::A26SdrPeg),
"A27_XtzhMintAuth" => Some(Self::A27XtzhMintAuth),
"A28_XtzhBurnProcess" => Some(Self::A28XtzhBurnProcess),
"A29_XtzhAudit" => Some(Self::A29XtzhAudit),
"A30_XtzhCustodian" => Some(Self::A30XtzhCustodian),
"A31_XtzhEmergency" => Some(Self::A31XtzhEmergency),
"A32_XtzhTransparency" => Some(Self::A32XtzhTransparency),
"A33_JurisdictionIsolation" => Some(Self::A33JurisdictionIsolation),
"A34_CrossJurisdictionDualReceipt" => Some(Self::A34CrossJurisdictionDualReceipt),
"A35_JurisdictionDynamicJoin" => Some(Self::A35JurisdictionDynamicJoin),
"A36_ResourceFairShare" => Some(Self::A36ResourceFairShare),
"A37_JurisdictionCouncil" => Some(Self::A37JurisdictionCouncil),
"A38_PluginHashVerification" => Some(Self::A38PluginHashVerification),
"A39_AiComplianceCheck" => Some(Self::A39AiComplianceCheck),
"A40_AiValuationAccuracy" => Some(Self::A40AiValuationAccuracy),
"A41_AiAuditTrail" => Some(Self::A41AiAuditTrail),
"A42_AiModelUpdate" => Some(Self::A42AiModelUpdate),
"A43_AiHumanOversight" => Some(Self::A43AiHumanOversight),
"A44_NodeSharingProtocol" => Some(Self::A44NodeSharingProtocol),
"A45_NodeResourceQuota" => Some(Self::A45NodeResourceQuota),
"A46_NodeJoinConsensus" => Some(Self::A46NodeJoinConsensus),
"A47_NodeExitProcess" => Some(Self::A47NodeExitProcess),
"A48_NodeRewardDistribution" => Some(Self::A48NodeRewardDistribution),
"A49_NodePenaltyMechanism" => Some(Self::A49NodePenaltyMechanism),
"A50_NodeUpgradeGovernance" => Some(Self::A50NodeUpgradeGovernance),
"A51_NodeDataSovereignty" => Some(Self::A51NodeDataSovereignty),
"A52_NodeCrossChainBridge" => Some(Self::A52NodeCrossChainBridge),
"A53_Acc20cTokenStandard" => Some(Self::A53Acc20cTokenStandard),
"A54_Acc20cTransferRule" => Some(Self::A54Acc20cTransferRule),
"A55_Acc20cMintBurnAuth" => Some(Self::A55Acc20cMintBurnAuth),
"A56_Acc20cComplianceCheck" => Some(Self::A56Acc20cComplianceCheck),
"SYSTEM_GENESIS" => Some(Self::SystemGenesis),
"SYSTEM_UPGRADE" => Some(Self::SystemUpgrade),
_ => None,
}
}
/// 验证条款 ID 字符串是否合法
pub fn is_valid(s: &str) -> bool {
Self::from_str(s).is_some()
}
}
// ============================================================
// 带有宪法引用的状态值扩展(原有结构,保持不变)
// ============================================================
/// 带有宪法引用的状态值扩展
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstitutionalStateValue {
@ -20,10 +248,11 @@ pub struct ConstitutionalStateValue {
pub created_at: u64,
/// 更新时间
pub updated_at: u64,
// --- 以下为扩展字段 ---
/// 关联的宪法条款引用 (体现"宪法即是规则")
/// 格式:条款 ID 字符串,如 "A09_GnacsClassification"
pub constitution_ref: String,
/// 产生该状态变更的交易哈希
pub tx_hash: String,
@ -31,17 +260,57 @@ pub struct ConstitutionalStateValue {
pub block_height: u64,
}
impl ConstitutionalStateValue {
/// 创建新的状态值,验证 constitution_ref 合法性
pub fn new(
data: Vec<u8>,
version: u64,
created_at: u64,
constitution_ref: ConstitutionClauseId,
tx_hash: String,
block_height: u64,
) -> Self {
Self {
data,
version,
created_at,
updated_at: created_at,
constitution_ref: constitution_ref.as_str().to_string(),
tx_hash,
block_height,
}
}
/// 获取关联的宪法条款 ID类型安全
pub fn get_clause_id(&self) -> Option<ConstitutionClauseId> {
ConstitutionClauseId::from_str(&self.constitution_ref)
}
/// 验证 constitution_ref 是否合法
pub fn is_constitution_ref_valid(&self) -> bool {
ConstitutionClauseId::is_valid(&self.constitution_ref)
}
}
// ============================================================
// 状态快照(原有结构,保持不变)
// ============================================================
/// 状态快照 (用于历史状态查询)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateSnapshot {
pub height: u64,
pub state_root: String, // Merkle树根哈希
pub state_root: String, // Merkle 树根哈希SHA3-384
pub timestamp: u64,
}
/// GNACS状态索引
// ============================================================
// GNACS 状态索引(原有结构,保持不变)
// ============================================================
/// GNACS 状态索引
pub struct GNACSStateIndex {
/// GNACS编码 -> 资产状态键列表
/// GNACS 编码 -> 资产状态键列表
index: HashMap<String, Vec<String>>,
}
@ -63,3 +332,106 @@ impl GNACSStateIndex {
self.index.get(gnacs_code)
}
}
// ============================================================
// 宪法条款引用验证器
// ============================================================
/// 宪法条款引用验证器
/// 用于在写入状态数据库前验证 constitution_ref 的合法性
pub struct ConstitutionRefValidator;
impl ConstitutionRefValidator {
/// 验证 constitution_ref 字符串是否对应已知条款
pub fn validate(constitution_ref: &str) -> Result<ConstitutionClauseId, String> {
ConstitutionClauseId::from_str(constitution_ref)
.ok_or_else(|| format!(
"无效的宪法条款引用: '{}'。有效格式为 'A01_NativeStack' 至 'A56_Acc20cComplianceCheck'",
constitution_ref
))
}
/// 验证资产相关状态是否引用了正确的条款A09-A16
pub fn validate_asset_clause(constitution_ref: &str) -> bool {
matches!(
ConstitutionClauseId::from_str(constitution_ref),
Some(ConstitutionClauseId::A09GnacsClassification)
| Some(ConstitutionClauseId::A10RwaAssetVerification)
| Some(ConstitutionClauseId::A11AssetOwnershipDid)
| Some(ConstitutionClauseId::A12AssetTransferCr)
| Some(ConstitutionClauseId::A13CrossBorderCompliance)
| Some(ConstitutionClauseId::A14AssetValuation)
| Some(ConstitutionClauseId::A15AssetFreezing)
| Some(ConstitutionClauseId::A16AssetBurning)
)
}
/// 验证治理相关状态是否引用了正确的条款A17-A24
pub fn validate_governance_clause(constitution_ref: &str) -> bool {
matches!(
ConstitutionClauseId::from_str(constitution_ref),
Some(ConstitutionClauseId::A17XicVotingRight)
| Some(ConstitutionClauseId::A18AmendmentProcess)
| Some(ConstitutionClauseId::A19ConstitutionalCourt)
| Some(ConstitutionClauseId::A20JudgeElection)
| Some(ConstitutionClauseId::A21TransparencyRequirement)
| Some(ConstitutionClauseId::A22EmergencyPowers)
| Some(ConstitutionClauseId::A23ConstitutionalReview)
| Some(ConstitutionClauseId::A24AmendmentHistory)
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clause_id_roundtrip() {
let id = ConstitutionClauseId::A09GnacsClassification;
let s = id.as_str();
let parsed = ConstitutionClauseId::from_str(s).unwrap();
assert_eq!(id, parsed);
}
#[test]
fn test_invalid_clause_id() {
assert!(!ConstitutionClauseId::is_valid("A99_Unknown"));
assert!(!ConstitutionClauseId::is_valid(""));
assert!(!ConstitutionClauseId::is_valid("ERC20"));
}
#[test]
fn test_constitutional_state_value_creation() {
let val = ConstitutionalStateValue::new(
vec![1, 2, 3],
1,
1000000,
ConstitutionClauseId::A09GnacsClassification,
"0xabc".to_string(),
100,
);
assert!(val.is_constitution_ref_valid());
assert_eq!(val.get_clause_id(), Some(ConstitutionClauseId::A09GnacsClassification));
}
#[test]
fn test_asset_clause_validation() {
assert!(ConstitutionRefValidator::validate_asset_clause("A09_GnacsClassification"));
assert!(ConstitutionRefValidator::validate_asset_clause("A12_AssetTransferCr"));
assert!(!ConstitutionRefValidator::validate_asset_clause("A17_XicVotingRight"));
}
#[test]
fn test_all_56_clauses_defined() {
// 验证 A01-A08
for s in &["A01_NativeStack", "A02_CharterLanguage", "A03_NvmVirtualMachine",
"A04_CbppConsensus", "A05_CsnpNetwork", "A06_NacLensProtocol",
"A07_Acc20Standard", "A08_CnnlGovernance"] {
assert!(ConstitutionClauseId::is_valid(s), "条款 {} 未定义", s);
}
// 验证 A43 和 A56
assert!(ConstitutionClauseId::is_valid("A43_AiHumanOversight"));
assert!(ConstitutionClauseId::is_valid("A56_Acc20cComplianceCheck"));
}
}