Skip to main content

scp_kernel/
federated.rs

1use crate::qset;
2use std::collections::{HashMap, HashSet};
3use thiserror::Error;
4use tracing::{debug, instrument};
5
6pub use qset::{QSetError, is_qset_sane};
7
8pub fn for_all_nodes<F>(qset: &thruput_scp::SCPQuorumSet, proc: &mut F) -> bool
9where
10    F: FnMut(&thruput_scp::SCPNodeID) -> bool,
11{
12    for node in qset.validators.iter() {
13        if !proc(node) {
14            return false;
15        }
16    }
17
18    for inner_qset in qset.inner_sets.iter() {
19        if !for_all_nodes(inner_qset, proc) {
20            return false;
21        }
22    }
23
24    true
25}
26
27fn is_quorum_slice_internal(
28    qset: &thruput_scp::SCPQuorumSet,
29    node_set: &[thruput_scp::SCPNodeID],
30) -> bool {
31    let mut threshold_left = qset.threshold;
32
33    for validator in qset.validators.iter() {
34        if node_set.contains(validator) {
35            threshold_left = threshold_left.saturating_sub(1);
36            if threshold_left == 0 {
37                return true;
38            }
39        }
40    }
41
42    for inner_qset in qset.inner_sets.iter() {
43        if is_quorum_slice_internal(inner_qset, node_set) {
44            threshold_left = threshold_left.saturating_sub(1);
45            if threshold_left == 0 {
46                return true;
47            }
48        }
49    }
50
51    false
52}
53
54pub fn is_quorum_slice(
55    qset: &thruput_scp::SCPQuorumSet,
56    node_set: &[thruput_scp::SCPNodeID],
57) -> bool {
58    is_quorum_slice_internal(qset, node_set)
59}
60
61fn is_vblocking_internal(
62    qset: &thruput_scp::SCPQuorumSet,
63    node_set: &[thruput_scp::SCPNodeID],
64) -> bool {
65    // There is no v-blocking set for 0-threshold
66    if qset.threshold == 0 {
67        return false;
68    }
69
70    // Calculate nodes needed to block: total_entries - threshold + 1
71    let total_entries = qset.validators.len() + qset.inner_sets.len();
72    let mut left_till_block =
73        (total_entries + 1).saturating_sub(qset.threshold as usize) as i32;
74
75    // Check validators
76    for validator in qset.validators.iter() {
77        if node_set.contains(validator) {
78            left_till_block -= 1;
79            if left_till_block <= 0 {
80                return true;
81            }
82        }
83    }
84
85    // Check inner sets
86    for inner_qset in qset.inner_sets.iter() {
87        if is_vblocking_internal(inner_qset, node_set) {
88            left_till_block -= 1;
89            if left_till_block <= 0 {
90                return true;
91            }
92        }
93    }
94
95    false
96}
97
98pub fn is_vblocking_nodes(
99    qset: &thruput_scp::SCPQuorumSet,
100    nodes: &[thruput_scp::SCPNodeID],
101) -> bool {
102    is_vblocking_internal(qset, nodes)
103}
104
105/// Check if filtered envelopes form a v-blocking set
106#[instrument(skip(qset, envs, filter))]
107pub fn is_vblocking_envelopes<F>(
108    qset: &thruput_scp::SCPQuorumSet,
109    envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
110    filter: F,
111) -> bool
112where
113    F: Fn(&thruput_scp::SCPStatement) -> bool,
114{
115    // Collect node IDs where the envelope passes the filter
116    let filtered_nodes: Vec<thruput_scp::SCPNodeID> = envs
117        .iter()
118        .filter_map(|(node_id, envelope)| {
119            if filter(&envelope.statement) {
120                Some(node_id.clone())
121            } else {
122                None
123            }
124        })
125        .collect();
126
127    // Check if the filtered nodes form a v-blocking set
128    is_vblocking_internal(qset, &filtered_nodes)
129}
130
131/// Check if filtered envelopes form a quorum
132pub fn is_quorum<GetStmtQSet, FilterStmts>(
133    qset: &thruput_scp::SCPQuorumSet,
134    envelopes: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
135    get_stmt_qset: &GetStmtQSet,
136    filter: &FilterStmts,
137) -> bool
138where
139    GetStmtQSet:
140        Fn(&thruput_scp::SCPStatement) -> Option<thruput_scp::SCPQuorumSet>,
141    FilterStmts: Fn(&thruput_scp::SCPStatement) -> bool,
142{
143    // TODO(frost): Add an internal bound or bounded input type for consensus
144
145    // quorum evaluation; external proof payloads are bounded at the verifier
146    // boundary.
147    // Start with nodes that pass the filter
148    let mut p_nodes: Vec<thruput_scp::SCPNodeID> = envelopes
149        .iter()
150        .filter_map(|(node_id, envelope)| {
151            if filter(&envelope.statement) {
152                Some(node_id.clone())
153            } else {
154                None
155            }
156        })
157        .collect();
158
159    // Iterate until convergence (fixed point)
160    loop {
161        let count = p_nodes.len();
162
163        // Filter nodes that form quorum slices
164        let mut f_nodes = Vec::new();
165        for node_id in &p_nodes {
166            let envelope = envelopes.get(node_id).unwrap();
167            if let Some(node_qset) = get_stmt_qset(&envelope.statement) {
168                if is_quorum_slice_internal(&node_qset, &p_nodes) {
169                    f_nodes.push(node_id.clone());
170                }
171            } else {
172                debug!(
173                    "qset for {}'s envelope is missing",
174                    crate::to_str_key(node_id, false)
175                );
176            }
177        }
178
179        p_nodes = f_nodes;
180
181        // Break if no change (fixed point reached)
182        if count == p_nodes.len() {
183            break;
184        }
185    }
186
187    // Check if final set forms a quorum slice for the given qset
188    is_quorum_slice_internal(qset, &p_nodes)
189}
190
191// Computes the distance to the set of v-blocking sets given a set of nodes
192// that agree but can fail. `excluded`, if set, will be skipped altogether.
193pub fn find_closest_v_blocking_nodes(
194    qset: &thruput_scp::SCPQuorumSet,
195    nodes: &HashSet<thruput_scp::SCPNodeID>,
196    excluded: Option<&thruput_scp::SCPNodeID>,
197) -> Vec<thruput_scp::SCPNodeID> {
198    // Calculate nodes needed to block: total_entries - threshold + 1
199    let total_entries = qset.validators.len() + qset.inner_sets.len();
200    let mut left_till_block =
201        (total_entries + 1).saturating_sub(qset.threshold as usize);
202
203    let mut res = Vec::new();
204
205    // Check validators first
206    for validator in qset.validators.iter() {
207        // Skip excluded node
208        if let Some(ex) = excluded
209            && validator == ex
210        {
211            continue;
212        }
213
214        if !nodes.contains(validator) {
215            // This validator is not in the agreeing set, so it's already blocking
216            left_till_block = left_till_block.saturating_sub(1);
217            if left_till_block == 0 {
218                // Already blocked
219                return Vec::new();
220            }
221        } else {
222            res.push(validator.clone());
223        }
224    }
225
226    // Collect results from inner sets, ordered by size
227    let mut res_internals: Vec<Vec<thruput_scp::SCPNodeID>> = Vec::new();
228
229    for inner_qset in qset.inner_sets.iter() {
230        let inner_result =
231            find_closest_v_blocking_nodes(inner_qset, nodes, excluded);
232        if inner_result.is_empty() {
233            // This inner set is already blocked
234            left_till_block = left_till_block.saturating_sub(1);
235            if left_till_block == 0 {
236                return Vec::new();
237            }
238        } else {
239            res_internals.push(inner_result);
240        }
241    }
242
243    // Sort internal results by size (smallest first)
244    res_internals.sort_by_key(|v| v.len());
245
246    // Use top-level validators to get closer
247    if res.len() > left_till_block {
248        res.truncate(left_till_block);
249    }
250    left_till_block = left_till_block.saturating_sub(res.len());
251
252    // Use subsets to get closer, using the smallest ones first
253    for inner_res in res_internals.iter() {
254        if left_till_block == 0 {
255            break;
256        }
257        res.extend_from_slice(inner_res);
258        left_till_block = left_till_block.saturating_sub(1);
259    }
260
261    res
262}
263
264/// Find the closest v-blocking set from filtered envelopes
265pub fn find_closest_v_blocking_envelopes<F>(
266    qset: &thruput_scp::SCPQuorumSet,
267    envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
268    filter: F,
269    excluded: Option<&thruput_scp::SCPNodeID>,
270) -> Vec<thruput_scp::SCPNodeID>
271where
272    F: Fn(&thruput_scp::SCPStatement) -> bool,
273{
274    // Collect nodes that pass the filter into a HashSet
275    let nodes: HashSet<thruput_scp::SCPNodeID> = envs
276        .iter()
277        .filter_map(|(node_id, envelope)| {
278            if filter(&envelope.statement) {
279                Some(node_id.clone())
280            } else {
281                None
282            }
283        })
284        .collect();
285
286    find_closest_v_blocking_nodes(qset, &nodes, excluded)
287}
288
289/// Error returned when a statement does not carry a companion quorum-set hash.
290#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)]
291pub enum CompanionQuorumSetHashError {
292    #[error("statement does not carry a companion quorum-set hash")]
293    MissingStatementPledge,
294}
295
296/// Returns the companion quorum-set hash carried by an SCP statement.
297///
298/// For EXTERNALIZE statements this is `commit_quorum_set_hash`.
299pub fn try_get_companion_quorum_set_hash_from_statement(
300    statement: &thruput_scp::SCPStatement,
301) -> Result<thruput_scp::SCPHash, CompanionQuorumSetHashError> {
302    match &statement.pledges {
303        thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
304            Ok(prepare.quorum_set_hash)
305        }
306        thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
307            Ok(confirm.quorum_set_hash)
308        }
309        thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
310            externalize,
311        } => Ok(externalize.commit_quorum_set_hash),
312        thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { nominate } => {
313            Ok(nominate.quorum_set_hash)
314        }
315        _ => Err(CompanionQuorumSetHashError::MissingStatementPledge),
316    }
317}
318
319// Legacy infallible wrapper for kernel paths where malformed statement arms are
320// treated as internal bugs rather than peer-proof validation failures.
321pub fn get_companion_quorum_set_hash_from_statement(
322    statement: &thruput_scp::SCPStatement,
323) -> thruput_scp::SCPHash {
324    try_get_companion_quorum_set_hash_from_statement(statement)
325        .expect("bug: statement does not carry a companion quorum-set hash")
326}