Skip to main content

scp_kernel/
slot.rs

1use crate::*;
2use std::collections::{HashMap, HashSet};
3use std::time::SystemTime;
4use tracing::instrument;
5
6pub type SlotIndex = u64;
7
8// The number of times the timer has to expire before we consider the node
9// missing. Used for reporting purposes only.
10pub const NUM_TIMEOUTS_THRESHOLD_FOR_REPORTING: i64 = 2;
11
12#[derive(Debug)]
13pub struct SlotState {
14    pub slot_index: SlotIndex,
15    pub nomination: NominationState,
16    pub ballot: BallotState,
17    pub statements_history: Vec<HistoricalStatement>,
18    pub fully_validated: bool,
19    pub got_vblocking: bool,
20}
21
22#[derive(Debug, Clone)]
23pub struct HistoricalStatement {
24    pub when: SystemTime,
25    pub statement: thruput_scp::SCPStatement,
26    pub validated: bool,
27}
28
29impl SlotState {
30    pub fn new(slot_index: SlotIndex, is_validator: bool) -> Self {
31        SlotState {
32            slot_index,
33            nomination: NominationState::new(),
34            ballot: BallotState::new(),
35            statements_history: Vec::new(),
36            fully_validated: is_validator,
37            got_vblocking: false,
38        }
39    }
40}
41
42#[derive(Debug)]
43pub struct SlotProto<'a, C: Consensus, D: Driver> {
44    pub cd: &'a ConsensusDriver<C, D>,
45    pub local_state: &'a LocalState,
46    pub slot_state: &'a mut SlotState,
47}
48
49impl<'a, C: Consensus, D: Driver> SlotProto<'a, C, D> {
50    pub fn nomination_proto(&mut self) -> NominationProto<'_, 'a, C, D> {
51        NominationProto(self)
52    }
53
54    pub fn ballot_proto(&mut self) -> BallotProto<'_, 'a, C, D> {
55        BallotProto(self)
56    }
57
58    pub fn local_proto(&self) -> LocalProto<'_, C, D> {
59        LocalProto {
60            cd: self.cd,
61            local: self.local_state,
62        }
63    }
64
65    pub fn index(&self) -> SlotIndex {
66        self.slot_state.slot_index
67    }
68
69    pub fn ballot_state(&self) -> &BallotState {
70        &self.slot_state.ballot
71    }
72
73    pub fn ballot_state_mut(&mut self) -> &mut BallotState {
74        &mut self.slot_state.ballot
75    }
76
77    pub fn nomination(&self) -> &NominationState {
78        &self.slot_state.nomination
79    }
80
81    pub fn nomination_mut(&mut self) -> &mut NominationState {
82        &mut self.slot_state.nomination
83    }
84
85    pub fn driver(&self) -> &D {
86        &self.cd.driver
87    }
88
89    pub fn consensus(&self) -> &C {
90        &self.cd.consensus
91    }
92
93    pub fn driver_calling_back(&mut self, cb: DriverCallback) {
94        match cb {
95            DriverCallback::BallotTimerExpired { slot_index: _ } => {
96                self.ballot_proto().driver_calling_back(cb)
97            }
98            DriverCallback::NominationTimerExpired {
99                slot_index: _,
100                value: _,
101                prev_value: _,
102            } => self.nomination_proto().driver_calling_back(cb),
103        }
104    }
105
106    pub fn get_companion_quorum_set_hash_from_statement(
107        statement: &thruput_scp::SCPStatement,
108    ) -> thruput_scp::SCPHash {
109        federated::get_companion_quorum_set_hash_from_statement(statement)
110    }
111
112    /// returns (nom values, ballot values)
113    pub fn get_statement_values(
114        statement: &thruput_scp::SCPStatement,
115    ) -> (Vec<thruput_scp::SCPValue>, Vec<thruput_scp::SCPValue>) {
116        match &statement.pledges {
117            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => (
118                NominationProto::<C, D>::get_statement_values(statement),
119                vec![],
120            ),
121            _ => {
122                let vals = BallotProto::<C, D>::get_statement_values(statement);
123                (vec![], vals.into_iter().collect())
124            }
125        }
126    }
127
128    pub fn get_quorum_set_from_statement(
129        &self,
130        statement: &thruput_scp::SCPStatement,
131    ) -> Option<thruput_scp::SCPQuorumSet> {
132        match &statement.pledges {
133            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
134                ..
135            } => {
136                Some(self.local_proto().get_singleton_qset(&statement.node_id))
137            }
138            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
139                self.driver().get_qset(&prepare.quorum_set_hash)
140            }
141            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
142                self.driver().get_qset(&confirm.quorum_set_hash)
143            }
144            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { nominate } => {
145                self.driver().get_qset(&nominate.quorum_set_hash)
146            }
147            _ => panic!("unreachable"),
148        }
149    }
150
151    pub fn get_state(
152        &mut self,
153        node: &thruput_scp::SCPNodeID,
154        self_already_moved_on: bool,
155    ) -> QuorumInfoNodeState {
156        let ballot_state =
157            self.ballot_proto().get_state(node, self_already_moved_on);
158        if ballot_state != QuorumInfoNodeState::NoInfo {
159            return ballot_state;
160        }
161        self.nomination_proto()
162            .get_state(node, self_already_moved_on)
163    }
164
165    pub fn should_process_envelope(
166        &mut self,
167        env: &thruput_scp::SCPEnvelope,
168        ours: bool,
169    ) -> bool {
170        assert_eq!(env.statement.slot_index, self.index());
171        match &env.statement.pledges {
172            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
173                self.nomination_proto().should_process_envelope(env)
174            }
175            _ => self.ballot_proto().should_process_envelope(env, ours),
176        }
177    }
178
179    #[instrument(skip_all, name = "slot.process_envelope", fields(slot_index = i64::try_from(envelope.statement.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(envelope.statement.slot_index).unwrap_or(i64::MAX)))]
180    pub fn process_envelope(
181        &mut self,
182        envelope: &thruput_scp::SCPEnvelope,
183        ours: bool,
184    ) -> EnvelopeState {
185        assert_eq!(envelope.statement.slot_index, self.index());
186
187        tracing::trace!(
188            envelope = ?envelope,
189            slot_index = self.index(),
190            "slot proto process_envelope,   i: {}, e: {}",
191            self.index(),
192            self.cd.envelope_to_str(envelope, false),
193        );
194
195        let result =
196            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
197                match &envelope.statement.pledges {
198                    thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
199                        ..
200                    } => self.nomination_proto().process_envelope(envelope),
201                    _ => self.ballot_proto().process_envelope(envelope, ours),
202                }
203            }));
204
205        let result = match result {
206            Ok(envelope_state) => envelope_state,
207            Err(panic_payload) => {
208                let local_node_id = self.local_proto().get_node_id().clone();
209                tracing::error!(
210                    local_node_id = ?local_node_id,
211                    "SCP context {}",
212                    self.driver().to_short_string(&local_node_id),
213                );
214                let json_info = self.get_json_info(false);
215                tracing::error!(
216                    json_info = ?json_info,
217                    "slot JSON info: {}",
218                    serde_json::to_string_pretty(&json_info)
219                        .unwrap_or_else(|_| "failed to serialize".to_string()),
220                );
221                tracing::error!(
222                    slot_index = self.index(),
223                    envelope = ?envelope,
224                    "exception processing SCP messages,   i: {}, e: {}",
225                    self.index(),
226                    self.cd.envelope_to_str(envelope, false),
227                );
228                tracing::error!("INTERNAL BUG");
229
230                std::panic::resume_unwind(panic_payload);
231            }
232        };
233
234        let had_previous_message = self
235            .get_latest_message(&envelope.statement.node_id)
236            .is_some();
237        if !had_previous_message && result == EnvelopeState::Valid {
238            self.maybe_set_got_vblocking();
239        }
240
241        result
242    }
243
244    pub fn abandon_ballot(&mut self) -> bool {
245        self.ballot_proto().abandon_ballot(0)
246    }
247
248    pub fn bump_state(
249        &mut self,
250        value: &thruput_scp::SCPValue,
251        force: bool,
252    ) -> bool {
253        self.ballot_proto().bump_state(value.clone(), force)
254    }
255
256    pub fn nominate(
257        &mut self,
258        value: &thruput_scp::SCPValue,
259        previous_value: &thruput_scp::SCPValue,
260        timed_out: bool,
261    ) -> bool {
262        self.nomination_proto()
263            .nominate(value, previous_value, timed_out)
264    }
265
266    pub fn stop_nomination(&mut self) {
267        self.nomination_proto().stop_nomination()
268    }
269
270    pub fn get_nomination_leaders(
271        &mut self,
272    ) -> HashSet<thruput_scp::SCPNodeID> {
273        self.nomination_proto().get_leaders()
274    }
275
276    pub fn set_fully_validated(&mut self, validated: bool) {
277        self.slot_state.fully_validated = validated;
278    }
279
280    pub fn get_latest_composite_candidate(
281        &mut self,
282    ) -> Option<thruput_scp::SCPValue> {
283        self.nomination_proto().get_latest_composite_candidate()
284    }
285
286    pub fn create_envelope(
287        &mut self,
288        statement: thruput_scp::SCPStatement,
289    ) -> thruput_scp::SCPEnvelope {
290        use thruput_xdr::types::{Ed25519Signature, Signature};
291
292        let mut envelope = thruput_scp::SCPEnvelope {
293            statement,
294            signature: Signature::Ed25519 {
295                ed25519: Ed25519Signature::new([0u8; 64]),
296            },
297        };
298
299        envelope.statement.node_id = self.local_proto().get_node_id().clone();
300        envelope.statement.slot_index = self.index();
301
302        self.driver().sign_envelope(&mut envelope);
303
304        envelope
305    }
306
307    pub fn is_fully_validated(&self) -> bool {
308        self.slot_state.fully_validated
309    }
310
311    pub fn get_json_info(&mut self, full_keys: bool) -> serde_json::Value {
312        use serde_json::{Value, json};
313
314        let mut statements = Vec::new();
315        let mut qsets_used: HashMap<
316            thruput_scp::SCPHash,
317            thruput_scp::SCPQuorumSet,
318        > = HashMap::new();
319
320        for item in self.slot_state.statements_history.iter() {
321            let mut statement_array = Vec::new();
322
323            if let Ok(duration) =
324                item.when.duration_since(std::time::UNIX_EPOCH)
325            {
326                statement_array.push(Value::Number(serde_json::Number::from(
327                    duration.as_secs(),
328                )));
329            } else {
330                statement_array
331                    .push(Value::Number(serde_json::Number::from(0u64)));
332            }
333
334            statement_array.push(Value::String(
335                self.cd.statement_to_str(&item.statement, full_keys),
336            ));
337            statement_array.push(Value::Bool(item.validated));
338
339            let qset_hash = Self::get_companion_quorum_set_hash_from_statement(
340                &item.statement,
341            );
342            if let Some(qset) = self.driver().get_qset(&qset_hash) {
343                qsets_used.insert(qset_hash, qset.clone());
344            }
345
346            statements.push(Value::Array(statement_array));
347        }
348
349        let mut quorum_sets_obj = serde_json::Map::new();
350        for (hash, qset) in qsets_used {
351            let hash_abbrev = hex_abbrev(&hash);
352            quorum_sets_obj.insert(
353                hash_abbrev,
354                self.local_proto().to_json(&qset, full_keys),
355            );
356        }
357
358        json!({
359            "statements": statements,
360            "quorum_sets": quorum_sets_obj,
361            "validated": self.slot_state.fully_validated,
362            "nomination_proto": self.nomination_proto().get_json_info(),
363            "ballot_proto": self.ballot_proto().get_json_info()
364        })
365    }
366
367    pub fn get_json_quorum_info(
368        &mut self,
369        id: &thruput_scp::SCPNodeID,
370        summary: bool,
371        full_keys: bool,
372    ) -> serde_json::Value {
373        let mut ret = self
374            .ballot_proto()
375            .get_json_quorum_info(id, summary, full_keys);
376
377        if self.local_proto().is_validator() {
378            ret["validated"] =
379                serde_json::Value::Bool(self.is_fully_validated());
380        }
381
382        ret
383    }
384
385    #[instrument(skip_all)]
386    pub fn federated_accept<F1, F2>(
387        &self,
388        voted: &F1,
389        accepted: &F2,
390        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
391    ) -> bool
392    where
393        F1: Fn(&thruput_scp::SCPStatement) -> bool,
394        F2: Fn(&thruput_scp::SCPStatement) -> bool,
395    {
396        let local_proto = self.local_proto();
397        let qset = local_proto.get_qset();
398
399        // Checks if the nodes that claimed to accept the statement form a v-blocking set
400        if LocalProto::<C, D>::is_vblocking_envelopes(qset, envs, accepted) {
401            return true;
402        }
403
404        // Checks if the set of nodes that accepted or voted for it form a quorum
405        let ratify_filter = |st: &thruput_scp::SCPStatement| -> bool {
406            accepted(st) || voted(st)
407        };
408
409        let qset_getter =
410            |st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
411                self.get_quorum_set_from_statement(st)
412            };
413
414        LocalProto::<C, D>::is_quorum(qset, envs, &qset_getter, &ratify_filter)
415    }
416
417    #[instrument(skip_all)]
418    pub fn federated_ratify<F>(
419        &self,
420        voted: &F,
421        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
422    ) -> bool
423    where
424        F: Fn(&thruput_scp::SCPStatement) -> bool,
425    {
426        let local_proto = self.local_proto();
427        let qset = local_proto.get_qset();
428
429        let qset_getter =
430            |st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
431                self.get_quorum_set_from_statement(st)
432            };
433
434        LocalProto::<C, D>::is_quorum(qset, envs, &qset_getter, voted)
435    }
436
437    pub fn get_statement_count(&self) -> usize {
438        self.slot_state.statements_history.len()
439    }
440
441    pub fn got_vblocking(&self) -> bool {
442        self.slot_state.got_vblocking
443    }
444
445    pub fn get_entire_current_state(
446        &mut self,
447    ) -> Vec<thruput_scp::SCPEnvelope> {
448        let mut res = Vec::new();
449        self.process_current_state(
450            &mut |envelope: &thruput_scp::SCPEnvelope| {
451                res.push(envelope.clone());
452                true
453            },
454            true,
455        );
456        res
457    }
458
459    pub fn get_latest_messages_send(
460        &mut self,
461    ) -> Vec<thruput_scp::SCPEnvelope> {
462        let mut res = Vec::new();
463
464        if self.slot_state.fully_validated {
465            // Get nomination protocol's last message
466            if let Some(nomination_envelope) =
467                self.nomination_proto().get_last_message_send()
468            {
469                res.push(nomination_envelope);
470            }
471
472            // Get ballot protocol's last message
473            if let Some(ballot_envelope) =
474                self.ballot_proto().get_last_message_send()
475            {
476                res.push(ballot_envelope);
477            }
478        }
479
480        res
481    }
482
483    pub fn get_latest_message(
484        &mut self,
485        node_id: &thruput_scp::SCPNodeID,
486    ) -> Option<thruput_scp::SCPEnvelope> {
487        // Check ballot protocol first
488        if let Some(envelope) = self.ballot_proto().get_latest_message(node_id)
489        {
490            return Some(envelope);
491        }
492        // Fall back to nomination protocol
493        if let Some(envelope) =
494            self.nomination_proto().get_latest_message(node_id)
495        {
496            return Some(envelope);
497        }
498        None
499    }
500
501    pub fn maybe_set_got_vblocking(&mut self) {
502        if self.slot_state.got_vblocking {
503            // Already set
504            return;
505        }
506
507        let qset = self.local_proto().get_qset().clone();
508        let mut nodes = Vec::new();
509
510        LocalProto::<C, D>::for_all_nodes(&qset, &mut |node_id| {
511            if self.get_latest_message(node_id).is_some() {
512                nodes.push(node_id.clone());
513            }
514            true
515        });
516
517        self.slot_state.got_vblocking =
518            LocalProto::<C, D>::is_vblocking_nodes(&qset, &nodes);
519
520        if self.slot_state.got_vblocking {
521            tracing::trace!("got v-blocking for slot {}", self.index());
522        }
523    }
524
525    pub fn set_state_from_envelope(
526        &mut self,
527        envelope: &thruput_scp::SCPEnvelope,
528    ) {
529        let statement = &envelope.statement;
530        let local_node_id = self.local_proto().get_node_id().clone();
531
532        if statement.node_id == local_node_id
533            && statement.slot_index == self.index()
534        {
535            let had_previous_message =
536                self.get_latest_message(&statement.node_id).is_some();
537
538            match &statement.pledges {
539                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
540                    ..
541                } => {
542                    self.nomination_proto().set_state_from_envelope(envelope);
543                }
544                _ => {
545                    self.ballot_proto().set_state_from_envelope(envelope);
546                }
547            }
548
549            if !had_previous_message {
550                self.maybe_set_got_vblocking();
551            }
552        } else {
553            tracing::trace!(
554                env = ?envelope,
555                "slot proto set_state_from_envelope: invalid envelope for slot {} from node {:?}   e: {}",
556                self.slot_state.slot_index,
557                statement.node_id,
558                self.cd.envelope_to_str(envelope, false)
559            );
560        }
561    }
562
563    pub fn process_current_state<F>(&mut self, f: &mut F, force_self: bool)
564    where
565        F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
566    {
567        if self.nomination_proto().process_current_state(f, force_self) {
568            self.ballot_proto().process_current_state(f, force_self);
569        }
570    }
571
572    pub fn is_newer_nomination_or_ballot_st(
573        old_st: &thruput_scp::SCPStatement,
574        new_st: &thruput_scp::SCPStatement,
575    ) -> bool {
576        let old_nomination = matches!(
577            old_st.pledges,
578            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. }
579        );
580        let new_nomination = matches!(
581            new_st.pledges,
582            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. }
583        );
584
585        if old_nomination != new_nomination {
586            return false;
587        }
588
589        // Handle each type appropriately
590        if old_nomination {
591            if let (
592                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
593                    nominate: old_nom,
594                },
595                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
596                    nominate: new_nom,
597                },
598            ) = (&old_st.pledges, &new_st.pledges)
599            {
600                NominationProto::<C, D>::is_newer_statement(old_nom, new_nom)
601            } else {
602                panic!("bug")
603            }
604        } else {
605            BallotProto::<C, D>::is_newer_statement(old_st, new_st)
606        }
607    }
608
609    pub fn get_externalizing_state(&mut self) -> Vec<thruput_scp::SCPEnvelope> {
610        self.ballot_proto().get_externalizing_state()
611    }
612
613    /// Builds a proof snapshot for this slot after it externalizes.
614    ///
615    /// Returns `Ok(None)` only when the slot has no externalizing state yet.
616    pub fn get_externalized_slot_proof(
617        &mut self,
618    ) -> Result<Option<ExternalizedSlotProof>, ExternalizedSlotProofError> {
619        let envelopes = self.get_externalizing_state();
620        if envelopes.is_empty() {
621            return Ok(None);
622        }
623
624        let mut envelopes_by_node = HashMap::with_capacity(envelopes.len());
625        let mut companion_qsets = HashMap::new();
626
627        for envelope in envelopes {
628            let node_id = envelope.statement.node_id.clone();
629            if envelopes_by_node.contains_key(&node_id) {
630                return Err(
631                    ExternalizedSlotProofError::DuplicateNodeStatement {
632                        node_id,
633                    },
634                );
635            }
636            envelopes_by_node.insert(node_id, envelope.clone());
637
638            let qset_hash =
639                federated::try_get_companion_quorum_set_hash_from_statement(
640                    &envelope.statement,
641                )
642                .map_err(|error| {
643                    ExternalizedSlotProofError::MalformedEnvelope {
644                        reason: error.into(),
645                    }
646                })?;
647            if companion_qsets.contains_key(&qset_hash) {
648                continue;
649            }
650
651            let qset = self.driver().get_qset(&qset_hash).ok_or(
652                ExternalizedSlotProofError::MissingCompanionQuorumSet {
653                    hash: qset_hash,
654                },
655            )?;
656            let actual_hash = scp_util::hash_xdr_scp(&qset).map_err(|_| {
657                ExternalizedSlotProofError::CompanionQuorumSetHashFailed {
658                    hash: qset_hash,
659                }
660            })?;
661            if actual_hash != qset_hash {
662                return Err(
663                    ExternalizedSlotProofError::CompanionQuorumSetHashMismatch {
664                        claimed: qset_hash,
665                        actual: actual_hash,
666                    },
667                );
668            }
669            let qset_bytes = scp_util::marshal_xdr(&qset).map_err(|_| {
670                ExternalizedSlotProofError::CompanionQuorumSetEncodingFailed {
671                    hash: qset_hash,
672                }
673            })?;
674            companion_qsets.insert(qset_hash, qset_bytes);
675        }
676
677        Ok(Some(ExternalizedSlotProof::new(
678            envelopes_by_node,
679            companion_qsets,
680        )))
681    }
682
683    pub fn record_statement(&mut self, st: &thruput_scp::SCPStatement) {
684        let historical_statement = HistoricalStatement {
685            when: std::time::SystemTime::now(), //XXX:diff
686            statement: st.clone(),
687            validated: self.slot_state.fully_validated,
688        };
689
690        self.slot_state
691            .statements_history
692            .push(historical_statement);
693
694        // Log the statement (similar to C++ version)
695        tracing::debug!(
696            "new statement recorded, i: {} st: {} validated: {}",
697            self.slot_state.slot_index,
698            self.cd.statement_to_str(st, false),
699            self.slot_state.fully_validated,
700        );
701    }
702}