// NAC宪法执行引擎(CEE) //! Constitutional Execution Engine //! //! 宪法执行引擎是NAC公链宪法系统的核心组件,负责: //! - 执行宪法规则 //! - 验证交易和区块的合宪性 //! - 生成执行收据 //! - 与其他宪法模块集成 use nac_udm::primitives::{Address, Hash}; use serde::{Deserialize, Serialize}; use thiserror::Error; // 导出子模块 pub mod engine; pub mod integration; pub mod receipt; pub mod validator; // 重新导出常用类型 pub use engine::{ Action, CacheStats, Condition, Operator, Rule, RuleCache, RuleExecutor, RuleParser, RuleResult, RuleType, Value, }; pub use integration::{CbppIntegration, ClauseIntegration, MacroIntegration, StateIntegration}; pub use receipt::{ConstitutionalReceipt, ExecutionType, ReceiptGenerator, ReceiptStorage}; pub use validator::{ Block, BlockValidator, StateChange, StateValidator, Transaction, TransactionValidator, UpgradeProposal, UpgradeValidator, }; /// CEE错误类型 #[derive(Debug, Error)] pub enum CeeError { #[error("Clause not found: {0}")] ClauseNotFound(u64), #[error("Validation failed: {0}")] ValidationFailed(String), #[error("Rule parse error: {0}")] RuleParseError(String), #[error("Execution error: {0}")] ExecutionError(String), #[error("Storage error: {0}")] StorageError(String), #[error("Integration error: {0}")] IntegrationError(String), } /// 执行上下文 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExecutionContext { /// 调用者地址 pub caller: Address, /// 时间戳 pub timestamp: u64, /// 宪法条款索引 pub clause_index: u64, } /// 验证结果 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ValidationResult { /// 是否通过验证 pub passed: bool, /// 违反的宪法条款ID列表 pub violated_clauses: Vec, /// 警告信息 pub warnings: Vec, /// 详细信息 pub details: String, } /// 宪法执行引擎 pub struct ConstitutionalExecutionEngine { /// 规则解析器 parser: RuleParser, /// 规则执行器 executor: RuleExecutor, /// 规则缓存 cache: RuleCache, /// 交易验证器 tx_validator: TransactionValidator, /// 区块验证器 block_validator: BlockValidator, /// 状态验证器 state_validator: StateValidator, /// 升级验证器 upgrade_validator: UpgradeValidator, /// 收据生成器 receipt_generator: ReceiptGenerator, /// 收据存储 receipt_storage: ReceiptStorage, } impl ConstitutionalExecutionEngine { /// 创建新的宪法执行引擎 pub fn new() -> Self { Self { parser: RuleParser::new(), executor: RuleExecutor::new(), cache: RuleCache::new(1000, 3600), tx_validator: TransactionValidator::new(), block_validator: BlockValidator::new(), state_validator: StateValidator::new(), upgrade_validator: UpgradeValidator::new(), receipt_generator: ReceiptGenerator::new(), receipt_storage: ReceiptStorage::new(), } } /// 验证交易 pub fn validate_transaction( &mut self, transaction: &Transaction, rules: &[Rule], ) -> Result { // 验证交易 let result = self.tx_validator.validate(transaction, rules)?; // 生成收据 let receipt = self.receipt_generator.generate( ExecutionType::Transaction, transaction.hash, rules.iter().map(|r| r.clause_id).collect(), result, transaction.from, ); // 存储收据 self.receipt_storage.store(receipt.clone()); Ok(receipt) } /// 验证区块 pub fn validate_block( &mut self, block: &Block, rules: &[Rule], ) -> Result { // 验证区块 let result = self.block_validator.validate(block, rules)?; // 生成收据 let receipt = self.receipt_generator.generate( ExecutionType::Block, block.hash, rules.iter().map(|r| r.clause_id).collect(), result, block.proposer, ); // 存储收据 self.receipt_storage.store(receipt.clone()); Ok(receipt) } /// 验证状态变更 pub fn validate_state_change( &mut self, change: &StateChange, rules: &[Rule], ) -> Result { // 验证状态变更 let result = self.state_validator.validate(change, rules)?; // 生成收据(使用地址的哈希作为目标哈希) let target_hash = Hash::new({ let mut bytes = [0u8; 48]; bytes[0..32].copy_from_slice(change.address.as_bytes()); bytes }); let receipt = self.receipt_generator.generate( ExecutionType::State, target_hash, rules.iter().map(|r| r.clause_id).collect(), result, change.address, ); // 存储收据 self.receipt_storage.store(receipt.clone()); Ok(receipt) } /// 验证升级提案 pub fn validate_upgrade( &mut self, proposal: &UpgradeProposal, rules: &[Rule], ) -> Result { // 验证升级提案 let result = self.upgrade_validator.validate(proposal, rules)?; // 生成收据(使用提案ID的哈希作为目标哈希) let target_hash = Hash::new({ let mut bytes = [0u8; 48]; bytes[0..8].copy_from_slice(&proposal.proposal_id.to_be_bytes()); bytes }); let receipt = self.receipt_generator.generate( ExecutionType::Upgrade, target_hash, rules.iter().map(|r| r.clause_id).collect(), result, proposal.proposer, ); // 存储收据 self.receipt_storage.store(receipt.clone()); Ok(receipt) } /// 获取收据 pub fn get_receipt(&self, receipt_id: &Hash) -> Option<&ConstitutionalReceipt> { self.receipt_storage.get(receipt_id) } /// 获取规则解析器 pub fn parser(&mut self) -> &mut RuleParser { &mut self.parser } /// 获取规则缓存 pub fn cache(&mut self) -> &mut RuleCache { &mut self.cache } /// 获取缓存统计信息 pub fn cache_stats(&self) -> CacheStats { self.cache.stats() } /// 获取收据数量 pub fn receipt_count(&self) -> usize { self.receipt_storage.count() } } impl Default for ConstitutionalExecutionEngine { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_engine_creation() { let engine = ConstitutionalExecutionEngine::new(); assert_eq!(engine.receipt_count(), 0); } #[test] fn test_validate_transaction() { let mut engine = ConstitutionalExecutionEngine::new(); let tx = Transaction { hash: Hash::zero(), from: Address::new([1u8; 32]), to: Address::new([2u8; 32]), amount: 1000, nonce: 1, timestamp: 1000000, data: vec![], }; let rules = vec![]; let result = engine.validate_transaction(&tx, &rules); assert!(result.is_ok()); assert_eq!(engine.receipt_count(), 1); } #[test] fn test_validate_block() { let mut engine = ConstitutionalExecutionEngine::new(); let block = Block { hash: Hash::zero(), parent_hash: Hash::zero(), number: 1, timestamp: 1000000, proposer: Address::zero(), transactions: vec![], state_root: Hash::zero(), }; let rules = vec![]; let result = engine.validate_block(&block, &rules); assert!(result.is_ok()); assert_eq!(engine.receipt_count(), 1); } #[test] fn test_cache_stats() { let engine = ConstitutionalExecutionEngine::new(); let stats = engine.cache_stats(); assert_eq!(stats.size, 0); } } pub mod cross_jurisdiction_cluster;