Skip to main content

scp_kernel/
nomination.rs

1use crate::*;
2use std::collections::{HashMap, HashSet};
3use tracing::{Level, debug, enabled, error, instrument, trace};
4use xdr_common::VecM;
5
6#[derive(Debug, Default)]
7pub struct NominationState {
8    round_number: thruput_scp::SCPCount,
9    votes: HashSet<thruput_scp::SCPValue>, // X
10    accepted: HashSet<thruput_scp::SCPValue>, // Y
11    candidates: HashSet<thruput_scp::SCPValue>, // Z
12    latest_nominations:
13        HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>, // N
14    last_envelope: Option<thruput_scp::SCPEnvelope>, // last envelope emitted by this node
15    round_leaders: HashSet<thruput_scp::SCPNodeID>, // nodes from quorum set that have the highest priority this round
16    nomination_started: bool, // true if 'nominate' was called
17    latest_composite_candidate: Option<thruput_scp::SCPValue>, // the latest (if any) candidate value
18    previous_value: Option<thruput_scp::SCPValue>, // the value from the previous slot
19    timer_exp_count: i32, // the number of times the timer has expired; used for the quorum endpoint
20}
21
22impl NominationState {
23    pub fn new() -> Self {
24        Self::default()
25    }
26}
27
28#[derive(Debug)]
29pub struct NominationProto<'a, 'b, C: Consensus, D: Driver>(
30    pub &'a mut SlotProto<'b, C, D>,
31);
32
33impl<'a, 'b, C: Consensus, D: Driver> NominationProto<'a, 'b, C, D> {
34    fn slot_proto_mut(&mut self) -> &mut SlotProto<'b, C, D> {
35        self.0
36    }
37
38    fn slot_proto(&self) -> &SlotProto<'b, C, D> {
39        self.0
40    }
41
42    fn nomination(&self) -> &NominationState {
43        self.slot_proto().nomination()
44    }
45
46    fn nomination_mut(&mut self) -> &mut NominationState {
47        self.slot_proto_mut().nomination_mut()
48    }
49
50    fn driver(&self) -> &D {
51        self.slot_proto().driver()
52    }
53
54    fn consensus(&self) -> &C {
55        self.slot_proto().consensus()
56    }
57
58    pub fn is_newer_node_statement(
59        &self,
60        node_id: &thruput_scp::SCPNodeID,
61        st: &thruput_scp::SCPStatementNominate,
62    ) -> bool {
63        match self.nomination().latest_nominations.get(node_id) {
64            None => true,
65            Some(old_envelope) => {
66                if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
67                    nominate: old_st,
68                } = &old_envelope.statement.pledges
69                {
70                    Self::is_newer_statement(old_st, st)
71                } else {
72                    false
73                }
74            }
75        }
76    }
77
78    pub fn is_newer_statement(
79        oldst: &thruput_scp::SCPStatementNominate,
80        st: &thruput_scp::SCPStatementNominate,
81    ) -> bool {
82        let mut grows_votes = false;
83
84        if Self::is_subset(&oldst.votes, &st.votes, &mut grows_votes) {
85            let mut grows_accepted = false;
86            if Self::is_subset(
87                &oldst.accepted,
88                &st.accepted,
89                &mut grows_accepted,
90            ) {
91                grows_votes || grows_accepted
92            } else {
93                false
94            }
95        } else {
96            false
97        }
98    }
99
100    fn is_subset(
101        p: &VecM<thruput_scp::SCPValue>,
102        v: &VecM<thruput_scp::SCPValue>,
103        not_equal: &mut bool,
104    ) -> bool {
105        if p.len() <= v.len() {
106            let mut p_sorted: Vec<_> = p.iter().cloned().collect();
107            let mut v_sorted: Vec<_> = v.iter().cloned().collect();
108            p_sorted.sort();
109            v_sorted.sort();
110
111            let is_subset = p_sorted
112                .iter()
113                .all(|item| v_sorted.binary_search(item).is_ok());
114            if is_subset {
115                *not_equal = p.len() != v.len();
116            } else {
117                *not_equal = true;
118            }
119            is_subset
120        } else {
121            *not_equal = true;
122            false
123        }
124    }
125
126    pub fn is_sane(&self, st: &thruput_scp::SCPStatement) -> bool {
127        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
128            nominate: nom,
129        } = &st.pledges
130        {
131            // Check that nomination has at least one vote or accepted value
132            let has_content = !nom.votes.is_empty() || !nom.accepted.is_empty();
133
134            if !has_content {
135                return false;
136            }
137
138            // Check that votes are sorted
139            let votes_sorted = Self::is_sorted(&nom.votes);
140
141            // Check that accepted values are sorted
142            let accepted_sorted = Self::is_sorted(&nom.accepted);
143
144            votes_sorted && accepted_sorted
145        } else {
146            panic!("bug")
147        }
148    }
149
150    fn is_sorted(values: &VecM<thruput_scp::SCPValue>) -> bool {
151        if values.len() <= 1 {
152            return true;
153        }
154
155        let values_vec: Vec<_> = values.iter().collect();
156        values_vec.windows(2).all(|window| window[0] <= window[1])
157    }
158
159    pub fn record_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
160        let node_id = &env.statement.node_id;
161        self.nomination_mut()
162            .latest_nominations
163            .insert(node_id.clone(), env.clone());
164        self.slot_proto_mut().record_statement(&env.statement);
165    }
166
167    #[instrument(skip_all)]
168    pub fn emit_nomination(&mut self) {
169        // Create SCP statement for nomination
170        let node_id = self.slot_proto().local_proto().get_node_id().clone();
171        let qset_hash = *self.slot_proto().local_proto().get_qset_hash();
172
173        // Create the nomination statement
174        let mut votes = VecM(vec![]);
175        let mut accepted = VecM(vec![]);
176
177        // Copy votes from nomination state
178        for vote in &self.nomination().votes {
179            votes.0.push(vote.clone());
180        }
181
182        // Copy accepted values from nomination state
183        for accept in &self.nomination().accepted {
184            accepted.0.push(accept.clone());
185        }
186
187        // Sort the collections to ensure they're ordered
188        votes.0.sort();
189        accepted.0.sort();
190
191        let nominate = thruput_scp::SCPStatementNominate {
192            quorum_set_hash: qset_hash,
193            votes,
194            accepted,
195        };
196
197        let statement = thruput_scp::SCPStatement {
198            node_id,
199            slot_index: self.slot_proto().index(),
200            pledges: thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
201                nominate: nominate.clone(),
202            },
203        };
204
205        // Create envelope
206        let envelope = self.slot_proto_mut().create_envelope(statement.clone());
207
208        // Process the envelope first - this is crucial!
209        match self.slot_proto_mut().process_envelope(&envelope, true) {
210            EnvelopeState::Valid => {
211                // Check if this statement is newer than our last envelope
212                let should_update = match &self.nomination().last_envelope {
213                    None => true,
214                    Some(last_env) => {
215                        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
216                            nominate: last_nom,
217                        } = &last_env.statement.pledges
218                        {
219                            Self::is_newer_statement(last_nom, &nominate)
220                        } else {
221                            true
222                        }
223                    }
224                };
225
226                if should_update {
227                    self.nomination_mut().last_envelope =
228                        Some(envelope.clone());
229
230                    if self.slot_proto().is_fully_validated() {
231                        self.driver().emit_envelope(envelope);
232                    }
233                }
234            }
235            EnvelopeState::Invalid =>
236            // There is a bug in the application if it queued up
237            // a statement for itself that it considers invalid
238            {
239                error!(env = ?envelope, "nomination moved to a bad state, due to envelope: {}", 
240                    self.0.cd.envelope_to_str(&envelope, false));
241                panic!("moved to a bad state (nomination)")
242            }
243        }
244    }
245
246    pub fn accept_predicate(
247        v: &thruput_scp::SCPValue,
248        st: &thruput_scp::SCPStatement,
249    ) -> bool {
250        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
251            nominate: nom,
252        } = &st.pledges
253        {
254            nom.accepted.iter().any(|accepted_val| accepted_val == v)
255        } else {
256            false
257        }
258    }
259
260    pub fn apply_all<F>(
261        nom: &thruput_scp::SCPStatementNominate,
262        mut processor: F,
263    ) where
264        F: FnMut(&thruput_scp::SCPValue),
265    {
266        // Apply processor to all votes
267        for v in nom.votes.iter() {
268            processor(v);
269        }
270
271        // Apply processor to accepted values that are not already in votes
272        // NB: "accepted" should be a subset of "votes", so this should mostly no-op
273        for a in nom.accepted.iter() {
274            if !nom.votes.iter().any(|vote| vote == a) {
275                processor(a);
276            }
277        }
278    }
279
280    #[instrument(skip_all, fields(slot_index = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), round_number = i64::from(self.nomination().round_number)))]
281    pub fn update_round_leaders(&mut self) {
282        let mut my_qset = self.slot_proto().local_proto().get_qset().clone();
283        let local_id = self.slot_proto().local_proto().get_node_id().clone();
284
285        // Normalize qset (excludes self)
286        crate::qset::normalize_qset(&mut my_qset, Some(&local_id));
287
288        debug!(
289            "nomination, updating round leaders, normalizaed, my local node id: {}, my qset: {}",
290            self.driver().to_short_string(&local_id),
291            serde_json::to_string_pretty(&my_qset).unwrap()
292        );
293
294        // Count maximum leader count (includes self)
295        let mut max_leader_count = 1;
296        // note that node IDs here are unique ("sane"), so we can count by
297        // enumeration
298        LocalProto::<C, D>::for_all_nodes(&my_qset, &mut |_| {
299            max_leader_count += 1;
300            true
301        });
302
303        while self.nomination().round_leaders.len() < max_leader_count {
304            // Initialize priority with value derived from self
305            let mut new_round_leaders = HashSet::new();
306
307            new_round_leaders.insert(local_id.clone());
308            let mut top_priority = self.get_node_priority(&local_id, &my_qset);
309
310            // Check all nodes in quorum set for higher priority
311            LocalProto::<C, D>::for_all_nodes(&my_qset, &mut |cur| {
312                let weight = self.get_node_priority(cur, &my_qset);
313                if weight > top_priority {
314                    top_priority = weight;
315                    new_round_leaders.clear();
316                }
317                if weight == top_priority && weight > 0 {
318                    new_round_leaders.insert(cur.clone());
319                }
320                true
321            });
322
323            if top_priority == 0 {
324                // No one had priority, so all nodes would choose themselves
325                // resulting in a timeout. Clear newRoundLeaders, allowing the
326                // algorithm to fast timeout and try again.
327                new_round_leaders.clear();
328            }
329
330            // Expand round_leaders with the newly computed leaders
331            let old_size = self.nomination().round_leaders.len();
332
333            // Insert new leaders into round_leaders
334            for leader in new_round_leaders {
335                self.nomination_mut().round_leaders.insert(leader);
336            }
337
338            let new_size = self.nomination().round_leaders.len();
339
340            if old_size != new_size {
341                if enabled!(Level::DEBUG) {
342                    debug!(
343                        "nomination update_round_leaders: {} -> {}",
344                        old_size, new_size
345                    );
346                    for rl in &self.nomination().round_leaders {
347                        debug!(
348                            "  leader {}",
349                            self.driver().to_short_string(rl)
350                        );
351                    }
352                }
353                return;
354            } else {
355                self.nomination_mut().round_number += 1;
356                debug!(
357                    "nomination update_round_leaders fast timeout (would no op) -> round {}",
358                    self.nomination().round_number
359                );
360            }
361        }
362        debug!("nomination update_round_leaders: nothing to do")
363    }
364
365    #[instrument(skip_all)]
366    pub fn get_node_priority(
367        &self,
368        node_id: &thruput_scp::SCPNodeID,
369        qset: &thruput_scp::SCPQuorumSet,
370    ) -> u64 {
371        let is_local = node_id == self.slot_proto().local_proto().get_node_id();
372        let weight = self.driver().get_node_weight(node_id, qset, is_local);
373
374        // if weight > 0; weight is inclusive here as
375        // 0 <= hash_node <= u64::MAX
376        if weight > 0 && self.hash_node(false, node_id) <= weight {
377            self.hash_node(true, node_id)
378        } else {
379            0
380        }
381    }
382
383    #[instrument(skip_all)]
384    fn hash_node(
385        &self,
386        is_priority: bool,
387        node_id: &thruput_scp::SCPNodeID,
388    ) -> u64 {
389        if let Some(ref previous_value) = self.nomination().previous_value {
390            self.driver().compute_hash_node(
391                self.slot_proto().index(),
392                previous_value,
393                is_priority,
394                self.nomination().round_number,
395                node_id,
396            )
397        } else {
398            panic!("bug")
399        }
400    }
401
402    #[instrument(skip_all)]
403    fn hash_value(&self, value: &thruput_scp::SCPValue) -> u64 {
404        if let Some(ref previous_value) = self.nomination().previous_value {
405            self.driver().compute_value_hash(
406                self.slot_proto().index(),
407                previous_value,
408                self.nomination().round_number,
409                value,
410            )
411        } else {
412            panic!("bug")
413        }
414    }
415
416    #[instrument(skip_all)]
417    pub fn get_new_value_from_nomination(
418        &self,
419        nom: &thruput_scp::SCPStatementNominate,
420    ) -> Option<thruput_scp::SCPValue> {
421        // Pick the highest value we don't have from the nomination
422        // sorted using hash_value.
423        let mut new_vote: Option<thruput_scp::SCPValue> = None;
424        let mut new_hash = 0u64;
425        let mut found_valid_value = false;
426
427        let pick_value =
428            |value: &thruput_scp::SCPValue,
429             new_vote: &mut Option<thruput_scp::SCPValue>,
430             new_hash: &mut u64,
431             found_valid_value: &mut bool| {
432                let value_to_nominate = match self.validate_value(value) {
433                    ValidationLevel::FullyValid => Some(value.clone()),
434                    _ => self.extract_valid_value(value),
435                };
436
437                if let Some(valid_val) = value_to_nominate {
438                    *found_valid_value = true;
439                    if !self.nomination().votes.contains(&valid_val) {
440                        let cur_hash = self.hash_value(&valid_val);
441                        if cur_hash >= *new_hash {
442                            *new_hash = cur_hash;
443                            *new_vote = Some(valid_val);
444                        }
445                    }
446                }
447            };
448
449        // First look through accepted values
450        for val in nom.accepted.iter() {
451            pick_value(
452                val,
453                &mut new_vote,
454                &mut new_hash,
455                &mut found_valid_value,
456            );
457        }
458
459        // Move on to votes if we have not found a valid accepted value
460        if !found_valid_value {
461            for val in nom.votes.iter() {
462                pick_value(
463                    val,
464                    &mut new_vote,
465                    &mut new_hash,
466                    &mut found_valid_value,
467                );
468            }
469        }
470
471        new_vote
472    }
473
474    #[instrument(skip_all)]
475    fn validate_value(&self, value: &thruput_scp::SCPValue) -> ValidationLevel {
476        self.consensus()
477            .validate_nomination_value(self.slot_proto().index(), value)
478    }
479
480    #[instrument(skip_all)]
481    fn extract_valid_value(
482        &self,
483        value: &thruput_scp::SCPValue,
484    ) -> Option<thruput_scp::SCPValue> {
485        self.consensus()
486            .extract_valid_value(self.slot_proto().index(), value)
487    }
488
489    pub fn should_process_envelope(
490        &self,
491        env: &thruput_scp::SCPEnvelope,
492    ) -> bool {
493        let st = &env.statement;
494
495        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
496            nominate: nom,
497        } = &st.pledges
498        {
499            if !self.is_newer_node_statement(&st.node_id, nom) {
500                return false;
501            }
502
503            if !self.is_sane(st) {
504                trace!("nomination proto message didn't pass sanity check");
505                return false;
506            }
507
508            true
509        } else {
510            false
511        }
512    }
513
514    #[allow(dead_code)]
515    fn dbg_state_to_str(&self) -> String {
516        let mut s = "latest_envelopes: {\n".to_string();
517        for (node_id, env) in &self.nomination().latest_nominations {
518            s.push_str(&format!(
519                "   {} -> {}\n",
520                self.driver().to_str_key(node_id, false),
521                self.slot_proto().cd.envelope_to_str(env, false)
522            ));
523        }
524        s.push('}');
525        s
526    }
527
528    #[instrument(skip_all, name = "nomination.process_envelope", fields(slot_index = i64::try_from(envelope.statement.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(envelope.statement.slot_index).unwrap_or(i64::MAX)))]
529    pub fn process_envelope(
530        &mut self,
531        envelope: &thruput_scp::SCPEnvelope,
532    ) -> EnvelopeState {
533        let st = &envelope.statement;
534
535        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
536            nominate: nom,
537        } = &st.pledges
538        {
539            if !self.is_newer_node_statement(&st.node_id, nom) {
540                return EnvelopeState::Invalid;
541            }
542
543            if !self.is_sane(st) {
544                trace!("nomination proto message didn't pass sanity check");
545                return EnvelopeState::Invalid;
546            }
547
548            self.record_envelope(envelope);
549
550            if self.nomination().nomination_started {
551                // Track if we should emit a new nomination message
552                let mut modified = false;
553                let mut new_candidates = false;
554
555                // debug!(
556                //     "nomination before promotion:\ninfo: {}\nstate: {}\nenvelope: {}",
557                //     serde_json::to_string_pretty(&self.get_json_info()).unwrap(),
558                //     self.dbg_state_to_str(),
559                //     self.slot_proto().cd.envelope_to_str(envelope, false)
560                // );
561
562                // Attempt to promote some of the votes to accepted
563                for v in nom.votes.iter() {
564                    if self.nomination().accepted.contains(v) {
565                        // v is already accepted
566                        continue;
567                    }
568
569                    // Check if this value can be accepted via federated accept
570                    let votes_predicate =
571                        |st: &thruput_scp::SCPStatement| -> bool {
572                            if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { nominate: nom } =
573                            &st.pledges
574                        {
575                            nom.votes.iter().any(|vote| vote == v)
576                        } else {
577                            false
578                        }
579                        };
580
581                    let accept_predicate =
582                        |st: &thruput_scp::SCPStatement| -> bool {
583                            Self::accept_predicate(v, st)
584                        };
585
586                    if self.slot_proto().federated_accept(
587                        &votes_predicate,
588                        &accept_predicate,
589                        &self.nomination().latest_nominations,
590                    ) {
591                        let validation_level = self.validate_value(v);
592                        if validation_level == ValidationLevel::FullyValid {
593                            self.nomination_mut().accepted.insert(v.clone());
594                            self.nomination_mut().votes.insert(v.clone());
595                            modified = true;
596                        } else if let Some(valid_value) =
597                            self.extract_valid_value(v)
598                        {
599                            // The value made it pretty far: see if we can vote for a variation
600                            // that we consider valid
601                            if self.nomination_mut().votes.insert(valid_value) {
602                                modified = true;
603                            }
604                        }
605                    }
606                }
607
608                // Attempt to promote accepted values to candidates
609                for a in self.nomination().accepted.clone().iter() {
610                    if self.nomination().candidates.contains(a) {
611                        continue;
612                    }
613
614                    let accept_predicate =
615                        |st: &thruput_scp::SCPStatement| -> bool {
616                            Self::accept_predicate(a, st)
617                        };
618
619                    if self.slot_proto().federated_ratify(
620                        &accept_predicate,
621                        &self.nomination().latest_nominations,
622                    ) {
623                        self.nomination_mut().candidates.insert(a.clone());
624                        new_candidates = true;
625                        // Stop the timer, as there's no need to continue nominating
626                        self.driver().stop_timer(
627                            self.slot_proto().index(),
628                            Timer::Nomination,
629                        );
630                    }
631                }
632
633                // Only take round leader votes if we're still looking for candidates
634                if self.nomination().candidates.is_empty()
635                    && self.nomination().round_leaders.contains(&st.node_id)
636                    && let Some(new_vote) =
637                        self.get_new_value_from_nomination(nom)
638                {
639                    if self.nomination_mut().votes.insert(new_vote.clone()) {
640                        modified = true;
641                        self.consensus().nominating_value(
642                            self.slot_proto().index(),
643                            &new_vote,
644                        );
645                    } else {
646                        panic!("bug")
647                    }
648                }
649
650                if modified {
651                    self.emit_nomination();
652                }
653
654                if new_candidates {
655                    // Combine candidates and update state
656                    if let Some(composite) =
657                        self.consensus().combine_candidates(
658                            self.slot_proto().index(),
659                            &self.nomination().candidates,
660                        )
661                    {
662                        self.nomination_mut().latest_composite_candidate =
663                            Some(composite.clone());
664                        self.consensus().updated_candidate_value(
665                            self.slot_proto().index(),
666                            &composite,
667                        );
668                        self.slot_proto_mut().bump_state(&composite, false);
669                    }
670                }
671            }
672
673            EnvelopeState::Valid
674        } else {
675            // Not a nomination statement
676            EnvelopeState::Invalid
677        }
678    }
679
680    pub fn get_statement_values(
681        st: &thruput_scp::SCPStatement,
682    ) -> Vec<thruput_scp::SCPValue> {
683        let mut res = Vec::new();
684        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
685            nominate: nom,
686        } = &st.pledges
687        {
688            Self::apply_all(nom, |v| {
689                res.push(v.clone());
690            });
691        }
692        res
693    }
694
695    #[instrument(skip_all, fields(slot_index = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), entry_round_number = i64::from(self.nomination().round_number)))]
696    pub fn nominate(
697        &mut self,
698        value: &thruput_scp::SCPValue,
699        previous_value: &thruput_scp::SCPValue,
700        timed_out: bool,
701    ) -> bool {
702        debug!(
703            "nomination state: {}",
704            serde_json::to_string_pretty(&self.get_json_info()).unwrap()
705        );
706
707        // No need to continue nominating, as per the whitepaper:
708        // "As soon as `v` has a candidate value, however, it must cease
709        // voting to nominate `x` for any new values `x`"
710        if !self.nomination().candidates.is_empty() {
711            debug!(
712                "nomination skip nomination round {}, already have a candidate",
713                self.nomination().round_number
714            );
715            return false;
716        }
717
718        debug!(
719            "nomination nominate, round {}, value: {}",
720            self.nomination().round_number,
721            hah(value)
722        );
723
724        let mut updated = false;
725
726        if timed_out {
727            self.nomination_mut().timer_exp_count += 1;
728        }
729
730        if timed_out && !self.nomination().nomination_started {
731            debug!("nomination nominate, TIMED OUT");
732            return false;
733        }
734
735        self.nomination_mut().nomination_started = true;
736        self.nomination_mut().previous_value = Some(previous_value.clone());
737        self.nomination_mut().round_number += 1;
738
739        self.update_round_leaders();
740
741        let timeout = self
742            .driver()
743            .compute_timeout(self.nomination().round_number, true);
744
745        // Add a few more values from other leaders
746        for leader in self.nomination().round_leaders.clone().iter() {
747            if let Some(latest_nomination) =
748                self.nomination().latest_nominations.get(leader)
749                && let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
750                    nominate: nom,
751                } = &latest_nomination.statement.pledges
752                && let Some(new_vote) = self.get_new_value_from_nomination(nom)
753                && self.nomination_mut().votes.insert(new_vote.clone())
754            {
755                updated = true;
756                self.consensus()
757                    .nominating_value(self.slot_proto().index(), &new_vote);
758            }
759        }
760
761        // If we're leader, add our value if we haven't added any votes yet
762        let local_node_id =
763            self.slot_proto().local_proto().get_node_id().clone();
764        if self.nomination().round_leaders.contains(&local_node_id)
765            && self.nomination().votes.is_empty()
766        {
767            debug!(
768                "nomination, local node is leader, no votes yet, adding vote for value {}",
769                hah(value)
770            );
771            if self.nomination_mut().votes.insert(value.clone()) {
772                updated = true;
773                self.consensus()
774                    .nominating_value(self.slot_proto().index(), value);
775            }
776        }
777
778        // Setup timer for next nomination round
779        let slot_index = self.slot_proto().index();
780        self.driver().start_timer(
781            slot_index,
782            Timer::Nomination,
783            timeout,
784            DriverCallback::NominationTimerExpired {
785                slot_index,
786                value: value.clone(),
787                prev_value: previous_value.clone(),
788            },
789        );
790
791        if updated {
792            self.emit_nomination();
793        } else {
794            debug!("nomination nominate, SKIPPED");
795        }
796
797        updated
798    }
799
800    pub fn driver_calling_back(&mut self, cb: DriverCallback) {
801        if let DriverCallback::NominationTimerExpired {
802            slot_index: _,
803            value,
804            prev_value,
805        } = cb
806        {
807            let _ = self.nominate(&value, &prev_value, true);
808        }
809    }
810
811    pub fn stop_nomination(&mut self) {
812        self.nomination_mut().nomination_started = false;
813    }
814
815    pub fn get_leaders(&self) -> HashSet<thruput_scp::SCPNodeID> {
816        self.nomination().round_leaders.clone()
817    }
818
819    pub fn get_json_info(&self) -> serde_json::Value {
820        let mut ret = serde_json::json!({});
821
822        ret["roundnumber"] =
823            serde_json::Value::from(self.nomination().round_number);
824        ret["started"] =
825            serde_json::Value::from(self.nomination().nomination_started);
826
827        let mut votes_array = Vec::new();
828        for vote in &self.nomination().votes {
829            votes_array.push(serde_json::Value::String(
830                self.driver().get_value_string(vote),
831            ));
832        }
833        ret["X"] = serde_json::Value::Array(votes_array);
834
835        let mut accepted_array = Vec::new();
836        for accepted in &self.nomination().accepted {
837            accepted_array.push(serde_json::Value::String(
838                self.driver().get_value_string(accepted),
839            ));
840        }
841        ret["Y"] = serde_json::Value::Array(accepted_array);
842
843        let mut candidates_array = Vec::new();
844        for candidate in &self.nomination().candidates {
845            candidates_array.push(serde_json::Value::String(
846                self.driver().get_value_string(candidate),
847            ));
848        }
849        ret["Z"] = serde_json::Value::Array(candidates_array);
850
851        ret
852    }
853
854    pub fn get_state(
855        &self,
856        node_id: &thruput_scp::SCPNodeID,
857        self_already_moved_on: bool,
858    ) -> QuorumInfoNodeState {
859        let mut state = QuorumInfoNodeState::Agree;
860
861        if node_id == self.slot_proto().local_proto().get_node_id() {
862            // always mark myself as AGREE.
863            return state;
864        }
865
866        let enough_time_has_passed =
867            i64::from(self.nomination().timer_exp_count)
868                >= NUM_TIMEOUTS_THRESHOLD_FOR_REPORTING
869                || self_already_moved_on;
870
871        match self.nomination().latest_nominations.get(node_id) {
872            None => {
873                if enough_time_has_passed {
874                    state = QuorumInfoNodeState::Missing;
875                } else {
876                    // Not enough time has passed to start calling this node missing.
877                    state = QuorumInfoNodeState::NoInfo;
878                }
879            }
880            Some(other_envelope) => {
881                if enough_time_has_passed
882                    && let Some(ref last_envelope) =
883                        self.nomination().last_envelope
884                    && let (
885                        thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
886                            nominate: other_nom,
887                        },
888                        thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
889                            nominate: my_nom,
890                        },
891                    ) = (
892                        &other_envelope.statement.pledges,
893                        &last_envelope.statement.pledges,
894                    )
895                {
896                    // Enough time has passed & we have some information on this node.
897                    // We'll examine the information to determine the state of this node.
898                    let mut not_equal = false;
899                    let is_subset = Self::is_subset(
900                        &other_nom.accepted,
901                        &my_nom.accepted,
902                        &mut not_equal,
903                    );
904
905                    if is_subset {
906                        if not_equal {
907                            // If there's some values that I've accepted that
908                            // they haven't, they are slow.
909                            state = QuorumInfoNodeState::Delayed;
910                        }
911                        // else remains AGREE
912                    } else {
913                        // If they have accepted a value that I haven't,
914                        // it's likely that I'll never accept it.
915                        state = QuorumInfoNodeState::Disagree;
916                    }
917                }
918            }
919        }
920
921        state
922    }
923
924    pub fn set_state_from_envelope(
925        &mut self,
926        envelope: &thruput_scp::SCPEnvelope,
927    ) {
928        if self.nomination().nomination_started {
929            panic!("cannot set state after nomination is started");
930        }
931
932        self.record_envelope(envelope);
933
934        if let thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
935            nominate: nom,
936        } = &envelope.statement.pledges
937        {
938            // Add all accepted values from the envelope
939            for accepted_value in nom.accepted.iter() {
940                self.nomination_mut()
941                    .accepted
942                    .insert(accepted_value.clone());
943            }
944
945            // Add all votes from the envelope
946            for vote_value in nom.votes.iter() {
947                self.nomination_mut().votes.insert(vote_value.clone());
948            }
949
950            // Set this as the last envelope
951            self.nomination_mut().last_envelope = Some(envelope.clone());
952        } else {
953            panic!("bug")
954        }
955    }
956
957    pub fn process_current_state<F>(&self, f: &mut F, force_self: bool) -> bool
958    where
959        F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
960    {
961        for (node_id, envelope) in &self.nomination().latest_nominations {
962            // only return messages for self if the slot is fully validated
963            if (force_self
964                || node_id != self.slot_proto().local_proto().get_node_id()
965                || self.slot_proto().is_fully_validated())
966                && !f(envelope)
967            {
968                return false;
969            }
970        }
971        true
972    }
973
974    pub fn get_latest_message(
975        &self,
976        node_id: &thruput_scp::SCPNodeID,
977    ) -> Option<thruput_scp::SCPEnvelope> {
978        self.nomination().latest_nominations.get(node_id).cloned()
979    }
980
981    pub fn get_latest_composite_candidate(
982        &self,
983    ) -> Option<thruput_scp::SCPValue> {
984        self.nomination().latest_composite_candidate.clone()
985    }
986
987    pub fn get_last_message_send(&self) -> Option<thruput_scp::SCPEnvelope> {
988        self.nomination().last_envelope.clone()
989    }
990}
991
992impl<'a, 'b, C: Consensus, D: Driver> NominationProto<'a, 'b, C, D> {
993    pub fn dbg_set_previous_value(&mut self, v: &thruput_scp::SCPValue) {
994        self.nomination_mut().previous_value = Some(v.clone())
995    }
996
997    pub fn dbg_set_round_number(&mut self, r: thruput_scp::SCPCount) {
998        self.nomination_mut().round_number = r
999    }
1000
1001    pub fn dbg_get_round_leaders(
1002        &mut self,
1003    ) -> &HashSet<thruput_scp::SCPNodeID> {
1004        &self.nomination().round_leaders
1005    }
1006}