//! L1 元胞层: 元胞自动机路由(CAR - Cellular Automaton Routing) //! //! 元胞自动机路由特点: //! - 每个元胞维护到目标文明的特征向量梯度 //! - 数据包在当前元胞选择梯度下降最快的邻居转发 //! - 无中央路由表,完全分布式 use crate::types::{CellId, CellState, CivilizationId, CivilizationVector}; use crate::error::{Nrpc4Error, Result}; use std::collections::HashMap; use tracing::{debug, info, warn}; /// 元胞自动机路由器 pub struct CellularAutomatonRouter { /// 本地元胞状态 cell_state: CellState, /// 路由表 (文明ID -> 最佳下一跳元胞ID) routing_table: HashMap, } impl CellularAutomatonRouter { /// 创建新的元胞路由器 pub fn new(cell_id: CellId) -> Self { info!("Creating new CAR with cell_id: {:?}", cell_id); Self { cell_state: CellState::new(cell_id), routing_table: HashMap::new(), } } /// 更新邻居梯度 pub fn update_neighbor_gradient( &mut self, civilization_id: CivilizationId, vector: CivilizationVector, ) { debug!( "Updating gradient for civilization: {} from cell: {:?}", civilization_id, self.cell_state.cell_id ); self.cell_state.update_gradient(civilization_id, vector); } /// 计算到目标文明的梯度下降路径 /// /// 算法: /// 1. 查询所有邻居的梯度信息 /// 2. 选择梯度下降最快的邻居 /// 3. 返回最佳下一跳 pub fn compute_gradient_descent(&self, target_civilization: &CivilizationId) -> Result { debug!("Computing gradient descent to civilization: {}", target_civilization); // 查找目标文明的梯度信息 let gradients = &self.cell_state.neighbor_gradients; if let Some(_vector) = gradients.get(target_civilization) { // 简化实现: 返回第一个活跃连接 // 实际实现应该计算梯度并选择最优路径 if let Some(&next_hop) = self.cell_state.active_connections.first() { debug!("Found next hop: {:?}", next_hop); return Ok(next_hop); } } warn!("No route found to civilization: {}", target_civilization); Err(Nrpc4Error::CellRoutingError(format!( "No route to civilization: {}", target_civilization ))) } /// 路由数据包 pub fn route_packet( &mut self, target_civilization: &CivilizationId, payload: Vec, ) -> Result<(CellId, Vec)> { info!( "Routing packet to civilization: {} (payload size: {} bytes)", target_civilization, payload.len() ); // 计算下一跳 let next_hop = self.compute_gradient_descent(target_civilization)?; // 增加意识温度 (表示网络活跃度) self.cell_state.increase_consciousness(1); Ok((next_hop, payload)) } /// 添加活跃连接 pub fn add_connection(&mut self, peer_cell_id: CellId) { if !self.cell_state.active_connections.contains(&peer_cell_id) { info!("Adding connection to cell: {:?}", peer_cell_id); self.cell_state.active_connections.push(peer_cell_id); } } /// 移除连接 pub fn remove_connection(&mut self, peer_cell_id: &CellId) { self.cell_state.active_connections.retain(|id| id != peer_cell_id); info!("Removed connection to cell: {:?}", peer_cell_id); } /// 获取当前意识温度 pub fn get_consciousness_temp(&self) -> u64 { self.cell_state.consciousness_temp } /// 获取元胞ID pub fn get_cell_id(&self) -> CellId { self.cell_state.cell_id } } #[cfg(test)] mod tests { use super::*; #[test] fn test_car_creation() { let cell_id = [1u8; 32]; let router = CellularAutomatonRouter::new(cell_id); assert_eq!(router.get_cell_id(), cell_id); assert_eq!(router.get_consciousness_temp(), 0); } #[test] fn test_add_connection() { let mut router = CellularAutomatonRouter::new([1u8; 32]); let peer_id = [2u8; 32]; router.add_connection(peer_id); assert_eq!(router.cell_state.active_connections.len(), 1); } #[test] fn test_route_packet() { let mut router = CellularAutomatonRouter::new([1u8; 32]); let peer_id = [2u8; 32]; router.add_connection(peer_id); let civ_id = "nac-mainnet-001".to_string(); let vector = CivilizationVector::new(civ_id.clone(), [0u8; 32], [1u8; 32]); router.update_neighbor_gradient(civ_id.clone(), vector); let payload = vec![1, 2, 3, 4]; let result = router.route_packet(&civ_id, payload.clone()); assert!(result.is_ok()); let (next_hop, returned_payload) = result.unwrap(); assert_eq!(next_hop, peer_id); assert_eq!(returned_payload, payload); assert_eq!(router.get_consciousness_temp(), 1); } }