Skip to main content

scp_kernel/
heuristic.rs

1fn compute_weight(m: u64, total: u64, threshold: u64) -> u64 {
2    assert!(threshold <= total);
3    // Since threshold <= total, calculating res=m*threshold/total will always
4    // produce res <= m, and we do not need to handle the possibility of overflow.
5    // We implement big division with rounding up manually
6    let (r, overflow) = unsigned_div_up(m, threshold, total);
7    assert!(!overflow);
8    r
9}
10
11fn unsigned_div_up(a: u64, b: u64, c: u64) -> (u64, bool) {
12    assert!(c > 0);
13    let a: u128 = a.into();
14    let b: u128 = b.into();
15    let c: u128 = c.into();
16    let x = (a * b).div_ceil(c);
17    (x as u64, false)
18}
19
20/// Returns the weight of the node within the qset normalized between 0-u64::MAX.
21/// If `node_id` is the local node, then set `is_local_node` to `true`.
22///
23/// If a validator is repeated multiple times its weight is only the weight of
24/// the first occurrence.
25pub fn get_node_weight(
26    node_id: &thruput_scp::SCPNodeID,
27    qset: &thruput_scp::SCPQuorumSet,
28    is_local_node: bool,
29) -> u64 {
30    if is_local_node {
31        // local node is in all quorum sets
32        return u64::MAX;
33    }
34
35    let n = qset.threshold as u64;
36    let d = qset.inner_sets.len() as u64 + qset.validators.len() as u64;
37
38    // Check if the node is directly in the validators list
39    for qset_node in qset.validators.iter() {
40        if qset_node == node_id {
41            return compute_weight(u64::MAX, d, n);
42        }
43    }
44
45    // Recursively check inner sets
46    for q in qset.inner_sets.iter() {
47        let leaf_w = get_node_weight(node_id, q, is_local_node);
48        if leaf_w != 0 {
49            return compute_weight(leaf_w, d, n);
50        }
51    }
52
53    0
54}