NAC_Blockchain/nac-constitution-state/src/lib.rs

369 lines
10 KiB
Rust

//! NAC宪法状态管理系统
//!
//! 提供完整的宪法版本管理、升级验证、持久化和历史追踪功能
use nac_udm::primitives::{Hash, Address};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::fs;
use std::io;
mod version;
mod upgrade;
mod storage;
mod history;
mod error;
pub use version::*;
pub use upgrade::*;
pub use storage::*;
pub use history::*;
pub use error::*;
/// 宪法版本信息
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ConstitutionVersion {
/// 版本号
pub version: u64,
/// 宪法哈希
pub constitution_hash: Hash,
/// 生效区块高度
pub effective_from: u64,
/// 条款数量
pub clause_count: u64,
/// 创建时间戳
pub created_at: u64,
/// 创建者地址
pub created_by: Address,
/// 版本描述
pub description: String,
}
impl ConstitutionVersion {
/// 创建新版本
pub fn new(
version: u64,
constitution_hash: Hash,
effective_from: u64,
clause_count: u64,
created_at: u64,
created_by: Address,
description: String,
) -> Self {
Self {
version,
constitution_hash,
effective_from,
clause_count,
created_at,
created_by,
description,
}
}
/// 比较版本号
pub fn compare(&self, other: &Self) -> std::cmp::Ordering {
self.version.cmp(&other.version)
}
/// 检查是否已生效
pub fn is_effective(&self, current_height: u64) -> bool {
current_height >= self.effective_from
}
/// 验证版本有效性
pub fn validate(&self) -> Result<()> {
if self.clause_count == 0 {
return Err(Error::InvalidVersion("条款数量不能为0".to_string()));
}
if self.description.is_empty() {
return Err(Error::InvalidVersion("版本描述不能为空".to_string()));
}
Ok(())
}
}
/// 宪法状态机
pub struct ConstitutionStateMachine {
/// 当前版本
current_version: ConstitutionVersion,
/// 历史版本
history: Vec<ConstitutionVersion>,
/// 待处理的升级
pending_upgrades: HashMap<u64, ConstitutionVersion>,
/// 存储路径
storage_path: PathBuf,
/// 升级验证器
upgrade_validator: UpgradeValidator,
/// 历史追踪器
history_tracker: HistoryTracker,
}
impl ConstitutionStateMachine {
/// 创建新的状态机
pub fn new(initial_version: ConstitutionVersion, storage_path: PathBuf) -> Result<Self> {
initial_version.validate()?;
let mut state_machine = Self {
current_version: initial_version.clone(),
history: vec![initial_version.clone()],
pending_upgrades: HashMap::new(),
storage_path,
upgrade_validator: UpgradeValidator::new(),
history_tracker: HistoryTracker::new(),
};
// 记录初始版本
state_machine.history_tracker.record_version(&initial_version)?;
Ok(state_machine)
}
/// 从存储加载状态机
pub fn load(storage_path: PathBuf) -> Result<Self> {
let storage = Storage::new(storage_path.clone());
let state = storage.load()?;
let history_tracker = HistoryTracker::load(&storage_path)?;
Ok(Self {
current_version: state.current_version,
history: state.history,
pending_upgrades: state.pending_upgrades,
storage_path,
upgrade_validator: UpgradeValidator::new(),
history_tracker,
})
}
/// 保存状态到存储
pub fn save(&self) -> Result<()> {
let storage = Storage::new(self.storage_path.clone());
let state = StateSnapshot {
current_version: self.current_version.clone(),
history: self.history.clone(),
pending_upgrades: self.pending_upgrades.clone(),
};
storage.save(&state)?;
Ok(())
}
/// 提议升级
pub fn propose_upgrade(
&mut self,
new_version: ConstitutionVersion,
proposer: Address,
) -> Result<()> {
// 验证新版本
new_version.validate()?;
// 验证升级权限
self.upgrade_validator.validate_permission(&proposer)?;
// 验证升级条件
self.upgrade_validator.validate_upgrade(&self.current_version, &new_version)?;
// 添加到待处理升级
self.pending_upgrades.insert(new_version.version, new_version.clone());
// 记录提议
self.history_tracker.record_proposal(&new_version, &proposer)?;
// 保存状态
self.save()?;
Ok(())
}
/// 执行升级
pub fn execute_upgrade(&mut self, version: u64, current_height: u64) -> Result<()> {
// 获取待处理的升级
let new_version = self.pending_upgrades
.remove(&version)
.ok_or(Error::UpgradeNotFound(version))?;
// 检查是否已到生效高度
if !new_version.is_effective(current_height) {
return Err(Error::UpgradeNotEffective(version, current_height));
}
// 执行升级
self.history.push(self.current_version.clone());
self.current_version = new_version.clone();
// 记录升级
self.history_tracker.record_upgrade(&new_version, current_height)?;
// 保存状态
self.save()?;
Ok(())
}
/// 取消升级
pub fn cancel_upgrade(&mut self, version: u64, canceller: Address) -> Result<()> {
// 验证取消权限
self.upgrade_validator.validate_permission(&canceller)?;
// 移除待处理的升级
let upgrade = self.pending_upgrades
.remove(&version)
.ok_or(Error::UpgradeNotFound(version))?;
// 记录取消
self.history_tracker.record_cancellation(&upgrade, &canceller)?;
// 保存状态
self.save()?;
Ok(())
}
/// 回滚到指定版本
pub fn rollback(&mut self, version: u64, operator: Address) -> Result<()> {
// 验证回滚权限
self.upgrade_validator.validate_permission(&operator)?;
// 查找目标版本
let target_version = self.history
.iter()
.find(|v| v.version == version)
.ok_or(Error::VersionNotFound(version))?
.clone();
// 执行回滚
self.current_version = target_version.clone();
// 记录回滚
self.history_tracker.record_rollback(&target_version, &operator)?;
// 保存状态
self.save()?;
Ok(())
}
/// 获取当前版本
pub fn get_current_version(&self) -> &ConstitutionVersion {
&self.current_version
}
/// 获取历史版本
pub fn get_history(&self) -> &[ConstitutionVersion] {
&self.history
}
/// 获取指定版本
pub fn get_version(&self, version: u64) -> Option<&ConstitutionVersion> {
if self.current_version.version == version {
return Some(&self.current_version);
}
self.history.iter().find(|v| v.version == version)
}
/// 获取待处理的升级
pub fn get_pending_upgrades(&self) -> &HashMap<u64, ConstitutionVersion> {
&self.pending_upgrades
}
/// 获取版本数量
pub fn version_count(&self) -> usize {
self.history.len() + 1 // history + current
}
/// 查询历史记录
pub fn query_history(&self, filter: HistoryFilter) -> Result<Vec<HistoryRecord>> {
self.history_tracker.query(filter)
}
/// 获取审计日志
pub fn get_audit_log(&self, from: u64, to: u64) -> Result<Vec<AuditLog>> {
self.history_tracker.get_audit_log(from, to)
}
/// 同步状态
pub fn sync(&mut self, remote_state: StateSnapshot) -> Result<()> {
// 验证远程状态
remote_state.current_version.validate()?;
// 比较版本
if remote_state.current_version.version > self.current_version.version {
// 更新到远程状态
self.current_version = remote_state.current_version;
self.history = remote_state.history;
self.pending_upgrades = remote_state.pending_upgrades;
// 保存状态
self.save()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn create_test_version(version: u64) -> ConstitutionVersion {
ConstitutionVersion::new(
version,
Hash::zero(),
version * 1000,
10,
version * 100,
Address::zero(),
format!("Version {}", version),
)
}
#[test]
fn test_version_creation() {
let version = create_test_version(1);
assert_eq!(version.version, 1);
assert_eq!(version.clause_count, 10);
assert!(version.validate().is_ok());
}
#[test]
fn test_version_comparison() {
let v1 = create_test_version(1);
let v2 = create_test_version(2);
assert_eq!(v1.compare(&v2), std::cmp::Ordering::Less);
assert_eq!(v2.compare(&v1), std::cmp::Ordering::Greater);
assert_eq!(v1.compare(&v1), std::cmp::Ordering::Equal);
}
#[test]
fn test_version_effectiveness() {
let version = create_test_version(1);
assert!(!version.is_effective(500));
assert!(version.is_effective(1000));
assert!(version.is_effective(2000));
}
#[test]
fn test_state_machine_creation() {
let temp_dir = std::env::temp_dir().join("nac_test_state");
let version = create_test_version(1);
let state_machine = ConstitutionStateMachine::new(version, temp_dir);
assert!(state_machine.is_ok());
}
#[test]
fn test_get_current_version() {
let temp_dir = std::env::temp_dir().join("nac_test_state");
let version = create_test_version(1);
let state_machine = ConstitutionStateMachine::new(version.clone(), temp_dir).unwrap();
assert_eq!(state_machine.get_current_version().version, 1);
}
#[test]
fn test_version_history() {
let temp_dir = std::env::temp_dir().join("nac_test_state");
let version = create_test_version(1);
let state_machine = ConstitutionStateMachine::new(version, temp_dir).unwrap();
assert_eq!(state_machine.get_history().len(), 1);
}
}