/
consensus.rs
1878 lines (1690 loc) · 63.3 KB
/
consensus.rs
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
//! Defines types used internally by consensus components.
use crate::{
artifact::ConsensusMessageId,
batch::{BatchPayload, ValidationContext},
crypto::threshold_sig::ni_dkg::NiDkgId,
crypto::*,
replica_version::ReplicaVersion,
signature::*,
*,
};
use ic_base_types::PrincipalIdError;
#[cfg(test)]
use ic_exhaustive_derive::ExhaustiveSet;
use ic_protobuf::types::v1::{self as pb, consensus_message::Msg};
use ic_protobuf::{
log::block_log_entry::v1::BlockLogEntry,
proxy::{try_from_option_field, ProxyDecodeError},
};
use serde::{Deserialize, Serialize};
use std::cmp::PartialOrd;
use std::convert::TryInto;
use std::hash::Hash;
pub mod block_maker;
pub mod catchup;
pub mod certification;
pub mod dkg;
pub mod ecdsa;
mod ecdsa_refs;
pub mod hashed;
mod payload;
pub mod thunk;
pub use catchup::*;
use hashed::Hashed;
pub use payload::{BlockPayload, DataPayload, Payload, PayloadType, SummaryPayload};
/// Abstract messages with height attribute
pub trait HasHeight {
fn height(&self) -> Height;
}
/// Abstract messages with block hash
pub trait HasBlockHash {
fn block_hash(&self) -> &CryptoHashOf<Block>;
}
/// Abstract messages with rank attribute
pub trait HasRank {
fn rank(&self) -> Rank;
}
/// Abstract messages with committee attribute
pub trait HasCommittee {
fn committee() -> Committee;
}
/// Abstract messages with version attribute
pub trait HasVersion {
fn version(&self) -> &ReplicaVersion;
}
/// Abstract messages that may be a share or not
pub trait IsShare {
fn is_share(&self) -> bool;
}
/// Abstract messages with hash attribute. The [`hash`] implementation is expected
/// to return an existing hash value, instead of computing one.
pub trait HasHash {
fn hash(&self) -> &CryptoHash;
}
impl<T: HasHeight, S> HasHeight for Signed<T, S> {
fn height(&self) -> Height {
self.content.height()
}
}
impl<T: HasBlockHash, S> HasBlockHash for Signed<T, S> {
fn block_hash(&self) -> &CryptoHashOf<Block> {
self.content.block_hash()
}
}
impl<T: HasRank, S> HasRank for Signed<T, S> {
fn rank(&self) -> Rank {
self.content.rank()
}
}
impl<T: HasCommittee, S> HasCommittee for Signed<T, S> {
fn committee() -> Committee {
T::committee()
}
}
impl<T: HasVersion, S> HasVersion for Signed<T, S> {
fn version(&self) -> &ReplicaVersion {
self.content.version()
}
}
impl HasVersion for Block {
fn version(&self) -> &ReplicaVersion {
&self.version
}
}
impl<H, T: HasVersion> HasVersion for Hashed<H, T> {
fn version(&self) -> &ReplicaVersion {
self.value.version()
}
}
impl HasHeight for Block {
fn height(&self) -> Height {
self.height
}
}
impl<H, T: HasHeight> HasHeight for Hashed<H, T> {
fn height(&self) -> Height {
self.value.height()
}
}
impl HasRank for Block {
fn rank(&self) -> Rank {
self.rank
}
}
impl<H, T: HasRank> HasRank for Hashed<H, T> {
fn rank(&self) -> Rank {
self.value.rank()
}
}
impl HasVersion for NotarizationContent {
fn version(&self) -> &ReplicaVersion {
&self.version
}
}
impl HasHeight for NotarizationContent {
fn height(&self) -> Height {
self.height
}
}
impl HasBlockHash for HashedBlock {
fn block_hash(&self) -> &CryptoHashOf<Block> {
&self.hash
}
}
impl HasBlockHash for NotarizationContent {
fn block_hash(&self) -> &CryptoHashOf<Block> {
&self.block
}
}
impl HasCommittee for NotarizationContent {
fn committee() -> Committee {
Committee::Notarization
}
}
impl HasVersion for FinalizationContent {
fn version(&self) -> &ReplicaVersion {
&self.version
}
}
impl HasHeight for FinalizationContent {
fn height(&self) -> Height {
self.height
}
}
impl HasBlockHash for FinalizationContent {
fn block_hash(&self) -> &CryptoHashOf<Block> {
&self.block
}
}
impl HasCommittee for FinalizationContent {
fn committee() -> Committee {
Committee::Notarization
}
}
impl HasVersion for RandomBeaconContent {
fn version(&self) -> &ReplicaVersion {
&self.version
}
}
impl HasHeight for RandomBeaconContent {
fn height(&self) -> Height {
self.height
}
}
impl HasCommittee for RandomBeaconContent {
fn committee() -> Committee {
Committee::LowThreshold
}
}
impl HasVersion for RandomTapeContent {
fn version(&self) -> &ReplicaVersion {
&self.version
}
}
impl HasHeight for RandomTapeContent {
fn height(&self) -> Height {
self.height
}
}
impl HasCommittee for RandomTapeContent {
fn committee() -> Committee {
Committee::LowThreshold
}
}
/// Rank is used to indicate the priority of a block maker, where 0 indicates
/// the highest priority.
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(test, derive(ExhaustiveSet))]
pub struct Rank(pub u64);
/// Block is the type that is used to create blocks out of which we build a
/// block chain
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(test, derive(ExhaustiveSet))]
pub struct Block {
pub version: ReplicaVersion,
/// the parent block that this block extends, forming a block chain
pub parent: CryptoHashOf<Block>,
/// the payload of the block
pub payload: Payload,
/// the height of the block, which is the height of the parent + 1
pub height: Height,
/// rank indicates the rank of the block maker that created this block
pub rank: Rank,
/// the context with respect to which this block should be validated
pub context: ValidationContext,
}
impl Block {
/// Create a new block
pub fn new(
parent: CryptoHashOf<Block>,
payload: Payload,
height: Height,
rank: Rank,
context: ValidationContext,
) -> Self {
Block {
version: ReplicaVersion::default(),
parent,
payload,
height,
rank,
context,
}
}
/// Create a BlockLogEntry from this block
pub fn log_entry(&self, block_hash: String) -> BlockLogEntry {
BlockLogEntry {
byte_size: None,
certified_height: Some(self.context.certified_height.get()),
dkg_payload_type: Some(self.payload.as_ref().payload_type().to_string()),
hash: Some(block_hash),
height: Some(self.height.get()),
parent_hash: Some(hex::encode(self.parent.get_ref().0.clone())),
rank: Some(self.rank.0),
registry_version: Some(self.context.registry_version.get()),
time: Some(self.context.time.as_nanos_since_unix_epoch()),
version: Some(self.version().to_string()),
}
}
}
impl SignedBytesWithoutDomainSeparator for BlockMetadata {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
serde_cbor::to_vec(&self).unwrap()
}
}
/// HashedBlock contains a Block together with its hash
pub type HashedBlock = Hashed<CryptoHashOf<Block>, Block>;
/// BlockMetadata contains the version, height and hash of a block
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BlockMetadata {
version: ReplicaVersion,
height: Height,
hash: CryptoHashOf<Block>,
}
impl From<&HashedBlock> for BlockMetadata {
fn from(block: &HashedBlock) -> Self {
Self {
version: block.version().clone(),
height: block.height(),
hash: block.get_hash().clone(),
}
}
}
/// A BlockProposal is a HashedBlock with BlockMetadata signed by the block maker.
pub type BlockProposal = Signed<HashedBlock, BasicSignature<BlockMetadata>>;
impl From<&BlockProposal> for pb::BlockProposal {
fn from(block_proposal: &BlockProposal) -> Self {
Self {
hash: block_proposal.content.hash.clone().get().0,
value: Some((&block_proposal.content.value).into()),
signature: block_proposal.signature.signature.clone().get().0,
signer: Some(node_id_into_protobuf(block_proposal.signature.signer)),
}
}
}
impl TryFrom<pb::BlockProposal> for BlockProposal {
type Error = ProxyDecodeError;
fn try_from(block_proposal: pb::BlockProposal) -> Result<Self, Self::Error> {
Ok(Signed {
content: Hashed {
value: Block::try_from(
block_proposal
.value
.ok_or_else(|| ProxyDecodeError::MissingField("BlockProposal::value"))?,
)
.map_err(ProxyDecodeError::Other)?,
hash: CryptoHashOf::from(CryptoHash(block_proposal.hash)),
},
signature: BasicSignature {
signature: BasicSigOf::from(BasicSig(block_proposal.signature)),
signer: node_id_try_from_option(block_proposal.signer)?,
},
})
}
}
impl From<BlockProposal> for Block {
fn from(proposal: BlockProposal) -> Block {
proposal.content.value
}
}
impl AsRef<Block> for BlockProposal {
fn as_ref(&self) -> &Block {
self.content.as_ref()
}
}
/// NotarizationContent holds the values that are signed in a notarization
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NotarizationContent {
pub version: ReplicaVersion,
pub height: Height,
pub block: CryptoHashOf<Block>,
}
impl NotarizationContent {
/// Create a new notarization content from a height and a block hash
pub fn new(height: Height, block: CryptoHashOf<Block>) -> Self {
NotarizationContent {
version: ReplicaVersion::default(),
height,
block,
}
}
}
impl SignedBytesWithoutDomainSeparator for NotarizationContent {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
serde_cbor::to_vec(&self).unwrap()
}
}
/// A notarization is a multi-signature on a NotarizationContent
pub type Notarization = Signed<NotarizationContent, MultiSignature<NotarizationContent>>;
impl From<&Notarization> for pb::Notarization {
fn from(notarization: &Notarization) -> Self {
Self {
version: notarization.content.version.to_string(),
height: notarization.content.height.get(),
block: notarization.content.block.clone().get().0,
signature: notarization.signature.signature.clone().get().0,
signers: notarization
.signature
.signers
.iter()
.map(|node_id| (*node_id).get().into_vec())
.collect(),
}
}
}
impl TryFrom<pb::Notarization> for Notarization {
type Error = ProxyDecodeError;
fn try_from(notarization: pb::Notarization) -> Result<Self, Self::Error> {
Ok(Signed {
content: NotarizationContent {
version: ReplicaVersion::try_from(notarization.version.as_str())?,
height: Height::from(notarization.height),
block: CryptoHashOf::from(CryptoHash(notarization.block)),
},
signature: MultiSignature {
signature: CombinedMultiSigOf::from(CombinedMultiSig(notarization.signature)),
signers: notarization
.signers
.iter()
.map(|n| Ok(NodeId::from(PrincipalId::try_from(&n[..])?)))
.collect::<Result<_, PrincipalIdError>>()?,
},
})
}
}
/// A notarization share is a multi-signature share on a notarization content.
/// If sufficiently many replicas create notarization shares, the shares can be
/// aggregated into a full notarization.
pub type NotarizationShare = Signed<NotarizationContent, MultiSignatureShare<NotarizationContent>>;
impl From<&NotarizationShare> for pb::NotarizationShare {
fn from(notarization: &NotarizationShare) -> Self {
Self {
version: notarization.content.version.to_string(),
height: notarization.content.height.get(),
block: notarization.content.block.clone().get().0,
signature: notarization.signature.signature.clone().get().0,
signer: Some(node_id_into_protobuf(notarization.signature.signer)),
}
}
}
impl TryFrom<pb::NotarizationShare> for NotarizationShare {
type Error = ProxyDecodeError;
fn try_from(notarization: pb::NotarizationShare) -> Result<Self, Self::Error> {
Ok(Signed {
content: NotarizationContent {
version: ReplicaVersion::try_from(notarization.version.as_str())?,
height: Height::from(notarization.height),
block: CryptoHashOf::from(CryptoHash(notarization.block)),
},
signature: MultiSignatureShare {
signature: IndividualMultiSigOf::new(IndividualMultiSig(notarization.signature)),
signer: node_id_try_from_option(notarization.signer)?,
},
})
}
}
/// FinalizationContent holds the values that are signed in a finalization
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct FinalizationContent {
pub version: ReplicaVersion,
pub height: Height,
pub block: CryptoHashOf<Block>,
}
impl FinalizationContent {
pub fn new(height: Height, block: CryptoHashOf<Block>) -> Self {
FinalizationContent {
version: ReplicaVersion::default(),
height,
block,
}
}
}
impl SignedBytesWithoutDomainSeparator for FinalizationContent {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
serde_cbor::to_vec(&self).unwrap()
}
}
/// A finalization is a multi-signature on a FinalizationContent. A finalization
/// proves that the block identified by the block hash in the finalization
/// content (and the block chain it implies) is agreed upon.
pub type Finalization = Signed<FinalizationContent, MultiSignature<FinalizationContent>>;
impl From<&Finalization> for pb::Finalization {
fn from(finalization: &Finalization) -> Self {
Self {
version: finalization.content.version.to_string(),
height: finalization.content.height.get(),
block: finalization.content.block.clone().get().0,
signature: finalization.signature.signature.clone().get().0,
signers: finalization
.signature
.signers
.iter()
.map(|node_id| (*node_id).get().into_vec())
.collect(),
}
}
}
impl TryFrom<pb::Finalization> for Finalization {
type Error = ProxyDecodeError;
fn try_from(finalization: pb::Finalization) -> Result<Self, Self::Error> {
Ok(Signed {
content: FinalizationContent {
version: ReplicaVersion::try_from(finalization.version.as_str())?,
height: Height::from(finalization.height),
block: CryptoHashOf::from(CryptoHash(finalization.block)),
},
signature: MultiSignature {
signature: CombinedMultiSigOf::from(CombinedMultiSig(finalization.signature)),
signers: finalization
.signers
.iter()
.map(|n| Ok(NodeId::from(PrincipalId::try_from(&n[..])?)))
.collect::<Result<_, PrincipalIdError>>()?,
},
})
}
}
/// A finalization share is a multi-signature share on a finalization content.
/// If sufficiently many replicas create finalization shares, the shares can be
/// aggregated into a full finalization.
pub type FinalizationShare = Signed<FinalizationContent, MultiSignatureShare<FinalizationContent>>;
impl From<&FinalizationShare> for pb::FinalizationShare {
fn from(finalization: &FinalizationShare) -> Self {
Self {
version: finalization.content.version.to_string(),
height: finalization.content.height.get(),
block: finalization.content.block.clone().get().0,
signature: finalization.signature.signature.clone().get().0,
signer: Some(node_id_into_protobuf(finalization.signature.signer)),
}
}
}
impl TryFrom<pb::FinalizationShare> for FinalizationShare {
type Error = ProxyDecodeError;
fn try_from(finalization: pb::FinalizationShare) -> Result<Self, Self::Error> {
Ok(Signed {
content: FinalizationContent {
version: ReplicaVersion::try_from(finalization.version.as_str())?,
height: Height::from(finalization.height),
block: CryptoHashOf::from(CryptoHash(finalization.block)),
},
signature: MultiSignatureShare {
signature: IndividualMultiSigOf::new(IndividualMultiSig(finalization.signature)),
signer: node_id_try_from_option(finalization.signer)?,
},
})
}
}
/// RandomBeaconContent holds the content that is signed in the random beacon,
/// which is the previous random beacon, the height, and the replica version
/// used to create the random beacon.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(test, derive(ExhaustiveSet))]
pub struct RandomBeaconContent {
pub version: ReplicaVersion,
pub height: Height,
pub parent: CryptoHashOf<RandomBeacon>,
}
/// HashedRandomBeacon holds a RandomBeacon and its hash
pub type HashedRandomBeacon = Hashed<CryptoHashOf<RandomBeacon>, RandomBeacon>;
impl RandomBeaconContent {
/// Create a new RandomBeaconContent with a given height and parent
/// RandomBeacon
pub fn new(height: Height, parent: CryptoHashOf<RandomBeacon>) -> Self {
Self {
version: ReplicaVersion::default(),
height,
parent,
}
}
}
impl SignedBytesWithoutDomainSeparator for RandomBeaconContent {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
serde_cbor::to_vec(&self).unwrap()
}
}
/// A RandomBeacon is a RandomBeaconContent signed using a threshold signature.
/// The RandomBeacon provides pseudo-randomness to the consensus protocol that
/// is used to assign ranks to block makers and determine which replicas are
/// notaries.
pub type RandomBeacon = Signed<RandomBeaconContent, ThresholdSignature<RandomBeaconContent>>;
impl From<&RandomBeacon> for pb::RandomBeacon {
fn from(random_beacon: &RandomBeacon) -> Self {
Self {
version: random_beacon.content.version.to_string(),
height: random_beacon.content.height.get(),
parent: random_beacon.content.parent.clone().get().0,
signature: random_beacon.signature.signature.clone().get().0,
signer: Some(pb::NiDkgId::from(random_beacon.signature.signer)),
}
}
}
impl TryFrom<pb::RandomBeacon> for RandomBeacon {
type Error = ProxyDecodeError;
fn try_from(beacon: pb::RandomBeacon) -> Result<Self, Self::Error> {
Ok(Signed {
content: RandomBeaconContent {
version: ReplicaVersion::try_from(beacon.version.as_str())
.map_err(|e| ProxyDecodeError::ReplicaVersionParseError(Box::new(e)))?,
height: Height::from(beacon.height),
parent: CryptoHashOf::from(CryptoHash(beacon.parent)),
},
signature: ThresholdSignature {
signature: CombinedThresholdSigOf::new(CombinedThresholdSig(beacon.signature)),
signer: try_from_option_field(beacon.signer, "RandomBeacon::signer")?,
},
})
}
}
/// RandomBeaconShare is a threshold signature share on a RandomBeaconContent.
/// If sufficiently many replicas create random beacon shares, the shares can be
/// aggregated into a RandomBeacon.
pub type RandomBeaconShare =
Signed<RandomBeaconContent, ThresholdSignatureShare<RandomBeaconContent>>;
impl From<&RandomBeaconShare> for pb::RandomBeaconShare {
fn from(random_beacon: &RandomBeaconShare) -> Self {
Self {
version: random_beacon.content.version.to_string(),
height: random_beacon.content.height.get(),
parent: random_beacon.content.parent.clone().get().0,
signature: random_beacon.signature.signature.clone().get().0,
signer: Some(node_id_into_protobuf(random_beacon.signature.signer)),
}
}
}
impl TryFrom<pb::RandomBeaconShare> for RandomBeaconShare {
type Error = ProxyDecodeError;
fn try_from(beacon: pb::RandomBeaconShare) -> Result<Self, Self::Error> {
Ok(Signed {
content: RandomBeaconContent {
version: ReplicaVersion::try_from(beacon.version.as_str())
.map_err(|e| ProxyDecodeError::ReplicaVersionParseError(Box::new(e)))?,
height: Height::from(beacon.height),
parent: CryptoHashOf::from(CryptoHash(beacon.parent)),
},
signature: ThresholdSignatureShare {
signature: ThresholdSigShareOf::new(ThresholdSigShare(beacon.signature)),
signer: node_id_try_from_option(beacon.signer)?,
},
})
}
}
/// RandomTapeContent holds the content that is signed in the random tape,
/// which is the height and the replica version used to create the random
/// tape.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct RandomTapeContent {
pub version: ReplicaVersion,
pub height: Height,
}
impl SignedBytesWithoutDomainSeparator for RandomTapeContent {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
serde_cbor::to_vec(&self).unwrap()
}
}
impl RandomTapeContent {
/// Create a new RandomTapeContent from a given height
pub fn new(height: Height) -> Self {
RandomTapeContent {
version: ReplicaVersion::default(),
height,
}
}
}
/// A RandomTape is a RandomTapeContent signed using a threshold signature.
/// The RandomTape provides pseudo-randomness for executing the messages ordered
/// by consensus.
pub type RandomTape = Signed<RandomTapeContent, ThresholdSignature<RandomTapeContent>>;
impl From<&RandomTape> for pb::RandomTape {
fn from(random_tape: &RandomTape) -> Self {
Self {
version: random_tape.content.version.to_string(),
height: random_tape.content.height.get(),
signature: random_tape.signature.signature.clone().get().0,
signer: Some(pb::NiDkgId::from(random_tape.signature.signer)),
}
}
}
impl TryFrom<pb::RandomTape> for RandomTape {
type Error = ProxyDecodeError;
fn try_from(tape: pb::RandomTape) -> Result<Self, Self::Error> {
Ok(Signed {
content: RandomTapeContent {
version: ReplicaVersion::try_from(tape.version.as_str())?,
height: Height::from(tape.height),
},
signature: ThresholdSignature {
signature: CombinedThresholdSigOf::new(CombinedThresholdSig(tape.signature)),
signer: try_from_option_field(tape.signer, "RandomTape::signer")?,
},
})
}
}
/// RandomTapeShare is a threshold signature share on a RandomTapeContent. If
/// sufficiently many replicas create random tape shares, the shares can be
/// aggregated into a RandomTape.
pub type RandomTapeShare = Signed<RandomTapeContent, ThresholdSignatureShare<RandomTapeContent>>;
impl From<&RandomTapeShare> for pb::RandomTapeShare {
fn from(tape_share: &RandomTapeShare) -> Self {
Self {
version: tape_share.content.version.to_string(),
height: tape_share.content.height.get(),
signature: tape_share.signature.signature.clone().get().0,
signer: Some(node_id_into_protobuf(tape_share.signature.signer)),
}
}
}
impl TryFrom<pb::RandomTapeShare> for RandomTapeShare {
type Error = ProxyDecodeError;
fn try_from(tape_share: pb::RandomTapeShare) -> Result<Self, Self::Error> {
Ok(Signed {
content: RandomTapeContent {
version: ReplicaVersion::try_from(tape_share.version.as_str())?,
height: Height::from(tape_share.height),
},
signature: ThresholdSignatureShare {
signature: ThresholdSigShareOf::new(ThresholdSigShare(tape_share.signature)),
signer: node_id_try_from_option(tape_share.signer)?,
},
})
}
}
/// The enum encompassing all of the consensus artifacts exchanged between
/// replicas.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum ConsensusMessage {
RandomBeacon(RandomBeacon),
Finalization(Finalization),
Notarization(Notarization),
BlockProposal(BlockProposal),
RandomBeaconShare(RandomBeaconShare),
NotarizationShare(NotarizationShare),
FinalizationShare(FinalizationShare),
RandomTape(RandomTape),
RandomTapeShare(RandomTapeShare),
CatchUpPackage(CatchUpPackage),
CatchUpPackageShare(CatchUpPackageShare),
}
impl From<ConsensusMessage> for pb::ConsensusMessage {
fn from(value: ConsensusMessage) -> Self {
Self {
msg: Some(match value {
ConsensusMessage::RandomBeacon(ref x) => Msg::RandomBeacon(x.into()),
ConsensusMessage::Finalization(ref x) => Msg::Finalization(x.into()),
ConsensusMessage::Notarization(ref x) => Msg::Notarization(x.into()),
ConsensusMessage::BlockProposal(ref x) => Msg::BlockProposal(x.into()),
ConsensusMessage::RandomBeaconShare(ref x) => Msg::RandomBeaconShare(x.into()),
ConsensusMessage::NotarizationShare(ref x) => Msg::NotarizationShare(x.into()),
ConsensusMessage::FinalizationShare(ref x) => Msg::FinalizationShare(x.into()),
ConsensusMessage::RandomTape(ref x) => Msg::RandomTape(x.into()),
ConsensusMessage::RandomTapeShare(ref x) => Msg::RandomTapeShare(x.into()),
ConsensusMessage::CatchUpPackage(ref x) => Msg::Cup(x.into()),
ConsensusMessage::CatchUpPackageShare(ref x) => Msg::CupShare(x.into()),
}),
}
}
}
impl TryFrom<pb::ConsensusMessage> for ConsensusMessage {
type Error = ProxyDecodeError;
fn try_from(value: pb::ConsensusMessage) -> Result<Self, Self::Error> {
let Some(msg) = value.msg else {
return Err(ProxyDecodeError::MissingField("ConsensusMessage::msg"));
};
Ok(match msg {
Msg::RandomBeacon(x) => ConsensusMessage::RandomBeacon(x.try_into()?),
Msg::Finalization(x) => ConsensusMessage::Finalization(x.try_into()?),
Msg::Notarization(x) => ConsensusMessage::Notarization(x.try_into()?),
Msg::BlockProposal(x) => ConsensusMessage::BlockProposal(x.try_into()?),
Msg::RandomBeaconShare(x) => ConsensusMessage::RandomBeaconShare(x.try_into()?),
Msg::NotarizationShare(x) => ConsensusMessage::NotarizationShare(x.try_into()?),
Msg::FinalizationShare(x) => ConsensusMessage::FinalizationShare(x.try_into()?),
Msg::RandomTape(x) => ConsensusMessage::RandomTape(x.try_into()?),
Msg::RandomTapeShare(x) => ConsensusMessage::RandomTapeShare(x.try_into()?),
Msg::Cup(ref x) => ConsensusMessage::CatchUpPackage(x.try_into()?),
Msg::CupShare(x) => ConsensusMessage::CatchUpPackageShare(x.try_into()?),
})
}
}
impl TryFrom<ConsensusMessage> for RandomBeacon {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomBeacon(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for Finalization {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::Finalization(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for Notarization {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::Notarization(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for BlockProposal {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::BlockProposal(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for RandomBeaconShare {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomBeaconShare(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for NotarizationShare {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::NotarizationShare(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for FinalizationShare {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::FinalizationShare(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for RandomTape {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomTape(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for RandomTapeShare {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomTapeShare(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for CatchUpPackage {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::CatchUpPackage(x) => Ok(x),
_ => Err(msg),
}
}
}
impl TryFrom<ConsensusMessage> for CatchUpPackageShare {
type Error = ConsensusMessage;
fn try_from(msg: ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::CatchUpPackageShare(x) => Ok(x),
_ => Err(msg),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a RandomBeacon {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomBeacon(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a Finalization {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::Finalization(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a Notarization {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::Notarization(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a BlockProposal {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::BlockProposal(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a RandomBeaconShare {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomBeaconShare(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a NotarizationShare {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::NotarizationShare(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a FinalizationShare {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::FinalizationShare(x) => Ok(x),
_ => Err(()),
}
}
}
impl<'a> TryFrom<&'a ConsensusMessage> for &'a RandomTape {
type Error = ();
fn try_from(msg: &'a ConsensusMessage) -> Result<Self, Self::Error> {
match msg {
ConsensusMessage::RandomTape(x) => Ok(x),
_ => Err(()),