1use std::{
5 cmp::Ordering,
6 collections::BTreeMap,
7 fmt::{self, Debug, Display, Formatter},
8 hash::{Hash, Hasher},
9 ops::{Deref, Range, RangeInclusive},
10 sync::Arc,
11};
12
13use bytes::Bytes;
14use consensus_config::{DIGEST_LENGTH, DefaultHashFunction};
15use consensus_types::block::{BlockRef, BlockTimestampMs, Round, TransactionIndex};
16use enum_dispatch::enum_dispatch;
17use fastcrypto::hash::{Digest, HashFunction as _};
18use itertools::Itertools as _;
19use serde::{Deserialize, Serialize};
20
21use crate::{
22 block::{BlockAPI, Slot, VerifiedBlock},
23 leader_scoring::ReputationScores,
24 storage::Store,
25};
26
27pub type CommitIndex = u32;
29
30pub(crate) const GENESIS_COMMIT_INDEX: CommitIndex = 0;
31
32pub(crate) const DEFAULT_WAVE_LENGTH: Round = MINIMUM_WAVE_LENGTH;
38
39pub(crate) const MINIMUM_WAVE_LENGTH: Round = 3;
41
42pub(crate) type WaveNumber = u32;
45
46#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
59#[enum_dispatch(CommitAPI)]
60pub enum Commit {
61 V1(CommitV1),
62}
63
64impl Commit {
65 pub(crate) fn new(
67 index: CommitIndex,
68 previous_digest: CommitDigest,
69 timestamp_ms: BlockTimestampMs,
70 leader: BlockRef,
71 blocks: Vec<BlockRef>,
72 ) -> Self {
73 Commit::V1(CommitV1 {
74 index,
75 previous_digest,
76 timestamp_ms,
77 leader,
78 blocks,
79 })
80 }
81
82 pub(crate) fn serialize(&self) -> Result<Bytes, bcs::Error> {
83 let bytes = bcs::to_bytes(self)?;
84 Ok(bytes.into())
85 }
86}
87
88#[enum_dispatch]
90pub trait CommitAPI {
91 fn round(&self) -> Round;
92 fn index(&self) -> CommitIndex;
93 fn previous_digest(&self) -> CommitDigest;
94 fn timestamp_ms(&self) -> BlockTimestampMs;
95 fn leader(&self) -> BlockRef;
96 fn blocks(&self) -> &[BlockRef];
97}
98
99#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
102pub struct CommitV1 {
103 index: CommitIndex,
106 previous_digest: CommitDigest,
109 timestamp_ms: BlockTimestampMs,
111 leader: BlockRef,
113 blocks: Vec<BlockRef>,
115}
116
117impl CommitAPI for CommitV1 {
118 fn round(&self) -> Round {
119 self.leader.round
120 }
121
122 fn index(&self) -> CommitIndex {
123 self.index
124 }
125
126 fn previous_digest(&self) -> CommitDigest {
127 self.previous_digest
128 }
129
130 fn timestamp_ms(&self) -> BlockTimestampMs {
131 self.timestamp_ms
132 }
133
134 fn leader(&self) -> BlockRef {
135 self.leader
136 }
137
138 fn blocks(&self) -> &[BlockRef] {
139 &self.blocks
140 }
141}
142
143#[derive(Clone, Debug, PartialEq)]
149pub struct TrustedCommit {
150 inner: Arc<Commit>,
151
152 digest: CommitDigest,
154 serialized: Bytes,
155}
156
157impl TrustedCommit {
158 pub(crate) fn new_trusted(commit: Commit, serialized: Bytes) -> Self {
159 let digest = Self::compute_digest(&serialized);
160 Self {
161 inner: Arc::new(commit),
162 digest,
163 serialized,
164 }
165 }
166
167 pub(crate) fn new_for_test(
168 index: CommitIndex,
169 previous_digest: CommitDigest,
170 timestamp_ms: BlockTimestampMs,
171 leader: BlockRef,
172 blocks: Vec<BlockRef>,
173 ) -> Self {
174 let commit = Commit::new(index, previous_digest, timestamp_ms, leader, blocks);
175 let serialized = commit.serialize().unwrap();
176 Self::new_trusted(commit, serialized)
177 }
178
179 pub fn reference(&self) -> CommitRef {
180 CommitRef {
181 index: self.index(),
182 digest: self.digest(),
183 }
184 }
185
186 pub(crate) fn digest(&self) -> CommitDigest {
187 self.digest
188 }
189
190 pub(crate) fn serialized(&self) -> &Bytes {
191 &self.serialized
192 }
193
194 pub(crate) fn compute_digest(serialized: &[u8]) -> CommitDigest {
195 let mut hasher = DefaultHashFunction::new();
196 hasher.update(serialized);
197 CommitDigest(hasher.finalize().into())
198 }
199}
200
201impl Deref for TrustedCommit {
203 type Target = Commit;
204
205 fn deref(&self) -> &Self::Target {
206 &self.inner
207 }
208}
209
210#[derive(Clone, Debug)]
213pub(crate) struct CertifiedCommits {
214 commits: Vec<CertifiedCommit>,
215 votes: Vec<VerifiedBlock>,
216}
217
218impl CertifiedCommits {
219 pub(crate) fn new(commits: Vec<CertifiedCommit>, votes: Vec<VerifiedBlock>) -> Self {
220 Self { commits, votes }
221 }
222
223 pub(crate) fn commits(&self) -> &[CertifiedCommit] {
224 &self.commits
225 }
226
227 pub(crate) fn votes(&self) -> &[VerifiedBlock] {
228 &self.votes
229 }
230}
231
232#[derive(Clone, Debug)]
234pub(crate) struct CertifiedCommit {
235 commit: Arc<TrustedCommit>,
236 blocks: Vec<VerifiedBlock>,
237}
238
239impl CertifiedCommit {
240 pub(crate) fn new_certified(commit: TrustedCommit, blocks: Vec<VerifiedBlock>) -> Self {
241 Self {
242 commit: Arc::new(commit),
243 blocks,
244 }
245 }
246
247 pub fn blocks(&self) -> &[VerifiedBlock] {
248 &self.blocks
249 }
250}
251
252impl Deref for CertifiedCommit {
253 type Target = TrustedCommit;
254
255 fn deref(&self) -> &Self::Target {
256 &self.commit
257 }
258}
259
260#[derive(Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
262pub struct CommitDigest([u8; consensus_config::DIGEST_LENGTH]);
263
264impl CommitDigest {
265 pub const MIN: Self = Self([u8::MIN; consensus_config::DIGEST_LENGTH]);
267 pub const MAX: Self = Self([u8::MAX; consensus_config::DIGEST_LENGTH]);
268
269 pub fn into_inner(self) -> [u8; consensus_config::DIGEST_LENGTH] {
270 self.0
271 }
272}
273
274impl Hash for CommitDigest {
275 fn hash<H: Hasher>(&self, state: &mut H) {
276 state.write(&self.0[..8]);
277 }
278}
279
280impl From<CommitDigest> for Digest<{ DIGEST_LENGTH }> {
281 fn from(hd: CommitDigest) -> Self {
282 Digest::new(hd.0)
283 }
284}
285
286impl fmt::Display for CommitDigest {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
288 write!(
289 f,
290 "{}",
291 base64::Engine::encode(&base64::engine::general_purpose::STANDARD, self.0)
292 .get(0..4)
293 .ok_or(fmt::Error)?
294 )
295 }
296}
297
298impl fmt::Debug for CommitDigest {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
300 write!(
301 f,
302 "{}",
303 base64::Engine::encode(&base64::engine::general_purpose::STANDARD, self.0)
304 )
305 }
306}
307
308#[derive(Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq, PartialOrd, Ord)]
310pub struct CommitRef {
311 pub index: CommitIndex,
312 pub digest: CommitDigest,
313}
314
315impl CommitRef {
316 pub fn new(index: CommitIndex, digest: CommitDigest) -> Self {
317 Self { index, digest }
318 }
319}
320
321impl fmt::Display for CommitRef {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
323 write!(f, "C{}({})", self.index, self.digest)
324 }
325}
326
327impl fmt::Debug for CommitRef {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
329 write!(f, "C{}({:?})", self.index, self.digest)
330 }
331}
332
333pub type CommitVote = CommitRef;
335
336#[derive(Clone, PartialEq)]
343pub struct CommittedSubDag {
344 pub leader: BlockRef,
348 pub blocks: Vec<VerifiedBlock>,
350 pub timestamp_ms: BlockTimestampMs,
352 pub commit_ref: CommitRef,
356
357 pub decided_with_local_blocks: bool,
372 pub recovered_rejected_transactions: bool,
374
375 pub rejected_transactions_by_block: BTreeMap<BlockRef, Vec<TransactionIndex>>,
379}
380
381impl CommittedSubDag {
382 pub fn new(
384 leader: BlockRef,
385 blocks: Vec<VerifiedBlock>,
386 timestamp_ms: BlockTimestampMs,
387 commit_ref: CommitRef,
388 ) -> Self {
389 Self {
390 leader,
391 blocks,
392 timestamp_ms,
393 commit_ref,
394 decided_with_local_blocks: true,
395 recovered_rejected_transactions: false,
396 rejected_transactions_by_block: BTreeMap::new(),
397 }
398 }
399}
400
401pub(crate) fn sort_sub_dag_blocks(blocks: &mut [VerifiedBlock]) {
404 blocks.sort_by(|a, b| {
405 a.round()
406 .cmp(&b.round())
407 .then_with(|| a.author().cmp(&b.author()))
408 })
409}
410
411pub(crate) fn compute_sort_seed(committed_leaders: &[VerifiedBlock]) -> [u8; DIGEST_LENGTH] {
413 let mut hasher = DefaultHashFunction::new();
414 for leader in committed_leaders {
415 hasher.update(leader.digest().as_ref());
416 }
417 hasher.finalize().into()
418}
419
420fn block_sort_key(
424 seed: &[u8; DIGEST_LENGTH],
425 block_ref: &BlockRef,
426) -> (Round, [u8; DIGEST_LENGTH]) {
427 let mut hasher = DefaultHashFunction::new();
428 hasher.update(seed);
429 hasher.update(block_ref.digest);
430 (block_ref.round, hasher.finalize().into())
431}
432
433pub(crate) fn sort_committed_blocks(blocks: &mut [VerifiedBlock], seed: &[u8; DIGEST_LENGTH]) {
434 blocks.sort_by_cached_key(|b| block_sort_key(seed, &b.reference()));
435}
436
437impl Display for CommittedSubDag {
438 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
439 write!(
440 f,
441 "{}@{} [{}])",
442 self.commit_ref,
443 self.leader,
444 self.blocks
445 .iter()
446 .map(|b| b.reference().to_string())
447 .join(", ")
448 )
449 }
450}
451
452impl fmt::Debug for CommittedSubDag {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 write!(
455 f,
456 "{}@{} [{}])",
457 self.commit_ref,
458 self.leader,
459 self.blocks
460 .iter()
461 .map(|b| b.reference().to_string())
462 .join(", ")
463 )?;
464 write!(
465 f,
466 ";{}ms;{};{};[{}]",
467 self.timestamp_ms,
468 self.decided_with_local_blocks,
469 self.recovered_rejected_transactions,
470 self.rejected_transactions_by_block
471 .iter()
472 .map(|(block_ref, transactions)| {
473 format!("{}: {}, ", block_ref, transactions.len())
474 })
475 .collect::<Vec<_>>()
476 .join(", "),
477 )
478 }
479}
480
481pub(crate) fn load_committed_subdag_from_store(
483 store: &dyn Store,
484 commit: TrustedCommit,
485) -> CommittedSubDag {
486 let mut leader_block_idx = None;
487 let commit_blocks = store
488 .read_blocks(commit.blocks())
489 .expect("We should have the block referenced in the commit data");
490 let blocks = commit_blocks
491 .into_iter()
492 .enumerate()
493 .map(|(idx, commit_block_opt)| {
494 let commit_block =
495 commit_block_opt.expect("We should have the block referenced in the commit data");
496 if commit_block.reference() == commit.leader() {
497 leader_block_idx = Some(idx);
498 }
499 commit_block
500 })
501 .collect::<Vec<_>>();
502 let leader_block_idx = leader_block_idx.expect("Leader block must be in the sub-dag");
503 let leader_block_ref = blocks[leader_block_idx].reference();
504
505 let mut subdag = CommittedSubDag::new(
506 leader_block_ref,
507 blocks,
508 commit.timestamp_ms(),
509 commit.reference(),
510 );
511
512 let reject_votes = store
513 .read_rejected_transactions(commit.reference())
514 .unwrap();
515 if let Some(reject_votes) = reject_votes {
516 subdag.decided_with_local_blocks = true;
517 subdag.recovered_rejected_transactions = true;
518 subdag.rejected_transactions_by_block = reject_votes;
519 } else {
520 subdag.decided_with_local_blocks = false;
521 subdag.recovered_rejected_transactions = false;
522 }
523
524 subdag
525}
526
527#[derive(Debug, Clone, Copy, Eq, PartialEq)]
528pub(crate) enum Decision {
529 Direct,
530 Indirect,
531 Certified, }
533
534#[derive(Debug, Clone, PartialEq)]
536pub(crate) enum LeaderStatus {
537 Commit(VerifiedBlock),
538 Skip(Slot),
539 Undecided(Slot),
540}
541
542impl LeaderStatus {
543 pub(crate) fn round(&self) -> Round {
544 match self {
545 Self::Commit(block) => block.round(),
546 Self::Skip(leader) => leader.round,
547 Self::Undecided(leader) => leader.round,
548 }
549 }
550
551 pub(crate) fn is_decided(&self) -> bool {
552 match self {
553 Self::Commit(_) => true,
554 Self::Skip(_) => true,
555 Self::Undecided(_) => false,
556 }
557 }
558
559 pub(crate) fn into_decided_leader(self, direct: bool) -> Option<DecidedLeader> {
560 match self {
561 Self::Commit(block) => Some(DecidedLeader::Commit(block, direct)),
562 Self::Skip(slot) => Some(DecidedLeader::Skip(slot)),
563 Self::Undecided(..) => None,
564 }
565 }
566}
567
568impl Display for LeaderStatus {
569 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
570 match self {
571 Self::Commit(block) => write!(f, "Commit({})", block.reference()),
572 Self::Skip(slot) => write!(f, "Skip({slot})"),
573 Self::Undecided(slot) => write!(f, "Undecided({slot})"),
574 }
575 }
576}
577
578#[derive(Debug, Clone, PartialEq)]
580pub(crate) enum DecidedLeader {
581 Commit(VerifiedBlock, bool),
585 Skip(Slot),
587}
588
589impl DecidedLeader {
590 pub(crate) fn slot(&self) -> Slot {
592 match self {
593 Self::Commit(block, _direct) => block.reference().into(),
594 Self::Skip(slot) => *slot,
595 }
596 }
597
598 pub(crate) fn into_committed_block(self) -> Option<VerifiedBlock> {
600 match self {
601 Self::Commit(block, _direct) => Some(block),
602 Self::Skip(_) => None,
603 }
604 }
605
606 #[cfg(test)]
607 pub(crate) fn round(&self) -> Round {
608 match self {
609 Self::Commit(block, _direct) => block.round(),
610 Self::Skip(leader) => leader.round,
611 }
612 }
613
614 #[cfg(test)]
615 pub(crate) fn authority(&self) -> consensus_config::AuthorityIndex {
616 match self {
617 Self::Commit(block, _direct) => block.author(),
618 Self::Skip(leader) => leader.authority,
619 }
620 }
621}
622
623impl Display for DecidedLeader {
624 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
625 match self {
626 Self::Commit(block, _direct) => write!(f, "Commit({})", block.reference()),
627 Self::Skip(slot) => write!(f, "Skip({slot})"),
628 }
629 }
630}
631
632#[derive(Clone, Debug, Serialize, Deserialize)]
638pub struct CommitInfo {
639 pub(crate) committed_rounds: Vec<Round>,
640 pub(crate) reputation_scores: ReputationScores,
641}
642
643#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
649pub struct CommitRange(Range<CommitIndex>);
650
651impl CommitRange {
652 pub fn new(range: RangeInclusive<CommitIndex>) -> Self {
653 Self(*range.start()..(*range.end()).saturating_add(1))
656 }
657
658 pub fn start(&self) -> CommitIndex {
660 self.0.start
661 }
662
663 pub fn end(&self) -> CommitIndex {
665 self.0.end.saturating_sub(1)
666 }
667
668 pub fn extend_to(&mut self, other: CommitIndex) {
669 let new_end = other.saturating_add(1);
670 assert!(self.0.end <= new_end);
671 self.0 = self.0.start..new_end;
672 }
673
674 pub fn size(&self) -> usize {
675 self.0
676 .end
677 .checked_sub(self.0.start)
678 .expect("Range should never have end < start") as usize
679 }
680
681 pub fn is_equal_size(&self, other: &Self) -> bool {
683 self.size() == other.size()
684 }
685
686 pub fn is_next_range(&self, other: &Self) -> bool {
688 self.0.end == other.0.start
689 }
690}
691
692impl Ord for CommitRange {
693 fn cmp(&self, other: &Self) -> Ordering {
694 self.start()
695 .cmp(&other.start())
696 .then_with(|| self.end().cmp(&other.end()))
697 }
698}
699
700impl PartialOrd for CommitRange {
701 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
702 Some(self.cmp(other))
703 }
704}
705
706impl From<RangeInclusive<CommitIndex>> for CommitRange {
707 fn from(range: RangeInclusive<CommitIndex>) -> Self {
708 Self::new(range)
709 }
710}
711
712impl Debug for CommitRange {
714 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
715 write!(f, "CommitRange({}..={})", self.start(), self.end())
716 }
717}
718
719#[cfg(test)]
720mod tests {
721 use std::sync::Arc;
722
723 use super::*;
724 use crate::{
725 block::TestBlock,
726 context::Context,
727 storage::{WriteBatch, mem_store::MemStore},
728 };
729
730 #[tokio::test]
731 async fn test_new_subdag_from_commit() {
732 let store = Arc::new(MemStore::new());
733 let context = Arc::new(Context::new_for_test(4).0);
734 let wave_length = DEFAULT_WAVE_LENGTH;
735
736 let first_wave_rounds: u32 = wave_length;
738 let num_authorities: u32 = 4;
739
740 let mut blocks = Vec::new();
741 let (genesis_references, genesis): (Vec<_>, Vec<_>) = context
742 .committee
743 .authorities()
744 .map(|index| {
745 let author_idx = index.0.value() as u32;
746 let block = TestBlock::new(0, author_idx).build();
747 VerifiedBlock::new_for_test(block)
748 })
749 .map(|block| (block.reference(), block))
750 .unzip();
751 store.write(WriteBatch::default().blocks(genesis)).unwrap();
753 blocks.append(&mut genesis_references.clone());
754
755 let mut ancestors = genesis_references;
756 let mut leader = None;
757 for round in 1..=first_wave_rounds {
758 let mut new_ancestors = vec![];
759 for author in 0..num_authorities {
760 let base_ts = round as BlockTimestampMs * 1000;
761 let block = VerifiedBlock::new_for_test(
762 TestBlock::new(round, author)
763 .set_timestamp_ms(base_ts + (author + round) as u64)
764 .set_ancestors(ancestors.clone())
765 .build(),
766 );
767 store
768 .write(WriteBatch::default().blocks(vec![block.clone()]))
769 .unwrap();
770 new_ancestors.push(block.reference());
771 blocks.push(block.reference());
772
773 if round == first_wave_rounds {
776 leader = Some(block.clone());
777 break;
778 }
779 }
780 ancestors = new_ancestors;
781 }
782
783 let leader_block = leader.unwrap();
784 let leader_ref = leader_block.reference();
785 let commit_index = 1;
786 let commit = TrustedCommit::new_for_test(
787 commit_index,
788 CommitDigest::MIN,
789 leader_block.timestamp_ms(),
790 leader_ref,
791 blocks.clone(),
792 );
793 let subdag = load_committed_subdag_from_store(store.as_ref(), commit.clone());
794 assert_eq!(subdag.leader, leader_ref);
795 assert_eq!(subdag.timestamp_ms, leader_block.timestamp_ms());
796 assert_eq!(
797 subdag.blocks.len(),
798 (num_authorities * wave_length) as usize + 1
799 );
800 assert_eq!(subdag.commit_ref, commit.reference());
801 }
802
803 #[tokio::test]
804 async fn test_commit_range() {
805 telemetry_subscribers::init_for_testing();
806 let mut range1 = CommitRange::new(1..=5);
807 let range2 = CommitRange::new(2..=6);
808 let range3 = CommitRange::new(5..=10);
809 let range4 = CommitRange::new(6..=10);
810 let range5 = CommitRange::new(6..=9);
811 let range6 = CommitRange::new(1..=1);
812
813 assert_eq!(range1.start(), 1);
814 assert_eq!(range1.end(), 5);
815
816 assert_eq!(range1.size(), 5);
818 assert_eq!(range3.size(), 6);
819 assert_eq!(range6.size(), 1);
820
821 assert!(!range1.is_next_range(&range2));
823 assert!(!range1.is_next_range(&range3));
824 assert!(range1.is_next_range(&range4));
825 assert!(range1.is_next_range(&range5));
826
827 assert!(range1.is_equal_size(&range2));
829 assert!(!range1.is_equal_size(&range3));
830 assert!(range1.is_equal_size(&range4));
831 assert!(!range1.is_equal_size(&range5));
832
833 assert!(range1 < range2);
835 assert!(range2 < range3);
836 assert!(range3 < range4);
837 assert!(range5 < range4);
838
839 range1.extend_to(10);
841 assert_eq!(range1.start(), 1);
842 assert_eq!(range1.end(), 10);
843 assert_eq!(range1.size(), 10);
844
845 range1.extend_to(20);
846 assert_eq!(range1.start(), 1);
847 assert_eq!(range1.end(), 20);
848 assert_eq!(range1.size(), 20);
849 }
850}