-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
primary.rs
2147 lines (1923 loc) · 95 KB
/
primary.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
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkOS library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
events::{BatchPropose, BatchSignature, Event},
helpers::{
assign_to_worker,
assign_to_workers,
fmt_id,
init_sync_channels,
init_worker_channels,
now,
BFTSender,
PrimaryReceiver,
PrimarySender,
Proposal,
Storage,
},
spawn_blocking,
Gateway,
Sync,
Transport,
Worker,
MAX_BATCH_DELAY_IN_MS,
MAX_WORKERS,
PRIMARY_PING_IN_MS,
WORKER_PING_IN_MS,
};
use snarkos_account::Account;
use snarkos_node_bft_events::PrimaryPing;
use snarkos_node_bft_ledger_service::LedgerService;
use snarkvm::{
console::{
account::Signature,
prelude::*,
types::{Address, Field},
},
ledger::{
block::Transaction,
coinbase::{ProverSolution, PuzzleCommitment},
narwhal::{BatchCertificate, BatchHeader, Data, Transmission, TransmissionID},
},
prelude::committee::Committee,
};
use colored::Colorize;
use futures::stream::{FuturesUnordered, StreamExt};
use indexmap::{IndexMap, IndexSet};
use parking_lot::{Mutex, RwLock};
use rayon::prelude::*;
use std::{
collections::{HashMap, HashSet},
future::Future,
net::SocketAddr,
sync::Arc,
time::Duration,
};
use tokio::{
sync::{Mutex as TMutex, OnceCell},
task::JoinHandle,
};
/// A helper type for an optional proposed batch.
pub type ProposedBatch<N> = RwLock<Option<Proposal<N>>>;
#[derive(Clone)]
pub struct Primary<N: Network> {
/// The sync module.
sync: Sync<N>,
/// The gateway.
gateway: Gateway<N>,
/// The storage.
storage: Storage<N>,
/// The ledger service.
ledger: Arc<dyn LedgerService<N>>,
/// The workers.
workers: Arc<[Worker<N>]>,
/// The BFT sender.
bft_sender: Arc<OnceCell<BFTSender<N>>>,
/// The batch proposal, if the primary is currently proposing a batch.
proposed_batch: Arc<ProposedBatch<N>>,
/// The recently-signed batch proposals (a map from the address to the round, batch ID, and signature).
signed_proposals: Arc<RwLock<HashMap<Address<N>, (u64, Field<N>, Signature<N>)>>>,
/// The spawned handles.
handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
/// The lock for propose_batch.
propose_lock: Arc<TMutex<u64>>,
}
impl<N: Network> Primary<N> {
/// The maximum number of unconfirmed transmissions to send to the primary.
pub const MAX_TRANSMISSIONS_TOLERANCE: usize = BatchHeader::<N>::MAX_TRANSMISSIONS_PER_BATCH * 2;
/// Initializes a new primary instance.
pub fn new(
account: Account<N>,
storage: Storage<N>,
ledger: Arc<dyn LedgerService<N>>,
ip: Option<SocketAddr>,
trusted_validators: &[SocketAddr],
dev: Option<u16>,
) -> Result<Self> {
// Initialize the gateway.
let gateway = Gateway::new(account, storage.clone(), ledger.clone(), ip, trusted_validators, dev)?;
// Initialize the sync module.
let sync = Sync::new(gateway.clone(), storage.clone(), ledger.clone());
// Initialize the primary instance.
Ok(Self {
sync,
gateway,
storage,
ledger,
workers: Arc::from(vec![]),
bft_sender: Default::default(),
proposed_batch: Default::default(),
signed_proposals: Default::default(),
handles: Default::default(),
propose_lock: Default::default(),
})
}
/// Run the primary instance.
pub async fn run(
&mut self,
bft_sender: Option<BFTSender<N>>,
primary_sender: PrimarySender<N>,
primary_receiver: PrimaryReceiver<N>,
) -> Result<()> {
info!("Starting the primary instance of the memory pool...");
// Set the BFT sender.
if let Some(bft_sender) = &bft_sender {
// Set the BFT sender in the primary.
self.bft_sender.set(bft_sender.clone()).expect("BFT sender already set");
}
// Construct a map of the worker senders.
let mut worker_senders = IndexMap::new();
// Construct a map for the workers.
let mut workers = Vec::new();
// Initialize the workers.
for id in 0..MAX_WORKERS {
// Construct the worker channels.
let (tx_worker, rx_worker) = init_worker_channels();
// Construct the worker instance.
let worker = Worker::new(
id,
Arc::new(self.gateway.clone()),
self.storage.clone(),
self.ledger.clone(),
self.proposed_batch.clone(),
)?;
// Run the worker instance.
worker.run(rx_worker);
// Add the worker to the list of workers.
workers.push(worker);
// Add the worker sender to the map.
worker_senders.insert(id, tx_worker);
}
// Set the workers.
self.workers = Arc::from(workers);
// First, initialize the sync channels.
let (sync_sender, sync_receiver) = init_sync_channels();
// Next, initialize the sync module.
self.sync.run(bft_sender, sync_receiver).await?;
// Next, initialize the gateway.
self.gateway.run(primary_sender, worker_senders, Some(sync_sender)).await;
// Lastly, start the primary handlers.
// Note: This ensures the primary does not start communicating before syncing is complete.
self.start_handlers(primary_receiver);
Ok(())
}
/// Returns the current round.
pub fn current_round(&self) -> u64 {
self.storage.current_round()
}
/// Returns `true` if the primary is synced.
pub fn is_synced(&self) -> bool {
self.sync.is_synced()
}
/// Returns the gateway.
pub const fn gateway(&self) -> &Gateway<N> {
&self.gateway
}
/// Returns the storage.
pub const fn storage(&self) -> &Storage<N> {
&self.storage
}
/// Returns the ledger.
pub const fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
&self.ledger
}
/// Returns the number of workers.
pub fn num_workers(&self) -> u8 {
u8::try_from(self.workers.len()).expect("Too many workers")
}
/// Returns the workers.
pub const fn workers(&self) -> &Arc<[Worker<N>]> {
&self.workers
}
/// Returns the batch proposal of our primary, if one currently exists.
pub fn proposed_batch(&self) -> &Arc<ProposedBatch<N>> {
&self.proposed_batch
}
}
impl<N: Network> Primary<N> {
/// Returns the number of unconfirmed transmissions.
pub fn num_unconfirmed_transmissions(&self) -> usize {
self.workers.iter().map(|worker| worker.num_transmissions()).sum()
}
/// Returns the number of unconfirmed ratifications.
pub fn num_unconfirmed_ratifications(&self) -> usize {
self.workers.iter().map(|worker| worker.num_ratifications()).sum()
}
/// Returns the number of solutions.
pub fn num_unconfirmed_solutions(&self) -> usize {
self.workers.iter().map(|worker| worker.num_solutions()).sum()
}
/// Returns the number of unconfirmed transactions.
pub fn num_unconfirmed_transactions(&self) -> usize {
self.workers.iter().map(|worker| worker.num_transactions()).sum()
}
}
impl<N: Network> Primary<N> {
/// Returns the unconfirmed transmission IDs.
pub fn unconfirmed_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
self.workers.iter().flat_map(|worker| worker.transmission_ids())
}
/// Returns the unconfirmed transmissions.
pub fn unconfirmed_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
self.workers.iter().flat_map(|worker| worker.transmissions())
}
/// Returns the unconfirmed solutions.
pub fn unconfirmed_solutions(&self) -> impl '_ + Iterator<Item = (PuzzleCommitment<N>, Data<ProverSolution<N>>)> {
self.workers.iter().flat_map(|worker| worker.solutions())
}
/// Returns the unconfirmed transactions.
pub fn unconfirmed_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
self.workers.iter().flat_map(|worker| worker.transactions())
}
}
impl<N: Network> Primary<N> {
/// Proposes the batch for the current round.
///
/// This method performs the following steps:
/// 1. Drain the workers.
/// 2. Sign the batch.
/// 3. Set the batch proposal in the primary.
/// 4. Broadcast the batch header to all validators for signing.
pub async fn propose_batch(&self) -> Result<()> {
// This function isn't re-entrant.
let mut lock_guard = self.propose_lock.lock().await;
// Check if the proposed batch has expired, and clear it if it has expired.
if let Err(e) = self.check_proposed_batch_for_expiration().await {
warn!("Failed to check the proposed batch for expiration - {e}");
return Ok(());
}
// If there is a batch being proposed already,
// rebroadcast the batch header to the non-signers, and return early.
if let Some(proposal) = self.proposed_batch.read().as_ref() {
// Construct the event.
// TODO(ljedrz): the BatchHeader should be serialized only once in advance before being sent to non-signers.
let event = Event::BatchPropose(proposal.batch_header().clone().into());
// Iterate through the non-signers.
for address in proposal.nonsigners(&self.ledger.get_committee_lookback_for_round(proposal.round())?) {
// Resolve the address to the peer IP.
match self.gateway.resolver().get_peer_ip_for_address(address) {
// Resend the batch proposal to the validator for signing.
Some(peer_ip) => {
let (gateway, event_, round) = (self.gateway.clone(), event.clone(), proposal.round());
tokio::spawn(async move {
debug!("Resending batch proposal for round {round} to peer '{peer_ip}'");
// Resend the batch proposal to the peer.
if gateway.send(peer_ip, event_).await.is_none() {
warn!("Failed to resend batch proposal for round {round} to peer '{peer_ip}'");
}
});
}
None => continue,
}
}
debug!("Proposed batch for round {} is still valid", proposal.round());
return Ok(());
}
// Retrieve the current round.
let round = self.current_round();
#[cfg(feature = "metrics")]
metrics::gauge(metrics::bft::PROPOSAL_ROUND, round as f64);
// Ensure the primary has not proposed a batch for this round before.
if self.storage.contains_certificate_in_round_from(round, self.gateway.account().address()) {
// If a BFT sender was provided, attempt to advance the current round.
if let Some(bft_sender) = self.bft_sender.get() {
match bft_sender.send_primary_round_to_bft(self.current_round()).await {
// 'is_ready' is true if the primary is ready to propose a batch for the next round.
Ok(true) => (), // continue,
// 'is_ready' is false if the primary is not ready to propose a batch for the next round.
Ok(false) => return Ok(()),
// An error occurred while attempting to advance the current round.
Err(e) => {
warn!("Failed to update the BFT to the next round - {e}");
return Err(e);
}
}
}
bail!("Primary is safely skipping {}", format!("(round {round} was already certified)").dimmed());
}
// Retrieve the committee to check against.
let committee_lookback = self.ledger.get_committee_lookback_for_round(round)?;
// Check if the primary is connected to enough validators to reach quorum threshold.
{
// Retrieve the connected validator addresses.
let mut connected_validators = self.gateway.connected_addresses();
// Append the primary to the set.
connected_validators.insert(self.gateway.account().address());
// If quorum threshold is not reached, return early.
if !committee_lookback.is_quorum_threshold_reached(&connected_validators) {
debug!(
"Primary is safely skipping a batch proposal {}",
"(please connect to more validators)".dimmed()
);
trace!("Primary is connected to {} validators", connected_validators.len() - 1);
return Ok(());
}
}
// Compute the previous round.
let previous_round = round.saturating_sub(1);
// Retrieve the previous certificates.
let previous_certificates = self.storage.get_certificates_for_round(previous_round);
// Check if the batch is ready to be proposed.
// Note: The primary starts at round 1, and round 0 contains no certificates, by definition.
let mut is_ready = previous_round == 0;
// If the previous round is not 0, check if the previous certificates have reached the quorum threshold.
if previous_round > 0 {
// Retrieve the committee lookback for the round.
let Ok(previous_committee_lookback) = self.ledger.get_committee_lookback_for_round(previous_round) else {
bail!("Cannot propose a batch for round {round}: the committee lookback is not known yet")
};
// Construct a set over the authors.
let authors = previous_certificates.iter().map(BatchCertificate::author).collect();
// Check if the previous certificates have reached the quorum threshold.
if previous_committee_lookback.is_quorum_threshold_reached(&authors) {
is_ready = true;
}
}
// If the batch is not ready to be proposed, return early.
if !is_ready {
debug!(
"Primary is safely skipping a batch proposal {}",
format!("(previous round {previous_round} has not reached quorum)").dimmed()
);
return Ok(());
}
// Determined the required number of transmissions per worker.
let num_transmissions_per_worker = BatchHeader::<N>::MAX_TRANSMISSIONS_PER_BATCH / self.num_workers() as usize;
// Initialize the map of transmissions.
let mut transmissions: IndexMap<_, _> = Default::default();
// Initialize a tracker for the number of transactions.
let mut num_transactions = 0;
// Take the transmissions from the workers.
for worker in self.workers.iter() {
// Initialize a tracker for included transmissions for the current worker.
let mut num_transmissions_included_for_worker = 0;
// Keep draining the worker until the desired number of transmissions is reached or the worker is empty.
'outer: while num_transmissions_included_for_worker < num_transmissions_per_worker {
// Determine the number of remaining transmissions for the worker.
let num_remaining_transmissions =
num_transmissions_per_worker.saturating_sub(num_transmissions_included_for_worker);
// Drain the worker.
let mut worker_transmissions = worker.drain(num_remaining_transmissions).peekable();
// If the worker is empty, break early.
if worker_transmissions.peek().is_none() {
break 'outer;
}
// Iterate through the worker transmissions.
'inner: for (id, transmission) in worker_transmissions {
// Check if the ledger already contains the transmission.
if self.ledger.contains_transmission(&id).unwrap_or(true) {
trace!("Proposing - Skipping transmission '{}' - Already in ledger", fmt_id(id));
continue 'inner;
}
// Check if the storage already contain the transmission.
// Note: We do not skip if this is the first transmission in the proposal, to ensure that
// the primary does not propose a batch with no transmissions.
if !transmissions.is_empty() && self.storage.contains_transmission(id) {
trace!("Proposing - Skipping transmission '{}' - Already in storage", fmt_id(id));
continue 'inner;
}
// Check the transmission is still valid.
match (id, transmission.clone()) {
(TransmissionID::Solution(solution_id), Transmission::Solution(solution)) => {
// Check if the solution is still valid.
if let Err(e) = self.ledger.check_solution_basic(solution_id, solution).await {
trace!("Proposing - Skipping solution '{}' - {e}", fmt_id(solution_id));
continue 'inner;
}
}
(TransmissionID::Transaction(transaction_id), Transmission::Transaction(transaction)) => {
// Check if the transaction is still valid.
if let Err(e) = self.ledger.check_transaction_basic(transaction_id, transaction).await {
trace!("Proposing - Skipping transaction '{}' - {e}", fmt_id(transaction_id));
continue 'inner;
}
// Increment the number of transactions.
num_transactions += 1;
}
// Note: We explicitly forbid including ratifications,
// as the protocol currently does not support ratifications.
(TransmissionID::Ratification, Transmission::Ratification) => continue,
// All other combinations are clearly invalid.
_ => continue 'inner,
}
// Insert the transmission into the map.
transmissions.insert(id, transmission);
num_transmissions_included_for_worker += 1;
}
}
}
// If there are no unconfirmed transmissions to propose, return early.
if transmissions.is_empty() {
debug!("Primary is safely skipping a batch proposal {}", "(no unconfirmed transmissions)".dimmed());
return Ok(());
}
// If there are no unconfirmed transactions to propose, return early.
if num_transactions == 0 {
debug!("Primary is safely skipping a batch proposal {}", "(no unconfirmed transactions)".dimmed());
return Ok(());
}
// Ditto if the batch had already been proposed.
ensure!(round > 0, "Round 0 cannot have transaction batches");
if *lock_guard == round {
warn!("Primary is safely skipping a batch proposal - round {round} already proposed");
return Ok(());
}
*lock_guard = round;
/* Proceeding to sign & propose the batch. */
info!("Proposing a batch with {} transmissions for round {round}...", transmissions.len());
// Retrieve the private key.
let private_key = *self.gateway.account().private_key();
// Retrieve the committee ID.
let committee_id = committee_lookback.id();
// Prepare the transmission IDs.
let transmission_ids = transmissions.keys().copied().collect();
// Prepare the previous batch certificate IDs.
let previous_certificate_ids = previous_certificates.into_iter().map(|c| c.id()).collect();
// Sign the batch header.
let batch_header = spawn_blocking!(BatchHeader::new(
&private_key,
round,
now(),
committee_id,
transmission_ids,
previous_certificate_ids,
&mut rand::thread_rng()
))?;
// Construct the proposal.
let proposal = Proposal::new(committee_lookback, batch_header.clone(), transmissions)?;
// Broadcast the batch to all validators for signing.
self.gateway.broadcast(Event::BatchPropose(batch_header.into()));
// Set the proposed batch.
*self.proposed_batch.write() = Some(proposal);
Ok(())
}
/// Processes a batch propose from a peer.
///
/// This method performs the following steps:
/// 1. Verify the batch.
/// 2. Sign the batch.
/// 3. Broadcast the signature back to the validator.
///
/// If our primary is ahead of the peer, we will not sign the batch.
/// If our primary is behind the peer, but within GC range, we will sync up to the peer's round, and then sign the batch.
async fn process_batch_propose_from_peer(&self, peer_ip: SocketAddr, batch_propose: BatchPropose<N>) -> Result<()> {
let BatchPropose { round: batch_round, batch_header } = batch_propose;
// Deserialize the batch header.
let batch_header = spawn_blocking!(batch_header.deserialize_blocking())?;
// Ensure the round matches in the batch header.
if batch_round != batch_header.round() {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - proposed round {batch_round}, but sent batch for round {}", batch_header.round());
}
// Retrieve the batch author.
let batch_author = batch_header.author();
// Ensure the batch proposal is from the validator.
match self.gateway.resolver().get_address(peer_ip) {
// If the peer is a validator, then ensure the batch proposal is from the validator.
Some(address) => {
if address != batch_author {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - proposed batch from a different validator ({batch_author})");
}
}
None => bail!("Batch proposal from a disconnected validator"),
}
// Ensure the batch author is a current committee member.
if !self.gateway.is_authorized_validator_address(batch_author) {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - proposed batch from a non-committee member ({batch_author})");
}
// Ensure the batch proposal is not from the current primary.
if self.gateway.account().address() == batch_author {
bail!("Invalid peer - proposed batch from myself ({batch_author})");
}
// Ensure that the batch proposal's committee ID matches the expected committee ID.
let expected_committee_id = self.ledger.get_committee_lookback_for_round(batch_round)?.id();
if expected_committee_id != batch_header.committee_id() {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!(
"Malicious peer - proposed batch has a different committee ID ({expected_committee_id} != {})",
batch_header.committee_id()
);
}
// Retrieve the cached round and batch ID for this validator.
if let Some((signed_round, signed_batch_id, signature)) =
self.signed_proposals.read().get(&batch_author).copied()
{
// If the signed round is ahead of the peer's batch round, then the validator is malicious.
if signed_round > batch_header.round() {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - proposed a batch for a previous round ({})", batch_header.round());
}
// If the round matches and the batch ID differs, then the validator is malicious.
if signed_round == batch_header.round() && signed_batch_id != batch_header.batch_id() {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - proposed another batch for the same round ({signed_round})");
}
// If the round and batch ID matches, then skip signing the batch a second time.
// Instead, rebroadcast the cached signature to the peer.
if signed_round == batch_header.round() && signed_batch_id == batch_header.batch_id() {
let gateway = self.gateway.clone();
tokio::spawn(async move {
debug!("Resending a signature for a batch in round {batch_round} from '{peer_ip}'");
let event = Event::BatchSignature(BatchSignature::new(batch_header.batch_id(), signature));
// Resend the batch signature to the peer.
if gateway.send(peer_ip, event).await.is_none() {
warn!("Failed to resend a signature for a batch in round {batch_round} to '{peer_ip}'");
}
});
// Return early.
return Ok(());
}
}
// If the peer is ahead, use the batch header to sync up to the peer.
let mut transmissions = self.sync_with_batch_header_from_peer(peer_ip, &batch_header).await?;
// Check that the transmission ids match and are not fee transactions.
if let Err(err) = cfg_iter_mut!(transmissions).try_for_each(|(transmission_id, transmission)| {
// If the transmission is not well-formed, then return early.
self.ledger.ensure_transmission_is_well_formed(*transmission_id, transmission)
}) {
debug!("Batch propose from '{peer_ip}' contains an invalid transmission - {err}",);
return Ok(());
}
// Ensure the batch is for the current round.
// This method must be called after fetching previous certificates (above),
// and prior to checking the batch header (below).
if let Err(e) = self.ensure_is_signing_round(batch_round) {
// If the primary is not signing for the peer's round, then return early.
debug!("{e} from '{peer_ip}'");
return Ok(());
}
// Ensure the batch header from the peer is valid.
let (storage, header) = (self.storage.clone(), batch_header.clone());
let missing_transmissions = spawn_blocking!(storage.check_batch_header(&header, transmissions))?;
// Inserts the missing transmissions into the workers.
self.insert_missing_transmissions_into_workers(peer_ip, missing_transmissions.into_iter())?;
/* Proceeding to sign the batch. */
// Retrieve the batch ID.
let batch_id = batch_header.batch_id();
// Sign the batch ID.
let account = self.gateway.account().clone();
let signature = spawn_blocking!(account.sign(&[batch_id], &mut rand::thread_rng()))?;
// Ensure the proposal has not already been signed.
//
// Note: Due to the need to sync the batch header with the peer, it is possible
// for the primary to receive the same 'BatchPropose' event again, whereby only
// one instance of this handler should sign the batch. This check guarantees this.
match self.signed_proposals.write().entry(batch_author) {
std::collections::hash_map::Entry::Occupied(mut entry) => {
// If the validator has already signed a batch for this round, then return early,
// since, if the peer still has not received the signature, they will request it again,
// and the logic at the start of this function will resend the (now cached) signature
// to the peer if asked to sign this batch proposal again.
if entry.get().0 == batch_round {
return Ok(());
}
// Otherwise, cache the round, batch ID, and signature for this validator.
entry.insert((batch_round, batch_id, signature));
}
// If the validator has not signed a batch before, then continue.
std::collections::hash_map::Entry::Vacant(entry) => {
// Cache the round, batch ID, and signature for this validator.
entry.insert((batch_round, batch_id, signature));
}
};
// Broadcast the signature back to the validator.
let self_ = self.clone();
tokio::spawn(async move {
let event = Event::BatchSignature(BatchSignature::new(batch_id, signature));
// Send the batch signature to the peer.
if self_.gateway.send(peer_ip, event).await.is_some() {
debug!("Signed a batch for round {batch_round} from '{peer_ip}'");
}
});
Ok(())
}
/// Processes a batch signature from a peer.
///
/// This method performs the following steps:
/// 1. Ensure the proposed batch has not expired.
/// 2. Verify the signature, ensuring it corresponds to the proposed batch.
/// 3. Store the signature.
/// 4. Certify the batch if enough signatures have been received.
/// 5. Broadcast the batch certificate to all validators.
async fn process_batch_signature_from_peer(
&self,
peer_ip: SocketAddr,
batch_signature: BatchSignature<N>,
) -> Result<()> {
// Ensure the proposed batch has not expired, and clear the proposed batch if it has expired.
self.check_proposed_batch_for_expiration().await?;
// Retrieve the signature and timestamp.
let BatchSignature { batch_id, signature } = batch_signature;
// Retrieve the signer.
let signer = signature.to_address();
// Ensure the batch signature is signed by the validator.
if self.gateway.resolver().get_address(peer_ip).map_or(true, |address| address != signer) {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - batch signature is from a different validator ({signer})");
}
// Ensure the batch signature is not from the current primary.
if self.gateway.account().address() == signer {
bail!("Invalid peer - received a batch signature from myself ({signer})");
}
let self_ = self.clone();
let Some(proposal) = spawn_blocking!({
// Acquire the write lock.
let mut proposed_batch = self_.proposed_batch.write();
// Add the signature to the batch, and determine if the batch is ready to be certified.
match proposed_batch.as_mut() {
Some(proposal) => {
// Ensure the batch ID matches the currently proposed batch ID.
if proposal.batch_id() != batch_id {
match self_.storage.contains_batch(batch_id) {
true => bail!("This batch was already certified"),
false => bail!(
"Unknown batch ID '{batch_id}', expected '{}' for round {}",
proposal.batch_id(),
proposal.round()
),
}
}
// Retrieve the committee lookback for the round.
let committee_lookback = self_.ledger.get_committee_lookback_for_round(proposal.round())?;
// Retrieve the address of the validator.
let Some(signer) = self_.gateway.resolver().get_address(peer_ip) else {
bail!("Signature is from a disconnected validator");
};
// Add the signature to the batch.
proposal.add_signature(signer, signature, &committee_lookback)?;
info!("Received a batch signature for round {} from '{peer_ip}'", proposal.round());
// Check if the batch is ready to be certified.
if !proposal.is_quorum_threshold_reached(&committee_lookback) {
// If the batch is not ready to be certified, return early.
return Ok(None);
}
}
// There is no proposed batch, so return early.
None => return Ok(None),
};
// Retrieve the batch proposal, clearing the proposed batch.
match proposed_batch.take() {
Some(proposal) => Ok(Some(proposal)),
None => Ok(None),
}
})?
else {
return Ok(());
};
/* Proceeding to certify the batch. */
info!("Quorum threshold reached - Preparing to certify our batch for round {}...", proposal.round());
// Retrieve the committee lookback for the round.
let committee_lookback = self.ledger.get_committee_lookback_for_round(proposal.round())?;
// Store the certified batch and broadcast it to all validators.
// If there was an error storing the certificate, reinsert the transmissions back into the ready queue.
if let Err(e) = self.store_and_broadcast_certificate(&proposal, &committee_lookback).await {
// Reinsert the transmissions back into the ready queue for the next proposal.
self.reinsert_transmissions_into_workers(proposal)?;
return Err(e);
}
#[cfg(feature = "metrics")]
metrics::increment_gauge(metrics::bft::CERTIFIED_BATCHES, 1.0);
Ok(())
}
/// Processes a batch certificate from a peer.
///
/// This method performs the following steps:
/// 1. Stores the given batch certificate, after ensuring it is valid.
/// 2. If there are enough certificates to reach quorum threshold for the current round,
/// then proceed to advance to the next round.
async fn process_batch_certificate_from_peer(
&self,
peer_ip: SocketAddr,
certificate: BatchCertificate<N>,
) -> Result<()> {
// Ensure storage does not already contain the certificate.
if self.storage.contains_certificate(certificate.id()) {
return Ok(());
}
// Retrieve the batch certificate author.
let author = certificate.author();
// Retrieve the batch certificate round.
let certificate_round = certificate.round();
// Retrieve the batch certificate committee ID.
let committee_id = certificate.committee_id();
// Ensure the batch certificate is from an authorized validator.
if !self.gateway.is_authorized_validator_ip(peer_ip) {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Malicious peer - Received a batch certificate from an unauthorized validator IP ({peer_ip})");
}
// Ensure the batch certificate is not from the current primary.
if self.gateway.account().address() == author {
bail!("Received a batch certificate for myself ({author})");
}
// Store the certificate, after ensuring it is valid.
self.sync_with_certificate_from_peer(peer_ip, certificate).await?;
// If there are enough certificates to reach quorum threshold for the certificate round,
// then proceed to advance to the next round.
// Retrieve the committee lookback.
let committee_lookback = self.ledger.get_committee_lookback_for_round(certificate_round)?;
// Retrieve the certificates.
let certificates = self.storage.get_certificates_for_round(certificate_round);
// Construct a set over the authors.
let authors = certificates.iter().map(BatchCertificate::author).collect();
// Check if the certificates have reached the quorum threshold.
let is_quorum = committee_lookback.is_quorum_threshold_reached(&authors);
// Ensure that the batch certificate's committee ID matches the expected committee ID.
let expected_committee_id = committee_lookback.id();
if expected_committee_id != committee_id {
// Proceed to disconnect the validator.
self.gateway.disconnect(peer_ip);
bail!("Batch certificate has a different committee ID ({expected_committee_id} != {committee_id})");
}
// Determine if we are currently proposing a round that is relevant.
// Note: This is important, because while our peers have advanced,
// they may not be proposing yet, and thus still able to sign our proposed batch.
let should_advance = match &*self.proposed_batch.read() {
// We advance if the proposal round is less than the current round that was just certified.
Some(proposal) => proposal.round() < certificate_round,
// If there's no proposal, we consider advancing.
None => true,
};
// Retrieve the current round.
let current_round = self.current_round();
// Determine whether to advance to the next round.
if is_quorum && should_advance && certificate_round >= current_round {
// If we have reached the quorum threshold and the round should advance, then proceed to the next round.
self.try_increment_to_the_next_round(current_round + 1).await?;
}
Ok(())
}
}
impl<N: Network> Primary<N> {
/// Starts the primary handlers.
fn start_handlers(&self, primary_receiver: PrimaryReceiver<N>) {
let PrimaryReceiver {
mut rx_batch_propose,
mut rx_batch_signature,
mut rx_batch_certified,
mut rx_primary_ping,
mut rx_unconfirmed_solution,
mut rx_unconfirmed_transaction,
} = primary_receiver;
// Start the primary ping.
if self.sync.is_gateway_mode() {
let self_ = self.clone();
self.spawn(async move {
loop {
// Sleep briefly.
tokio::time::sleep(Duration::from_millis(PRIMARY_PING_IN_MS)).await;
// Retrieve the block locators.
let self__ = self_.clone();
let block_locators = match spawn_blocking!(self__.sync.get_block_locators()) {
Ok(block_locators) => block_locators,
Err(e) => {
warn!("Failed to retrieve block locators - {e}");
continue;
}
};
// Retrieve the latest certificate of the primary.
let primary_certificate = {
// Retrieve the primary address.
let primary_address = self_.gateway.account().address();
// Iterate backwards from the latest round to find the primary certificate.
let mut certificate = None;
let mut current_round = self_.current_round();
while certificate.is_none() {
// If the current round is 0, then break the while loop.
if current_round == 0 {
break;
}
// Retrieve the certificates.
let certificates = self_.storage.get_certificates_for_round(current_round);
// Retrieve the primary certificate.
certificate =
certificates.into_iter().find(|certificate| certificate.author() == primary_address);
// If the primary certificate was not found, decrement the round.
if certificate.is_none() {
current_round = current_round.saturating_sub(1);
}
}
// Determine if the primary certificate was found.
match certificate {
Some(certificate) => certificate,
// Skip this iteration of the loop (do not send a primary ping).
None => continue,
}
};
// Construct the primary ping.
let primary_ping = PrimaryPing::from((<Event<N>>::VERSION, block_locators, primary_certificate));
// Broadcast the event.
self_.gateway.broadcast(Event::PrimaryPing(primary_ping));
}
});
}
// Start the primary ping handler.
let self_ = self.clone();
self.spawn(async move {
while let Some((peer_ip, primary_certificate)) = rx_primary_ping.recv().await {
// If the primary is not synced, then do not process the primary ping.
if !self_.sync.is_synced() {
trace!("Skipping a primary ping from '{peer_ip}' {}", "(node is syncing)".dimmed());
continue;
}
// Spawn a task to process the primary certificate.
{
let self_ = self_.clone();
tokio::spawn(async move {
// Deserialize the primary certificate in the primary ping.
let Ok(primary_certificate) = spawn_blocking!(primary_certificate.deserialize_blocking())
else {
warn!("Failed to deserialize primary certificate in 'PrimaryPing' from '{peer_ip}'");
return;
};
// Process the primary certificate.
if let Err(e) = self_.process_batch_certificate_from_peer(peer_ip, primary_certificate).await {
warn!("Cannot process a primary certificate in a 'PrimaryPing' from '{peer_ip}' - {e}");
}
});
}
}
});
// Start the worker ping(s).
if self.sync.is_gateway_mode() {
let self_ = self.clone();
self.spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(WORKER_PING_IN_MS)).await;
// If the primary is not synced, then do not broadcast the worker ping(s).
if !self_.sync.is_synced() {
trace!("Skipping worker ping(s) {}", "(node is syncing)".dimmed());
continue;
}
// Broadcast the worker ping(s).
for worker in self_.workers.iter() {
worker.broadcast_ping();
}
}
});
}
// Start the batch proposer.
let self_ = self.clone();
self.spawn(async move {
loop {
// Sleep briefly, but longer than if there were no batch.
tokio::time::sleep(Duration::from_millis(MAX_BATCH_DELAY_IN_MS)).await;
// If the primary is not synced, then do not propose a batch.
if !self_.sync.is_synced() {
debug!("Skipping batch proposal {}", "(node is syncing)".dimmed());
continue;
}
// A best-effort attempt to skip the scheduled batch proposal if
// round progression already triggered one.
if self_.propose_lock.try_lock().is_err() {
trace!("Skipping batch proposal {}", "(node is already proposing)".dimmed());
continue;
};
// If there is no proposed batch, attempt to propose a batch.
// Note: Do NOT spawn a task around this function call. Proposing a batch is a critical path,
// and only one batch needs be proposed at a time.
if let Err(e) = self_.propose_batch().await {
warn!("Cannot propose a batch - {e}");
}
}
});
// Process the proposed batch.
let self_ = self.clone();
self.spawn(async move {
while let Some((peer_ip, batch_propose)) = rx_batch_propose.recv().await {
// If the primary is not synced, then do not sign the batch.
if !self_.sync.is_synced() {
trace!("Skipping a batch proposal from '{peer_ip}' {}", "(node is syncing)".dimmed());
continue;
}
// Spawn a task to process the proposed batch.
let self_ = self_.clone();