NAC_Blockchain/nvm_v2/nvm-l1/src/cbpp/constitutional_receipt.rs

261 lines
6.5 KiB
Rust
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.

// 宪法收据 (Constitutional Receipt, CR)
// CBPP核心组件交易进入区块链的唯一门票
use serde::{Deserialize, Serialize};
use sha2::{Sha256, Digest};
/// 宪法收据
/// 任何试图改变链状态的操作必须先获得CR
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstitutionalReceipt {
/// 收据ID
pub receipt_id: Vec<u8>,
/// 交易哈希
pub transaction_hash: Vec<u8>,
/// 宪法哈希(确保收据只在特定宪法版本下有效)
pub constitutional_hash: Vec<u8>,
/// 执行结果哈希AI校验结果的存在性证明
pub execution_result_hash: Vec<u8>,
/// 签发时间戳
pub timestamp: u64,
/// 有效期窗口(秒)
pub validity_window: u64,
/// 签发者公钥CEE实例
pub issuer_pubkey: Vec<u8>,
/// 签名
pub signature: Vec<u8>,
/// 验证结果
pub validation_results: Vec<ValidationResult>,
}
/// 验证结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
/// 验证类型
pub validation_type: ValidationType,
/// 是否通过
pub passed: bool,
/// 验证详情哈希
pub details_hash: Vec<u8>,
}
/// 验证类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ValidationType {
/// KYC验证
KYC,
/// AML反洗钱
AML,
/// 资产估值
AssetValuation,
/// 合规审查
ComplianceCheck,
/// 司法辖区验证
JurisdictionCheck,
/// 宪法条款验证
ConstitutionalClause,
/// 智能合约验证
SmartContractValidation,
/// 其他
Other(String),
}
impl ConstitutionalReceipt {
/// 创建新的宪法收据
pub fn new(
transaction_hash: Vec<u8>,
constitutional_hash: Vec<u8>,
execution_result_hash: Vec<u8>,
issuer_pubkey: Vec<u8>,
validity_window: u64,
) -> Self {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let receipt_id = Self::generate_receipt_id(
&transaction_hash,
&constitutional_hash,
timestamp,
);
Self {
receipt_id,
transaction_hash,
constitutional_hash,
execution_result_hash,
timestamp,
validity_window,
issuer_pubkey,
signature: vec![],
validation_results: vec![],
}
}
/// 生成收据ID
fn generate_receipt_id(
tx_hash: &[u8],
const_hash: &[u8],
timestamp: u64,
) -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.update(tx_hash);
hasher.update(const_hash);
hasher.update(timestamp.to_be_bytes());
hasher.finalize().to_vec()
}
/// 添加验证结果
pub fn add_validation_result(&mut self, result: ValidationResult) {
self.validation_results.push(result);
}
/// 签名收据
pub fn sign(&mut self, signature: Vec<u8>) {
self.signature = signature;
}
/// 验证收据有效性
pub fn verify(&self, current_time: u64, valid_constitutional_hash: &[u8]) -> bool {
// 1. 检查宪法哈希
if self.constitutional_hash != valid_constitutional_hash {
return false;
}
// 2. 检查时效性
if current_time > self.timestamp + self.validity_window {
return false;
}
// 3. 检查所有验证结果都通过
if !self.validation_results.iter().all(|r| r.passed) {
return false;
}
// 4. 检查签名(简化版本,实际应验证数字签名)
if self.signature.is_empty() {
return false;
}
true
}
/// 检查是否过期
pub fn is_expired(&self, current_time: u64) -> bool {
current_time > self.timestamp + self.validity_window
}
/// 获取收据权重(用于分叉选择)
pub fn get_weight(&self) -> u64 {
// 权重基于验证结果数量和类型
self.validation_results.len() as u64
}
}
impl ValidationResult {
/// 创建新的验证结果
pub fn new(validation_type: ValidationType, passed: bool, details: &[u8]) -> Self {
let mut hasher = Sha256::new();
hasher.update(details);
let details_hash = hasher.finalize().to_vec();
Self {
validation_type,
passed,
details_hash,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_constitutional_receipt_creation() {
let tx_hash = vec![1u8; 32];
let const_hash = vec![2u8; 32];
let exec_hash = vec![3u8; 32];
let issuer_key = vec![4u8; 33];
let cr = ConstitutionalReceipt::new(
tx_hash.clone(),
const_hash.clone(),
exec_hash,
issuer_key,
3600, // 1小时有效期
);
assert_eq!(cr.transaction_hash, tx_hash);
assert_eq!(cr.constitutional_hash, const_hash);
assert_eq!(cr.validity_window, 3600);
}
#[test]
fn test_receipt_verification() {
let mut cr = ConstitutionalReceipt::new(
vec![1u8; 32],
vec![2u8; 32],
vec![3u8; 32],
vec![4u8; 33],
3600,
);
// 添加验证结果
cr.add_validation_result(ValidationResult::new(
ValidationType::KYC,
true,
b"KYC passed",
));
cr.add_validation_result(ValidationResult::new(
ValidationType::AML,
true,
b"AML passed",
));
// 签名
cr.sign(vec![5u8; 64]);
// 验证
let current_time = cr.timestamp + 1800; // 30分钟后
assert!(cr.verify(current_time, &vec![2u8; 32]));
// 测试过期
let expired_time = cr.timestamp + 3601;
assert!(!cr.verify(expired_time, &vec![2u8; 32]));
}
#[test]
fn test_receipt_expiration() {
let cr = ConstitutionalReceipt::new(
vec![1u8; 32],
vec![2u8; 32],
vec![3u8; 32],
vec![4u8; 33],
3600,
);
assert!(!cr.is_expired(cr.timestamp + 1800)); // 未过期
assert!(cr.is_expired(cr.timestamp + 3601)); // 已过期
}
}