Skip to main content

scp_kernel/
local.rs

1use crate::*;
2use std::collections::{HashMap, HashSet};
3use tracing::{debug, instrument};
4use xdr_common::VecM;
5
6#[derive(Debug)]
7pub struct LocalState {
8    node_id: thruput_scp::SCPNodeID,
9    is_validator: bool,
10    qset: thruput_scp::SCPQuorumSet,
11    qset_hash: thruput_scp::SCPHash,
12    #[allow(dead_code)]
13    single_qset: Option<thruput_scp::SCPQuorumSet>,
14    #[allow(dead_code)]
15    single_qset_hash: Option<thruput_scp::SCPHash>,
16}
17
18impl LocalState {
19    pub fn new(
20        node_id: thruput_scp::SCPNodeID,
21        is_validator: bool,
22        qset: thruput_scp::SCPQuorumSet,
23        get_hash_of: impl Fn(&[u8]) -> thruput_scp::SCPHash,
24    ) -> LocalState {
25        debug!(
26            "local, new, qset: {}",
27            serde_json::to_string_pretty(&qset).unwrap()
28        );
29
30        // Normalize the quorum set (equivalent to normalizeQSet(mQSet) in C++)
31        let mut normalized_qset = qset;
32        normalize_qset(&mut normalized_qset, None);
33
34        debug!(
35            "local, new, normalized qset: {}",
36            serde_json::to_string_pretty(&normalized_qset).unwrap()
37        );
38
39        // Calculate hash of the normalized quorum set (equivalent to mQSetHash = driver.getHashOf(...))
40        let qset_bytes = scp_util::marshal_xdr(&normalized_qset).unwrap();
41        let qset_hash = get_hash_of(&qset_bytes);
42
43        // Build singleton quorum set (equivalent to buildSingletonQSet(mNodeID))
44        let single_qset = Self::build_singleton_qset(&node_id);
45
46        // Calculate hash of singleton quorum set
47        let single_qset_bytes = scp_util::marshal_xdr(&single_qset).unwrap();
48        let single_qset_hash = get_hash_of(&single_qset_bytes);
49
50        LocalState {
51            node_id,
52            is_validator,
53            qset: normalized_qset,
54            qset_hash,
55            single_qset: Some(single_qset),
56            single_qset_hash: Some(single_qset_hash),
57        }
58    }
59
60    fn build_singleton_qset(
61        node_id: &thruput_scp::SCPNodeID,
62    ) -> thruput_scp::SCPQuorumSet {
63        thruput_scp::SCPQuorumSet {
64            threshold: 1,
65            validators: VecM(vec![node_id.clone()]),
66            inner_sets: VecM(vec![]),
67        }
68    }
69}
70
71#[derive(Debug)]
72pub struct LocalProto<'a, C: Consensus, D: Driver> {
73    pub cd: &'a ConsensusDriver<C, D>,
74    pub local: &'a LocalState,
75}
76
77#[derive(Debug)]
78pub struct LocalProtoMut<'a, C: Consensus, D: Driver> {
79    pub cd: &'a ConsensusDriver<C, D>,
80    pub local: &'a mut LocalState,
81}
82
83impl<'a, C: Consensus, D: Driver> LocalProtoMut<'a, C, D> {
84    #[instrument(skip_all)]
85    pub fn update_quorum_set(&mut self, qset: &thruput_scp::SCPQuorumSet) {
86        debug!(
87            "local, update_quorum_set, qset: {}",
88            serde_json::to_string_pretty(qset).unwrap()
89        );
90
91        let mut normalized_qset = qset.clone();
92        normalize_qset(&mut normalized_qset, None);
93
94        debug!(
95            "local, update_quorum_set, normalized qset: {}",
96            serde_json::to_string_pretty(&normalized_qset).unwrap()
97        );
98
99        let qset_bytes = scp_util::marshal_xdr(&normalized_qset).unwrap();
100        let qset_hash = self.cd.driver.get_hash_of(&qset_bytes);
101
102        self.local.qset = normalized_qset;
103        self.local.qset_hash = qset_hash;
104    }
105}
106
107impl<'a, C: Consensus, D: Driver> LocalProto<'a, C, D> {
108    pub fn get_qset(&self) -> &thruput_scp::SCPQuorumSet {
109        &self.local.qset
110    }
111
112    pub fn get_qset_hash(&self) -> &thruput_scp::SCPHash {
113        &self.local.qset_hash
114    }
115
116    pub fn get_singleton_qset(
117        &self,
118        node_id: &thruput_scp::SCPNodeID,
119    ) -> thruput_scp::SCPQuorumSet {
120        LocalState::build_singleton_qset(node_id)
121    }
122
123    pub fn get_node_id(&self) -> &thruput_scp::SCPNodeID {
124        &self.local.node_id
125    }
126
127    pub fn is_validator(&self) -> bool {
128        self.local.is_validator
129    }
130
131    pub fn for_all_nodes<F>(
132        qset: &thruput_scp::SCPQuorumSet,
133        proc: &mut F,
134    ) -> bool
135    where
136        F: FnMut(&thruput_scp::SCPNodeID) -> bool,
137    {
138        federated::for_all_nodes(qset, proc)
139    }
140
141    pub fn is_quorum_slice(
142        qset: &thruput_scp::SCPQuorumSet,
143        node_set: &[thruput_scp::SCPNodeID],
144    ) -> bool {
145        federated::is_quorum_slice(qset, node_set)
146    }
147
148    pub fn is_vblocking_nodes(
149        qset: &thruput_scp::SCPQuorumSet,
150        nodes: &[thruput_scp::SCPNodeID],
151    ) -> bool {
152        federated::is_vblocking_nodes(qset, nodes)
153    }
154
155    /// Check if filtered envelopes form a v-blocking set
156    pub fn is_vblocking_envelopes<F>(
157        qset: &thruput_scp::SCPQuorumSet,
158        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
159        filter: F,
160    ) -> bool
161    where
162        F: Fn(&thruput_scp::SCPStatement) -> bool,
163    {
164        federated::is_vblocking_envelopes(qset, envs, filter)
165    }
166
167    /// Check if filtered envelopes form a quorum
168    pub fn is_quorum<GetStmtQSet, FilterStmts>(
169        qset: &thruput_scp::SCPQuorumSet,
170        envelopes: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
171        get_stmt_qset: &GetStmtQSet,
172        filter: &FilterStmts,
173    ) -> bool
174    where
175        GetStmtQSet:
176            Fn(&thruput_scp::SCPStatement) -> Option<thruput_scp::SCPQuorumSet>,
177        FilterStmts: Fn(&thruput_scp::SCPStatement) -> bool,
178    {
179        federated::is_quorum(qset, envelopes, get_stmt_qset, filter)
180    }
181
182    // computes the distance to the set of v-blocking sets given
183    // a set of nodes that agree (but can fail)
184    // excluded, if set will be skipped altogether
185    pub fn find_closest_v_blocking_nodes(
186        qset: &thruput_scp::SCPQuorumSet,
187        nodes: &HashSet<thruput_scp::SCPNodeID>,
188        excluded: Option<&thruput_scp::SCPNodeID>,
189    ) -> Vec<thruput_scp::SCPNodeID> {
190        federated::find_closest_v_blocking_nodes(qset, nodes, excluded)
191    }
192
193    /// Find the closest v-blocking set from filtered envelopes
194    pub fn find_closest_v_blocking_envelopes<F>(
195        &self,
196        qset: &thruput_scp::SCPQuorumSet,
197        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
198        filter: F,
199        excluded: Option<&thruput_scp::SCPNodeID>,
200    ) -> Vec<thruput_scp::SCPNodeID>
201    where
202        F: Fn(&thruput_scp::SCPStatement) -> bool,
203    {
204        federated::find_closest_v_blocking_envelopes(
205            qset, envs, filter, excluded,
206        )
207    }
208
209    pub fn to_json(
210        &self,
211        qset: &thruput_scp::SCPQuorumSet,
212        full_keys: bool,
213    ) -> serde_json::Value {
214        Self::to_json_with_formatter(qset, &|node_id| {
215            self.cd.driver.to_str_key(node_id, full_keys)
216        })
217    }
218
219    pub fn to_json_with_formatter<F>(
220        qset: &thruput_scp::SCPQuorumSet,
221        formatter: &F,
222    ) -> serde_json::Value
223    where
224        F: Fn(&thruput_scp::SCPNodeID) -> String,
225    {
226        let mut ret = serde_json::Map::new();
227        ret.insert(
228            "t".to_string(),
229            serde_json::Value::Number(qset.threshold.into()),
230        );
231
232        let mut entries = Vec::new();
233
234        // Add validators as strings
235        for validator in qset.validators.iter() {
236            let str_key = formatter(validator);
237            if str_key.is_empty() {
238                // In Rust we'll use a default representation instead of throwing
239                entries.push(serde_json::Value::String(format!(
240                    "{:?}",
241                    validator
242                )));
243            } else {
244                entries.push(serde_json::Value::String(str_key));
245            }
246        }
247
248        // Recursively add inner sets
249        for inner_set in qset.inner_sets.iter() {
250            entries.push(Self::to_json_with_formatter(inner_set, formatter));
251        }
252
253        ret.insert("v".to_string(), serde_json::Value::Array(entries));
254        serde_json::Value::Object(ret)
255    }
256
257    /// Parse a quorum set from JSON representation
258    pub fn from_json_with(
259        &self,
260        qset_json: &serde_json::Value,
261    ) -> Result<thruput_scp::SCPQuorumSet, String> {
262        let from_str_key = |s: &str| self.cd.driver.from_str_key(s);
263        Self::from_json_with_parser(qset_json, &from_str_key)
264    }
265
266    /// Parse a quorum set from JSON representation
267    pub fn from_json_with_parser<F>(
268        qset_json: &serde_json::Value,
269        from_str_key: &F,
270    ) -> Result<thruput_scp::SCPQuorumSet, String>
271    where
272        F: Fn(&str) -> Result<thruput_scp::SCPNodeID, String>,
273    {
274        if !qset_json.is_object() {
275            return Err("JSON field 'qset' must be an object".to_string());
276        }
277
278        let obj = qset_json.as_object().unwrap();
279
280        // Check for required threshold field
281        let threshold = match obj.get("t") {
282            Some(t) if t.is_number() => match t.as_u64() {
283                Some(val) if val <= u32::MAX as u64 => val as u32,
284                _ => {
285                    return Err(
286                        "JSON field 't' must be a valid unsigned 32-bit integer".to_string()
287                    );
288                }
289            },
290            _ => {
291                return Err(
292                    "JSON field 't' must exist and be an unsigned integer"
293                        .to_string(),
294                );
295            }
296        };
297
298        // Check for required validators array field
299        let entries = match obj.get("v") {
300            Some(v) if v.is_array() => v.as_array().unwrap(),
301            _ => {
302                return Err(
303                    "JSON field 'v' must exist and be an array".to_string()
304                );
305            }
306        };
307
308        let mut validators = Vec::new();
309        let mut inner_sets = Vec::new();
310
311        for entry in entries {
312            if entry.is_string() {
313                // Parse validator key string
314                let key_str = entry.as_str().unwrap();
315                match from_str_key(key_str) {
316                    Ok(node_id) => validators.push(node_id),
317                    Err(e) => {
318                        return Err(format!(
319                            "Invalid validator key in 'v' array: {}",
320                            e
321                        ));
322                    }
323                }
324            } else if entry.is_object() {
325                // Recursively parse inner quorum set
326                inner_sets
327                    .push(Self::from_json_with_parser(entry, from_str_key)?);
328            } else {
329                return Err("Each entry in 'v' must be either a string (validator key) or an object (inner quorum set)".to_string());
330            }
331        }
332
333        Ok(thruput_scp::SCPQuorumSet {
334            threshold,
335            validators: VecM(validators),
336            inner_sets: VecM(inner_sets),
337        })
338    }
339
340    pub fn to_string(&self, qset: &thruput_scp::SCPQuorumSet) -> String {
341        let json = self.to_json(qset, false);
342        serde_json::to_string(&json).unwrap()
343    }
344}