File size: 1,552 Bytes
e68c89d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use crate::state::VMState;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerState {
    pub node_id: String,
    pub state: VMState,
    pub timestamp: u64,
}

#[derive(Debug)]
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()
}