1
//! Calculate consensus routerstatus entries for one relay - select RS entries
2

            
3
use super::*;
4
use rs_common::*;
5

            
6
impl ConsensusesFromVotes<PlainPreamble> for Vec<RouterStatusVote> {
7
    type PlainOutput = Vec<netstatus::plain::RouterStatus>;
8
    type MdOutput = Vec<netstatus::md::RouterStatus>;
9

            
10
16
    fn consensuses<'i>(
11
16
        context: ConsensusContextRefs<PlainPreamble>,
12
16
        inputs: impl ComponentInVotes<&'i Self>,
13
16
    ) -> Result<(Self::PlainOutput, Self::MdOutput), ConsensusError>
14
16
    where
15
16
        Self: 'i,
16
    {
17
        // ---------- Calculate IdTuples to include ----------
18
        //
19
        // https://spec.torproject.org/dir-spec/computing-consensus.html#choosing-relay-ids
20

            
21
        let output_ids;
22
        let voters_per_id; // buffer; TODO want to use super let instead
23
        {
24
16
            let mut per_id = HashMap::<IdTuple, VoterSet>::new();
25
16
            for (vnum, voter_rs_list) in inputs.iter() {
26
86
                for rs in voter_rs_list {
27
418
                    let id = IdTuple::from_rs(rs);
28
418
                    per_id.entry(id).or_default().insert(vnum);
29
                }
30
            }
31
16
            voters_per_id = per_id;
32

            
33
16
            output_ids = voters_per_id
34
16
                .iter()
35
76
                .filter(|(_id, voters)| {
36
76
                    context.is_enough_of_all_auths::<MoreThanHalf>(voters.len())
37
76
                })
38
                .map(|(id, _voters)| id)
39
                .collect::<HashSet<&IdTuple>>();
40

            
41
16
            let discrep_report_filter = DiscrepReportFilter::from_outputs(&output_ids);
42

            
43
16
            for (id, voters) in &voters_per_id {
44
76
                if discrep_report_filter.id_is_discrepant(id) {
45
                    // Spec says to log the loose identities.  We log them in their pairs.
46
                    info!("discrepant relay identity {id} ({} voters)", voters.len());
47
76
                }
48
            }
49
        };
50

            
51
        // ---------- Choose StatusTuple for each output identity ----------
52
        //
53
        // https://spec.torproject.org/dir-spec/computing-consensus.html#choosing-relay-descs
54

            
55
        let status_tuple_cmp_key = |(status_tuple, voter_set): &'_ (
56
            StatusTuple,
57
            Box<RouterStatusPerRelevantVoter<'_>>,
58
71
        )| {
59
            (
60
                // matches the largest set
61
403
                voter_set.iter().filter(|rs| rs.is_some()).count(),
62
                // breaking ties in favor of the most recently published
63
71
                status_tuple.publication,
64
                // and then in favor of the smaller server descriptor digest
65
71
                cmp::Reverse(status_tuple.doc_digest),
66
            )
67
71
        };
68

            
69
        let output_rs_inputs = {
70
16
            let mut candidate_status_tuples = HashMap::<
71
16
                IdTuple,
72
16
                // for each possible output status-tuple, who voted for it:
73
16
                HashMap<StatusTuple, Box<RouterStatusPerRelevantVoter>>,
74
16
            >::new();
75
16
            for (vnum, voter_rs_list) in inputs.iter() {
76
86
                for rs in voter_rs_list {
77
418
                    let id = IdTuple::from_rs(rs);
78
418
                    if !output_ids.contains(&id) {
79
15
                        continue;
80
403
                    }
81
403
                    let status_tuple = StatusTuple::from_rs(rs);
82
403
                    *candidate_status_tuples
83
403
                        .entry(id)
84
403
                        .or_default()
85
403
                        .entry(status_tuple)
86
71
                        .or_insert_with(|| ti_vec![None; context.votes.len()].into_boxed_slice())
87
                        // If multiple routerstatuses in the vote for the same id,
88
                        // we choose arbitrarily
89
403
                        .get_mut(vnum)
90
                        .ok_or_else(|| internal!("{vnum:?} out of range"))?
91
                        // Store in the slot for this voter
92
403
                        = Some(rs);
93
                }
94
            }
95

            
96
16
            candidate_status_tuples
97
16
                .into_iter()
98
71
                .map(|(id, status_tuples)| {
99
                    // Determine the inputs to the per-routerstatus calculation.
100

            
101
                    // Select the preferred status-tuple.
102
71
                    let (status_tuple, per_voter) = status_tuples
103
71
                        .into_iter()
104
71
                        .max_by_key(status_tuple_cmp_key)
105
71
                        .expect("entry with no content, impossible");
106

            
107
71
                    ResolvedRouterStatusInputs {
108
71
                        id,
109
71
                        status_tuple,
110
71
                        per_voter,
111
71
                    }
112
71
                })
113
        };
114

            
115
16
        output_rs_inputs
116
71
            .map(|resolved_rs_input| {
117
71
                resolved_rs_input
118
71
                    .consensuses(context.with_computed(&RouterStatusAC(context.computed)))
119
71
            })
120
16
            .process_results(|rss_iter| {
121
16
                rss_iter
122
71
                    .map(|both| {
123
71
                        both.map(|(plain, md)| (Some(plain), md))
124
                            .unwrap_or_default()
125
71
                    })
126
                    .filter_collect_unzip()
127
16
            })
128
16
    }
129
}