Spaces:
Sleeping
Sleeping
Create mesh.rs
Browse files- src/mesh.rs +60 -0
src/mesh.rs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::state::VMState;
|
| 2 |
+
use serde::{Serialize, Deserialize};
|
| 3 |
+
use std::collections::HashMap;
|
| 4 |
+
use std::time::{SystemTime, UNIX_EPOCH};
|
| 5 |
+
|
| 6 |
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
| 7 |
+
pub struct PeerState {
|
| 8 |
+
pub node_id: String,
|
| 9 |
+
pub state: VMState,
|
| 10 |
+
pub timestamp: u64,
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
#[derive(Debug)]
|
| 14 |
+
pub struct MeshNetwork {
|
| 15 |
+
pub node_id: String,
|
| 16 |
+
pub peers: HashMap<String, PeerState>,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
impl MeshNetwork {
|
| 20 |
+
pub fn new(node_id: String) -> Self {
|
| 21 |
+
Self {
|
| 22 |
+
node_id,
|
| 23 |
+
peers: HashMap::new(),
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
pub fn local_snapshot(&self, state: &VMState) -> PeerState {
|
| 28 |
+
PeerState {
|
| 29 |
+
node_id: self.node_id.clone(),
|
| 30 |
+
state: state.clone(),
|
| 31 |
+
timestamp: now(),
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
pub fn ingest_peer(&mut self, peer: PeerState) {
|
| 36 |
+
match self.peers.get(&peer.node_id) {
|
| 37 |
+
Some(existing) if existing.timestamp >= peer.timestamp => return,
|
| 38 |
+
_ => {
|
| 39 |
+
self.peers.insert(peer.node_id.clone(), peer);
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
pub fn reconcile(&self, local: &mut VMState) {
|
| 45 |
+
for peer in self.peers.values() {
|
| 46 |
+
// Conservative merge rule (anti-inflation)
|
| 47 |
+
local.trust = local.trust.min(peer.state.trust);
|
| 48 |
+
local.credit_balance =
|
| 49 |
+
local.credit_balance.min(peer.state.credit_balance);
|
| 50 |
+
local.flow_total += peer.state.flow_total / 10;
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
fn now() -> u64 {
|
| 56 |
+
SystemTime::now()
|
| 57 |
+
.duration_since(UNIX_EPOCH)
|
| 58 |
+
.unwrap()
|
| 59 |
+
.as_secs()
|
| 60 |
+
}
|