Skip to main content

scp_kernel/
stellar.rs

1use crate::*;
2use std::collections::HashMap;
3
4#[derive(Debug, Clone)]
5pub struct ConsensusDriver<C: Consensus, D: Driver> {
6    pub consensus: C,
7    pub driver: D,
8}
9
10impl<C: Consensus, D: Driver> ConsensusDriver<C, D> {
11    pub fn new(consensus: C, driver: D) -> ConsensusDriver<C, D> {
12        ConsensusDriver { consensus, driver }
13    }
14
15    pub fn ballot_to_str(&self, b: &thruput_scp::SCPBallot) -> String {
16        format!("<{},{}>", b.counter, self.driver.get_value_string(&b.value),)
17    }
18
19    pub fn opt_ballot_to_str(
20        &self,
21        b: Option<&thruput_scp::SCPBallot>,
22    ) -> String {
23        match b {
24            Some(b) => self.ballot_to_str(b),
25            None => "<,>".to_string(),
26        }
27    }
28
29    pub fn envelope_to_str(
30        &self,
31        env: &thruput_scp::SCPEnvelope,
32        full_keys: bool,
33    ) -> String {
34        self.statement_to_str(&env.statement, full_keys)
35    }
36
37    pub fn statement_to_str(
38        &self,
39        st: &thruput_scp::SCPStatement,
40        full_keys: bool,
41    ) -> String {
42        let qset_hash =
43            SlotProto::<C, D>::get_companion_quorum_set_hash_from_statement(st);
44        let node_id = self.driver.to_str_key(&st.node_id, full_keys);
45
46        let mut result = format!("{{ENV@{} |  i: {}", node_id, st.slot_index);
47
48        match &st.pledges {
49            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
50                result.push_str(&format!(
51                    " | PREPARE | D: {} | b: {} | p: {} | p': {} | c.n: {} | h.n: {}",
52                    hex_abbrev(&qset_hash),
53                    self.ballot_to_str(&prepare.ballot),
54                    self.opt_ballot_to_str(prepare.prepared.as_ref()),
55                    self.opt_ballot_to_str(prepare.prepared_prime.as_ref()),
56                    prepare.n_c,
57                    prepare.n_h
58                ));
59            }
60            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
61                result.push_str(&format!(
62                    " | CONFIRM | D: {} | b: {} | p.n: {} | c.n: {} | h.n: {}",
63                    hex_abbrev(&qset_hash),
64                    self.ballot_to_str(&confirm.ballot),
65                    confirm.n_prepared,
66                    confirm.n_commit,
67                    confirm.n_h
68                ));
69            }
70            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
71                externalize,
72            } => {
73                result.push_str(&format!(
74                    " | EXTERNALIZE | c: {} | h.n: {} | (lastD): {}",
75                    self.ballot_to_str(&externalize.commit),
76                    externalize.n_h,
77                    hex_abbrev(&qset_hash)
78                ));
79            }
80            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { nominate } => {
81                result.push_str(&format!(
82                    " | NOMINATE | D: {} | X: {{",
83                    hex_abbrev(&qset_hash)
84                ));
85
86                for (i, vote) in nominate.votes.iter().enumerate() {
87                    if i > 0 {
88                        result.push_str(" ,");
89                    }
90                    result.push_str(&format!(
91                        "'{}'",
92                        self.driver.get_value_string(vote)
93                    ));
94                }
95
96                result.push_str("} | Y: {");
97
98                for (i, accepted) in nominate.accepted.iter().enumerate() {
99                    if i > 0 {
100                        result.push_str(" ,");
101                    }
102                    result.push_str(&format!(
103                        "'{}'",
104                        self.driver.get_value_string(accepted)
105                    ));
106                }
107
108                result.push('}');
109            }
110            _ => panic!("unreachable"),
111        }
112
113        result.push_str(" }");
114        result
115    }
116
117    pub fn node_ids_to_str(&self, ns: &[thruput_scp::SCPNodeID]) -> String {
118        let mut s = "[".to_string();
119        for (i, n) in ns.iter().enumerate() {
120            s.push_str(&self.driver.to_str_key(n, false));
121            if i + 1 < ns.len() {
122                s.push_str(", ");
123            }
124        }
125        s
126    }
127}
128
129#[derive(Debug)]
130pub struct StellarState {
131    local: LocalState,
132    known_slots: HashMap<SlotIndex, SlotState>,
133}
134
135impl StellarState {
136    pub fn new(
137        node_id: thruput_scp::SCPNodeID,
138        is_validator: bool,
139        qset: thruput_scp::SCPQuorumSet,
140        get_hash_of: impl Fn(&[u8]) -> thruput_scp::SCPHash,
141    ) -> StellarState {
142        StellarState {
143            local: LocalState::new(node_id, is_validator, qset, get_hash_of),
144            known_slots: HashMap::new(),
145        }
146    }
147}
148
149#[derive(Debug)]
150pub struct StellarProto<'a, C: Consensus, D: Driver> {
151    pub cd: &'a ConsensusDriver<C, D>,
152    pub state: &'a mut StellarState,
153}
154
155impl<'a, C: Consensus, D: Driver> StellarProto<'a, C, D> {
156    pub fn local_proto(&self) -> LocalProto<'_, C, D> {
157        LocalProto {
158            cd: self.cd,
159            local: &self.state.local,
160        }
161    }
162
163    pub fn local_proto_mut(&mut self) -> LocalProtoMut<'_, C, D> {
164        LocalProtoMut {
165            cd: self.cd,
166            local: &mut self.state.local,
167        }
168    }
169
170    pub fn slot_proto_or_create(
171        &mut self,
172        slot_index: SlotIndex,
173    ) -> SlotProto<'_, C, D> {
174        let is_validator = self.is_validator();
175        let known_slots = &mut self.state.known_slots;
176        known_slots
177            .entry(slot_index)
178            .or_insert_with(|| SlotState::new(slot_index, is_validator));
179        SlotProto {
180            cd: self.cd,
181            local_state: &mut self.state.local,
182            slot_state: known_slots.get_mut(&slot_index).unwrap(),
183        }
184    }
185
186    pub fn slot_proto(
187        &mut self,
188        slot_index: SlotIndex,
189    ) -> Option<SlotProto<'_, C, D>> {
190        self.state
191            .known_slots
192            .get_mut(&slot_index)
193            .map(|slot| SlotProto {
194                cd: self.cd,
195                local_state: &mut self.state.local,
196                slot_state: slot,
197            })
198    }
199
200    pub fn is_validator(&self) -> bool {
201        self.local_proto().is_validator()
202    }
203
204    /// returns (nom values, ballot values)
205    pub fn get_statement_values(
206        statement: &thruput_scp::SCPStatement,
207    ) -> (Vec<thruput_scp::SCPValue>, Vec<thruput_scp::SCPValue>) {
208        SlotProto::<'a, C, D>::get_statement_values(statement)
209    }
210
211    pub fn get_highest_known_slot_index(&self) -> SlotIndex {
212        self.state.known_slots.keys().max().cloned().unwrap_or(0)
213    }
214
215    pub fn nominate(
216        &mut self,
217        slot_index: SlotIndex,
218        value: &thruput_scp::SCPValue,
219        prev_value: &thruput_scp::SCPValue,
220    ) -> bool {
221        assert!(self.is_validator());
222        self.slot_proto_or_create(slot_index)
223            .nominate(value, prev_value, false)
224    }
225
226    pub fn stop_nomination(&mut self, slot_index: SlotIndex) {
227        if let Some(mut slot_proto) = self.slot_proto(slot_index) {
228            slot_proto.stop_nomination();
229        }
230    }
231
232    pub fn update_local_quorum_set(
233        &mut self,
234        qset: &thruput_scp::SCPQuorumSet,
235    ) {
236        self.local_proto_mut().update_quorum_set(qset);
237    }
238
239    pub fn get_local_quorum_set(&self) -> thruput_scp::SCPQuorumSet {
240        self.local_proto().get_qset().clone()
241    }
242
243    pub fn get_local_node_id(&self) -> thruput_scp::SCPNodeID {
244        self.local_proto().get_node_id().clone()
245    }
246
247    pub fn purge_slots(
248        &mut self,
249        max_slot_index: SlotIndex,
250        slot_to_keep: SlotIndex,
251    ) {
252        let mut slots_to_remove = Vec::new();
253
254        for &slot_index in self.state.known_slots.keys() {
255            if slot_index < max_slot_index && slot_index != slot_to_keep {
256                slots_to_remove.push(slot_index);
257            }
258        }
259
260        for slot_index in slots_to_remove {
261            self.state.known_slots.remove(&slot_index);
262        }
263    }
264
265    pub fn get_json_info(
266        &mut self,
267        limit: usize,
268        full_keys: bool,
269    ) -> serde_json::Value {
270        let mut ret = serde_json::Map::new();
271
272        // Get slot indices in descending order
273        let mut slot_indices: Vec<SlotIndex> =
274            self.state.known_slots.keys().cloned().collect();
275        slot_indices.sort_by(|a, b| b.cmp(a)); // Sort in descending order
276
277        for (count, slot_index) in slot_indices.into_iter().enumerate() {
278            if count >= limit {
279                break;
280            }
281
282            if let Some(mut slot_proto) = self.slot_proto(slot_index) {
283                ret.insert(
284                    slot_index.to_string(),
285                    slot_proto.get_json_info(full_keys),
286                );
287            }
288        }
289
290        serde_json::Value::Object(ret)
291    }
292
293    pub fn get_state(
294        &mut self,
295        node: &thruput_scp::SCPNodeID,
296        slot_index: SlotIndex,
297    ) -> QuorumInfoNodeState {
298        const NUM_SLOTS_TO_CHECK_FOR_REPORTING: i32 = 2;
299
300        for k in 0..NUM_SLOTS_TO_CHECK_FOR_REPORTING {
301            if slot_index <= k as SlotIndex {
302                break;
303            }
304
305            let check_slot_index = slot_index - k as SlotIndex;
306            if let Some(mut slot) = self.slot_proto(check_slot_index) {
307                let self_already_moved_on = k > 0;
308                let state = slot.get_state(node, self_already_moved_on);
309                if state != QuorumInfoNodeState::NoInfo {
310                    return state;
311                }
312            }
313        }
314
315        // We have no messages from this node in N slots.
316        // At this point, we'll consider this node MISSING.
317        QuorumInfoNodeState::Missing
318    }
319
320    pub fn get_json_quorum_info(
321        &mut self,
322        id: &thruput_scp::SCPNodeID,
323        summary: bool,
324        full_keys: bool,
325        index: SlotIndex,
326    ) -> serde_json::Value {
327        if self.state.known_slots.is_empty() {
328            return serde_json::Value::Object(serde_json::Map::new());
329        }
330
331        let index = if index == 0 {
332            self.get_highest_known_slot_index()
333        } else {
334            index
335        };
336
337        if let Some(mut slot) = self.slot_proto(index) {
338            let mut ret = slot.get_json_quorum_info(id, summary, full_keys);
339            let qset = self.local_proto().get_qset().clone();
340
341            if summary {
342                let mut n_disagree = 0;
343                let mut n_missing = 0;
344                let mut n_delayed = 0;
345                let mut n_agree = 0;
346
347                // Categorize each node's state
348                LocalProto::<C, D>::for_all_nodes(&qset, &mut |node| {
349                    let state = self.get_state(node, index);
350                    match state {
351                        QuorumInfoNodeState::Disagree => n_disagree += 1,
352                        QuorumInfoNodeState::Delayed => n_delayed += 1,
353                        QuorumInfoNodeState::Missing => n_missing += 1,
354                        QuorumInfoNodeState::Agree => n_agree += 1,
355                        QuorumInfoNodeState::NoInfo => {
356                            tracing::error!(
357                                "get_state should never return NoInfo"
358                            );
359                            return false;
360                        }
361                    }
362                    true
363                });
364
365                ret["disagree"] = serde_json::Value::Number(n_disagree.into());
366                ret["missing"] = serde_json::Value::Number(n_missing.into());
367                ret["delayed"] = serde_json::Value::Number(n_delayed.into());
368                ret["agree"] = serde_json::Value::Number(n_agree.into());
369            } else {
370                let mut disagree = Vec::new();
371                let mut missing = Vec::new();
372                let mut delayed = Vec::new();
373                let mut agree = Vec::new();
374
375                // Categorize each node's state
376                LocalProto::<C, D>::for_all_nodes(&qset, &mut |node| {
377                    let state = self.get_state(node, index);
378                    let key = self.cd.driver.to_str_key(node, full_keys);
379
380                    match state {
381                        QuorumInfoNodeState::Disagree => {
382                            disagree.push(serde_json::Value::String(key))
383                        }
384                        QuorumInfoNodeState::Delayed => {
385                            delayed.push(serde_json::Value::String(key))
386                        }
387                        QuorumInfoNodeState::Missing => {
388                            missing.push(serde_json::Value::String(key))
389                        }
390                        QuorumInfoNodeState::Agree => {
391                            agree.push(serde_json::Value::String(key))
392                        }
393                        QuorumInfoNodeState::NoInfo => {
394                            tracing::error!(
395                                "get_state should never return NoInfo"
396                            );
397                            return false;
398                        }
399                    }
400                    true
401                });
402
403                ret["disagree"] = serde_json::Value::Array(disagree);
404                ret["missing"] = serde_json::Value::Array(missing);
405                ret["delayed"] = serde_json::Value::Array(delayed);
406                ret["agree"] = serde_json::Value::Array(agree);
407            }
408
409            ret["ledger"] = serde_json::Value::Number(index.into());
410            ret
411        } else {
412            serde_json::Value::Object(serde_json::Map::new())
413        }
414    }
415
416    pub fn is_slot_fully_validated(&mut self, slot_index: SlotIndex) -> bool {
417        if let Some(slot) = self.slot_proto(slot_index) {
418            slot.is_fully_validated()
419        } else {
420            false
421        }
422    }
423
424    pub fn got_vblocking(&mut self, slot_index: SlotIndex) -> bool {
425        if let Some(slot) = self.slot_proto(slot_index) {
426            slot.got_vblocking()
427        } else {
428            false
429        }
430    }
431
432    pub fn get_known_slots_count(&self) -> usize {
433        self.state.known_slots.len()
434    }
435
436    pub fn get_cumulative_statement_count(&mut self) -> usize {
437        let mut count = 0;
438        for slot_index in
439            self.state.known_slots.keys().cloned().collect::<Vec<_>>()
440        {
441            if let Some(slot) = self.slot_proto(slot_index) {
442                count += slot.get_statement_count();
443            }
444        }
445        count
446    }
447
448    pub fn get_latest_messages_send(
449        &mut self,
450        slot_index: SlotIndex,
451    ) -> Vec<thruput_scp::SCPEnvelope> {
452        if let Some(mut slot) = self.slot_proto(slot_index) {
453            slot.get_latest_messages_send()
454        } else {
455            Vec::new()
456        }
457    }
458
459    pub fn empty(&self) -> bool {
460        self.state.known_slots.is_empty()
461    }
462
463    pub fn process_current_state<F>(
464        &mut self,
465        slot_index: SlotIndex,
466        f: &mut F,
467        force_self: bool,
468    ) where
469        F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
470    {
471        if let Some(mut slot) = self.slot_proto(slot_index) {
472            slot.process_current_state(f, force_self)
473        }
474    }
475
476    pub fn process_slots_ascending_from<F>(
477        &self,
478        starting_slot: SlotIndex,
479        f: &mut F,
480    ) where
481        F: FnMut(SlotIndex) -> bool,
482    {
483        // Get slot indices in ascending order starting from starting_slot
484        let mut slot_indices: Vec<SlotIndex> = self
485            .state
486            .known_slots
487            .keys()
488            .filter(|&&slot_index| slot_index >= starting_slot)
489            .cloned()
490            .collect();
491        slot_indices.sort();
492
493        for slot_index in slot_indices {
494            if !f(slot_index) {
495                break;
496            }
497        }
498    }
499
500    pub fn process_slots_descending_from<F>(
501        &self,
502        starting_slot: SlotIndex,
503        f: &mut F,
504    ) where
505        F: FnMut(SlotIndex) -> bool,
506    {
507        // Get slot indices in descending order up to and including starting_slot
508        let mut slot_indices: Vec<SlotIndex> = self
509            .state
510            .known_slots
511            .keys()
512            .filter(|&&slot_index| slot_index <= starting_slot)
513            .cloned()
514            .collect();
515        slot_indices.sort_by(|a, b| b.cmp(a)); // Sort in descending order
516
517        for slot_index in slot_indices {
518            if !f(slot_index) {
519                break;
520            }
521        }
522    }
523
524    pub fn get_latest_message(
525        &mut self,
526        id: &thruput_scp::SCPNodeID,
527    ) -> Option<thruput_scp::SCPEnvelope> {
528        // Iterate through slots in reverse order (highest to lowest)
529        let mut slot_indices: Vec<SlotIndex> =
530            self.state.known_slots.keys().cloned().collect();
531        slot_indices.sort_by(|a, b| b.cmp(a)); // Sort in descending order
532
533        for slot_index in slot_indices {
534            if let Some(mut slot) = self.slot_proto(slot_index)
535                && let Some(envelope) = slot.get_latest_message(id)
536            {
537                return Some(envelope);
538            }
539        }
540        None
541    }
542
543    pub fn is_newer_nomination_or_ballot_st(
544        &mut self,
545        old_st: &thruput_scp::SCPStatement,
546        new_st: &thruput_scp::SCPStatement,
547    ) -> bool {
548        if old_st.slot_index != new_st.slot_index
549            || old_st.node_id != new_st.node_id
550        {
551            return false;
552        }
553
554        if let Some(_slot) = self.slot_proto(old_st.slot_index) {
555            SlotProto::<C, D>::is_newer_nomination_or_ballot_st(old_st, new_st)
556        } else {
557            false
558        }
559    }
560
561    pub fn get_externalizing_state(
562        &mut self,
563        slot_index: SlotIndex,
564    ) -> Vec<thruput_scp::SCPEnvelope> {
565        if let Some(mut slot) = self.slot_proto(slot_index) {
566            slot.get_externalizing_state()
567        } else {
568            Vec::new()
569        }
570    }
571
572    /// Builds a proof snapshot for `slot_index` after it externalizes.
573    ///
574    /// Returns `Ok(None)` only when the slot is unknown or has no externalizing
575    /// state yet.
576    pub fn get_externalized_slot_proof(
577        &mut self,
578        slot_index: SlotIndex,
579    ) -> Result<Option<ExternalizedSlotProof>, ExternalizedSlotProofError> {
580        match self.slot_proto(slot_index) {
581            Some(mut slot) => slot.get_externalized_slot_proof(),
582            None => Ok(None),
583        }
584    }
585
586    pub fn get_value_string(&self, value: &thruput_scp::SCPValue) -> String {
587        self.cd.driver.get_value_string(value)
588    }
589
590    pub fn should_process_envelope(
591        &mut self,
592        env: &thruput_scp::SCPEnvelope,
593    ) -> bool {
594        let slot_index = env.statement.slot_index;
595        self.slot_proto_or_create(slot_index)
596            .should_process_envelope(env, false)
597    }
598
599    pub fn envelope_to_str(
600        &self,
601        env: &thruput_scp::SCPEnvelope,
602        full_keys: bool,
603    ) -> String {
604        self.cd.envelope_to_str(env, full_keys)
605    }
606
607    pub fn statement_to_str(
608        &self,
609        st: &thruput_scp::SCPStatement,
610        full_keys: bool,
611    ) -> String {
612        self.cd.statement_to_str(st, full_keys)
613    }
614}
615
616impl<'a, C: Consensus, D: Driver> DriverCb for StellarProto<'a, C, D> {
617    fn received_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
618        // println!(
619        //     "{}<--{}",
620        //     self.cd
621        //         .driver
622        //         .to_str_key(self.local_proto().get_node_id(), false),
623        //     self.cd.envelope_to_str(env, false)
624        // );
625        let slot_index = env.statement.slot_index;
626        let _ = self
627            .slot_proto_or_create(slot_index)
628            .process_envelope(env, false);
629    }
630
631    fn driver_calling_back(&mut self, cb: DriverCallback) {
632        match cb {
633            DriverCallback::BallotTimerExpired { slot_index }
634            | DriverCallback::NominationTimerExpired {
635                slot_index,
636                value: _,
637                prev_value: _,
638            } => {
639                if let Some(mut sp) = self.slot_proto(slot_index) {
640                    sp.driver_calling_back(cb);
641                }
642            }
643        }
644    }
645
646    fn set_state_from_envelope(
647        &mut self,
648        slot_index: SlotIndex,
649        envelope: &thruput_scp::SCPEnvelope,
650    ) {
651        let mut slot = self.slot_proto_or_create(slot_index);
652        slot.set_state_from_envelope(envelope);
653    }
654}