97 lines
2.9 KiB
Rust
97 lines
2.9 KiB
Rust
//! L4 宪法层: 全息编码、分片存储
|
|
|
|
use crate::types::{ConstitutionHolographicFragment, Hash};
|
|
use crate::error::{NacLensError, Result};
|
|
use tracing::info;
|
|
use sha2::{Sha256, Digest};
|
|
|
|
/// 宪法全息编码器
|
|
pub struct ConstitutionHolographicEncoder {
|
|
min_fragments: u32,
|
|
#[allow(dead_code)]
|
|
redundancy_factor: f32,
|
|
}
|
|
|
|
impl ConstitutionHolographicEncoder {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
min_fragments: 16,
|
|
redundancy_factor: 1.5,
|
|
}
|
|
}
|
|
|
|
/// 编码宪法为全息片段
|
|
pub fn encode(&self, constitution: &[u8], num_fragments: u32) -> Result<Vec<ConstitutionHolographicFragment>> {
|
|
if num_fragments < self.min_fragments {
|
|
return Err(NacLensError::ConstitutionError(
|
|
format!("片段数量不足,至少需要{}个", self.min_fragments)
|
|
));
|
|
}
|
|
|
|
info!("开始全息编码宪法,目标片段数: {}", num_fragments);
|
|
|
|
let constitution_hash = Self::hash_data(constitution);
|
|
let chunk_size = (constitution.len() + num_fragments as usize - 1) / num_fragments as usize;
|
|
|
|
let mut fragments = Vec::new();
|
|
|
|
for i in 0..num_fragments {
|
|
let start = (i as usize * chunk_size).min(constitution.len());
|
|
let end = ((i + 1) as usize * chunk_size).min(constitution.len());
|
|
let chunk = &constitution[start..end];
|
|
|
|
let fragment = ConstitutionHolographicFragment {
|
|
fragment_id: i,
|
|
total_fragments: num_fragments,
|
|
constitution_hash: constitution_hash.clone(),
|
|
data: chunk.to_vec(),
|
|
checksum: Self::calculate_checksum(chunk),
|
|
merkle_proof: vec![],
|
|
};
|
|
|
|
fragments.push(fragment);
|
|
}
|
|
|
|
Ok(fragments)
|
|
}
|
|
|
|
/// 从片段重构宪法
|
|
pub fn reconstruct(&self, mut fragments: Vec<ConstitutionHolographicFragment>) -> Result<Vec<u8>> {
|
|
if fragments.is_empty() {
|
|
return Err(NacLensError::ConstitutionError("片段列表为空".to_string()));
|
|
}
|
|
|
|
fragments.sort_by_key(|f| f.fragment_id);
|
|
|
|
let mut constitution = Vec::new();
|
|
for fragment in fragments {
|
|
constitution.extend_from_slice(&fragment.data);
|
|
}
|
|
|
|
Ok(constitution)
|
|
}
|
|
|
|
fn hash_data(data: &[u8]) -> Hash {
|
|
let mut hasher = Sha256::new();
|
|
hasher.update(data);
|
|
let result = hasher.finalize();
|
|
let mut hash = [0u8; 32];
|
|
hash.copy_from_slice(&result);
|
|
hash
|
|
}
|
|
|
|
fn calculate_checksum(data: &[u8]) -> u64 {
|
|
let mut checksum: u64 = 0;
|
|
for (i, &byte) in data.iter().enumerate() {
|
|
checksum = checksum.wrapping_add((byte as u64).wrapping_mul((i as u64 + 1)));
|
|
}
|
|
checksum
|
|
}
|
|
}
|
|
|
|
impl Default for ConstitutionHolographicEncoder {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|