thruput-scp-kernel 3.0.0

Stellar Consensus Protocol (SCP) kernel: nomination, ballot protocol and quorum sets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use crate::*;
use std::collections::{HashMap, HashSet};
use std::time::SystemTime;
use tracing::instrument;

pub type SlotIndex = u64;

// The number of times the timer has to expire before we consider the node
// missing. Used for reporting purposes only.
pub const NUM_TIMEOUTS_THRESHOLD_FOR_REPORTING: i64 = 2;

#[derive(Debug)]
pub struct SlotState {
    pub slot_index: SlotIndex,
    pub nomination: NominationState,
    pub ballot: BallotState,
    pub statements_history: Vec<HistoricalStatement>,
    pub fully_validated: bool,
    pub got_vblocking: bool,
}

#[derive(Debug, Clone)]
pub struct HistoricalStatement {
    pub when: SystemTime,
    pub statement: thruput_scp::SCPStatement,
    pub validated: bool,
}

impl SlotState {
    pub fn new(slot_index: SlotIndex, is_validator: bool) -> Self {
        SlotState {
            slot_index,
            nomination: NominationState::new(),
            ballot: BallotState::new(),
            statements_history: Vec::new(),
            fully_validated: is_validator,
            got_vblocking: false,
        }
    }
}

#[derive(Debug)]
pub struct SlotProto<'a, C: Consensus, D: Driver> {
    pub cd: &'a ConsensusDriver<C, D>,
    pub local_state: &'a LocalState,
    pub slot_state: &'a mut SlotState,
}

impl<'a, C: Consensus, D: Driver> SlotProto<'a, C, D> {
    pub fn nomination_proto(&mut self) -> NominationProto<'_, 'a, C, D> {
        NominationProto(self)
    }

    pub fn ballot_proto(&mut self) -> BallotProto<'_, 'a, C, D> {
        BallotProto(self)
    }

    pub fn local_proto(&self) -> LocalProto<'_, C, D> {
        LocalProto {
            cd: self.cd,
            local: self.local_state,
        }
    }

    pub fn index(&self) -> SlotIndex {
        self.slot_state.slot_index
    }

    pub fn ballot_state(&self) -> &BallotState {
        &self.slot_state.ballot
    }

    pub fn ballot_state_mut(&mut self) -> &mut BallotState {
        &mut self.slot_state.ballot
    }

    pub fn nomination(&self) -> &NominationState {
        &self.slot_state.nomination
    }

    pub fn nomination_mut(&mut self) -> &mut NominationState {
        &mut self.slot_state.nomination
    }

    pub fn driver(&self) -> &D {
        &self.cd.driver
    }

    pub fn consensus(&self) -> &C {
        &self.cd.consensus
    }

    pub fn driver_calling_back(&mut self, cb: DriverCallback) {
        match cb {
            DriverCallback::BallotTimerExpired { slot_index: _ } => {
                self.ballot_proto().driver_calling_back(cb)
            }
            DriverCallback::NominationTimerExpired {
                slot_index: _,
                value: _,
                prev_value: _,
            } => self.nomination_proto().driver_calling_back(cb),
        }
    }

    pub fn get_companion_quorum_set_hash_from_statement(
        statement: &thruput_scp::SCPStatement,
    ) -> thruput_scp::SCPHash {
        federated::get_companion_quorum_set_hash_from_statement(statement)
    }

    /// returns (nom values, ballot values)
    pub fn get_statement_values(
        statement: &thruput_scp::SCPStatement,
    ) -> (Vec<thruput_scp::SCPValue>, Vec<thruput_scp::SCPValue>) {
        match &statement.pledges {
            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => (
                NominationProto::<C, D>::get_statement_values(statement),
                vec![],
            ),
            _ => {
                let vals = BallotProto::<C, D>::get_statement_values(statement);
                (vec![], vals.into_iter().collect())
            }
        }
    }

    pub fn get_quorum_set_from_statement(
        &self,
        statement: &thruput_scp::SCPStatement,
    ) -> Option<thruput_scp::SCPQuorumSet> {
        match &statement.pledges {
            thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
                ..
            } => {
                Some(self.local_proto().get_singleton_qset(&statement.node_id))
            }
            thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
                self.driver().get_qset(&prepare.quorum_set_hash)
            }
            thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
                self.driver().get_qset(&confirm.quorum_set_hash)
            }
            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { nominate } => {
                self.driver().get_qset(&nominate.quorum_set_hash)
            }
            _ => panic!("unreachable"),
        }
    }

    pub fn get_state(
        &mut self,
        node: &thruput_scp::SCPNodeID,
        self_already_moved_on: bool,
    ) -> QuorumInfoNodeState {
        let ballot_state =
            self.ballot_proto().get_state(node, self_already_moved_on);
        if ballot_state != QuorumInfoNodeState::NoInfo {
            return ballot_state;
        }
        self.nomination_proto()
            .get_state(node, self_already_moved_on)
    }

    pub fn should_process_envelope(
        &mut self,
        env: &thruput_scp::SCPEnvelope,
        ours: bool,
    ) -> bool {
        assert_eq!(env.statement.slot_index, self.index());
        match &env.statement.pledges {
            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
                self.nomination_proto().should_process_envelope(env)
            }
            _ => self.ballot_proto().should_process_envelope(env, ours),
        }
    }

    #[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)))]
    pub fn process_envelope(
        &mut self,
        envelope: &thruput_scp::SCPEnvelope,
        ours: bool,
    ) -> EnvelopeState {
        assert_eq!(envelope.statement.slot_index, self.index());

        tracing::trace!(
            envelope = ?envelope,
            slot_index = self.index(),
            "slot proto process_envelope,   i: {}, e: {}",
            self.index(),
            self.cd.envelope_to_str(envelope, false),
        );

        let result =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                match &envelope.statement.pledges {
                    thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
                        ..
                    } => self.nomination_proto().process_envelope(envelope),
                    _ => self.ballot_proto().process_envelope(envelope, ours),
                }
            }));

        let result = match result {
            Ok(envelope_state) => envelope_state,
            Err(panic_payload) => {
                let local_node_id = self.local_proto().get_node_id().clone();
                tracing::error!(
                    local_node_id = ?local_node_id,
                    "SCP context {}",
                    self.driver().to_short_string(&local_node_id),
                );
                let json_info = self.get_json_info(false);
                tracing::error!(
                    json_info = ?json_info,
                    "slot JSON info: {}",
                    serde_json::to_string_pretty(&json_info)
                        .unwrap_or_else(|_| "failed to serialize".to_string()),
                );
                tracing::error!(
                    slot_index = self.index(),
                    envelope = ?envelope,
                    "exception processing SCP messages,   i: {}, e: {}",
                    self.index(),
                    self.cd.envelope_to_str(envelope, false),
                );
                tracing::error!("INTERNAL BUG");

                std::panic::resume_unwind(panic_payload);
            }
        };

        let had_previous_message = self
            .get_latest_message(&envelope.statement.node_id)
            .is_some();
        if !had_previous_message && result == EnvelopeState::Valid {
            self.maybe_set_got_vblocking();
        }

        result
    }

    pub fn abandon_ballot(&mut self) -> bool {
        self.ballot_proto().abandon_ballot(0)
    }

    pub fn bump_state(
        &mut self,
        value: &thruput_scp::SCPValue,
        force: bool,
    ) -> bool {
        self.ballot_proto().bump_state(value.clone(), force)
    }

    pub fn nominate(
        &mut self,
        value: &thruput_scp::SCPValue,
        previous_value: &thruput_scp::SCPValue,
        timed_out: bool,
    ) -> bool {
        self.nomination_proto()
            .nominate(value, previous_value, timed_out)
    }

    pub fn stop_nomination(&mut self) {
        self.nomination_proto().stop_nomination()
    }

    pub fn get_nomination_leaders(
        &mut self,
    ) -> HashSet<thruput_scp::SCPNodeID> {
        self.nomination_proto().get_leaders()
    }

    pub fn set_fully_validated(&mut self, validated: bool) {
        self.slot_state.fully_validated = validated;
    }

    pub fn get_latest_composite_candidate(
        &mut self,
    ) -> Option<thruput_scp::SCPValue> {
        self.nomination_proto().get_latest_composite_candidate()
    }

    pub fn create_envelope(
        &mut self,
        statement: thruput_scp::SCPStatement,
    ) -> thruput_scp::SCPEnvelope {
        use thruput_xdr::types::{Ed25519Signature, Signature};

        let mut envelope = thruput_scp::SCPEnvelope {
            statement,
            signature: Signature::Ed25519 {
                ed25519: Ed25519Signature::new([0u8; 64]),
            },
        };

        envelope.statement.node_id = self.local_proto().get_node_id().clone();
        envelope.statement.slot_index = self.index();

        self.driver().sign_envelope(&mut envelope);

        envelope
    }

    pub fn is_fully_validated(&self) -> bool {
        self.slot_state.fully_validated
    }

    pub fn get_json_info(&mut self, full_keys: bool) -> serde_json::Value {
        use serde_json::{Value, json};

        let mut statements = Vec::new();
        let mut qsets_used: HashMap<
            thruput_scp::SCPHash,
            thruput_scp::SCPQuorumSet,
        > = HashMap::new();

        for item in self.slot_state.statements_history.iter() {
            let mut statement_array = Vec::new();

            if let Ok(duration) =
                item.when.duration_since(std::time::UNIX_EPOCH)
            {
                statement_array.push(Value::Number(serde_json::Number::from(
                    duration.as_secs(),
                )));
            } else {
                statement_array
                    .push(Value::Number(serde_json::Number::from(0u64)));
            }

            statement_array.push(Value::String(
                self.cd.statement_to_str(&item.statement, full_keys),
            ));
            statement_array.push(Value::Bool(item.validated));

            let qset_hash = Self::get_companion_quorum_set_hash_from_statement(
                &item.statement,
            );
            if let Some(qset) = self.driver().get_qset(&qset_hash) {
                qsets_used.insert(qset_hash, qset.clone());
            }

            statements.push(Value::Array(statement_array));
        }

        let mut quorum_sets_obj = serde_json::Map::new();
        for (hash, qset) in qsets_used {
            let hash_abbrev = hex_abbrev(&hash);
            quorum_sets_obj.insert(
                hash_abbrev,
                self.local_proto().to_json(&qset, full_keys),
            );
        }

        json!({
            "statements": statements,
            "quorum_sets": quorum_sets_obj,
            "validated": self.slot_state.fully_validated,
            "nomination_proto": self.nomination_proto().get_json_info(),
            "ballot_proto": self.ballot_proto().get_json_info()
        })
    }

    pub fn get_json_quorum_info(
        &mut self,
        id: &thruput_scp::SCPNodeID,
        summary: bool,
        full_keys: bool,
    ) -> serde_json::Value {
        let mut ret = self
            .ballot_proto()
            .get_json_quorum_info(id, summary, full_keys);

        if self.local_proto().is_validator() {
            ret["validated"] =
                serde_json::Value::Bool(self.is_fully_validated());
        }

        ret
    }

    #[instrument(skip_all)]
    pub fn federated_accept<F1, F2>(
        &self,
        voted: &F1,
        accepted: &F2,
        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
    ) -> bool
    where
        F1: Fn(&thruput_scp::SCPStatement) -> bool,
        F2: Fn(&thruput_scp::SCPStatement) -> bool,
    {
        let local_proto = self.local_proto();
        let qset = local_proto.get_qset();

        // Checks if the nodes that claimed to accept the statement form a v-blocking set
        if LocalProto::<C, D>::is_vblocking_envelopes(qset, envs, accepted) {
            return true;
        }

        // Checks if the set of nodes that accepted or voted for it form a quorum
        let ratify_filter = |st: &thruput_scp::SCPStatement| -> bool {
            accepted(st) || voted(st)
        };

        let qset_getter =
            |st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
                self.get_quorum_set_from_statement(st)
            };

        LocalProto::<C, D>::is_quorum(qset, envs, &qset_getter, &ratify_filter)
    }

    #[instrument(skip_all)]
    pub fn federated_ratify<F>(
        &self,
        voted: &F,
        envs: &HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>,
    ) -> bool
    where
        F: Fn(&thruput_scp::SCPStatement) -> bool,
    {
        let local_proto = self.local_proto();
        let qset = local_proto.get_qset();

        let qset_getter =
            |st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
                self.get_quorum_set_from_statement(st)
            };

        LocalProto::<C, D>::is_quorum(qset, envs, &qset_getter, voted)
    }

    pub fn get_statement_count(&self) -> usize {
        self.slot_state.statements_history.len()
    }

    pub fn got_vblocking(&self) -> bool {
        self.slot_state.got_vblocking
    }

    pub fn get_entire_current_state(
        &mut self,
    ) -> Vec<thruput_scp::SCPEnvelope> {
        let mut res = Vec::new();
        self.process_current_state(
            &mut |envelope: &thruput_scp::SCPEnvelope| {
                res.push(envelope.clone());
                true
            },
            true,
        );
        res
    }

    pub fn get_latest_messages_send(
        &mut self,
    ) -> Vec<thruput_scp::SCPEnvelope> {
        let mut res = Vec::new();

        if self.slot_state.fully_validated {
            // Get nomination protocol's last message
            if let Some(nomination_envelope) =
                self.nomination_proto().get_last_message_send()
            {
                res.push(nomination_envelope);
            }

            // Get ballot protocol's last message
            if let Some(ballot_envelope) =
                self.ballot_proto().get_last_message_send()
            {
                res.push(ballot_envelope);
            }
        }

        res
    }

    pub fn get_latest_message(
        &mut self,
        node_id: &thruput_scp::SCPNodeID,
    ) -> Option<thruput_scp::SCPEnvelope> {
        // Check ballot protocol first
        if let Some(envelope) = self.ballot_proto().get_latest_message(node_id)
        {
            return Some(envelope);
        }
        // Fall back to nomination protocol
        if let Some(envelope) =
            self.nomination_proto().get_latest_message(node_id)
        {
            return Some(envelope);
        }
        None
    }

    pub fn maybe_set_got_vblocking(&mut self) {
        if self.slot_state.got_vblocking {
            // Already set
            return;
        }

        let qset = self.local_proto().get_qset().clone();
        let mut nodes = Vec::new();

        LocalProto::<C, D>::for_all_nodes(&qset, &mut |node_id| {
            if self.get_latest_message(node_id).is_some() {
                nodes.push(node_id.clone());
            }
            true
        });

        self.slot_state.got_vblocking =
            LocalProto::<C, D>::is_vblocking_nodes(&qset, &nodes);

        if self.slot_state.got_vblocking {
            tracing::trace!("got v-blocking for slot {}", self.index());
        }
    }

    pub fn set_state_from_envelope(
        &mut self,
        envelope: &thruput_scp::SCPEnvelope,
    ) {
        let statement = &envelope.statement;
        let local_node_id = self.local_proto().get_node_id().clone();

        if statement.node_id == local_node_id
            && statement.slot_index == self.index()
        {
            let had_previous_message =
                self.get_latest_message(&statement.node_id).is_some();

            match &statement.pledges {
                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
                    ..
                } => {
                    self.nomination_proto().set_state_from_envelope(envelope);
                }
                _ => {
                    self.ballot_proto().set_state_from_envelope(envelope);
                }
            }

            if !had_previous_message {
                self.maybe_set_got_vblocking();
            }
        } else {
            tracing::trace!(
                env = ?envelope,
                "slot proto set_state_from_envelope: invalid envelope for slot {} from node {:?}   e: {}",
                self.slot_state.slot_index,
                statement.node_id,
                self.cd.envelope_to_str(envelope, false)
            );
        }
    }

    pub fn process_current_state<F>(&mut self, f: &mut F, force_self: bool)
    where
        F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
    {
        if self.nomination_proto().process_current_state(f, force_self) {
            self.ballot_proto().process_current_state(f, force_self);
        }
    }

    pub fn is_newer_nomination_or_ballot_st(
        old_st: &thruput_scp::SCPStatement,
        new_st: &thruput_scp::SCPStatement,
    ) -> bool {
        let old_nomination = matches!(
            old_st.pledges,
            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. }
        );
        let new_nomination = matches!(
            new_st.pledges,
            thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. }
        );

        if old_nomination != new_nomination {
            return false;
        }

        // Handle each type appropriately
        if old_nomination {
            if let (
                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
                    nominate: old_nom,
                },
                thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
                    nominate: new_nom,
                },
            ) = (&old_st.pledges, &new_st.pledges)
            {
                NominationProto::<C, D>::is_newer_statement(old_nom, new_nom)
            } else {
                panic!("bug")
            }
        } else {
            BallotProto::<C, D>::is_newer_statement(old_st, new_st)
        }
    }

    pub fn get_externalizing_state(&mut self) -> Vec<thruput_scp::SCPEnvelope> {
        self.ballot_proto().get_externalizing_state()
    }

    /// Builds a proof snapshot for this slot after it externalizes.
    ///
    /// Returns `Ok(None)` only when the slot has no externalizing state yet.
    pub fn get_externalized_slot_proof(
        &mut self,
    ) -> Result<Option<ExternalizedSlotProof>, ExternalizedSlotProofError> {
        let envelopes = self.get_externalizing_state();
        if envelopes.is_empty() {
            return Ok(None);
        }

        let mut envelopes_by_node = HashMap::with_capacity(envelopes.len());
        let mut companion_qsets = HashMap::new();

        for envelope in envelopes {
            let node_id = envelope.statement.node_id.clone();
            if envelopes_by_node.contains_key(&node_id) {
                return Err(
                    ExternalizedSlotProofError::DuplicateNodeStatement {
                        node_id,
                    },
                );
            }
            envelopes_by_node.insert(node_id, envelope.clone());

            let qset_hash =
                federated::try_get_companion_quorum_set_hash_from_statement(
                    &envelope.statement,
                )
                .map_err(|error| {
                    ExternalizedSlotProofError::MalformedEnvelope {
                        reason: error.into(),
                    }
                })?;
            if companion_qsets.contains_key(&qset_hash) {
                continue;
            }

            let qset = self.driver().get_qset(&qset_hash).ok_or(
                ExternalizedSlotProofError::MissingCompanionQuorumSet {
                    hash: qset_hash,
                },
            )?;
            let actual_hash = scp_util::hash_xdr_scp(&qset).map_err(|_| {
                ExternalizedSlotProofError::CompanionQuorumSetHashFailed {
                    hash: qset_hash,
                }
            })?;
            if actual_hash != qset_hash {
                return Err(
                    ExternalizedSlotProofError::CompanionQuorumSetHashMismatch {
                        claimed: qset_hash,
                        actual: actual_hash,
                    },
                );
            }
            let qset_bytes = scp_util::marshal_xdr(&qset).map_err(|_| {
                ExternalizedSlotProofError::CompanionQuorumSetEncodingFailed {
                    hash: qset_hash,
                }
            })?;
            companion_qsets.insert(qset_hash, qset_bytes);
        }

        Ok(Some(ExternalizedSlotProof::new(
            envelopes_by_node,
            companion_qsets,
        )))
    }

    pub fn record_statement(&mut self, st: &thruput_scp::SCPStatement) {
        let historical_statement = HistoricalStatement {
            when: std::time::SystemTime::now(), //XXX:diff
            statement: st.clone(),
            validated: self.slot_state.fully_validated,
        };

        self.slot_state
            .statements_history
            .push(historical_statement);

        // Log the statement (similar to C++ version)
        tracing::debug!(
            "new statement recorded, i: {} st: {} validated: {}",
            self.slot_state.slot_index,
            self.cd.statement_to_str(st, false),
            self.slot_state.fully_validated,
        );
    }
}