-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathmod.rs
More file actions
6227 lines (5816 loc) · 268 KB
/
mod.rs
File metadata and controls
6227 lines (5816 loc) · 268 KB
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Simple and fast BFT agreement inspired by Simplex Consensus.
//!
//! Inspired by [Simplex Consensus](https://eprint.iacr.org/2023/463), `simplex` provides simple and fast BFT
//! agreement with network-speed view (i.e. block time) latency and optimal finalization latency in a
//! partially synchronous setting.
//!
//! # Features
//!
//! * Wicked Fast Block Times (2 Network Hops)
//! * Optimal Finalization Latency (3 Network Hops)
//! * Externalized Uptime and Fault Proofs
//! * Require Certification Before Finalization
//! * Decoupled Block Broadcast and Sync
//! * Lazy Message Verification
//! * Application-Defined Block Format
//! * Pluggable Hashing and Cryptography
//! * Embedded VRF (via [scheme::bls12381_threshold::vrf])
//!
//! # Design
//!
//! ## Protocol Description
//!
//! ### Genesis
//!
//! Genesis (view 0) is implicitly finalized. There is no finalization certificate for genesis;
//! the digest returned by [`Automaton::genesis`](crate::Automaton::genesis) serves as the initial
//! finalized state. Voting begins at view 1, with the first proposal referencing genesis as its parent.
//!
//! ### Specification for View `v`
//!
//! Upon entering view `v`:
//! * Determine leader `l` for view `v`
//! * Set timer for leader proposal `t_l = 2Δ` and advance `t_a = 3Δ`
//! * If leader `l` has not been active in last `r` views, set `t_l` to 0.
//! * If leader `l`, broadcast `notarize(c,v)`
//! * If can't propose container in view `v` because missing notarization/nullification for a
//! previous view `v_m`, request `v_m`
//!
//! Upon receiving first `notarize(c,v)` from `l`:
//! * Cancel `t_l`
//! * If the container's parent `c_parent` is finalized (or both notarized and certified) at `v_parent`
//! and we have nullifications for all views between `v` and `v_parent`, verify `c` and broadcast `notarize(c,v)`
//! * If verification of `c` fails, immediately broadcast `nullify(v)`
//!
//! Upon receiving `2f+1` `notarize(c,v)`:
//! * Cancel `t_a`
//! * Mark `c` as notarized
//! * Broadcast `notarization(c,v)` (even if we have not verified `c`)
//! * Attempt to certify `c` (see [Certification](#certification))
//! * On success: broadcast `finalize(c,v)` (if have not broadcast `nullify(v)`) and enter `v+1`
//! * On failure: broadcast `nullify(v)`
//!
//! Upon receiving `2f+1` `nullify(v)`:
//! * Broadcast `nullification(v)`
//! * Enter `v+1`
//!
//! Upon receiving `2f+1` `finalize(c,v)`:
//! * Mark `c` as finalized (and recursively finalize its parents)
//! * Broadcast `finalization(c,v)` (even if we have not verified `c`)
//!
//! Upon `t_l` or `t_a` firing:
//! * Broadcast `nullify(v)`
//! * Every `t_r` after `nullify(v)` broadcast that we are still in view `v`:
//! * Rebroadcast `nullify(v)` and either `notarization(v-1)` or `nullification(v-1)`
//!
//! _When `2f+1` votes of a given type (`notarize(c,v)`, `nullify(v)`, or `finalize(c,v)`) have been have been collected
//! from unique participants, a certificate (`notarization(c,v)`, `nullification(v)`, or `finalization(c,v)`) can be assembled.
//! These certificates serve as a standalone proof of consensus progress that downstream systems can ingest without executing
//! the protocol._
//!
//! ### Joining Consensus
//!
//! As soon as `2f+1` nullifies or finalizes are observed for some view `v`, the `Voter` will
//! enter `v+1`. Notarizations advance the view if-and-only-if the application certifies them.
//! This means that a new participant joining consensus will immediately jump ahead on the previous
//! view's nullification or finalization and begin participating in consensus at the current view.
//!
//! ### Certification
//!
//! After a payload is notarized, the application can optionally delay or prevent finalization via the
//! [`CertifiableAutomaton::certify`](crate::CertifiableAutomaton::certify) method. By default, `certify`
//! returns `true` for all payloads, meaning finalization proceeds immediately after notarization.
//!
//! Customizing `certify` is useful for systems that employ erasure coding, where participants may want
//! to wait until they have received enough shards to reconstruct and validate the full block before
//! voting to finalize.
//!
//! If `certify` returns `true`, the participant broadcasts a `finalize` vote for the payload and enters the
//! next view. If `certify` returns `false`, the participant broadcasts `nullify` for the view instead (treating
//! it as an immediate timeout), and will refuse to build upon the proposal or notarize proposals that build upon it.
//! Thus, a payload can only be finalized if a quorum of participants certify it.
//!
//! Certification of some notarization should only be abandoned once a finalization at the same or higher view is observed.
//! Until then (say a nullification certificate for a view arrives before certification completes), the application should continue
//! attempting to complete certification. This increases the likelihood that we can vote on the next honest proposer's block (which
//! may build on our in-flight certification or the nullification). If we did not do this, it is possible that different parts of
//! the network (neither with quorum) would refuse to vote on each other's blocks (halting consensus).
//!
//! _The decision returned by `certify` must be deterministic and consistent across all honest participants to ensure
//! liveness._
//!
//! ### Deviations from Simplex Consensus
//!
//! * Fetch missing notarizations/nullifications as needed rather than assuming each proposal contains
//! a set of all notarizations/nullifications for all historical blocks.
//! * Introduce distinct messages for `notarize` and `nullify` rather than referring to both as a `vote` for
//! either a "block" or a "dummy block", respectively.
//! * Introduce a "leader timeout" to trigger early view transitions for unresponsive leaders.
//! * Skip "leader timeout" and "certification timeout" if a designated leader hasn't participated in
//! some number of views (again to trigger early view transition for an unresponsive leader).
//! * Introduce message rebroadcast to continue making progress if messages from a given view are dropped (only way
//! to ensure messages are reliably delivered is with a heavyweight reliable broadcast protocol).
//! * Treat local proposal failure as immediate timeout expiry and broadcast `nullify(v)`.
//! * Treat local verification failure as immediate timeout expiry and broadcast `nullify(v)`.
//! * Consider the current leader's `nullify(v)` as immediate timeout expiry and broadcast `nullify(v)`.
//! * Upon seeing `notarization(c,v)`, instead of moving to the view `v+1` immediately, request certification from
//! the application (see [Certification](#certification)). Only move to view `v+1` and broadcast `finalize(c,v)`
//! if certification succeeds, otherwise broadcast `nullify(v)` and refuse to build upon `c`.
//!
//! ## Protocol Properties
//!
//! ### Forced Inclusion (Tail-Forking Resistance)
//!
//! A notarized payload in view `v` must appear in the canonical chain if no nullification
//! certificate exists for `v`. This follows directly from the protocol rules:
//!
//! 1. To propose in view `v+k`, the leader must reference a certified parent in some view `v_p`
//! and possess nullification certificates for every view between `v_p` and `v+k`.
//! 2. A nullification certificate for view `v` requires `2f+1` `nullify(v)` votes.
//! 3. An honest participant only broadcasts `nullify(v)` when a timeout fires (`t_l` or `t_a`)
//! or when certification fails.
//!
//! Therefore, if view `v` completes without timeout and certification succeeds, no honest
//! participant has broadcast `nullify(v)`. With at most `f` Byzantine participants, at most `f`
//! `nullify(v)` votes exist, which is insufficient to form a nullification certificate. Without
//! that certificate, no future leader can skip view `v`, and the notarized payload must be
//! included as an ancestor in all subsequent proposals.
//!
//! ### Optimistic Finality
//!
//! The forced inclusion property provides a weaker but faster form of finality: once a
//! notarization certificate is observed for view `v` (without any timeout having fired),
//! the notarized payload can be treated as speculatively final. No future sequence of
//! proposals can exclude it from the canonical chain.
//!
//! This "speculative finality" is available after just 2 network hops (proposal + notarization),
//! compared to the 3 hops required for full finalization (proposal + notarization + finalization).
//! A notarized-but-not-yet-finalized payload can only be excluded in two scenarios:
//! `f+1` or more honest participants timed out, or certification failed. Because
//! certification is deterministic, it either fails for all honest participants or none,
//! so a certification failure always produces a nullification. In the common case
//! (no faults, no timeouts), exclusion cannot happen.
//!
//! ### Unchained Finalization
//!
//! Finalization does not require consecutive honest views. When a participant certifies
//! `notarization(c,v)`, it broadcasts `finalize(c,v)` and immediately enters `v+1`,
//! regardless of what happens in subsequent views. These `finalize(c,v)` votes accumulate
//! independently of the current view: even if views `v+1` through `v+k` all time out
//! (producing nullifications), the `finalize(c,v)` votes still count toward the `2f+1`
//! threshold needed to form `finalization(c,v)`.
//!
//! This means a payload notarized in view `v` can be finalized while the network is
//! in view `v+k` for any `k >= 1`. There is no requirement that a particular view
//! after `v` succeeds or that any subsequent leader cooperates. As long as `2f+1`
//! participants eventually certify and broadcast `finalize(c,v)`, the finalization
//! certificate will form.
//!
//! ## Architecture
//!
//! All logic is split into four components: the `Batcher`, the `Voter`, the `Resolver`, and the `Application` (provided by the user).
//! The `Batcher` is responsible for collecting messages from peers and lazily verifying them when a quorum is met. The `Voter`
//! is responsible for directing participation in the current view. The `Resolver` is responsible for
//! fetching artifacts from previous views required to verify proposed blocks in the latest view. Lastly, the `Application`
//! is responsible for proposing new blocks and indicating whether some block is valid.
//!
//! To drive great performance, all interactions between `Batcher`, `Voter`, `Resolver`, and `Application` are
//! non-blocking. This means that, for example, the `Voter` can continue processing messages while the
//! `Application` verifies a proposed block or the `Resolver` fetches a notarization.
//!
//! ```txt
//! +------------+ +++++++++++++++
//! | +--------->+ +
//! | Batcher | + Peers +
//! | |<---------+ +
//! +-------+----+ +++++++++++++++
//! | ^
//! | |
//! | |
//! | |
//! v |
//! +---------------+ +---------+ +++++++++++++++
//! | |<----------+ +----------->+ +
//! | Application | | Voter | + Peers +
//! | +---------->| |<-----------+ +
//! +---------------+ +--+------+ +++++++++++++++
//! | ^
//! | |
//! | |
//! | |
//! v |
//! +-------+----+ +++++++++++++++
//! | +--------->+ +
//! | Resolver | + Peers +
//! | |<---------+ +
//! +------------+ +++++++++++++++
//! ```
//!
//! ### Batched Verification
//!
//! Unlike other consensus constructions that verify all incoming messages received from peers, for schemes
//! where [`Scheme::is_batchable()`](commonware_cryptography::certificate::Scheme::is_batchable) returns `true`
//! (such as [scheme::ed25519], [scheme::bls12381_multisig] and [scheme::bls12381_threshold]), `simplex` lazily
//! verifies messages (only when a quorum is met), enabling efficient batch verification. For schemes where
//! `is_batchable()` returns `false` (such as [scheme::secp256r1]), signatures are verified eagerly as they
//! arrive since there is no batching benefit.
//!
//! If an invalid signature is detected, the `Batcher` will perform repeated bisections over collected
//! messages to find the offending message (and block the peer(s) that sent it via [commonware_p2p::Blocker]).
//!
//! _If using a p2p implementation that is not authenticated, it is not safe to employ this optimization
//! as any attacking peer could simply reconnect from a different address. We recommend [commonware_p2p::authenticated]._
//!
//! ### Fetching Missing Certificates
//!
//! Instead of trying to fetch all possible certificates above the floor, we only attempt to fetch
//! nullifications for all views from the floor (last certified notarization or finalization) to the current view.
//! This technique, however, is not sufficient to guarantee progress.
//!
//! Consider the case where `f` honest participants have seen a finalization for a given view `v` (and nullifications only
//! from `v` to the current view `c`) but the remaining `f+1` honest participants have not (they have exclusively seen
//! nullifications from some view `o < v` to `c`). Neither partition of participants will vote for the other's proposals.
//!
//! To ensure progress is eventually made, leaders with nullified proposals directly broadcast the best finalization
//! certificate they are aware of to ensure all honest participants eventually consider the same proposal ancestry valid.
//!
//! _While a more aggressive recovery mechanism could be employed, like requiring all participants to broadcast their highest
//! finalization certificate after nullification, it would impose significant overhead under normal network
//! conditions (whereas the approach described incurs no overhead under normal network conditions). Recall, honest participants
//! already broadcast observed certificates to all other participants in each view (and misaligned participants should only ever
//! be observed following severe network degradation)._
//!
//! ## Pluggable Hashing and Cryptography
//!
//! Hashing is abstracted via the [commonware_cryptography::Hasher] trait and cryptography is abstracted via
//! the [commonware_cryptography::certificate::Scheme] trait, allowing deployments to employ approaches that best match their
//! requirements (or to provide their own without modifying any consensus logic). The following schemes
//! are supported out-of-the-box:
//!
//! ### [scheme::ed25519]
//!
//! [commonware_cryptography::ed25519] signatures are ["High-speed high-security signatures"](https://eprint.iacr.org/2011/368)
//! with 32 byte public keys and 64 byte signatures. While they are well-supported by commercial HSMs and offer efficient batch
//! verification, the signatures are not aggregatable (and certificates grow linearly with the quorum size).
//!
//! ### [scheme::bls12381_multisig]
//!
//! [commonware_cryptography::bls12381] is a ["digital signature scheme with aggregation properties"](https://www.ietf.org/archive/id/draft-irtf-cfrg-bls-signature-05.txt).
//! Unlike [commonware_cryptography::ed25519], signatures from multiple participants (say the signers in a certificate) can be aggregated
//! into a single signature (reducing bandwidth usage per broadcast). That being said, [commonware_cryptography::bls12381] is much slower
//! to verify than [commonware_cryptography::ed25519] and isn't supported by most HSMs (a standardization effort expired in 2022).
//!
//! ### [scheme::secp256r1]
//!
//! [commonware_cryptography::secp256r1] signatures use the NIST P-256 elliptic curve (also known as prime256v1), which is widely
//! supported by commercial HSMs and hardware security modules. Unlike [commonware_cryptography::ed25519], Secp256r1 does not
//! benefit from batch verification, so signatures are verified individually. Certificates grow linearly with quorum size
//! (similar to ed25519).
//!
//! ### [scheme::bls12381_threshold]
//!
//! [scheme::bls12381_threshold] employs threshold cryptography (BLS12-381 threshold signatures with a `2f+1` of `3f+1` quorum)
//! to generate succinct consensus certificates (verifiable with just the static public key). This scheme requires instantiating
//! the shared secret via [commonware_cryptography::bls12381::dkg] and resharing whenever participants change.
//!
//! Two (non-attributable) variants are provided:
//!
//! - [scheme::bls12381_threshold::standard]: Certificates contain only a vote signature.
//!
//! - [scheme::bls12381_threshold::vrf]: Certificates contain a vote signature and a view signature (i.e. a seed that can be used
//! as a VRF). This variant can be configured for random leader election (via [elector::Random]) and/or incorporate this randomness
//! into execution.
//!
//! #### Embedded VRF ([scheme::bls12381_threshold::vrf])
//!
//! Every `notarize(c,v)` or `nullify(v)` message includes an `attestation(v)` (a partial signature over the view `v`). After `2f+1`
//! `notarize(c,v)` or `nullify(v)` messages are collected from unique participants, `seed(v)` can be recovered. Because `attestation(v)` is
//! only over the view `v`, the seed derived for a given view `v` is the same regardless of whether or not a block was notarized in said
//! view `v`.
//!
//! Because the value of `seed(v)` cannot be known prior to message broadcast by any participant (including the leader) in view `v`
//! and cannot be manipulated by any participant (deterministic for any `2f+1` signers at a given view `v`), it can be used both as a beacon
//! for leader election (where `seed(v)` determines the leader for `v+1`) and a source of randomness in execution (where `seed(v)`
//! is used as a seed in `v`).
//!
//! #### Succinct Certificates
//!
//! All broadcast consensus messages (`notarize(c,v)`, `nullify(v)`, `finalize(c,v)`) contain attestations (partial signatures) for a static
//! public key (derived from a group polynomial that can be recomputed during reconfiguration using [dkg](commonware_cryptography::bls12381::dkg)).
//! As soon as `2f+1` messages are collected, a threshold signature over `notarization(c,v)`, `nullification(v)`, and `finalization(c,v)`
//! can be recovered, respectively. Because the public key is static, any of these certificates can be verified by an external
//! process without following the consensus instance and/or tracking the current set of participants (as is typically required
//! to operate a lite client).
//!
//! These threshold signatures over `notarization(c,v)`, `nullification(v)`, and `finalization(c,v)` (i.e. the consensus certificates)
//! can be used to secure interoperability between different consensus instances and user interactions with an infrastructure provider
//! (where any data served can be proven to derive from some finalized block of some consensus instance with a known static public key).
//!
//! ## Persistence
//!
//! The `Voter` caches all data required to participate in consensus to avoid any disk reads on
//! on the critical path. To enable recovery, the `Voter` writes valid messages it receives from
//! consensus and messages it generates to a write-ahead log (WAL) implemented by [commonware_storage::journal::segmented::variable::Journal].
//! Before sending a message, the `Journal` sync is invoked to prevent inadvertent Byzantine behavior
//! on restart (especially in the case of unclean shutdown).
use crate::types::Round;
use commonware_cryptography::PublicKey;
pub mod elector;
pub mod scheme;
pub mod types;
cfg_if::cfg_if! {
if #[cfg(not(target_arch = "wasm32"))] {
mod actors;
pub mod config;
pub use config::{Config, ForwardingPolicy};
mod engine;
pub use engine::Engine;
mod metrics;
}
}
#[cfg(any(test, feature = "mocks"))]
pub mod mocks;
#[cfg(not(target_arch = "wasm32"))]
use crate::types::{View, ViewDelta};
/// The minimum view we are tracking both in-memory and on-disk.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const fn min_active(activity_timeout: ViewDelta, last_finalized: View) -> View {
last_finalized.saturating_sub(activity_timeout)
}
/// Whether or not a view is interesting to us. This is a function
/// of both `min_active` and whether or not the view is too far
/// in the future (based on the view we are currently in).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn interesting(
activity_timeout: ViewDelta,
last_finalized: View,
current: View,
pending: View,
allow_future: bool,
) -> bool {
// If the view is genesis, skip it, genesis doesn't have votes
if pending.is_zero() {
return false;
}
if pending < min_active(activity_timeout, last_finalized) {
return false;
}
if !allow_future && pending > current.next() {
return false;
}
true
}
/// Describes how a payload should be broadcast to the network.
pub enum Plan<P: PublicKey> {
/// Initial broadcast of a newly proposed block to all participants.
Propose,
/// Forward a block to a specific set of peers.
Forward {
/// The round in which the forwarded block was proposed.
round: Round,
/// The peers to forward the block to.
peers: Vec<P>,
},
}
/// Convenience alias for [`N3f1::quorum`].
#[cfg(test)]
pub(crate) fn quorum(n: u32) -> u32 {
use commonware_utils::{Faults, N3f1};
N3f1::quorum(n)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
simplex::{
elector::{Config as Elector, Random, RoundRobin},
mocks::{
scheme as scheme_mocks,
twins::{self, Elector as TwinsElector},
wrapped,
},
scheme::{
bls12381_multisig,
bls12381_threshold::{
standard as bls12381_threshold_std,
vrf::{self as bls12381_threshold_vrf, Seedable},
},
ed25519, secp256r1, Scheme,
},
types::{
Certificate, Finalization as TFinalization, Finalize as TFinalize,
Notarization as TNotarization, Notarize as TNotarize,
Nullification as TNullification, Nullify as TNullify, Proposal, Vote,
},
},
types::{Epoch, Round},
Monitor, Viewable,
};
use commonware_codec::{Decode, DecodeExt, Encode};
use commonware_cryptography::{
bls12381::primitives::variant::{MinPk, MinSig, Variant},
certificate::mocks::Fixture,
ed25519::{PrivateKey, PublicKey},
sha256::{Digest as Sha256Digest, Digest as D},
Hasher as _, Sha256, Signer as _,
};
use commonware_macros::{select, test_group, test_traced};
use commonware_p2p::{
simulated::{Config, Link, Network, Oracle, Receiver, Sender, SplitOrigin},
utils::mocks::inert_channel,
Manager as _, Recipients, Sender as _, TrackedPeers,
};
use commonware_parallel::Sequential;
use commonware_runtime::{
buffer::paged::CacheRef, count_running_tasks, deterministic, Clock, IoBuf, Metrics, Quota,
Runner, Spawner,
};
use commonware_utils::{ordered::Set, sync::Mutex, test_rng, Faults, N3f1, NZUsize, NZU16};
use engine::Engine;
use futures::future::join_all;
use rand::{rngs::StdRng, Rng as _, SeedableRng};
use std::{
collections::{BTreeMap, HashMap, HashSet},
num::{NonZeroU16, NonZeroU32, NonZeroUsize},
sync::Arc,
time::Duration,
};
use tracing::{debug, info, warn};
use types::Activity;
const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);
const TEST_QUOTA: Quota = Quota::per_second(NonZeroU32::MAX);
#[test]
fn test_interesting() {
let activity_timeout = ViewDelta::new(10);
// Genesis view is never interesting
assert!(!interesting(
activity_timeout,
View::zero(),
View::zero(),
View::zero(),
false
));
assert!(!interesting(
activity_timeout,
View::zero(),
View::new(1),
View::zero(),
true
));
// View below min_active is not interesting
assert!(!interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(5), // below min_active (10)
false
));
// View at min_active boundary is interesting
assert!(interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(10), // exactly min_active
false
));
// Future view beyond current.next() is not interesting when allow_future is false
assert!(!interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(27),
false
));
// Future view beyond current.next() is interesting when allow_future is true
assert!(interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(27),
true
));
// View at current.next() is interesting
assert!(interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(26),
false
));
// View within valid range is interesting
assert!(interesting(
activity_timeout,
View::new(20),
View::new(25),
View::new(22),
false
));
// When last_finalized is 0 and activity_timeout would underflow
// min_active saturates at 0, so view 1 should still be interesting
assert!(interesting(
activity_timeout,
View::zero(),
View::new(5),
View::new(1),
false
));
}
/// Register a validator with the oracle.
async fn register_validator(
oracle: &mut Oracle<PublicKey, deterministic::Context>,
validator: PublicKey,
) -> (
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
) {
let control = oracle.control(validator.clone());
let (vote_sender, vote_receiver) = control.register(0, TEST_QUOTA).await.unwrap();
let (certificate_sender, certificate_receiver) =
control.register(1, TEST_QUOTA).await.unwrap();
let (resolver_sender, resolver_receiver) = control.register(2, TEST_QUOTA).await.unwrap();
(
(vote_sender, vote_receiver),
(certificate_sender, certificate_receiver),
(resolver_sender, resolver_receiver),
)
}
/// Registers all validators using the oracle.
async fn register_validators(
oracle: &mut Oracle<PublicKey, deterministic::Context>,
validators: &[PublicKey],
) -> HashMap<
PublicKey,
(
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
(
Sender<PublicKey, deterministic::Context>,
Receiver<PublicKey>,
),
),
> {
let mut registrations = HashMap::new();
for validator in validators.iter() {
let registration = register_validator(oracle, validator.clone()).await;
registrations.insert(validator.clone(), registration);
}
registrations
}
async fn start_test_network_with_peers<I>(
context: deterministic::Context,
peers: I,
disconnect_on_block: bool,
) -> Oracle<PublicKey, deterministic::Context>
where
I: IntoIterator<Item = PublicKey>,
{
let (network, oracle) = Network::new_with_peers(
context.with_label("network"),
Config {
max_size: 1024 * 1024,
disconnect_on_block,
tracked_peer_sets: NZUsize!(1),
},
peers,
)
.await;
network.start();
oracle
}
async fn start_test_network_with_split_peers<I, J>(
context: deterministic::Context,
primary: I,
secondary: J,
disconnect_on_block: bool,
) -> Oracle<PublicKey, deterministic::Context>
where
I: IntoIterator<Item = PublicKey>,
J: IntoIterator<Item = PublicKey>,
{
let (network, oracle) = Network::new_with_split_peers(
context.with_label("network"),
Config {
max_size: 1024 * 1024,
disconnect_on_block,
tracked_peer_sets: NZUsize!(1),
},
primary,
secondary,
)
.await;
network.start();
oracle
}
/// Enum to describe the action to take when linking validators.
enum Action {
Link(Link),
Update(Link), // Unlink and then link
Unlink,
}
/// Links (or unlinks) validators using the oracle.
///
/// The `action` parameter determines the action (e.g. link, unlink) to take.
/// The `restrict_to` function can be used to restrict the linking to certain connections,
/// otherwise all validators will be linked to all other validators.
async fn link_validators(
oracle: &mut Oracle<PublicKey, deterministic::Context>,
validators: &[PublicKey],
action: Action,
restrict_to: Option<fn(usize, usize, usize) -> bool>,
) {
for (i1, v1) in validators.iter().enumerate() {
for (i2, v2) in validators.iter().enumerate() {
// Ignore self
if v2 == v1 {
continue;
}
// Restrict to certain connections
if let Some(f) = restrict_to {
if !f(validators.len(), i1, i2) {
continue;
}
}
// Do any unlinking first
match action {
Action::Update(_) | Action::Unlink => {
oracle.remove_link(v1.clone(), v2.clone()).await.unwrap();
}
_ => {}
}
// Do any linking after
match action {
Action::Link(ref link) | Action::Update(ref link) => {
oracle
.add_link(v1.clone(), v2.clone(), link.clone())
.await
.unwrap();
}
_ => {}
}
}
}
}
/// Counts lines where all patterns match and the trailing value is non-zero.
fn count_nonzero_metric_lines(encoded: &str, patterns: &[&str]) -> u32 {
encoded
.lines()
.filter(|line| patterns.iter().all(|p| line.contains(p)))
.filter(|line| {
line.split_whitespace()
.last()
.and_then(|s| s.parse::<u64>().ok())
.is_some_and(|n| n > 0)
})
.count() as u32
}
fn all_online<S, F, L>(mut fixture: F)
where
S: Scheme<Sha256Digest, PublicKey = PublicKey>,
F: FnMut(&mut deterministic::Context, &[u8], u32) -> Fixture<S>,
L: Elector<S>,
{
// Create context
let n = 5;
let quorum = quorum(n) as usize;
let required_containers = View::new(100);
let activity_timeout = ViewDelta::new(10);
let skip_timeout = ViewDelta::new(5);
let namespace = b"consensus".to_vec();
let executor = deterministic::Runner::timed(Duration::from_secs(300));
executor.start(|mut context| async move {
// Register participants
let Fixture {
participants,
schemes,
..
} = fixture(&mut context, &namespace, n);
let mut oracle =
start_test_network_with_peers(context.clone(), participants.clone(), true).await;
let mut registrations = register_validators(&mut oracle, &participants).await;
// Link all validators
let link = Link {
latency: Duration::from_millis(10),
jitter: Duration::from_millis(1),
success_rate: 1.0,
};
link_validators(&mut oracle, &participants, Action::Link(link), None).await;
// Create engines
let elector = L::default();
let relay = Arc::new(mocks::relay::Relay::new());
let mut reporters = Vec::new();
let mut engine_handlers = Vec::new();
for (idx, validator) in participants.iter().enumerate() {
// Create scheme context
let context = context.with_label(&format!("validator_{}", *validator));
// Configure engine
let reporter_config = mocks::reporter::Config {
participants: participants.clone().try_into().unwrap(),
scheme: schemes[idx].clone(),
elector: elector.clone(),
};
let reporter =
mocks::reporter::Reporter::new(context.with_label("reporter"), reporter_config);
reporters.push(reporter.clone());
let application_cfg = mocks::application::Config {
hasher: Sha256::default(),
relay: relay.clone(),
me: validator.clone(),
propose_latency: (10.0, 5.0),
verify_latency: (10.0, 5.0),
certify_latency: (10.0, 5.0),
should_certify: mocks::application::Certifier::Sometimes,
};
let (actor, application) = mocks::application::Application::new(
context.with_label("application"),
application_cfg,
);
actor.start();
let blocker = oracle.control(validator.clone());
let cfg = config::Config {
scheme: schemes[idx].clone(),
elector: elector.clone(),
blocker,
automaton: application.clone(),
relay: application.clone(),
reporter: reporter.clone(),
strategy: Sequential,
partition: validator.to_string(),
mailbox_size: 1024,
epoch: Epoch::new(333),
leader_timeout: Duration::from_secs(1),
certification_timeout: Duration::from_secs(2),
timeout_retry: Duration::from_secs(10),
fetch_timeout: Duration::from_secs(1),
activity_timeout,
skip_timeout,
fetch_concurrent: 4,
replay_buffer: NZUsize!(1024 * 1024),
write_buffer: NZUsize!(1024 * 1024),
page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
forwarding: ForwardingPolicy::Disabled,
};
let engine = Engine::new(context.with_label("engine"), cfg);
// Start engine
let (pending, recovered, resolver) = registrations
.remove(validator)
.expect("validator should be registered");
engine_handlers.push(engine.start(pending, recovered, resolver));
}
// Wait for all engines to finish
let mut finalizers = Vec::new();
for reporter in reporters.iter_mut() {
let (mut latest, mut monitor) = reporter.subscribe().await;
finalizers.push(context.with_label("finalizer").spawn(move |_| async move {
while latest < required_containers {
latest = monitor.recv().await.expect("event missing");
}
}));
}
join_all(finalizers).await;
// Check reporters for correct activity
let latest_complete = required_containers.saturating_sub(activity_timeout);
for reporter in reporters.iter() {
// Ensure no faults
reporter.assert_no_faults();
// Ensure no invalid signatures
reporter.assert_no_invalid();
// Ensure certificates for all views
{
let certified = reporter.certified.lock();
for view in View::range(View::new(1), latest_complete) {
// Ensure certificate for every view
if !certified.contains(&view) {
panic!("view: {view}");
}
}
}
// Ensure no forks
let mut notarized = HashMap::new();
let mut finalized = HashMap::new();
{
let notarizes = reporter.notarizes.lock();
for view in View::range(View::new(1), latest_complete) {
// Ensure only one payload proposed per view
let Some(payloads) = notarizes.get(&view) else {
continue;
};
if payloads.len() > 1 {
panic!("view: {view}");
}
let (digest, notarizers) = payloads.iter().next().unwrap();
notarized.insert(view, *digest);
if notarizers.len() < quorum {
// We can't verify that everyone participated at every view because some nodes may
// have started later.
panic!("view: {view}");
}
}
}
{
let notarizations = reporter.notarizations.lock();
for view in View::range(View::new(1), latest_complete) {
// Ensure notarization matches digest from notarizes
let Some(notarization) = notarizations.get(&view) else {
continue;
};
let Some(digest) = notarized.get(&view) else {
continue;
};
assert_eq!(¬arization.proposal.payload, digest);
}
}
{
let finalizes = reporter.finalizes.lock();
for view in View::range(View::new(1), latest_complete) {
// Ensure only one payload proposed per view
let Some(payloads) = finalizes.get(&view) else {
continue;
};
if payloads.len() > 1 {
panic!("view: {view}");
}
let (digest, finalizers) = payloads.iter().next().unwrap();
finalized.insert(view, *digest);
// Only check at views below timeout
if view > latest_complete {
continue;
}
// Ensure everyone participating
if finalizers.len() < quorum {
// We can't verify that everyone participated at every view because some nodes may
// have started later.
panic!("view: {view}");
}
// Ensure no nullifies for any finalizers
let nullifies = reporter.nullifies.lock();
let Some(nullifies) = nullifies.get(&view) else {
continue;
};
for (_, finalizers) in payloads.iter() {
for finalizer in finalizers.iter() {
if nullifies.contains(finalizer) {
panic!("should not nullify and finalize at same view");
}
}
}
}
}
{
let finalizations = reporter.finalizations.lock();
for view in View::range(View::new(1), latest_complete) {
// Ensure finalization matches digest from finalizes
let Some(finalization) = finalizations.get(&view) else {
continue;
};
let Some(digest) = finalized.get(&view) else {
continue;
};
assert_eq!(&finalization.proposal.payload, digest);
}
}
}
// Ensure no blocked connections
let blocked = oracle.blocked().await.unwrap();
assert!(blocked.is_empty());
});
}
#[test_group("slow")]
#[test_traced]
fn test_all_online() {
all_online::<_, _, Random>(bls12381_threshold_vrf::fixture::<MinPk, _>);
all_online::<_, _, Random>(bls12381_threshold_vrf::fixture::<MinSig, _>);
all_online::<_, _, RoundRobin>(bls12381_threshold_std::fixture::<MinPk, _>);
all_online::<_, _, RoundRobin>(bls12381_threshold_std::fixture::<MinSig, _>);
all_online::<_, _, RoundRobin>(bls12381_multisig::fixture::<MinPk, _>);
all_online::<_, _, RoundRobin>(bls12381_multisig::fixture::<MinSig, _>);
all_online::<_, _, RoundRobin>(ed25519::fixture);
all_online::<_, _, RoundRobin>(secp256r1::fixture);
}
fn observer<S, F, L>(mut fixture: F)
where
S: Scheme<Sha256Digest, PublicKey = PublicKey>,
F: FnMut(&mut deterministic::Context, &[u8], u32) -> Fixture<S>,
L: Elector<S>,
{
// Create context
let n_active = 5;
let required_containers = View::new(100);
let activity_timeout = ViewDelta::new(10);
let skip_timeout = ViewDelta::new(5);
let namespace = b"consensus".to_vec();
let executor = deterministic::Runner::timed(Duration::from_secs(300));
executor.start(|mut context| async move {
// Register participants (active)
let Fixture {
participants,
schemes,
verifier,
..
} = fixture(&mut context, &namespace, n_active);
// Add observer (no share)
let private_key_observer = PrivateKey::from_seed(n_active as u64);
let public_key_observer = private_key_observer.public_key();
let mut oracle = start_test_network_with_split_peers(
context.clone(),
participants.clone(),
[public_key_observer.clone()],
true,
)
.await;
// Register all (including observer) with the network
let mut all_validators = participants.clone();
all_validators.push(public_key_observer.clone());
all_validators.sort();
let mut registrations = register_validators(&mut oracle, &all_validators).await;
// Link all peers (including observer)
let link = Link {
latency: Duration::from_millis(10),
jitter: Duration::from_millis(1),
success_rate: 1.0,
};
link_validators(&mut oracle, &all_validators, Action::Link(link), None).await;