Spaces:
Sleeping
Sleeping
| use crate::state::VMState; | |
| use serde::{Serialize, Deserialize}; | |
| use std::collections::HashMap; | |
| use std::time::{SystemTime, UNIX_EPOCH}; | |
| pub struct PeerState { | |
| pub node_id: String, | |
| pub state: VMState, | |
| pub timestamp: u64, | |
| } | |
| pub struct MeshNetwork { | |
| pub node_id: String, | |
| pub peers: HashMap<String, PeerState>, | |
| } | |
| impl MeshNetwork { | |
| pub fn new(node_id: String) -> Self { | |
| Self { | |
| node_id, | |
| peers: HashMap::new(), | |
| } | |
| } | |
| pub fn local_snapshot(&self, state: &VMState) -> PeerState { | |
| PeerState { | |
| node_id: self.node_id.clone(), | |
| state: state.clone(), | |
| timestamp: now(), | |
| } | |
| } | |
| pub fn ingest_peer(&mut self, peer: PeerState) { | |
| match self.peers.get(&peer.node_id) { | |
| Some(existing) if existing.timestamp >= peer.timestamp => return, | |
| _ => { | |
| self.peers.insert(peer.node_id.clone(), peer); | |
| } | |
| } | |
| } | |
| pub fn reconcile(&self, local: &mut VMState) { | |
| for peer in self.peers.values() { | |
| // Conservative merge rule (anti-inflation) | |
| local.trust = local.trust.min(peer.state.trust); | |
| local.credit_balance = | |
| local.credit_balance.min(peer.state.credit_balance); | |
| local.flow_total += peer.state.flow_total / 10; | |
| } | |
| } | |
| } | |
| fn now() -> u64 { | |
| SystemTime::now() | |
| .duration_since(UNIX_EPOCH) | |
| .unwrap() | |
| .as_secs() | |
| } |