Skip to main content

scp_kernel/
ballot.rs

1use crate::*;
2use serde_json::json;
3use std::cmp::Ordering;
4use std::collections::{HashMap, HashSet};
5use std::mem::discriminant;
6use tracing::{debug, error, instrument, trace};
7
8#[derive(Debug)]
9pub struct BallotState {
10    heard_from_quorum: bool,
11
12    current: Option<thruput_scp::SCPBallot>, // b
13    prepared: Option<thruput_scp::SCPBallot>, // p
14    prepared_prime: Option<thruput_scp::SCPBallot>, // p'
15    high: Option<thruput_scp::SCPBallot>,    // h
16    commit: Option<thruput_scp::SCPBallot>,  // c
17    value_override: Option<thruput_scp::SCPValue>, // z
18    latest_envelopes: HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>, // M
19    phase: Phase, // phi
20
21    msg_level: i64, // number of messages triggered in one run
22    timer_exp_count: i64, // number of times the timer has expired; used for the quorum endpoint
23
24    last_envelope_gen: Option<thruput_scp::SCPEnvelope>, // last envelope generated by this node
25    last_envelope_emit: Option<thruput_scp::SCPEnvelope>, // last envelope emitted by this node
26}
27
28impl Default for BallotState {
29    fn default() -> Self {
30        BallotState {
31            heard_from_quorum: false,
32            current: None,
33            prepared: None,
34            prepared_prime: None,
35            high: None,
36            commit: None,
37            value_override: None,
38            latest_envelopes: HashMap::new(),
39            phase: Phase::Prepare,
40            msg_level: 0,
41            timer_exp_count: 0,
42            last_envelope_gen: None,
43            last_envelope_emit: None,
44        }
45    }
46}
47
48impl BallotState {
49    pub fn new() -> Self {
50        Self::default()
51    }
52}
53
54#[derive(Debug)]
55pub struct BallotProto<'a, 'b, C: Consensus, D: Driver>(
56    pub &'a mut SlotProto<'b, C, D>,
57);
58
59impl<'a, 'b, C: Consensus, D: Driver> BallotProto<'a, 'b, C, D> {
60    fn slot_proto_mut(&mut self) -> &mut SlotProto<'b, C, D> {
61        self.0
62    }
63
64    fn slot_proto(&self) -> &SlotProto<'b, C, D> {
65        self.0
66    }
67
68    fn ballot_state(&self) -> &BallotState {
69        self.slot_proto().ballot_state()
70    }
71
72    fn ballot_state_mut(&mut self) -> &mut BallotState {
73        self.slot_proto_mut().ballot_state_mut()
74    }
75
76    fn driver(&self) -> &D {
77        self.slot_proto().driver()
78    }
79
80    fn consensus(&self) -> &C {
81        self.slot_proto().consensus()
82    }
83
84    // proto
85
86    fn record_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
87        let node_id = env.statement.node_id.clone();
88        self.ballot_state_mut()
89            .latest_envelopes
90            .insert(node_id, env.clone());
91        self.slot_proto_mut().record_statement(&env.statement);
92    }
93
94    pub fn is_newer_node_statement(
95        &self,
96        node_id: &thruput_scp::SCPNodeID,
97        st: &thruput_scp::SCPStatement,
98    ) -> bool {
99        match self.ballot_state().latest_envelopes.get(node_id) {
100            Some(old) => Self::is_newer_statement(&old.statement, st),
101            None => true,
102        }
103    }
104
105    pub fn is_newer_statement(
106        older: &thruput_scp::SCPStatement,
107        newer: &thruput_scp::SCPStatement,
108    ) -> bool {
109        if discriminant(&older.pledges) != discriminant(&newer.pledges) {
110            older.pledges.stmt_type() < newer.pledges.stmt_type()
111        } else if newer.pledges.stmt_type()
112            == thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE
113        {
114            false
115        } else {
116            match (&older.pledges, &newer.pledges) {
117                // both confirm
118                (
119                    thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
120                        confirm: older_confirm,
121                    },
122                    thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
123                        confirm: newer_confirm,
124                    },
125                ) => match compare_ballots(
126                    &older_confirm.ballot,
127                    &newer_confirm.ballot,
128                ) {
129                    Ordering::Less => true,
130                    Ordering::Equal => {
131                        if older_confirm.n_prepared == newer_confirm.n_prepared
132                        {
133                            older_confirm.n_h < newer_confirm.n_h
134                        } else {
135                            older_confirm.n_prepared < newer_confirm.n_prepared
136                        }
137                    }
138                    Ordering::Greater => false,
139                },
140                // both prepare
141                (
142                    thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
143                        prepare: older_prepare,
144                    },
145                    thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
146                        prepare: newer_prepare,
147                    },
148                ) => match compare_ballots(
149                    &older_prepare.ballot,
150                    &newer_prepare.ballot,
151                ) {
152                    Ordering::Less => true,
153                    Ordering::Equal => {
154                        match compare_opt_ballots(
155                            &older_prepare.prepared,
156                            &newer_prepare.prepared,
157                        ) {
158                            Ordering::Less => true,
159                            Ordering::Equal => match compare_opt_ballots(
160                                &older_prepare.prepared_prime,
161                                &newer_prepare.prepared_prime,
162                            ) {
163                                Ordering::Less => true,
164                                Ordering::Equal => {
165                                    older_prepare.n_h < newer_prepare.n_h
166                                }
167                                Ordering::Greater => false,
168                            },
169                            Ordering::Greater => false,
170                        }
171                    }
172                    Ordering::Greater => false,
173                },
174                // unreachable
175                _ => panic!(),
176            }
177        }
178    }
179
180    pub fn get_statement_values(
181        st: &thruput_scp::SCPStatement,
182    ) -> HashSet<thruput_scp::SCPValue> {
183        let mut values = HashSet::new();
184
185        match &st.pledges {
186            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
187                let b = &prepare.ballot;
188                if b.counter != 0 {
189                    values.insert(prepare.ballot.value.clone());
190                }
191                if let Some(prepared) = &prepare.prepared {
192                    values.insert(prepared.value.clone());
193                }
194                if let Some(prepared_prime) = &prepare.prepared_prime {
195                    values.insert(prepared_prime.value.clone());
196                }
197            }
198            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
199                values.insert(confirm.ballot.value.clone());
200            }
201            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
202                externalize,
203            } => {
204                values.insert(externalize.commit.value.clone());
205            }
206            _ => panic!("bug"),
207        }
208
209        values
210    }
211
212    fn check_valid(
213        ballot_proto: &BallotProto<'a, 'b, C, D>,
214        statement: &thruput_scp::SCPStatement,
215        ours: bool,
216        env: &thruput_scp::SCPEnvelope,
217    ) -> EnvelopeState {
218        if !ballot_proto.is_statement_sane(statement, ours) {
219            if ours {
220                error!(env = ?env, "not sane statement from self, skipping   e: {}", ballot_proto.0.cd.envelope_to_str(env, false));
221            }
222            return EnvelopeState::Invalid;
223        }
224        if !ballot_proto.is_newer_node_statement(&statement.node_id, statement)
225        {
226            if ours {
227                error!(env = ?env, "stale statement from self, skipping   e: {}", ballot_proto.0.cd.envelope_to_str(env, false))
228            } else {
229                trace!(
230                    slot_index = ballot_proto.slot_proto().index(),
231                    "stale statement, skipping"
232                )
233            }
234            return EnvelopeState::Invalid;
235        }
236        EnvelopeState::Valid
237    }
238
239    pub fn should_process_envelope(
240        &self,
241        env: &thruput_scp::SCPEnvelope,
242        ours: bool,
243    ) -> bool {
244        assert!(env.statement.slot_index == self.slot_proto().index());
245
246        let statement = &env.statement;
247
248        !matches!(
249            Self::check_valid(self, statement, ours, env),
250            EnvelopeState::Invalid
251        )
252    }
253
254    #[instrument(skip_all, name = "ballot.process_envelope", fields(slot_index = i64::try_from(env.statement.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(env.statement.slot_index).unwrap_or(i64::MAX)))]
255    pub fn process_envelope(
256        &mut self,
257        env: &thruput_scp::SCPEnvelope,
258        ours: bool,
259    ) -> EnvelopeState {
260        assert!(env.statement.slot_index == self.slot_proto().index());
261
262        let statement = &env.statement;
263
264        if let EnvelopeState::Invalid =
265            Self::check_valid(self, statement, ours, env)
266        {
267            return EnvelopeState::Invalid;
268        }
269
270        let validation_result = self.validate_values(statement);
271        if validation_result == ValidationLevel::Invalid {
272            if ours {
273                error!(env = ?env, "invalid value from self, skipping   e: {}", self.0.cd.envelope_to_str(env, false))
274            } else {
275                trace!(slot_index = self.slot_proto().index(), "invalid value")
276            }
277            return EnvelopeState::Invalid;
278        }
279
280        // check if validity has changed since the call into the app
281        if let EnvelopeState::Invalid =
282            Self::check_valid(self, statement, ours, env)
283        {
284            return EnvelopeState::Invalid;
285        }
286
287        if !matches!(self.ballot_state().phase, Phase::Externalize) {
288            if let ValidationLevel::MaybeValid = validation_result {
289                self.slot_proto_mut().set_fully_validated(false);
290            }
291            self.record_envelope(env);
292            self.advance_slot(statement);
293            return EnvelopeState::Valid;
294        }
295
296        // this handles also our own messages
297        // in particular our final EXTERNALIZE message
298        match &self.ballot_state().commit {
299            Some(c) => {
300                if c.value == Self::get_working_ballot(statement).value {
301                    self.record_envelope(env);
302                    return EnvelopeState::Valid;
303                }
304            }
305            _ => unreachable!(),
306        }
307
308        if ours {
309            error!(env = ?env, "externalize statement with invalid value from self, skipping   e: {}", self.0.cd.envelope_to_str(env, false));
310        }
311
312        EnvelopeState::Invalid
313    }
314
315    pub fn is_statement_sane(
316        &self,
317        statement: &thruput_scp::SCPStatement,
318        ours: bool,
319    ) -> bool {
320        match &self.slot_proto().get_quorum_set_from_statement(statement) {
321            Some(qset) => {
322                if let Result::Err(e) = is_qset_sane(qset, false) {
323                    debug!(err = ?e, "invalid quorum set received");
324                    return false;
325                }
326            }
327            None => {
328                debug!(statement = ?statement, "unknown quorum set");
329                return false;
330            }
331        }
332
333        match &statement.pledges {
334            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
335                // self is allowed to have b = 0 (as long as it never gets emitted)
336                if !(ours || prepare.ballot.counter > 0) {
337                    trace!(statement = ?statement, "malformed PREPARE message");
338                    return false;
339                }
340                if let (Some(pp), Some(p)) =
341                    (&prepare.prepared_prime, &prepare.prepared)
342                    && !are_ballots_less_and_incompatible(pp, p)
343                {
344                    trace!(statement = ?statement, "malformed PREPARE message");
345                    return false;
346                }
347                if prepare.n_h != 0 {
348                    match &prepare.prepared {
349                        Some(p) => {
350                            if prepare.n_h > p.counter {
351                                trace!(statement = ?statement, "malformed PREPARE message");
352                                return false;
353                            }
354                        }
355                        _ => {
356                            trace!(statement = ?statement, "malformed PREPARE message");
357                            return false;
358                        }
359                    }
360                }
361                // c != 0 -> c <= h <= b
362                if prepare.n_c != 0
363                    && !(prepare.n_h != 0
364                        && prepare.ballot.counter >= prepare.n_h
365                        && prepare.n_h >= prepare.n_c)
366                {
367                    trace!(statement = ?statement, "malformed PREPARE message");
368                    return false;
369                }
370                true
371            }
372            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
373                // c <= h <= b
374                if confirm.ballot.counter == 0 {
375                    trace!(statement = ?statement, "malformed CONFIRM message");
376                    return false;
377                }
378                if confirm.n_h > confirm.ballot.counter {
379                    trace!(statement = ?statement, "malformed CONFIRM message");
380                    return false;
381                }
382                if confirm.n_commit > confirm.n_h {
383                    trace!(statement = ?statement, "malformed CONFIRM message");
384                    return false;
385                }
386                true
387            }
388            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
389                externalize,
390            } => {
391                if externalize.commit.counter == 0 {
392                    trace!(statement = ?statement, "malformed EXTERNALIZE message");
393                    return false;
394                }
395                if externalize.n_h < externalize.commit.counter {
396                    trace!(statement = ?statement, "malformed EXTERNALIZE message");
397                    return false;
398                }
399                true
400            }
401            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
402                nominate: _,
403            } => {
404                panic!("unreachable");
405            }
406            _ => panic!("unreachable"),
407        }
408    }
409
410    #[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), ballot_counter = i64::from(n)))]
411    pub fn abandon_ballot(&mut self, n: u32) -> bool {
412        trace!("abandoning ballot");
413        let v = match self.slot_proto_mut().get_latest_composite_candidate() {
414            Some(w) => {
415                if w.is_empty() {
416                    self.ballot_state()
417                        .current
418                        .as_ref()
419                        .map(|cv| cv.value.clone())
420                } else {
421                    Some(w.clone())
422                }
423            }
424            None => self
425                .ballot_state()
426                .current
427                .as_ref()
428                .map(|cv| cv.value.clone()),
429        };
430        match v {
431            Some(w) => {
432                if w.is_empty() {
433                    false
434                } else if n == 0 {
435                    self.bump_state(w, true)
436                } else {
437                    self.bump_state_n(w, n)
438                }
439            }
440            None => false,
441        }
442    }
443
444    #[instrument(skip_all)]
445    pub fn bump_state(
446        &mut self,
447        value: thruput_scp::SCPValue,
448        force: bool,
449    ) -> bool {
450        let n = match &self.ballot_state().current {
451            Some(b) => {
452                if !force {
453                    return false;
454                }
455                b.counter + 1
456            }
457            None => 1,
458        };
459        self.bump_state_n(value, n)
460    }
461
462    fn bump_state_n(&mut self, value: thruput_scp::SCPValue, n: u32) -> bool {
463        match self.ballot_state().phase {
464            Phase::Prepare | Phase::Confirm => {
465                let newv = match &self.ballot_state().value_override {
466                    Some(v) => v.clone(),
467                    None => value,
468                };
469                let newb = thruput_scp::SCPBallot {
470                    counter: n,
471                    value: newv,
472                };
473                trace!(
474                    slot_index = self.slot_proto().index(),
475                    ballot = ?newb,
476                    "ballot protocol bump state"
477                );
478                let updated = self.update_current_value(newb);
479                if updated {
480                    self.emit_current_state_statement();
481                    self.check_heard_from_quorum();
482                };
483                updated
484            }
485            Phase::Externalize | Phase::Num => false,
486        }
487    }
488
489    /// updates the local state based to the specified ballot
490    /// (that could be a prepared ballot) enforcing invariants
491    #[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), ballot_counter = i64::from(new_ballot.counter)))]
492    fn update_current_value(
493        &mut self,
494        new_ballot: thruput_scp::SCPBallot,
495    ) -> bool {
496        if self.ballot_state().phase != Phase::Prepare
497            && self.ballot_state().phase != Phase::Confirm
498        {
499            return false;
500        };
501        let updated = match &self.ballot_state().current {
502            None => {
503                self.bump_to_ballot(new_ballot, true);
504                true
505            }
506            Some(current) => {
507                assert!(
508                    compare_ballots(current, &new_ballot) != Ordering::Greater
509                );
510                if let Some(commit) = &self.ballot_state().commit
511                    && !are_ballots_compatible(commit, &new_ballot)
512                {
513                    return false;
514                }
515                match compare_ballots(current, &new_ballot) {
516                    Ordering::Less => {
517                        self.bump_to_ballot(new_ballot, true);
518                        true
519                    }
520                    Ordering::Equal => false,
521                    Ordering::Greater => {
522                        // this code probably changes with the final version
523                        // of the conciliator
524                        // this case may happen if the other nodes are not
525                        // following the protocol (and we end up with a smaller value)
526                        // not sure what is the best way to deal
527                        // with this situation
528                        error!(
529                            "ballot protocol update_current_value attempt to bump to a smaller value"
530                        );
531                        // can't just bump to the value as we may already have
532                        // statements at counter+1
533                        return false;
534                    }
535                }
536            }
537        };
538        self.check_invariants();
539        updated
540    }
541
542    #[instrument(
543        skip_all,
544        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), ballot_counter = i64::from(ballot.counter))
545    )]
546    fn bump_to_ballot(&mut self, ballot: thruput_scp::SCPBallot, check: bool) {
547        trace!(
548            slot_index = self.slot_proto().index(),
549            ballot = ?ballot,
550            "ballot proto bump_to_ballot"
551        );
552
553        // `bump_to_ballot` should be never called once we committed
554        assert!(self.ballot_state().phase != Phase::Externalize);
555
556        if check && let Some(current) = &self.ballot_state().current {
557            assert!(compare_ballots(&ballot, current) != Ordering::Less);
558        }
559
560        let got_bumped = match &self.ballot_state().current {
561            Some(current) => current.counter != ballot.counter,
562            None => true,
563        };
564
565        if self.ballot_state().current.is_none() {
566            self.slot_proto()
567                .cd
568                .consensus
569                .started_ballot_proto(self.slot_proto().index(), &ballot);
570        }
571
572        self.ballot_state_mut().current = Some(ballot);
573
574        // we have to clear some fields (and recompute them based on latest
575        // messages)
576        // invariant: h.value = b.value
577        if let Some(high) = &self.ballot_state().high
578            && !are_ballots_compatible(
579                self.ballot_state().current.as_ref().unwrap(),
580                high,
581            )
582        {
583            self.ballot_state_mut().high = None;
584            // invariant: c set only when h is set
585            self.ballot_state_mut().commit = None;
586        }
587
588        if got_bumped {
589            self.ballot_state_mut().heard_from_quorum = false;
590        }
591    }
592
593    fn start_timer(&mut self) {
594        let driver = &self.slot_proto().cd.driver;
595        let timeout = driver.compute_timeout(
596            self.ballot_state().current.as_ref().unwrap().counter,
597            false,
598        );
599        let slot_index = self.slot_proto().index();
600        driver.start_timer(
601            slot_index,
602            Timer::Ballot,
603            timeout,
604            DriverCallback::BallotTimerExpired { slot_index },
605        );
606    }
607
608    fn stop_timer(&mut self) {
609        let driver = &self.slot_proto().cd.driver;
610        driver.stop_timer(self.slot_proto().index(), Timer::Ballot);
611    }
612
613    pub fn driver_calling_back(&mut self, cb: DriverCallback) {
614        if let DriverCallback::BallotTimerExpired { slot_index: _ } = cb {
615            self.timer_expired();
616        }
617    }
618
619    pub fn timer_expired(&mut self) {
620        self.ballot_state_mut().timer_exp_count += 1;
621        self.abandon_ballot(0);
622    }
623
624    #[instrument(skip_all)]
625    fn create_statement(
626        &self,
627        typ: thruput_scp::SCPStatementType,
628    ) -> thruput_scp::SCPStatement {
629        self.check_invariants();
630
631        let pledges = match typ {
632            thruput_scp::SCPStatementType::SCP_ST_PREPARE => {
633                let mut prepare = thruput_scp::SCPStatementPrepare {
634                    quorum_set_hash: *self
635                        .slot_proto()
636                        .local_proto()
637                        .get_qset_hash(),
638                    ballot: thruput_scp::SCPBallot {
639                        counter: 0,
640                        value: Default::default(),
641                    },
642                    prepared: None,
643                    prepared_prime: None,
644                    n_c: 0,
645                    n_h: 0,
646                };
647
648                if let Some(ref current) = self.ballot_state().current {
649                    prepare.ballot = current.clone();
650                }
651
652                if let Some(ref commit) = self.ballot_state().commit {
653                    prepare.n_c = commit.counter;
654                }
655
656                if let Some(ref prepared) = self.ballot_state().prepared {
657                    prepare.prepared = Some(prepared.clone());
658                }
659
660                if let Some(ref prepared_prime) =
661                    self.ballot_state().prepared_prime
662                {
663                    prepare.prepared_prime = Some(prepared_prime.clone());
664                }
665
666                if let Some(ref high) = self.ballot_state().high {
667                    prepare.n_h = high.counter;
668                }
669
670                thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare }
671            }
672
673            thruput_scp::SCPStatementType::SCP_ST_CONFIRM => {
674                let confirm = thruput_scp::SCPStatementConfirm {
675                    ballot: self
676                        .ballot_state()
677                        .current
678                        .as_ref()
679                        .unwrap()
680                        .clone(),
681                    n_prepared: self
682                        .ballot_state()
683                        .prepared
684                        .as_ref()
685                        .unwrap()
686                        .counter,
687                    n_commit: self
688                        .ballot_state()
689                        .commit
690                        .as_ref()
691                        .unwrap()
692                        .counter,
693                    n_h: self.ballot_state().high.as_ref().unwrap().counter,
694                    quorum_set_hash: *self
695                        .slot_proto()
696                        .local_proto()
697                        .get_qset_hash(),
698                };
699
700                thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm }
701            }
702
703            thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE => {
704                let externalize = thruput_scp::SCPStatementExternalize {
705                    commit: self
706                        .ballot_state()
707                        .commit
708                        .as_ref()
709                        .unwrap()
710                        .clone(),
711                    n_h: self.ballot_state().high.as_ref().unwrap().counter,
712                    commit_quorum_set_hash: *self
713                        .slot_proto()
714                        .local_proto()
715                        .get_qset_hash(),
716                };
717
718                thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
719                    externalize,
720                }
721            }
722
723            thruput_scp::SCPStatementType::SCP_ST_NOMINATE => {
724                panic!(
725                    "create_statement should not be called with SCP_ST_NOMINATE"
726                );
727            }
728
729            _ => panic!("unreachable"),
730        };
731
732        thruput_scp::SCPStatement {
733            node_id: self.slot_proto().local_proto().get_node_id().clone(),
734            slot_index: self.slot_proto().index(),
735            pledges,
736        }
737    }
738
739    #[instrument(skip_all)]
740    fn send_latest_envelope(&mut self) {
741        // emit current envelope if needed
742        if self.ballot_state().msg_level == 0
743            && self.slot_proto().is_fully_validated()
744        {
745            let driver = &self.slot_proto().cd.driver;
746            let ballot_mut = self.ballot_state_mut();
747            if let Some(last_gen) = &ballot_mut.last_envelope_gen {
748                let should_emit = match &ballot_mut.last_envelope_emit {
749                    None => true,
750                    Some(last_emit) => last_gen != last_emit,
751                };
752
753                if should_emit {
754                    ballot_mut.last_envelope_emit = Some(last_gen.clone());
755                    driver.emit_envelope(last_gen.clone());
756                }
757            }
758        }
759    }
760
761    #[instrument(skip_all)]
762    fn emit_current_state_statement(&mut self) {
763        let statement_type = match self.ballot_state().phase {
764            Phase::Prepare => thruput_scp::SCPStatementType::SCP_ST_PREPARE,
765            Phase::Confirm => thruput_scp::SCPStatementType::SCP_ST_CONFIRM,
766            Phase::Externalize => {
767                thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE
768            }
769            Phase::Num => panic!("bug"),
770        };
771
772        let statement = self.create_statement(statement_type);
773        let envelope = self.slot_proto_mut().create_envelope(statement);
774
775        let can_emit = self.ballot_state().current.is_some();
776
777        // if we generate the same envelope, don't process it again
778        // this can occur when updating h in PREPARE phase
779        // as statements only keep track of h.n (but h.x could be different)
780        let local_proto = self.slot_proto().local_proto();
781        let local_node_id = local_proto.get_node_id();
782        let last_env = self.ballot_state().latest_envelopes.get(local_node_id);
783
784        let should_process = match last_env {
785            None => true,
786            Some(last_envelope) => last_envelope != &envelope,
787        };
788
789        if should_process {
790            let envelope_state = self.process_envelope(&envelope, true);
791            if envelope_state == EnvelopeState::Valid {
792                let should_emit = can_emit && {
793                    match &self.ballot_state().last_envelope_gen {
794                        None => true,
795                        Some(last_gen) => Self::is_newer_statement(
796                            &last_gen.statement,
797                            &envelope.statement,
798                        ),
799                    }
800                };
801
802                if should_emit {
803                    self.ballot_state_mut().last_envelope_gen =
804                        Some(envelope.clone());
805                    // this will no-op if invoked from advanceSlot
806                    // as advanceSlot consolidates all messages sent
807                    self.send_latest_envelope();
808                }
809            } else {
810                // there is a bug in the application if it queued up
811                // a statement for itself that it considers invalid
812                error!(env = ?envelope, "ballot moved to a bad state, due to envelope: {}", 
813                    self.0.cd.envelope_to_str(&envelope, false));
814                panic!("moved to a bad state (ballot protocol)");
815            }
816        }
817    }
818
819    #[instrument(skip_all)]
820    fn get_prepare_candidates(
821        &self,
822        hint: &thruput_scp::SCPStatement,
823    ) -> HashSet<thruput_scp::SCPBallot> {
824        let mut hint_ballots = HashSet::new();
825
826        match &hint.pledges {
827            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
828                hint_ballots.insert(prepare.ballot.clone());
829                if let Some(ref prepared) = prepare.prepared {
830                    hint_ballots.insert(prepared.clone());
831                }
832                if let Some(ref prepared_prime) = prepare.prepared_prime {
833                    hint_ballots.insert(prepared_prime.clone());
834                }
835            }
836            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
837                hint_ballots.insert(thruput_scp::SCPBallot {
838                    counter: confirm.n_prepared,
839                    value: confirm.ballot.value.clone(),
840                });
841                hint_ballots.insert(thruput_scp::SCPBallot {
842                    counter: u32::MAX,
843                    value: confirm.ballot.value.clone(),
844                });
845            }
846            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
847                externalize,
848            } => {
849                hint_ballots.insert(thruput_scp::SCPBallot {
850                    counter: u32::MAX,
851                    value: externalize.commit.value.clone(),
852                });
853            }
854            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
855                panic!(
856                    "getPrepareCandidates should not be called with SCP_ST_NOMINATE"
857                );
858            }
859            _ => panic!("unreachable"),
860        }
861
862        let mut candidates = HashSet::new();
863
864        // Process hint ballots from highest to lowest
865        while !hint_ballots.is_empty() {
866            // Find the highest ballot (by counter, then by value)
867            let top_vote = hint_ballots
868                .iter()
869                .max_by(|a, b| compare_ballots(a, b))
870                .unwrap()
871                .clone();
872            hint_ballots.remove(&top_vote);
873
874            let val = &top_vote.value;
875
876            // Find candidates that may have been prepared
877            for envelope in self.ballot_state().latest_envelopes.values() {
878                match &envelope.statement.pledges {
879                    thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
880                        prepare,
881                    } => {
882                        if are_ballots_less_and_compatible(
883                            &prepare.ballot,
884                            &top_vote,
885                        ) {
886                            candidates.insert(prepare.ballot.clone());
887                        }
888                        if let Some(ref prepared) = prepare.prepared
889                            && are_ballots_less_and_compatible(
890                                prepared, &top_vote,
891                            )
892                        {
893                            candidates.insert(prepared.clone());
894                        }
895                        if let Some(ref prepared_prime) = prepare.prepared_prime
896                            && are_ballots_less_and_compatible(
897                                prepared_prime,
898                                &top_vote,
899                            )
900                        {
901                            candidates.insert(prepared_prime.clone());
902                        }
903                    }
904                    thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
905                        confirm,
906                    } => {
907                        if are_ballots_compatible(&top_vote, &confirm.ballot) {
908                            candidates.insert(top_vote.clone());
909                            if confirm.n_prepared < top_vote.counter {
910                                candidates.insert(thruput_scp::SCPBallot {
911                                    counter: confirm.n_prepared,
912                                    value: val.clone(),
913                                });
914                            }
915                        }
916                    }
917                    thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
918                        externalize,
919                    } => {
920                        if are_ballots_compatible(
921                            &top_vote,
922                            &externalize.commit,
923                        ) {
924                            candidates.insert(top_vote.clone());
925                        }
926                    }
927                    thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
928                        ..
929                    } => {
930                        panic!("bug");
931                    }
932                    _ => panic!("unreachable"),
933                }
934            }
935        }
936
937        candidates
938    }
939
940    fn update_current_if_needed(&mut self, h: &thruput_scp::SCPBallot) -> bool {
941        let should_update = match &self.ballot_state().current {
942            None => true,
943            Some(current) => compare_ballots(current, h) == Ordering::Less,
944        };
945
946        if should_update {
947            self.bump_to_ballot(h.clone(), true);
948            true
949        } else {
950            false
951        }
952    }
953
954    fn has_prepared_ballot(
955        ballot: &thruput_scp::SCPBallot,
956        st: &thruput_scp::SCPStatement,
957    ) -> bool {
958        match &st.pledges {
959            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
960                let prepared_check = prepare
961                    .prepared
962                    .as_ref()
963                    .map(|p| are_ballots_less_and_compatible(ballot, p))
964                    .unwrap_or(false);
965
966                let prepared_prime_check = prepare
967                    .prepared_prime
968                    .as_ref()
969                    .map(|pp| are_ballots_less_and_compatible(ballot, pp))
970                    .unwrap_or(false);
971
972                prepared_check || prepared_prime_check
973            }
974            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
975                let prepared = thruput_scp::SCPBallot {
976                    counter: confirm.n_prepared,
977                    value: confirm.ballot.value.clone(),
978                };
979                are_ballots_less_and_compatible(ballot, &prepared)
980            }
981            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
982                externalize,
983            } => are_ballots_compatible(ballot, &externalize.commit),
984            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
985                panic!("bug");
986            }
987            _ => panic!("unreachable"),
988        }
989    }
990
991    #[instrument(skip(self, voted, accepted))]
992    fn federated_accept<F1, F2>(&self, voted: &F1, accepted: &F2) -> bool
993    where
994        F1: Fn(&thruput_scp::SCPStatement) -> bool,
995        F2: Fn(&thruput_scp::SCPStatement) -> bool,
996    {
997        self.slot_proto().federated_accept(
998            voted,
999            accepted,
1000            &self.ballot_state().latest_envelopes,
1001        )
1002    }
1003
1004    fn set_accept_prepared(&mut self, ballot: &thruput_scp::SCPBallot) -> bool {
1005        trace!(
1006            slot_index = self.slot_proto().index(),
1007            ballot = ?ballot,
1008            "ballot proto set_accept_prepared"
1009        );
1010
1011        // Update our state
1012        let mut did_work = self.set_prepared(ballot.clone());
1013
1014        // Check if we also need to clear 'c'
1015        if let (Some(_commit), Some(high)) =
1016            (&self.ballot_state().commit, &self.ballot_state().high)
1017        {
1018            let should_clear_commit =
1019                if let Some(prepared) = &self.ballot_state().prepared {
1020                    are_ballots_less_and_incompatible(high, prepared)
1021                } else {
1022                    false
1023                } || if let Some(prepared_prime) =
1024                    &self.ballot_state().prepared_prime
1025                {
1026                    are_ballots_less_and_incompatible(high, prepared_prime)
1027                } else {
1028                    false
1029                };
1030
1031            if should_clear_commit {
1032                assert_eq!(self.ballot_state().phase, Phase::Prepare);
1033                self.ballot_state_mut().commit = None;
1034                did_work = true;
1035            }
1036        }
1037
1038        if did_work {
1039            self.consensus()
1040                .accepted_ballot_prepared(self.slot_proto().index(), ballot);
1041            self.emit_current_state_statement();
1042        }
1043
1044        did_work
1045    }
1046
1047    fn set_prepared(&mut self, ballot: thruput_scp::SCPBallot) -> bool {
1048        let mut did_work = false;
1049
1050        // p and p' are the two highest prepared and incompatible ballots
1051        if let Some(ref prepared) = self.ballot_state().prepared {
1052            match compare_ballots(prepared, &ballot) {
1053                Ordering::Less => {
1054                    // as we're replacing p, we see if we should also replace p'
1055                    if !are_ballots_compatible(prepared, &ballot) {
1056                        self.ballot_state_mut().prepared_prime =
1057                            Some(prepared.clone());
1058                    }
1059                    self.ballot_state_mut().prepared = Some(ballot);
1060                    did_work = true;
1061                }
1062                Ordering::Greater => {
1063                    // check if we should update only p', this happens
1064                    // either p' was NULL
1065                    // or p' gets replaced by ballot
1066                    //      (p' < ballot and ballot is incompatible with p)
1067                    // note, the later check is here out of paranoia as this function is
1068                    // not called with a value that would not allow us to make progress
1069
1070                    let should_update_prime = match &self
1071                        .ballot_state()
1072                        .prepared_prime
1073                    {
1074                        None => true,
1075                        Some(prepared_prime) => {
1076                            compare_ballots(prepared_prime, &ballot)
1077                                == Ordering::Less
1078                                && !are_ballots_compatible(prepared, &ballot)
1079                        }
1080                    };
1081
1082                    if should_update_prime {
1083                        self.ballot_state_mut().prepared_prime = Some(ballot);
1084                        did_work = true;
1085                    }
1086                }
1087                Ordering::Equal => {
1088                    // Already have this ballot prepared, no work needed
1089                }
1090            }
1091        } else {
1092            self.ballot_state_mut().prepared = Some(ballot);
1093            did_work = true;
1094        }
1095
1096        did_work
1097    }
1098
1099    #[instrument(skip(self, voted))]
1100    fn federated_ratify<F>(&self, voted: F) -> bool
1101    where
1102        F: Fn(&thruput_scp::SCPStatement) -> bool,
1103    {
1104        self.slot_proto()
1105            .federated_ratify(&voted, &self.ballot_state().latest_envelopes)
1106    }
1107
1108    #[instrument(skip_all)]
1109    fn set_confirm_prepared(
1110        &mut self,
1111        new_c: &thruput_scp::SCPBallot,
1112        new_h: &thruput_scp::SCPBallot,
1113    ) -> bool {
1114        trace!(
1115            slot_index = self.slot_proto().index(),
1116            new_h = ?new_h,
1117            "ballot proto set_confirm_prepared"
1118        );
1119
1120        let mut did_work = false;
1121
1122        // remember newH's value
1123        self.ballot_state_mut().value_override = Some(new_h.value.clone());
1124
1125        // we don't set c/h if we're not on a compatible ballot
1126        let should_update = match &self.ballot_state().current {
1127            None => true,
1128            Some(current) => are_ballots_compatible(current, new_h),
1129        };
1130
1131        if should_update {
1132            if let Some(ref high) = self.ballot_state().high {
1133                if compare_ballots(new_h, high) == Ordering::Greater {
1134                    did_work = true;
1135                    self.ballot_state_mut().high = Some(new_h.clone());
1136                }
1137            } else {
1138                did_work = true;
1139                self.ballot_state_mut().high = Some(new_h.clone());
1140            }
1141
1142            if new_c.counter != 0 {
1143                assert!(self.ballot_state().commit.is_none());
1144                self.ballot_state_mut().commit = Some(new_c.clone());
1145                did_work = true;
1146            }
1147
1148            if did_work {
1149                self.consensus().confirmed_ballot_prepared(
1150                    self.slot_proto().index(),
1151                    new_h,
1152                );
1153            }
1154        }
1155
1156        // always perform step (8) with the computed value of h
1157        let current_updated = self.update_current_if_needed(new_h);
1158        did_work = current_updated || did_work;
1159
1160        if did_work {
1161            self.emit_current_state_statement();
1162        }
1163
1164        did_work
1165    }
1166
1167    fn attempt_confirm_prepared(
1168        &mut self,
1169        hint: &thruput_scp::SCPStatement,
1170    ) -> bool {
1171        if self.ballot_state().phase != Phase::Prepare {
1172            return false;
1173        }
1174
1175        // check if we could accept this ballot as prepared
1176        if self.ballot_state().prepared.is_none() {
1177            return false;
1178        }
1179
1180        let candidates = self.get_prepare_candidates(hint);
1181
1182        // See if we can accept any of the candidates, starting with the highest
1183        let mut new_h: Option<thruput_scp::SCPBallot> = None;
1184        let mut sorted_candidates: Vec<_> = candidates.into_iter().collect();
1185        sorted_candidates.sort_by(|a, b| compare_ballots(b, a)); // Sort in descending order
1186
1187        // find newH
1188        let mut iter = sorted_candidates.iter();
1189        let mut cur = iter.next();
1190        while cur.is_some() {
1191            let ballot = cur.unwrap();
1192
1193            // only consider it if we can potentially raise h
1194            if let Some(ref high) = self.ballot_state().high
1195                && compare_ballots(high, ballot) != Ordering::Less
1196            {
1197                break;
1198            }
1199
1200            let ratified = self.federated_ratify(
1201                |st: &thruput_scp::SCPStatement| -> bool {
1202                    Self::has_prepared_ballot(ballot, st)
1203                },
1204            );
1205
1206            if ratified {
1207                new_h = Some(ballot.clone());
1208                break;
1209            }
1210
1211            cur = iter.next();
1212        }
1213
1214        if let Some(new_h_ballot) = new_h {
1215            let mut new_c = thruput_scp::SCPBallot {
1216                counter: 0,
1217                value: Default::default(),
1218            };
1219
1220            // now, look for newC (left as None if no update)
1221            // step (3) from the paper
1222            let current = match &self.ballot_state().current {
1223                Some(b) => b,
1224                None => &thruput_scp::SCPBallot {
1225                    counter: 0,
1226                    value: Default::default(),
1227                },
1228            };
1229
1230            let should_find_commit = self.ballot_state().commit.is_none()
1231                && (self
1232                    .ballot_state()
1233                    .prepared
1234                    .as_ref()
1235                    .map(|p| {
1236                        !are_ballots_less_and_incompatible(&new_h_ballot, p)
1237                    })
1238                    .unwrap_or(true))
1239                && (self
1240                    .ballot_state()
1241                    .prepared_prime
1242                    .as_ref()
1243                    .map(|pp| {
1244                        !are_ballots_less_and_incompatible(&new_h_ballot, pp)
1245                    })
1246                    .unwrap_or(true));
1247
1248            if should_find_commit {
1249                // continue where we left off (cur is at newH at this point)
1250                while cur.is_some() {
1251                    let ballot = cur.unwrap();
1252                    cur = iter.next();
1253
1254                    if compare_ballots(ballot, current) == Ordering::Less {
1255                        break;
1256                    }
1257
1258                    // c and h must be compatible
1259                    if !are_ballots_less_and_compatible(ballot, &new_h_ballot) {
1260                        continue;
1261                    }
1262
1263                    let ratified = self.federated_ratify(
1264                        |st: &thruput_scp::SCPStatement| -> bool {
1265                            Self::has_prepared_ballot(ballot, st)
1266                        },
1267                    );
1268
1269                    if ratified {
1270                        new_c = ballot.clone();
1271                    } else {
1272                        break;
1273                    }
1274                }
1275            }
1276
1277            return self.set_confirm_prepared(&new_c, &new_h_ballot);
1278        }
1279
1280        false
1281    }
1282
1283    #[instrument(skip_all)]
1284    fn check_heard_from_quorum(&mut self) {
1285        // this method is safe to call regardless of the transitions of the other
1286        // nodes on the network:
1287        // we guarantee that other nodes can only transition to higher counters
1288        // (messages are ignored upstream)
1289        // therefore the local node will not flip flop between "seen" and "not seen"
1290        // for a given counter on the local node
1291        if let Some(current_ballot) = &self.ballot_state().current.clone() {
1292            let is_quorum = LocalProto::<C, D>::is_quorum(
1293                self.slot_proto().local_proto().get_qset(),
1294                &self.ballot_state().latest_envelopes,
1295                &|st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
1296                    self.slot_proto().get_quorum_set_from_statement(st)
1297                },
1298                &|st: &thruput_scp::SCPStatement| -> bool {
1299                    match &st.pledges {
1300                        thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1301                            current_ballot.counter <= prepare.ballot.counter
1302                        }
1303                        _ => true,
1304                    }
1305                },
1306            );
1307
1308            if is_quorum {
1309                let old_hq = self.ballot_state().heard_from_quorum;
1310                self.ballot_state_mut().heard_from_quorum = true;
1311
1312                if !old_hq {
1313                    // if we transition from not heard -> heard, we start the timer
1314                    self.consensus().ballot_did_hear_from_quorum(
1315                        self.slot_proto().index(),
1316                        current_ballot,
1317                    );
1318                    if self.ballot_state().phase != Phase::Externalize {
1319                        self.start_timer();
1320                    }
1321                }
1322
1323                if self.ballot_state().phase == Phase::Externalize {
1324                    self.stop_timer();
1325                }
1326            } else {
1327                self.ballot_state_mut().heard_from_quorum = false;
1328                self.stop_timer();
1329            }
1330        }
1331    }
1332
1333    fn check_invariants(&self) {
1334        match self.ballot_state().phase {
1335            Phase::Prepare => {}
1336            Phase::Confirm | Phase::Externalize => {
1337                assert!(self.ballot_state().current.is_some());
1338                assert!(self.ballot_state().prepared.is_some());
1339                assert!(self.ballot_state().commit.is_some());
1340                assert!(self.ballot_state().high.is_some());
1341            }
1342            Phase::Num => {
1343                panic!("bug");
1344            }
1345        }
1346
1347        if let Some(current) = &self.ballot_state().current {
1348            assert!(current.counter != 0);
1349        }
1350
1351        if let (Some(prepared_prime), Some(prepared)) = (
1352            &self.ballot_state().prepared_prime,
1353            &self.ballot_state().prepared,
1354        ) {
1355            assert!(are_ballots_less_and_incompatible(
1356                prepared_prime,
1357                prepared
1358            ));
1359        }
1360
1361        if let Some(high) = &self.ballot_state().high {
1362            assert!(self.ballot_state().current.is_some(),);
1363            assert!(are_ballots_less_and_compatible(
1364                high,
1365                self.ballot_state().current.as_ref().unwrap()
1366            ),);
1367        }
1368
1369        if let Some(commit) = &self.ballot_state().commit {
1370            assert!(self.ballot_state().current.is_some());
1371            assert!(self.ballot_state().high.is_some());
1372
1373            let high = self.ballot_state().high.as_ref().unwrap();
1374            let current = self.ballot_state().current.as_ref().unwrap();
1375
1376            assert!(are_ballots_less_and_compatible(commit, high));
1377            assert!(are_ballots_less_and_compatible(high, current));
1378        }
1379    }
1380
1381    #[instrument(skip_all)]
1382    fn attempt_accept_prepared(
1383        &mut self,
1384        hint: &thruput_scp::SCPStatement,
1385    ) -> bool {
1386        if self.ballot_state().phase != Phase::Prepare
1387            && self.ballot_state().phase != Phase::Confirm
1388        {
1389            return false;
1390        }
1391
1392        let candidates = self.get_prepare_candidates(hint);
1393
1394        // see if we can accept any of the candidates, starting with the highest
1395        let mut sorted_candidates: Vec<_> = candidates.into_iter().collect();
1396        sorted_candidates.sort_by(|a, b| compare_ballots(b, a)); // Sort in descending order (reverse)
1397
1398        for ballot in sorted_candidates {
1399            if self.ballot_state().phase == Phase::Confirm {
1400                // only consider the ballot if it may help us increase
1401                // p (note: at this point, p ~ c)
1402                if !are_ballots_less_and_compatible(
1403                    self.ballot_state().prepared.as_ref().unwrap(),
1404                    &ballot,
1405                ) {
1406                    continue;
1407                }
1408                assert!(are_ballots_compatible(
1409                    self.ballot_state().commit.as_ref().unwrap(),
1410                    &ballot
1411                ));
1412            }
1413
1414            // if we already prepared this ballot, don't bother checking again
1415
1416            // if ballot <= p' ballot is neither a candidate for p nor p'
1417            if let Some(ref prepared_prime) = self.ballot_state().prepared_prime
1418                && compare_ballots(&ballot, prepared_prime) != Ordering::Greater
1419            {
1420                continue;
1421            }
1422
1423            if let Some(ref prepared) = self.ballot_state().prepared {
1424                // if ballot is already covered by p, skip
1425                if are_ballots_less_and_compatible(&ballot, prepared) {
1426                    continue;
1427                }
1428                // otherwise, there is a chance it increases p'
1429            }
1430
1431            let accepted = self.federated_accept(
1432                // checks if any node is voting for this ballot
1433                &|st: &thruput_scp::SCPStatement| -> bool {
1434                    match &st.pledges {
1435                        thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1436                            are_ballots_less_and_compatible(&ballot, &prepare.ballot)
1437                        }
1438                        thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1439                            are_ballots_compatible(&ballot, &confirm.ballot)
1440                        }
1441                        thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { externalize } => {
1442                            are_ballots_compatible(&ballot, &externalize.commit)
1443                        }
1444                        _ => panic!("bug"),
1445                    }
1446                },
1447                &|st: &thruput_scp::SCPStatement| -> bool { Self::has_prepared_ballot(&ballot, st) },
1448            );
1449
1450            if accepted {
1451                return self.set_accept_prepared(&ballot);
1452            }
1453        }
1454
1455        false
1456    }
1457
1458    fn commit_predicate(
1459        ballot: &thruput_scp::SCPBallot,
1460        check: &Interval,
1461        st: &thruput_scp::SCPStatement,
1462    ) -> bool {
1463        match &st.pledges {
1464            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { .. } => false,
1465            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1466                if are_ballots_compatible(ballot, &confirm.ballot) {
1467                    confirm.n_commit <= check.lo && check.hi <= confirm.n_h
1468                } else {
1469                    false
1470                }
1471            }
1472            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1473                externalize,
1474            } => {
1475                if are_ballots_compatible(ballot, &externalize.commit) {
1476                    externalize.commit.counter <= check.lo
1477                } else {
1478                    false
1479                }
1480            }
1481            _ => panic!("bug"),
1482        }
1483    }
1484
1485    /// helper function to find a contiguous range 'candidate' that satisfies the
1486    /// predicate. updates 'candidate' (or leave it unchanged)
1487    fn find_extended_interval<F>(
1488        candidate: &mut Interval,
1489        boundaries: &HashSet<thruput_scp::SCPCount>,
1490        pred: F,
1491    ) where
1492        F: Fn(&Interval) -> bool,
1493    {
1494        // collect boundaries into a vector and sort, then iterate from the top
1495        let mut sorted_boundaries: Vec<thruput_scp::SCPCount> =
1496            boundaries.iter().copied().collect();
1497        sorted_boundaries.sort();
1498
1499        for &b in sorted_boundaries.iter().rev() {
1500            let cur = if candidate.lo == 0 {
1501                // first, find the high bound
1502                Interval { lo: b, hi: b }
1503            } else if b > candidate.hi {
1504                // invalid
1505                continue;
1506            } else {
1507                Interval {
1508                    lo: b,
1509                    hi: candidate.hi,
1510                }
1511            };
1512
1513            if pred(&cur) {
1514                *candidate = cur;
1515            } else if candidate.lo != 0 {
1516                // could not extend further
1517                break;
1518            }
1519        }
1520    }
1521
1522    /// constructs the set of counters representing the
1523    /// commit ballots compatible with the ballot
1524    fn get_commit_boundaries_from_statements(
1525        &self,
1526        ballot: &thruput_scp::SCPBallot,
1527    ) -> HashSet<thruput_scp::SCPCount> {
1528        let mut res = HashSet::new();
1529
1530        for envelope in self.ballot_state().latest_envelopes.values() {
1531            match &envelope.statement.pledges {
1532                thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
1533                    prepare,
1534                } => {
1535                    if are_ballots_compatible(ballot, &prepare.ballot)
1536                        && prepare.n_c != 0
1537                    {
1538                        res.insert(prepare.n_c);
1539                        res.insert(prepare.n_h);
1540                    }
1541                }
1542                thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
1543                    confirm,
1544                } => {
1545                    if are_ballots_compatible(ballot, &confirm.ballot) {
1546                        res.insert(confirm.n_commit);
1547                        res.insert(confirm.n_h);
1548                    }
1549                }
1550                thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1551                    externalize,
1552                } => {
1553                    if are_ballots_compatible(ballot, &externalize.commit) {
1554                        res.insert(externalize.commit.counter);
1555                        res.insert(externalize.n_h);
1556                        res.insert(u32::MAX);
1557                    }
1558                }
1559                _ => panic!("bug"),
1560            }
1561        }
1562
1563        res
1564    }
1565
1566    #[instrument(skip_all)]
1567    fn set_accept_commit(
1568        &mut self,
1569        c: &thruput_scp::SCPBallot,
1570        h: &thruput_scp::SCPBallot,
1571    ) -> bool {
1572        trace!(
1573            slot_index = self.slot_proto().index(),
1574            c = ?c,
1575            h = ?h,
1576            "ballot proto set_accept_commit"
1577        );
1578
1579        let mut did_work = false;
1580
1581        // remember h's value
1582        self.ballot_state_mut().value_override = Some(h.value.clone());
1583
1584        let high_changed = match &self.ballot_state().high {
1585            None => true,
1586            Some(current_high) => {
1587                compare_ballots(current_high, h) != Ordering::Equal
1588            }
1589        };
1590
1591        let commit_changed = match &self.ballot_state().commit {
1592            None => true,
1593            Some(current_commit) => {
1594                compare_ballots(current_commit, c) != Ordering::Equal
1595            }
1596        };
1597
1598        if high_changed || commit_changed {
1599            self.ballot_state_mut().commit = Some(c.clone());
1600            self.ballot_state_mut().high = Some(h.clone());
1601            did_work = true;
1602        }
1603
1604        if self.ballot_state().phase == Phase::Prepare {
1605            self.ballot_state_mut().phase = Phase::Confirm;
1606
1607            if let Some(current) = &self.ballot_state().current
1608                && !are_ballots_less_and_compatible(h, current)
1609            {
1610                self.bump_to_ballot(h.clone(), false);
1611            }
1612
1613            self.ballot_state_mut().prepared_prime = None;
1614            did_work = true;
1615        }
1616
1617        if did_work {
1618            self.update_current_if_needed(
1619                &self.ballot_state().high.as_ref().unwrap().clone(),
1620            );
1621            self.consensus()
1622                .accepted_commit(self.slot_proto().index(), h);
1623            self.emit_current_state_statement();
1624        }
1625
1626        did_work
1627    }
1628
1629    #[instrument(skip_all)]
1630    fn attempt_accept_commit(
1631        &mut self,
1632        hint: &thruput_scp::SCPStatement,
1633    ) -> bool {
1634        if self.ballot_state().phase != Phase::Prepare
1635            && self.ballot_state().phase != Phase::Confirm
1636        {
1637            return false;
1638        }
1639
1640        // extracts value from hint
1641        // note: ballot.counter is only used for logging purpose as we're looking at
1642        // possible value to commit
1643        let ballot = match &hint.pledges {
1644            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1645                if prepare.n_c != 0 {
1646                    thruput_scp::SCPBallot {
1647                        counter: prepare.n_h,
1648                        value: prepare.ballot.value.clone(),
1649                    }
1650                } else {
1651                    return false;
1652                }
1653            }
1654            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1655                thruput_scp::SCPBallot {
1656                    counter: confirm.n_h,
1657                    value: confirm.ballot.value.clone(),
1658                }
1659            }
1660            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1661                externalize,
1662            } => thruput_scp::SCPBallot {
1663                counter: externalize.n_h,
1664                value: externalize.commit.value.clone(),
1665            },
1666            _ => panic!("bug"),
1667        };
1668
1669        if self.ballot_state().phase == Phase::Confirm
1670            && !are_ballots_compatible(
1671                &ballot,
1672                self.ballot_state().high.as_ref().unwrap(),
1673            )
1674        {
1675            return false;
1676        }
1677
1678        let pred = |cur: &Interval| -> bool {
1679            self.federated_accept(
1680                &|st: &thruput_scp::SCPStatement| -> bool {
1681                    match &st.pledges {
1682                        thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1683                            are_ballots_compatible(&ballot, &prepare.ballot)
1684                                && prepare.n_c != 0
1685                                && prepare.n_c <= cur.lo
1686                                && cur.hi <= prepare.n_h
1687                        }
1688                        thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1689                            if are_ballots_compatible(&ballot, &confirm.ballot) {
1690                                confirm.n_commit <= cur.lo
1691                            } else {
1692                                false
1693                            }
1694                        }
1695                        thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { externalize } => {
1696                            if are_ballots_compatible(&ballot, &externalize.commit) {
1697                                externalize.commit.counter <= cur.lo
1698                            } else {
1699                                false
1700                            }
1701                        }
1702                        _ => panic!("bug"),
1703                    }
1704                },
1705                &|st: &thruput_scp::SCPStatement| -> bool {
1706                    Self::commit_predicate(&ballot, cur, st)
1707                },
1708            )
1709        };
1710
1711        // build the boundaries to scan
1712        let boundaries = self.get_commit_boundaries_from_statements(&ballot);
1713
1714        if boundaries.is_empty() {
1715            return false;
1716        }
1717
1718        // now, look for the high interval
1719        let mut candidate = Interval { lo: 0, hi: 0 };
1720        Self::find_extended_interval(&mut candidate, &boundaries, pred);
1721
1722        if candidate.lo != 0
1723            && (self.ballot_state().phase != Phase::Confirm
1724                || candidate.hi
1725                    > self.ballot_state().high.as_ref().unwrap().counter)
1726        {
1727            let c = thruput_scp::SCPBallot {
1728                counter: candidate.lo,
1729                value: ballot.value.clone(),
1730            };
1731            let h = thruput_scp::SCPBallot {
1732                counter: candidate.hi,
1733                value: ballot.value.clone(),
1734            };
1735            return self.set_accept_commit(&c, &h);
1736        }
1737
1738        false
1739    }
1740
1741    #[instrument(skip_all)]
1742    fn attempt_bump(&mut self) -> bool {
1743        if self.ballot_state().phase == Phase::Prepare
1744            || self.ballot_state().phase == Phase::Confirm
1745        {
1746            // First check to see if this condition applies at all. If there
1747            // is no v-blocking set ahead of the local node, there's nothing
1748            // to do, return early.
1749            let local_counter = match &self.ballot_state().current {
1750                Some(current) => current.counter,
1751                None => 0,
1752            };
1753
1754            if !has_v_blocking_subset_strictly_ahead_of(
1755                &self.slot_proto().local_proto(),
1756                &self.ballot_state().latest_envelopes,
1757                local_counter,
1758            ) {
1759                return false;
1760            }
1761
1762            // Collect all possible counters we might need to advance to.
1763            let mut all_counters = HashSet::new();
1764            for envelope in self.ballot_state().latest_envelopes.values() {
1765                let c = statement_ballot_counter(&envelope.statement);
1766                if c > local_counter {
1767                    all_counters.insert(c);
1768                }
1769            }
1770
1771            let mut all_counters_sorted: Vec<thruput_scp::SCPCount> =
1772                all_counters.into_iter().collect();
1773            all_counters_sorted.sort();
1774
1775            // If we got to here, implicitly there _was_ a v-blocking subset
1776            // with counters above the local counter; we just need to find a
1777            // minimal n at which that's no longer true. So check them in
1778            // order, starting from the smallest.
1779            for n in all_counters_sorted {
1780                if !has_v_blocking_subset_strictly_ahead_of(
1781                    &self.slot_proto().local_proto(),
1782                    &self.ballot_state().latest_envelopes,
1783                    n,
1784                ) {
1785                    // Move to n.
1786                    return self.abandon_ballot(n);
1787                }
1788            }
1789        }
1790        false
1791    }
1792
1793    #[instrument(skip_all)]
1794    fn attempt_confirm_commit(
1795        &mut self,
1796        hint: &thruput_scp::SCPStatement,
1797    ) -> bool {
1798        if self.ballot_state().phase != Phase::Confirm {
1799            return false;
1800        }
1801
1802        if self.ballot_state().high.is_none()
1803            || self.ballot_state().commit.is_none()
1804        {
1805            return false;
1806        }
1807
1808        // extracts value from hint
1809        // note: ballot.counter is only used for logging purpose
1810        let ballot = match &hint.pledges {
1811            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { .. } => {
1812                return false;
1813            }
1814            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1815                thruput_scp::SCPBallot {
1816                    counter: confirm.n_h,
1817                    value: confirm.ballot.value.clone(),
1818                }
1819            }
1820            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1821                externalize,
1822            } => thruput_scp::SCPBallot {
1823                counter: externalize.n_h,
1824                value: externalize.commit.value.clone(),
1825            },
1826            _ => panic!("bug"),
1827        };
1828
1829        if !are_ballots_compatible(
1830            &ballot,
1831            self.ballot_state().commit.as_ref().unwrap(),
1832        ) {
1833            return false;
1834        }
1835
1836        let boundaries = self.get_commit_boundaries_from_statements(&ballot);
1837        let mut candidate = Interval { lo: 0, hi: 0 };
1838
1839        let pred = |cur: &Interval| -> bool {
1840            self.federated_ratify(|st: &thruput_scp::SCPStatement| -> bool {
1841                Self::commit_predicate(&ballot, cur, st)
1842            })
1843        };
1844
1845        Self::find_extended_interval(&mut candidate, &boundaries, pred);
1846
1847        if candidate.lo != 0 {
1848            let c = thruput_scp::SCPBallot {
1849                counter: candidate.lo,
1850                value: ballot.value.clone(),
1851            };
1852            let h = thruput_scp::SCPBallot {
1853                counter: candidate.hi,
1854                value: ballot.value.clone(),
1855            };
1856            return self.set_confirm_commit(&c, &h);
1857        }
1858
1859        false
1860    }
1861
1862    #[instrument(skip_all)]
1863    fn set_confirm_commit(
1864        &mut self,
1865        c: &thruput_scp::SCPBallot,
1866        h: &thruput_scp::SCPBallot,
1867    ) -> bool {
1868        trace!(
1869            slot_index = self.slot_proto().index(),
1870            c = ?c,
1871            h = ?h,
1872            "ballot proto set_confirm_commit"
1873        );
1874
1875        self.ballot_state_mut().commit = Some(c.clone());
1876        self.ballot_state_mut().high = Some(h.clone());
1877        self.update_current_if_needed(h);
1878
1879        self.ballot_state_mut().phase = Phase::Externalize;
1880
1881        self.emit_current_state_statement();
1882
1883        self.slot_proto_mut().stop_nomination();
1884
1885        self.consensus()
1886            .value_externalized(self.slot_proto().index(), &c.value);
1887
1888        true
1889    }
1890
1891    // helper function to retrieve b for PREPARE, P for CONFIRM or
1892    // c for EXTERNALIZE messages
1893    fn get_working_ballot(
1894        st: &thruput_scp::SCPStatement,
1895    ) -> thruput_scp::SCPBallot {
1896        match &st.pledges {
1897            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1898                prepare.ballot.clone()
1899            }
1900            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1901                thruput_scp::SCPBallot {
1902                    counter: confirm.n_commit,
1903                    value: confirm.ballot.value.clone(),
1904                }
1905            }
1906            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1907                externalize,
1908            } => externalize.commit.clone(),
1909            _ => panic!("bug"),
1910        }
1911    }
1912
1913    #[instrument(skip_all)]
1914    pub fn set_state_from_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
1915        // cannot set state after starting ballot protocol
1916        assert!(self.ballot_state().current.is_none());
1917
1918        self.record_envelope(env);
1919
1920        self.ballot_state_mut().last_envelope_gen = Some(env.clone());
1921        self.ballot_state_mut().last_envelope_emit = Some(env.clone());
1922
1923        match &env.statement.pledges {
1924            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
1925                let b = &prepare.ballot;
1926                self.bump_to_ballot(b.clone(), true);
1927
1928                if let Some(prepared) = &prepare.prepared {
1929                    self.ballot_state_mut().prepared = Some(prepared.clone());
1930                }
1931
1932                if let Some(prepared_prime) = &prepare.prepared_prime {
1933                    self.ballot_state_mut().prepared_prime =
1934                        Some(prepared_prime.clone());
1935                }
1936
1937                if prepare.n_h != 0 {
1938                    self.ballot_state_mut().high =
1939                        Some(thruput_scp::SCPBallot {
1940                            counter: prepare.n_h,
1941                            value: b.value.clone(),
1942                        });
1943                }
1944
1945                if prepare.n_c != 0 {
1946                    self.ballot_state_mut().commit =
1947                        Some(thruput_scp::SCPBallot {
1948                            counter: prepare.n_c,
1949                            value: b.value.clone(),
1950                        });
1951                }
1952
1953                self.ballot_state_mut().phase = Phase::Prepare;
1954            }
1955            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
1956                let v = &confirm.ballot.value;
1957                self.bump_to_ballot(confirm.ballot.clone(), true);
1958
1959                self.ballot_state_mut().prepared =
1960                    Some(thruput_scp::SCPBallot {
1961                        counter: confirm.n_prepared,
1962                        value: v.clone(),
1963                    });
1964
1965                self.ballot_state_mut().high = Some(thruput_scp::SCPBallot {
1966                    counter: confirm.n_h,
1967                    value: v.clone(),
1968                });
1969
1970                self.ballot_state_mut().commit = Some(thruput_scp::SCPBallot {
1971                    counter: confirm.n_commit,
1972                    value: v.clone(),
1973                });
1974
1975                self.ballot_state_mut().phase = Phase::Confirm;
1976            }
1977            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
1978                externalize,
1979            } => {
1980                let v = &externalize.commit.value;
1981                self.bump_to_ballot(
1982                    thruput_scp::SCPBallot {
1983                        counter: u32::MAX,
1984                        value: v.clone(),
1985                    },
1986                    true,
1987                );
1988
1989                self.ballot_state_mut().prepared =
1990                    Some(thruput_scp::SCPBallot {
1991                        counter: u32::MAX,
1992                        value: v.clone(),
1993                    });
1994
1995                self.ballot_state_mut().high = Some(thruput_scp::SCPBallot {
1996                    counter: externalize.n_h,
1997                    value: v.clone(),
1998                });
1999
2000                self.ballot_state_mut().commit =
2001                    Some(externalize.commit.clone());
2002
2003                self.ballot_state_mut().phase = Phase::Externalize;
2004            }
2005            _ => panic!("bug"),
2006        }
2007    }
2008
2009    pub fn process_current_state<F>(&self, f: &mut F, force_self: bool) -> bool
2010    where
2011        F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
2012    {
2013        for (node_id, envelope) in &self.ballot_state().latest_envelopes {
2014            // only return messages for self if the slot is fully validated
2015            if (force_self
2016                || node_id != self.slot_proto().local_proto().get_node_id()
2017                || self.slot_proto().is_fully_validated())
2018                && !f(envelope)
2019            {
2020                return false;
2021            }
2022        }
2023        true
2024    }
2025
2026    pub fn get_latest_message(
2027        &self,
2028        id: &thruput_scp::SCPNodeID,
2029    ) -> Option<thruput_scp::SCPEnvelope> {
2030        self.ballot_state().latest_envelopes.get(id).cloned()
2031    }
2032
2033    pub fn get_externalizing_state(&self) -> Vec<thruput_scp::SCPEnvelope> {
2034        let mut res = Vec::new();
2035
2036        if self.ballot_state().phase == Phase::Externalize {
2037            res.reserve(self.ballot_state().latest_envelopes.len());
2038
2039            for (node_id, envelope) in &self.ballot_state().latest_envelopes {
2040                if node_id != self.slot_proto().local_proto().get_node_id() {
2041                    // good approximation: statements with the value that externalized
2042                    // we could filter more using mConfirmedPrepared as well
2043                    if are_ballots_compatible(
2044                        &Self::get_working_ballot(&envelope.statement),
2045                        self.ballot_state().commit.as_ref().unwrap(),
2046                    ) {
2047                        res.push(envelope.clone());
2048                    }
2049                } else if self.slot_proto().is_fully_validated() {
2050                    // only return messages for self if the slot is fully validated
2051                    res.push(envelope.clone());
2052                }
2053            }
2054        }
2055
2056        res
2057    }
2058
2059    #[instrument(skip_all)]
2060    fn validate_values(
2061        &self,
2062        st: &thruput_scp::SCPStatement,
2063    ) -> ValidationLevel {
2064        let values = Self::get_statement_values(st);
2065
2066        if values.is_empty() {
2067            // This shouldn't happen
2068            return ValidationLevel::Invalid;
2069        }
2070
2071        let mut res = ValidationLevel::FullyValid;
2072        for value in values {
2073            if res > ValidationLevel::Invalid {
2074                let validation_result = self
2075                    .consensus()
2076                    .validate_ballot_value(self.slot_proto().index(), &value);
2077                res = std::cmp::min(validation_result, res);
2078            }
2079        }
2080
2081        res
2082    }
2083
2084    pub fn get_state(
2085        &self,
2086        n: &thruput_scp::SCPNodeID,
2087        self_already_moved_on: bool,
2088    ) -> QuorumInfoNodeState {
2089        let mut state = QuorumInfoNodeState::Agree;
2090
2091        if n == self.slot_proto().local_proto().get_node_id() {
2092            // always mark myself as AGREE.
2093            return state;
2094        }
2095
2096        if let Some(envelope) = self.ballot_state().latest_envelopes.get(n) {
2097            if let Some(last_envelope_emit) =
2098                &self.ballot_state().last_envelope_emit
2099            {
2100                let st = &envelope.statement;
2101                let externalized = matches!(
2102                    st.pledges,
2103                    thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { .. }
2104                );
2105
2106                let confirmed_commit = match &st.pledges {
2107                    thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
2108                        confirm,
2109                    } => confirm.ballot.counter == u32::MAX,
2110                    _ => false,
2111                };
2112
2113                if self.ballot_state().phase == Phase::Externalize
2114                    && (!externalized || !confirmed_commit)
2115                    && self_already_moved_on
2116                {
2117                    // We have already externalized and moved onto the next slot.
2118                    // However, this node hasn't externalized yet.
2119                    state = QuorumInfoNodeState::Delayed;
2120                }
2121
2122                let self_accepted_confirm = self.ballot_state().phase
2123                    == Phase::Confirm
2124                    || self.ballot_state().phase == Phase::Externalize;
2125
2126                let other_accepted_confirm = matches!(
2127                    st.pledges,
2128                    thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { .. }
2129                        | thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { .. }
2130                );
2131
2132                let self_st = &last_envelope_emit.statement;
2133
2134                if self_accepted_confirm
2135                    && other_accepted_confirm
2136                    && !are_ballots_compatible(
2137                        &Self::get_working_ballot(st),
2138                        &Self::get_working_ballot(self_st),
2139                    )
2140                {
2141                    // n has accepted to commit a different value than mine!
2142                    // Even if this node has been marked something else,
2143                    // we will overwrite it since this is bad.
2144                    state = QuorumInfoNodeState::Disagree;
2145                }
2146            }
2147        } else if self.ballot_state().timer_exp_count
2148            >= NUM_TIMEOUTS_THRESHOLD_FOR_REPORTING
2149            || self_already_moved_on
2150        {
2151            state = QuorumInfoNodeState::Missing;
2152        } else {
2153            // It's too soon to start calling this node MISSING.
2154            state = QuorumInfoNodeState::NoInfo;
2155        }
2156
2157        state
2158    }
2159
2160    pub fn get_json_quorum_info(
2161        &self,
2162        id: &thruput_scp::SCPNodeID,
2163        summary: bool,
2164        full_keys: bool,
2165    ) -> serde_json::Value {
2166        let mut ret = serde_json::json!({});
2167
2168        // find the state of the node `id`
2169        let mut b = thruput_scp::SCPBallot {
2170            counter: 0,
2171            value: thruput_scp::SCPValue::default(),
2172        };
2173        let mut q_set_hash = thruput_scp::SCPHash::default();
2174
2175        if let Some(envelope) = self.ballot_state().latest_envelopes.get(id) {
2176            let st = &envelope.statement;
2177
2178            match &st.pledges {
2179                thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
2180                    prepare,
2181                } => {
2182                    ret["phase"] =
2183                        serde_json::Value::String("PREPARE".to_string());
2184                    b = prepare.ballot.clone();
2185                }
2186                thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
2187                    confirm,
2188                } => {
2189                    ret["phase"] =
2190                        serde_json::Value::String("CONFIRM".to_string());
2191                    b = confirm.ballot.clone();
2192                }
2193                thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
2194                    externalize,
2195                } => {
2196                    ret["phase"] =
2197                        serde_json::Value::String("EXTERNALIZE".to_string());
2198                    b = externalize.commit.clone();
2199                }
2200                _ => panic!("bug"),
2201            }
2202
2203            // use the companion set here even for externalize to capture
2204            // the view of the quorum set during consensus
2205            q_set_hash =
2206                federated::get_companion_quorum_set_hash_from_statement(st);
2207        } else {
2208            ret["phase"] = serde_json::Value::String("unknown".to_string());
2209            if id == self.slot_proto().local_proto().get_node_id() {
2210                q_set_hash = *self.slot_proto().local_proto().get_qset_hash();
2211            }
2212        }
2213
2214        let Some(q_set) = self.driver().get_qset(&q_set_hash) else {
2215            ret["phase"] = serde_json::Value::String("expired".to_string());
2216            return ret;
2217        };
2218        let local_proto = self.slot_proto().local_proto();
2219        let f = local_proto.find_closest_v_blocking_envelopes(
2220            &q_set,
2221            &self.ballot_state().latest_envelopes,
2222            |st: &thruput_scp::SCPStatement| -> bool {
2223                are_ballots_compatible(&Self::get_working_ballot(st), &b)
2224            },
2225            Some(id),
2226        );
2227
2228        ret["fail_at"] =
2229            serde_json::Value::Number(serde_json::Number::from(f.len()));
2230
2231        if !summary {
2232            let mut f_ex = serde_json::json!([]);
2233            for n in f {
2234                f_ex.as_array_mut().unwrap().push(serde_json::Value::String(
2235                    self.driver().to_str_key(&n, full_keys),
2236                ));
2237            }
2238            ret["fail_with"] = f_ex;
2239            ret["value"] =
2240                self.slot_proto().local_proto().to_json(&q_set, full_keys);
2241        }
2242
2243        ret["hash"] = serde_json::Value::String(hex_abbrev(&q_set_hash));
2244
2245        ret
2246    }
2247
2248    // attempts to make progress using the latest statement as a hint
2249    // calls into the various attempt* methods, emits message
2250    // to make progress
2251    #[instrument(skip_all, fields(slot_index = i64::try_from(hint.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(hint.slot_index).unwrap_or(i64::MAX)))]
2252    fn advance_slot(&mut self, hint: &thruput_scp::SCPStatement) {
2253        const MAX_ADVANCE_SLOT_RECURSION: i64 = 100;
2254
2255        self.ballot_state_mut().msg_level += 1;
2256        trace!(
2257            msg_level = self.ballot_state().msg_level,
2258            local_state = ?self.get_local_state(),
2259            "ballot proto advance_slot"
2260        );
2261
2262        if self.ballot_state().msg_level >= MAX_ADVANCE_SLOT_RECURSION {
2263            panic!("maximum number of transitions reached in advance_slot");
2264        }
2265
2266        // attempt* methods will queue up messages, causing advance_slot to be
2267        // called recursively
2268
2269        // done in order so that we follow the steps from the white paper in
2270        // order allowing the state to be updated properly
2271
2272        let mut did_work = false;
2273
2274        did_work = self.attempt_accept_prepared(hint) || did_work;
2275
2276        did_work = self.attempt_confirm_prepared(hint) || did_work;
2277
2278        did_work = self.attempt_accept_commit(hint) || did_work;
2279
2280        did_work = self.attempt_confirm_commit(hint) || did_work;
2281
2282        // only bump after we're done with everything else
2283        if self.ballot_state().msg_level == 1 {
2284            #[allow(unused_assignments)]
2285            let mut did_bump = false;
2286            loop {
2287                // attempt_bump may invoke advance_slot recursively
2288                did_bump = self.attempt_bump();
2289                did_work = did_bump || did_work;
2290                if !did_bump {
2291                    break;
2292                }
2293            }
2294
2295            self.check_heard_from_quorum();
2296        }
2297
2298        trace!(
2299            msg_level = self.ballot_state().msg_level,
2300            local_state = ?self.get_local_state(),
2301            "ballot proto advance_slot exiting"
2302        );
2303
2304        self.ballot_state_mut().msg_level -= 1;
2305
2306        if did_work {
2307            self.send_latest_envelope();
2308        }
2309    }
2310
2311    fn get_local_state(&self) -> String {
2312        let state = BallotLocalState {
2313            slot_index: self.slot_proto().index(),
2314            ballot: self.ballot_state(),
2315        };
2316        format!("{:?}", state)
2317    }
2318
2319    pub fn get_json_info(&self) -> serde_json::Value {
2320        json!({
2321           "heard": self.ballot_state().heard_from_quorum,
2322           "ballot": self.0.cd.opt_ballot_to_str(self.ballot_state().current.as_ref()),
2323           "phase": self.ballot_state().phase.to_string(),
2324           "state": self.get_local_state(),
2325        })
2326    }
2327
2328    pub fn get_last_message_send(&self) -> Option<thruput_scp::SCPEnvelope> {
2329        self.ballot_state().last_envelope_emit.clone()
2330    }
2331}
2332
2333#[derive(Debug)]
2334#[allow(dead_code)]
2335struct BallotLocalState<'a> {
2336    pub slot_index: thruput_scp::SCPSlotIndex,
2337    pub ballot: &'a BallotState,
2338}