Skip to main content

snarkos_node_bft/
primary.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16mod proposal_task;
17pub use proposal_task::ProposalTask;
18
19use crate::{
20    Gateway,
21    MAX_BATCH_DELAY,
22    MAX_LEADER_CERTIFICATE_DELAY,
23    MAX_WORKERS,
24    MIN_BATCH_DELAY,
25    PRIMARY_PING_INTERVAL,
26    Sync,
27    Transport,
28    WORKER_PING_INTERVAL,
29    Worker,
30    events::{BatchPropose, BatchSignature, Event},
31    helpers::{
32        PrimaryReceiver,
33        PrimarySender,
34        Proposal,
35        ProposalCache,
36        SignedProposals,
37        Storage,
38        assign_to_worker,
39        assign_to_workers,
40        fmt_id,
41        init_sync_channels,
42        init_worker_channels,
43        now,
44    },
45    spawn_blocking,
46    sync::SyncCallback,
47};
48
49use snarkos_account::Account;
50use snarkos_node_bft_events::PrimaryPing;
51use snarkos_node_bft_ledger_service::LedgerService;
52#[cfg(test)]
53use snarkos_node_network::ConnectionMode;
54use snarkos_node_network::PeerPoolHandling;
55use snarkos_node_sync::{BlockSync, DUMMY_SELF_IP, Ping};
56use snarkos_utilities::{CallbackHandle, NodeDataDir};
57
58use snarkvm::{
59    console::{
60        prelude::*,
61        types::{Address, Field},
62    },
63    ledger::{
64        block::Transaction,
65        narwhal::{BatchCertificate, BatchHeader, Data, Transmission, TransmissionID},
66        puzzle::{Solution, SolutionID},
67    },
68    prelude::{Signature, committee::Committee},
69    utilities::flatten_error,
70};
71
72use anyhow::Context;
73use colored::Colorize;
74use futures::stream::{FuturesUnordered, StreamExt};
75use indexmap::{IndexMap, IndexSet};
76#[cfg(feature = "locktick")]
77use locktick::{
78    parking_lot::{Mutex, RwLock},
79    tokio::RwLock as TRwLock,
80};
81#[cfg(not(feature = "locktick"))]
82use parking_lot::{Mutex, RwLock};
83#[cfg(not(feature = "serial"))]
84use rayon::prelude::*;
85use std::{
86    collections::{HashMap, HashSet},
87    future::Future,
88    net::SocketAddr,
89    pin::Pin,
90    sync::{Arc, OnceLock},
91    time::Instant,
92};
93#[cfg(not(feature = "locktick"))]
94use tokio::sync::RwLock as TRwLock;
95use tokio::{sync::Notify, task::JoinHandle};
96
97/// The state of the primary's batch proposal.
98#[derive(Debug, PartialEq, Eq)]
99pub enum ProposedBatchState<N: Network> {
100    /// No batch is currently being proposed.
101    None,
102    /// A batch is being proposed and awaiting signatures.
103    Certifying(Box<Proposal<N>>),
104    /// A batch has reached quorum and is being inserted into storage.
105    /// Carries the batch ID so late-arriving signatures can be recognized and silently dropped.
106    Certified(Field<N>),
107}
108
109impl<N: Network> Default for ProposedBatchState<N> {
110    fn default() -> Self {
111        Self::None
112    }
113}
114
115impl<N: Network> ProposedBatchState<N> {
116    /// Returns `true` if the primary has no active batch proposal.
117    pub fn is_none(&self) -> bool {
118        matches!(self, Self::None)
119    }
120
121    /// Returns `true` if a batch is currently being proposed (awaiting signatures).
122    pub fn is_proposed(&self) -> bool {
123        matches!(self, Self::Certifying(_))
124    }
125
126    /// Returns a reference to the in-progress proposal, or `None` if not in the `Certifying` state.
127    pub fn as_proposal(&self) -> Option<&Proposal<N>> {
128        match self {
129            Self::Certifying(p) => Some(p.as_ref()),
130            _ => None,
131        }
132    }
133}
134
135/// A helper type to keep track of the state of the primary's batch proposal.
136pub type ProposedBatch<N> = RwLock<ProposedBatchState<N>>;
137
138/// This callback trait allows listening to changes in the Primary, such as round advancement.
139/// This is implemented by [`BFT`].
140#[async_trait::async_trait]
141pub trait PrimaryCallback<N: Network>: Send + std::marker::Sync {
142    /// Asks the callback to if we can move to the next round.
143    ///
144    /// # Arguments
145    /// * `current_round` - the round the Primary is in (to avoid race conditions)
146    ///
147    /// # Returns
148    /// `true` if we moved to the next round.
149    fn try_advance_to_next_round(&self, current_round: u64) -> bool;
150
151    /// Add a certificated that was created by the primary or received from a peer.
152    async fn add_new_certificate(&self, certificate: BatchCertificate<N>) -> Result<()>;
153}
154
155/// The primary logic of a node.
156/// AleoBFT adopts a primary-worker architecture as described in the Narwhal and Tusk paper (Section 4.2).
157#[derive(Clone)]
158pub struct Primary<N: Network> {
159    /// The sync module enables fetching data from other validators.
160    sync: Sync<N>,
161    /// The gateway allows talking to other nodes in the validator set.
162    gateway: Gateway<N>,
163    /// The storage.
164    storage: Storage<N>,
165    /// The ledger service.
166    ledger: Arc<dyn LedgerService<N>>,
167    /// The workers.
168    workers: Arc<OnceLock<Vec<Worker<N>>>>,
169
170    /// The primary callback (used by [`BFT`]).
171    primary_callback: Arc<CallbackHandle<Arc<dyn PrimaryCallback<N>>>>,
172
173    /// The batch proposal, if the primary is currently proposing a batch.
174    proposed_batch: Arc<ProposedBatch<N>>,
175
176    /// The instant at which the current batch was proposed (used to measure certification latency).
177    /// (used for higher precision in the metrics compared to the batch timestamp)
178    #[cfg(feature = "metrics")]
179    batch_propose_start: Arc<Mutex<Option<Instant>>>,
180
181    /// Holds the most recent round and timestamp that the primary proposed a batch for.
182    /// TODO(kaimast): avoiding using an async lock here, so this can be merged with the `proposed_batch`,
183    /// to have a unified `primary_state` field.
184    latest_proposal_timestamp: Arc<TRwLock<Option<(u64, i64)>>>,
185
186    /// The recently-signed batch proposals.
187    signed_proposals: Arc<RwLock<SignedProposals<N>>>,
188
189    /// The handles for all background tasks spawned by this primary.
190    handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
191
192    /// The node configuration directory.
193    node_data_dir: NodeDataDir,
194
195    /// Manages proposal readiness state and drives the batch proposal loop.
196    proposal_task: ProposalTask<N>,
197
198    /// Used to wake up a the dedicated round-increment task, if we may be able to advance to the next round.
199    /// This is used, so the timeout for round advancement is reset on every round increment.
200    round_increment_notify: Arc<Notify>,
201}
202
203impl<N: Network> Primary<N> {
204    /// The maximum number of unconfirmed transmissions to send to the primary.
205    pub const MAX_TRANSMISSIONS_TOLERANCE: usize = BatchHeader::<N>::MAX_TRANSMISSIONS_PER_BATCH * 2;
206
207    /// Initializes a new primary instance.
208    #[allow(clippy::too_many_arguments)]
209    pub fn new(
210        account: Account<N>,
211        storage: Storage<N>,
212        ledger: Arc<dyn LedgerService<N>>,
213        block_sync: Arc<BlockSync<N>>,
214        ip: Option<SocketAddr>,
215        trusted_validators: &[SocketAddr],
216        trusted_peers_only: bool,
217        node_data_dir: NodeDataDir,
218        dev: Option<u16>,
219    ) -> Result<Self> {
220        // Initialize the gateway.
221        let gateway = Gateway::new(
222            account,
223            storage.clone(),
224            ledger.clone(),
225            ip,
226            trusted_validators,
227            trusted_peers_only,
228            node_data_dir.clone(),
229            dev,
230        )?;
231        // Initialize the sync module.
232        let sync = Sync::new(gateway.clone(), storage.clone(), ledger.clone(), block_sync);
233
234        // Initialize the primary instance.
235        Ok(Self {
236            sync,
237            gateway,
238            storage,
239            ledger,
240            node_data_dir,
241            workers: Default::default(),
242            primary_callback: Default::default(),
243            proposed_batch: Default::default(),
244            #[cfg(feature = "metrics")]
245            batch_propose_start: Default::default(),
246            latest_proposal_timestamp: Default::default(),
247            signed_proposals: Default::default(),
248            handles: Default::default(),
249            proposal_task: Default::default(),
250            round_increment_notify: Default::default(),
251        })
252    }
253
254    /// Load the proposal cache file and update the Primary state with the stored data.
255    async fn load_proposal_cache(&self) -> Result<()> {
256        // Fetch the signed proposals from the file system if it exists.
257        match ProposalCache::<N>::exists(&self.node_data_dir) {
258            // If the proposal cache exists, then process the proposal cache.
259            true => match ProposalCache::<N>::load(self.gateway.account().address(), &self.node_data_dir) {
260                Ok(proposal_cache) => {
261                    // Extract the proposal and signed proposals.
262                    let (latest_certificate_round, proposed_batch, signed_proposals, pending_certificates) =
263                        proposal_cache.into();
264
265                    *self.latest_proposal_timestamp.write().await = Some((latest_certificate_round, now()));
266                    *self.proposed_batch.write() = match proposed_batch {
267                        Some(p) => ProposedBatchState::Certifying(Box::new(p)),
268                        None => ProposedBatchState::None,
269                    };
270                    *self.signed_proposals.write() = signed_proposals;
271
272                    // Update the storage with the pending certificates.
273                    for certificate in pending_certificates {
274                        let batch_id = certificate.batch_id();
275                        // We use a dummy IP because the node should not need to request from any peers.
276                        // The storage should have stored all the transmissions. If not, we simply
277                        // skip the certificate.
278                        if let Err(err) = self.sync_with_certificate_from_peer::<true>(DUMMY_SELF_IP, certificate).await
279                        {
280                            let err = err.context(format!(
281                                "Failed to load stored certificate {} from proposal cache",
282                                fmt_id(batch_id)
283                            ));
284                            warn!("{}", &flatten_error(err));
285                        }
286                    }
287                    Ok(())
288                }
289                Err(err) => Err(err.context("Failed to read the signed proposals from the file system")),
290            },
291            // If the proposal cache does not exist, then return early.
292            false => Ok(()),
293        }
294    }
295
296    /// Run the primary instance.
297    pub async fn run(
298        &self,
299        ping: Option<Arc<Ping<N>>>,
300        primary_callback: Option<Arc<dyn PrimaryCallback<N>>>,
301        sync_callback: Option<Arc<dyn SyncCallback<N>>>,
302        primary_sender: PrimarySender<N>,
303        primary_receiver: PrimaryReceiver<N>,
304    ) -> Result<()> {
305        info!("Starting the primary instance of the memory pool...");
306
307        // Set the BFT sender.
308        if let Some(callback) = primary_callback {
309            self.primary_callback.set(callback)?;
310        }
311
312        // Construct a map of the worker senders.
313        let mut worker_senders = IndexMap::new();
314        // Construct a map for the workers.
315        let mut workers = Vec::new();
316        // Initialize the workers.
317        for id in 0..MAX_WORKERS {
318            // Construct the worker channels.
319            let (tx_worker, rx_worker) = init_worker_channels();
320            // Construct the worker instance.
321            let worker = Worker::new(
322                id,
323                Arc::new(self.gateway.clone()),
324                self.storage.clone(),
325                self.ledger.clone(),
326                self.proposed_batch.clone(),
327            )?;
328            // Run the worker instance.
329            worker.run(rx_worker);
330            // Add the worker to the list of workers.
331            workers.push(worker);
332            // Add the worker sender to the map.
333            worker_senders.insert(id, tx_worker);
334        }
335        // Set the workers.
336        if self.workers.set(workers).is_err() {
337            bail!("Workers already set. `Primary::run` cannot be called more than once.");
338        }
339
340        // First, initialize the sync channels.
341        let (sync_sender, sync_receiver) = init_sync_channels();
342        // Next, initialize the sync module and sync the storage from ledger.
343        self.sync.initialize(sync_callback)?;
344        // Next, load and process the proposal cache before running the sync module.
345        self.load_proposal_cache().await?;
346        // Next, run the sync module.
347        self.sync.run(ping, sync_receiver).await?;
348        // Next, initialize the gateway.
349        self.gateway.run(primary_sender, worker_senders, Some(sync_sender)).await;
350        // Lastly, start the primary handlers.
351        // Note: This ensures the primary does not start communicating before syncing is complete.
352        self.start_handlers(primary_receiver);
353
354        Ok(())
355    }
356
357    /// Returns the current round.
358    pub fn current_round(&self) -> u64 {
359        self.storage.current_round()
360    }
361
362    /// Returns `true` if the primary is synced.
363    pub fn is_synced(&self) -> bool {
364        self.sync.is_synced()
365    }
366
367    /// Returns the gateway.
368    pub const fn gateway(&self) -> &Gateway<N> {
369        &self.gateway
370    }
371
372    /// Returns the storage.
373    pub const fn storage(&self) -> &Storage<N> {
374        &self.storage
375    }
376
377    /// Returns the ledger.
378    pub const fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
379        &self.ledger
380    }
381
382    /// Returns the number of workers.
383    pub fn num_workers(&self) -> u8 {
384        u8::try_from(self.workers.get().expect("Primary is not running yet").len()).expect("Too many workers")
385    }
386
387    /// Returns the workers.
388    pub fn workers(&self) -> &[Worker<N>] {
389        self.workers.get().expect("Primary is not running yet")
390    }
391}
392
393impl<N: Network> Primary<N> {
394    /// Returns the number of unconfirmed transmissions.
395    pub fn num_unconfirmed_transmissions(&self) -> usize {
396        self.workers().iter().map(|worker| worker.num_transmissions()).sum()
397    }
398
399    /// Returns the number of unconfirmed ratifications.
400    pub fn num_unconfirmed_ratifications(&self) -> usize {
401        self.workers().iter().map(|worker| worker.num_ratifications()).sum()
402    }
403
404    /// Returns the number of unconfirmed solutions.
405    pub fn num_unconfirmed_solutions(&self) -> usize {
406        self.workers().iter().map(|worker| worker.num_solutions()).sum()
407    }
408
409    /// Returns the number of unconfirmed transactions.
410    pub fn num_unconfirmed_transactions(&self) -> usize {
411        self.workers().iter().map(|worker| worker.num_transactions()).sum()
412    }
413}
414
415impl<N: Network> Primary<N> {
416    /// Returns the worker transmission IDs.
417    pub fn worker_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
418        self.workers().iter().flat_map(|worker| worker.transmission_ids())
419    }
420
421    /// Returns the worker transmissions.
422    pub fn worker_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
423        self.workers().iter().flat_map(|worker| worker.transmissions())
424    }
425
426    /// Returns the worker solutions.
427    pub fn worker_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
428        self.workers().iter().flat_map(|worker| worker.solutions())
429    }
430
431    /// Returns the worker transactions.
432    pub fn worker_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
433        self.workers().iter().flat_map(|worker| worker.transactions())
434    }
435}
436
437impl<N: Network> Primary<N> {
438    /// Clears the worker solutions.
439    pub fn clear_worker_solutions(&self) {
440        self.workers().iter().for_each(Worker::clear_solutions);
441    }
442}
443
444#[async_trait::async_trait]
445impl<N: Network> proposal_task::BatchPropose for Primary<N> {
446    fn current_round(&self) -> u64 {
447        Primary::current_round(self)
448    }
449
450    fn wait_for_synced_if_syncing(&self) -> Option<futures::future::BoxFuture<'_, ()>> {
451        self.sync.wait_for_synced_if_syncing()
452    }
453
454    fn is_synced(&self) -> bool {
455        self.sync.is_synced()
456    }
457
458    /// Proposes the batch for the current round.
459    ///
460    /// This method performs the following steps:
461    /// 1. Drain the workers.
462    /// 2. Sign the batch.
463    /// 3. Set the batch proposal in the primary.
464    /// 4. Broadcast the batch header to all validators for signing.
465    ///
466    /// # Returns
467    /// - `Ok(true)` if the batch was proposed.
468    /// - `Ok(false)` if the batch was not proposed for a benign reason, e.g., the timestamp is too soon after the previous certificate.
469    /// - `Err(err)` if an unexpected error occured.
470    async fn propose_batch(&self) -> Result<bool> {
471        // Ensure there are not concurrent executions of this function.
472        //
473        // Note, in the current design, this function is only invoked from the batch proposal task, and it is technically
474        // not possible for there to be concurrent invocations of the function, but we keep this lock for now.
475        let mut lock_guard = self.latest_proposal_timestamp.write().await;
476
477        // Check if the proposed batch has expired, and clear it if it has expired.
478        if let Err(err) = self
479            .check_proposed_batch_for_expiration()
480            .with_context(|| "Failed to check the proposed batch for expiration")
481        {
482            warn!("{}", flatten_error(&err));
483            return Ok(false);
484        }
485
486        // Retrieve the current round.
487        let round = self.current_round();
488        // Compute the previous round.
489        let previous_round = round.saturating_sub(1);
490
491        // If the current round is 0, return early.
492        // This can actually never happen, because of the invariant that the current round is never 0
493        // (see [`StorageInner::current_round`]).
494        ensure!(round > 0, "Round 0 cannot have transaction batches");
495
496        // If the current storage round is below the latest proposal round, then return early.
497        if let Some((latest_round, _)) = &*lock_guard
498            && round < *latest_round
499        {
500            warn!("Cannot propose a batch for round {round} - the latest proposal cache round is {latest_round}");
501            return Ok(false);
502        }
503
504        // If there is a batch being proposed or certified already, handle accordingly.
505        match &*self.proposed_batch.read() {
506            ProposedBatchState::Certifying(proposal) => {
507                // Ensure that the storage is caught up to the proposal before proceeding to rebroadcast this.
508                if round < proposal.round()
509                    || proposal
510                        .batch_header()
511                        .previous_certificate_ids()
512                        .iter()
513                        .any(|id| !self.storage.contains_certificate(*id))
514                {
515                    warn!(
516                        "Cannot propose a batch for round {} - the current storage (round {round}) is not caught up to the proposed batch.",
517                        proposal.round(),
518                    );
519                    return Ok(false);
520                }
521                // Construct the event.
522                // TODO(ljedrz): the BatchHeader should be serialized only once in advance before being sent to non-signers.
523                let event = Event::BatchPropose(proposal.batch_header().clone().into());
524                // Iterate through the non-signers.
525                for address in proposal.nonsigners(&self.ledger.get_committee_lookback_for_round(proposal.round())?) {
526                    // Resolve the address to the peer IP.
527                    match self.gateway.resolver().read().get_peer_ip_for_address(address) {
528                        // Resend the batch proposal to the validator for signing.
529                        Some(peer_ip) => {
530                            let (gateway, event_, round) = (self.gateway.clone(), event.clone(), proposal.round());
531                            tokio::spawn(async move {
532                                debug!("Resending batch proposal for round {round} to peer '{peer_ip}'");
533                                // Resend the batch proposal to the peer.
534                                if gateway.send(peer_ip, event_).await.is_none() {
535                                    warn!("Failed to resend batch proposal for round {round} to peer '{peer_ip}'");
536                                }
537                            });
538                        }
539                        None => continue,
540                    }
541                }
542                debug!("Proposed batch for round {} is still valid", proposal.round());
543                return Ok(false);
544            }
545            // A batch is being certified; wait until it completes before proposing another.
546            ProposedBatchState::Certified(_) => {
547                debug!("Cannot propose a batch for round {round} - a batch is currently being certified");
548                return Ok(false);
549            }
550            ProposedBatchState::None => {
551                // No batch in progress, so it is save to propose a new one.
552            }
553        }
554
555        #[cfg(feature = "metrics")]
556        metrics::gauge(metrics::bft::PROPOSAL_ROUND, round as f64);
557
558        // Ensure that the primary does not create a new proposal too quickly.
559        if let Some((_, latest_timestamp)) = &*lock_guard
560            && !self.check_own_proposal_timestamp(previous_round, *latest_timestamp, now())?
561        {
562            return Ok(false);
563        }
564
565        // Ensure the primary has not proposed a batch for this round before.
566        if self.storage.contains_certificate_in_round_from(round, self.gateway.account().address()) {
567            // If a BFT sender was provided, attempt to advance the current round.
568            if let Some(cb) = &*self.primary_callback.get_ref() {
569                match cb.try_advance_to_next_round(self.current_round()) {
570                    true => (), // continue,
571                    false => return Ok(false),
572                }
573            }
574            debug!("Primary is safely skipping {}", format!("(round {round} was already certified)").dimmed());
575            return Ok(false);
576        }
577
578        // Determine if the current round has been proposed.
579        // Note: Do NOT make this judgment in advance before rebroadcast and round update. Rebroadcasting is
580        // good for network reliability and should not be prevented for the already existing proposed_batch.
581        // If a certificate already exists for the current round, an attempt should be made to advance the
582        // round as early as possible.
583        if let Some((latest_round, _)) = &*lock_guard
584            && *latest_round == round
585        {
586            debug!("Primary is safely skipping a batch proposal - round {round} already proposed");
587            return Ok(false);
588        }
589
590        // Retrieve the committee to check against.
591        let committee_lookback = self.ledger.get_committee_lookback_for_round(round)?;
592        // Check if the primary is connected to enough validators to reach quorum threshold.
593        {
594            // Retrieve the connected validator addresses.
595            let mut connected_validators = self.gateway.connected_addresses();
596            // Append the primary to the set.
597            connected_validators.insert(self.gateway.account().address());
598            // If quorum threshold is not reached, return early.
599            if !committee_lookback.is_quorum_threshold_reached(&connected_validators) {
600                debug!(
601                    "Primary is safely skipping a batch proposal for round {round} {}",
602                    "(please connect to more validators)".dimmed()
603                );
604                trace!("Primary is connected to {} validators", connected_validators.len() - 1);
605                return Ok(false);
606            }
607        }
608
609        // Retrieve the previous certificates.
610        let previous_certificates = self.storage.get_certificates_for_round(previous_round);
611
612        // Check if the batch is ready to be proposed.
613        // Note: The primary starts at round 1, and round 0 contains no certificates, by definition.
614        let mut is_ready = previous_round == 0;
615        // If the previous round is not 0, check if the previous certificates have reached the quorum threshold.
616        if previous_round > 0 {
617            // Retrieve the committee lookback for the round.
618            let Ok(previous_committee_lookback) = self.ledger.get_committee_lookback_for_round(previous_round) else {
619                bail!("Cannot propose a batch for round {round}: the committee lookback is not known yet")
620            };
621            // Construct a set over the authors.
622            let authors = previous_certificates.iter().map(BatchCertificate::author).collect();
623            // Check if the previous certificates have reached the quorum threshold.
624            if previous_committee_lookback.is_quorum_threshold_reached(&authors) {
625                is_ready = true;
626            }
627            #[cfg(feature = "test_network")]
628            {
629                // If we are using a hotswapped dev committee, use simplified checks to more easily advance.
630                if let Some(dev_committee) = self.ledger.dev_committee_for_round(previous_round)? {
631                    if round <= dev_committee.starting_round() {
632                        is_ready = true;
633                    }
634                }
635            }
636        }
637        // If the batch is not ready to be proposed, return early.
638        if !is_ready {
639            debug!(
640                "Primary is safely skipping a batch proposal for round {round} {}",
641                format!("(previous round {previous_round} has not reached quorum)").dimmed()
642            );
643            return Ok(false);
644        }
645
646        // Initialize the map of transmissions.
647        let mut transmissions: IndexMap<_, _> = Default::default();
648        // Track the total execution costs of the batch proposal as it is being constructed.
649        let mut proposal_cost = 0u64;
650        // Note: worker draining and transaction inclusion needs to be thought
651        // through carefully when there is more than one worker. The fairness
652        // provided by one worker (FIFO) is no longer guaranteed with multiple workers.
653        debug_assert_eq!(MAX_WORKERS, 1);
654
655        'outer: for worker in self.workers().iter() {
656            let mut num_worker_transmissions = 0usize;
657
658            while let Some((id, transmission)) = worker.remove_front() {
659                // Check the selected transmissions are below the batch limit.
660                if transmissions.len() >= BatchHeader::<N>::MAX_TRANSMISSIONS_PER_BATCH {
661                    // Reinsert the transmission into the worker.
662                    worker.insert_front(id, transmission);
663                    break 'outer;
664                }
665
666                // Check the max transmissions per worker is not exceeded.
667                if num_worker_transmissions >= Worker::<N>::MAX_TRANSMISSIONS_PER_WORKER {
668                    // Reinsert the transmission into the worker.
669                    worker.insert_front(id, transmission);
670                    continue 'outer;
671                }
672
673                // Check if the ledger already contains the transmission.
674                if self.ledger.contains_transmission(&id).unwrap_or(true) {
675                    trace!("Proposing - Skipping transmission '{}' - Already in ledger", fmt_id(id));
676                    continue;
677                }
678
679                // Check if the storage already contain the transmission.
680                // Note: We do not skip if this is the first transmission in the proposal, to ensure that
681                // the primary does not propose a batch with no transmissions.
682                if !transmissions.is_empty() && self.storage.contains_transmission(id) {
683                    trace!("Proposing - Skipping transmission '{}' - Already in storage", fmt_id(id));
684                    continue;
685                }
686
687                // Check the transmission is still valid.
688                match (id, transmission.clone()) {
689                    (TransmissionID::Solution(solution_id, checksum), Transmission::Solution(solution)) => {
690                        // Ensure the checksum matches. If not, skip the solution.
691                        if !matches!(solution.to_checksum::<N>(), Ok(solution_checksum) if solution_checksum == checksum)
692                        {
693                            trace!("Proposing - Skipping solution '{}' - Checksum mismatch", fmt_id(solution_id));
694                            continue;
695                        }
696                        // Check if the solution is still valid.
697                        if let Err(e) = self.ledger.check_solution_basic(solution_id, solution).await {
698                            trace!("Proposing - Skipping solution '{}' - {e}", fmt_id(solution_id));
699                            continue;
700                        }
701                    }
702                    (TransmissionID::Transaction(transaction_id, checksum), Transmission::Transaction(transaction)) => {
703                        // Ensure the checksum matches. If not, skip the transaction.
704                        if !matches!(transaction.to_checksum::<N>(), Ok(transaction_checksum) if transaction_checksum == checksum )
705                        {
706                            trace!("Proposing - Skipping transaction '{}' - Checksum mismatch", fmt_id(transaction_id));
707                            continue;
708                        }
709
710                        // Deserialize the transaction. If the transaction exceeds the maximum size, then return an error.
711                        let transaction = spawn_blocking!({
712                            match transaction {
713                                Data::Object(transaction) => Ok(transaction),
714                                Data::Buffer(bytes) => Ok(Transaction::<N>::read_le(
715                                    &mut bytes.take(N::LATEST_MAX_TRANSACTION_SIZE() as u64),
716                                )?),
717                            }
718                        })?;
719
720                        // Fetch the current block height and consensus version.
721                        let current_block_height = self.ledger.latest_block_height();
722                        let consensus_version = N::CONSENSUS_VERSION(current_block_height)?;
723
724                        // Compute the transaction spent cost (in microcredits).
725                        // Note: We purposefully discard this transaction if we are unable to compute the spent cost.
726                        let Ok(cost) = self.ledger.transaction_spend_in_microcredits(&transaction, consensus_version)
727                        else {
728                            debug!(
729                                "Proposing - Skipping and discarding transaction '{}' - Unable to compute transaction spent cost",
730                                fmt_id(transaction_id)
731                            );
732                            continue;
733                        };
734
735                        // Check if the transaction is still valid.
736                        if let Err(e) = self.ledger.check_transaction_basic(transaction_id, transaction).await {
737                            trace!("Proposing - Skipping transaction '{}' - {e}", fmt_id(transaction_id));
738                            continue;
739                        }
740
741                        // Compute the next proposal cost.
742                        // Note: We purposefully discard this transaction if the proposal cost overflows.
743                        let Some(next_proposal_cost) = proposal_cost.checked_add(cost) else {
744                            debug!(
745                                "Proposing - Skipping and discarding transaction '{}' - Proposal cost overflowed",
746                                fmt_id(transaction_id)
747                            );
748                            continue;
749                        };
750
751                        // Check if the next proposal cost exceeds the batch proposal spend limit.
752                        let batch_spend_limit = BatchHeader::<N>::batch_spend_limit(current_block_height);
753                        if next_proposal_cost > batch_spend_limit {
754                            debug!(
755                                "Proposing - Skipping transaction '{}' - Batch spend limit surpassed ({next_proposal_cost} > {})",
756                                fmt_id(transaction_id),
757                                batch_spend_limit
758                            );
759
760                            // Reinsert the transmission into the worker.
761                            worker.insert_front(id, transmission);
762                            break 'outer;
763                        }
764
765                        // Update the proposal cost.
766                        proposal_cost = next_proposal_cost;
767                    }
768
769                    // Note: We explicitly forbid including ratifications,
770                    // as the protocol currently does not support ratifications.
771                    (TransmissionID::Ratification, Transmission::Ratification) => continue,
772                    // All other combinations are clearly invalid.
773                    _ => continue,
774                }
775
776                // If the transmission is valid, insert it into the proposal's transmission list.
777                transmissions.insert(id, transmission);
778                num_worker_transmissions = num_worker_transmissions.saturating_add(1);
779            }
780        }
781
782        // Determine the current timestamp.
783        let current_timestamp = now();
784
785        /* Proceeding to sign & propose the batch. */
786        info!("Proposing a batch with {} transmissions for round {round}...", transmissions.len());
787
788        // Update the latest proposed round and timestamp.
789        *lock_guard = Some((round, current_timestamp));
790        // Retrieve the private key.
791        let private_key = *self.gateway.account().private_key();
792        // Retrieve the committee ID.
793        let committee_id = committee_lookback.id();
794        // Prepare the transmission IDs.
795        let transmission_ids = transmissions.keys().copied().collect();
796        // Prepare the previous batch certificate IDs.
797        let previous_certificate_ids = previous_certificates.into_iter().map(|c| c.id()).collect();
798        // Sign the batch header and construct the proposal.
799        let (batch_header, proposal) = spawn_blocking!(BatchHeader::new(
800            &private_key,
801            round,
802            current_timestamp,
803            committee_id,
804            transmission_ids,
805            previous_certificate_ids,
806            &mut rand::rng()
807        ))
808        .and_then(|batch_header| {
809            Proposal::new(committee_lookback, batch_header.clone(), transmissions.clone())
810                .map(|proposal| (batch_header, proposal))
811        })
812        .inspect_err(|_| {
813            // On error, reinsert the transmissions and then propagate the error.
814            if let Err(err) = self.reinsert_transmissions_into_workers(transmissions) {
815                error!("{}", flatten_error(err.context("Failed to reinsert transmissions")));
816            }
817        })?;
818
819        // Broadcast the batch to all validators for signing.
820        self.gateway.broadcast(Event::BatchPropose(batch_header.into()));
821        // Store the proposal in memory.
822        *self.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
823        // Record the wall-clock time at which the batch was proposed.
824        #[cfg(feature = "metrics")]
825        {
826            *self.batch_propose_start.lock() = Some(Instant::now());
827        }
828
829        Ok(true)
830    }
831}
832
833impl<N: Network> Primary<N> {
834    /// Processes a batch propose from a peer.
835    ///
836    /// This method performs the following steps:
837    /// 1. Verify the batch.
838    /// 2. Sign the batch.
839    /// 3. Broadcast the signature back to the validator.
840    ///
841    /// If our primary is ahead of the peer, we will not sign the batch.
842    /// 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.
843    async fn process_batch_propose_from_peer(&self, peer_ip: SocketAddr, batch_propose: BatchPropose<N>) -> Result<()> {
844        let BatchPropose { round: batch_round, batch_header } = batch_propose;
845
846        // Deserialize the batch header.
847        let batch_header = spawn_blocking!(batch_header.deserialize_blocking())?;
848        // Ensure the round matches in the batch header.
849        if batch_round != batch_header.round() {
850            // Proceed to disconnect the validator.
851            self.gateway.disconnect(peer_ip);
852            bail!("Malicious peer - proposed round {batch_round}, but sent batch for round {}", batch_header.round());
853        }
854
855        // Retrieve the batch author.
856        let batch_author = batch_header.author();
857
858        // Ensure the batch proposal is from the validator.
859        match self.gateway.resolve_to_aleo_addr(peer_ip) {
860            // If the peer is a validator, then ensure the batch proposal is from the validator.
861            Some(address) => {
862                if address != batch_author {
863                    // Proceed to disconnect the validator.
864                    self.gateway.disconnect(peer_ip);
865                    bail!("Malicious peer - proposed batch from a different validator ({batch_author})");
866                }
867            }
868            None => bail!("Batch proposal from a disconnected validator"),
869        }
870        // Ensure the batch author is a current committee member.
871        if !self.gateway.is_authorized_validator_address(batch_author) {
872            // Proceed to disconnect the validator.
873            self.gateway.disconnect(peer_ip);
874            bail!("Malicious peer - proposed batch from a non-committee member ({batch_author})");
875        }
876        // Ensure the batch proposal is not from the current primary.
877        if self.gateway.account().address() == batch_author {
878            bail!("Invalid peer - proposed batch from myself ({batch_author})");
879        }
880
881        // Ensure that the batch proposal's committee ID matches the expected committee ID.
882        // This may happen when the network forks. A transaction referencing a
883        // state root from one side of the fork will be aborted on the other
884        // side of the fork. This leads to a different view of stake and
885        // therefore a different view of the committee ID.
886        let expected_committee_id = self.ledger.get_committee_lookback_for_round(batch_round)?.id();
887        if expected_committee_id != batch_header.committee_id() {
888            // Proceed to disconnect the validator.
889            self.gateway.disconnect(peer_ip);
890            bail!(
891                "Malicious peer - proposed batch has a different committee ID ({expected_committee_id} != {})",
892                batch_header.committee_id()
893            );
894        }
895
896        // Retrieve the cached round and batch ID for this validator.
897        if let Some((signed_round, signed_batch_id, signature)) =
898            self.signed_proposals.read().get(&batch_author).copied()
899        {
900            // If the signed round is ahead of the peer's batch round, do not sign the proposal.
901            // Note: while this may be valid behavior, additional formal analysis and testing will need to be done before allowing it.
902            if signed_round > batch_header.round() {
903                bail!(
904                    "Peer ({batch_author}) proposed a batch for a previous round ({}), latest signed round: {signed_round}",
905                    batch_header.round()
906                );
907            }
908
909            // If the round matches and the batch ID differs, then the validator is malicious.
910            if signed_round == batch_header.round() && signed_batch_id != batch_header.batch_id() {
911                bail!("Peer ({batch_author}) proposed another batch for the same round ({signed_round})");
912            }
913            // If the round and batch ID matches, then skip signing the batch a second time.
914            // Instead, rebroadcast the cached signature to the peer.
915            if signed_round == batch_header.round() && signed_batch_id == batch_header.batch_id() {
916                let gateway = self.gateway.clone();
917                tokio::spawn(async move {
918                    debug!("Resending a signature for a batch in round {batch_round} from '{peer_ip}'");
919                    let event = Event::BatchSignature(BatchSignature::new(batch_header.batch_id(), signature));
920                    // Resend the batch signature to the peer.
921                    if gateway.send(peer_ip, event).await.is_none() {
922                        warn!("Failed to resend a signature for a batch in round {batch_round} to '{peer_ip}'");
923                    }
924                });
925                // Return early.
926                return Ok(());
927            }
928        }
929
930        // Ensure that the batch header doesn't already exist in storage.
931        // Note this is already checked in `check_batch_header`, however we can return early here without creating a blocking task.
932        if self.storage.contains_batch(batch_header.batch_id()) {
933            debug!(
934                "Primary is safely skipping a batch proposal from '{peer_ip}' - {}",
935                format!("batch for round {batch_round} already exists in storage").dimmed()
936            );
937            return Ok(());
938        }
939
940        // Compute the previous round.
941        let previous_round = batch_round.saturating_sub(1);
942        // Ensure that the peer did not propose a batch too quickly.
943        if let Err(err) = self.check_peer_proposal_timestamp(previous_round, batch_author, batch_header.timestamp()) {
944            // Proceed to disconnect the validator.
945            self.gateway.disconnect(peer_ip);
946            return Err(err.context(format!("Malicious behavior of peer '{peer_ip}'")));
947        }
948
949        // Ensure the batch header does not contain any ratifications.
950        if batch_header.contains(TransmissionID::Ratification) {
951            // Proceed to disconnect the validator.
952            self.gateway.disconnect(peer_ip);
953            bail!(
954                "Malicious peer - proposed batch contains an unsupported ratification transmissionID from '{peer_ip}'",
955            );
956        }
957
958        // If the peer is ahead, use the batch header to sync up to the peer.
959        let mut missing_transmissions =
960            self.sync_with_batch_header_from_peer::<false, true>(peer_ip, &batch_header).await?;
961
962        // Check that the transmission ids match and are not fee transactions.
963        if let Err(err) = cfg_iter_mut!(&mut missing_transmissions).try_for_each(|(transmission_id, transmission)| {
964            // If the transmission is not well-formed, then return early.
965            self.ledger.ensure_transmission_is_well_formed(*transmission_id, transmission)
966        }) {
967            let err = err.context(format!(
968                "Batch propose at round {batch_round} from '{peer_ip}' contains an invalid transmission"
969            ));
970            debug!("{}", flatten_error(err));
971            return Ok(());
972        }
973
974        // Ensure the batch is for the current round.
975        // This method must be called after fetching previous certificates (above),
976        // and prior to checking the batch header (below).
977        if let Err(e) = self.ensure_is_signing_round(batch_round) {
978            // If the primary is not signing for the peer's round, then return early.
979            debug!("{e} from '{peer_ip}'");
980            return Ok(());
981        }
982
983        // Ensure the batch header from the peer is valid.
984        let (storage, header) = (self.storage.clone(), batch_header.clone());
985
986        // Check the batch header, and return early if it already exists in storage.
987        let Some(missing_transmissions) =
988            spawn_blocking!(storage.check_batch_header(&header, missing_transmissions, Default::default()))?
989        else {
990            return Ok(());
991        };
992
993        // Inserts the missing transmissions into the workers.
994        self.insert_missing_transmissions_into_workers(peer_ip, missing_transmissions.into_iter())?;
995
996        /* Proceeding to sign the batch. */
997
998        // Retrieve the batch ID.
999        let batch_id = batch_header.batch_id();
1000        // Sign the batch ID.
1001        let account = self.gateway.account().clone();
1002        let signature = spawn_blocking!(account.sign(&[batch_id], &mut rand::rng()))?;
1003
1004        // Ensure the proposal has not already been signed.
1005        //
1006        // Note: Due to the need to sync the batch header with the peer, it is possible
1007        // for the primary to receive the same 'BatchPropose' event again, whereby only
1008        // one instance of this handler should sign the batch. This check guarantees this.
1009        match self.signed_proposals.write().0.entry(batch_author) {
1010            std::collections::hash_map::Entry::Occupied(mut entry) => {
1011                // If the validator has already signed a batch for this round, then return early,
1012                // since, if the peer still has not received the signature, they will request it again,
1013                // and the logic at the start of this function will resend the (now cached) signature
1014                // to the peer if asked to sign this batch proposal again.
1015                if entry.get().0 == batch_round {
1016                    return Ok(());
1017                }
1018                // Otherwise, cache the round, batch ID, and signature for this validator.
1019                entry.insert((batch_round, batch_id, signature));
1020            }
1021            // If the validator has not signed a batch before, then continue.
1022            std::collections::hash_map::Entry::Vacant(entry) => {
1023                // Cache the round, batch ID, and signature for this validator.
1024                entry.insert((batch_round, batch_id, signature));
1025            }
1026        };
1027
1028        // Broadcast the signature back to the validator.
1029        let self_ = self.clone();
1030        tokio::spawn(async move {
1031            let event = Event::BatchSignature(BatchSignature::new(batch_id, signature));
1032            // Send the batch signature to the peer.
1033            if self_.gateway.send(peer_ip, event).await.is_some() {
1034                debug!("Signed a batch for round {batch_round} from '{peer_ip}'");
1035            }
1036        });
1037
1038        Ok(())
1039    }
1040
1041    /// Attempts to add a peer's `signature` for `batch_id` to the current proposal.
1042    ///
1043    /// Consumes `state` and always returns the (possibly updated) state alongside a result so that
1044    /// the caller can restore it unconditionally, keeping `proposed_batch` consistent even on the
1045    /// error path.
1046    ///
1047    /// # Returns
1048    /// * `(Ok(Some(proposal)), Certified(id))` — quorum reached; caller should certify.
1049    /// * `(Ok(None), <restored state>)` — signature accepted or silently dropped; nothing to do.
1050    /// * `(Err(e), <restored state>)` — signature rejected; caller should propagate the error.
1051    fn add_signature_to_batch(
1052        &self,
1053        state: ProposedBatchState<N>,
1054        peer_ip: SocketAddr,
1055        batch_id: Field<N>,
1056        signature: Signature<N>,
1057    ) -> (Result<Option<Proposal<N>>>, ProposedBatchState<N>) {
1058        match state {
1059            ProposedBatchState::Certifying(mut proposal) if proposal.batch_id() == batch_id => {
1060                // This signature is for our currently active proposal.
1061                // Use an inner closure to keep `?` ergonomics while returning a tuple.
1062                let inner: Result<bool> = (|| {
1063                    let committee_lookback = self.ledger.get_committee_lookback_for_round(proposal.round())?;
1064                    let Some(signer) = self.gateway.resolve_to_aleo_addr(peer_ip) else {
1065                        bail!("Signature is from a disconnected validator");
1066                    };
1067                    let new_signature = proposal.add_signature(signer, signature, &committee_lookback)?;
1068                    if new_signature {
1069                        info!("Received a batch signature for round {} from '{peer_ip}'", proposal.round());
1070                        Ok(proposal.is_quorum_threshold_reached(&committee_lookback))
1071                    } else {
1072                        debug!(
1073                            "Received duplicated signature from '{peer_ip}' for batch \
1074                                {batch_id} in round {round}",
1075                            round = proposal.round()
1076                        );
1077                        Ok(false)
1078                    }
1079                })();
1080                match inner {
1081                    Ok(true) => {
1082                        let certified_id = proposal.batch_id();
1083                        (Ok(Some(*proposal)), ProposedBatchState::Certified(certified_id))
1084                    }
1085                    Ok(false) => (Ok(None), ProposedBatchState::Certifying(proposal)),
1086                    Err(e) => (Err(e), ProposedBatchState::Certifying(proposal)),
1087                }
1088            }
1089            ProposedBatchState::Certifying(proposal) => {
1090                // Certifying a different proposal — check if batch_id is already in storage.
1091                if self.storage.contains_batch(batch_id) {
1092                    debug!(
1093                        "Primary is safely skipping a batch signature from {peer_ip} for \
1094                            round {} - batch is already certified",
1095                        proposal.round()
1096                    );
1097                    (Ok(None), ProposedBatchState::Certifying(proposal))
1098                } else {
1099                    let expected_id = proposal.batch_id();
1100                    let round = proposal.round();
1101                    (
1102                        Err(anyhow!("Unknown batch ID '{batch_id}', expected '{expected_id}' for round {round}")),
1103                        ProposedBatchState::Certifying(proposal),
1104                    )
1105                }
1106            }
1107            ProposedBatchState::Certified(id) if id == batch_id => {
1108                // Quorum already reached; late-arriving signature is harmless.
1109                debug!(
1110                    "Skipping batch signature from {peer_ip} for batch '{batch_id}' - \
1111                        already received sufficient signatures"
1112                );
1113                (Ok(None), ProposedBatchState::Certified(id))
1114            }
1115            ProposedBatchState::Certified(id) => {
1116                let result = if self.storage.contains_batch(batch_id) {
1117                    // This is most likely not malicious, but could indicate connectivity issues.
1118                    warn!("Received signature for an older batch {batch_id}");
1119                    Ok(None)
1120                } else {
1121                    Err(anyhow!("Unknown batch ID '{batch_id}'"))
1122                };
1123
1124                (result, ProposedBatchState::Certified(id))
1125            }
1126            ProposedBatchState::None => {
1127                let result = if self.storage.contains_batch(batch_id) {
1128                    // This is most likely not malicious, but could indicate connectivity issues.
1129                    warn!("Received signature for an older batch {batch_id}");
1130                    Ok(None)
1131                } else {
1132                    Err(anyhow!("Unknown batch ID '{batch_id}'"))
1133                };
1134
1135                (result, ProposedBatchState::None)
1136            }
1137        }
1138    }
1139
1140    /// Processes a batch signature from a peer.
1141    ///
1142    /// This method performs the following steps:
1143    /// 1. Ensure the proposed batch has not expired.
1144    /// 2. Verify the signature, ensuring it corresponds to the proposed batch.
1145    /// 3. Store the signature.
1146    /// 4. Certify the batch if enough signatures have been received.
1147    /// 5. Broadcast the batch certificate to all validators.
1148    async fn process_batch_signature_from_peer(
1149        &self,
1150        peer_ip: SocketAddr,
1151        batch_signature: BatchSignature<N>,
1152    ) -> Result<()> {
1153        // Ensure the proposed batch has not expired, and clear the proposed batch if it has expired.
1154        self.check_proposed_batch_for_expiration()?;
1155
1156        // Retrieve the signature and timestamp.
1157        let BatchSignature { batch_id, signature } = batch_signature;
1158
1159        // Retrieve the signer.
1160        let signer = signature.to_address();
1161
1162        // Ensure the batch signature is signed by the validator.
1163        match self.gateway.resolve_to_aleo_addr(peer_ip) {
1164            // If the peer is a validator, then ensure the batch signature is from the validator.
1165            Some(address) => {
1166                if address != signer {
1167                    // Proceed to disconnect the validator.
1168                    self.gateway.disconnect(peer_ip);
1169                    bail!("Malicious peer - batch signature is from a different validator ({signer})");
1170                }
1171            }
1172            None => bail!("Batch signature from a disconnected validator"),
1173        }
1174        // Ensure the batch signature is not from the current primary.
1175        if self.gateway.account().address() == signer {
1176            bail!("Invalid peer - received a batch signature from myself ({signer})");
1177        }
1178
1179        let self_ = self.clone();
1180        let Some(proposal) = spawn_blocking!({
1181            // Acquire the write lock.
1182            let mut proposed_batch = self_.proposed_batch.write();
1183
1184            let (result, new_state) =
1185                self_.add_signature_to_batch(std::mem::take(&mut *proposed_batch), peer_ip, batch_id, signature);
1186            *proposed_batch = new_state;
1187            result
1188        })?
1189        else {
1190            return Ok(());
1191        };
1192
1193        /* Proceeding to certify the batch. */
1194
1195        info!("Quorum threshold reached - Preparing to certify our batch for round {}...", proposal.round());
1196
1197        // Retrieve the committee lookback for the round.
1198        let committee_lookback = self.ledger.get_committee_lookback_for_round(proposal.round())?;
1199        // Store the certified batch and broadcast it to all validators.
1200        // If there was an error storing the certificate, reinsert the transmissions back into the ready queue.
1201        if let Err(e) = self.store_and_broadcast_certificate(&proposal, &committee_lookback).await {
1202            // Reinsert the transmissions back into the ready queue for the next proposal.
1203            self.reinsert_transmissions_into_workers(proposal.into_transmissions())?;
1204            return Err(e);
1205        }
1206
1207        #[cfg(feature = "metrics")]
1208        metrics::increment_gauge(metrics::bft::CERTIFIED_BATCHES, 1.0);
1209        Ok(())
1210    }
1211
1212    /// Processes a batch certificate from a peer.
1213    ///
1214    /// This method performs the following steps:
1215    /// 1. Stores the given batch certificate, after ensuring it is valid.
1216    /// 2. If there are enough certificates to reach quorum threshold for the current round,
1217    ///    then proceed to advance to the next round.
1218    async fn process_batch_certificate_from_peer(
1219        &self,
1220        peer_ip: SocketAddr,
1221        certificate: BatchCertificate<N>,
1222    ) -> Result<()> {
1223        // Ensure the batch certificate is from an authorized validator.
1224        if !self.gateway.is_authorized_validator_ip(peer_ip) {
1225            // Proceed to disconnect the validator.
1226            self.gateway.disconnect(peer_ip);
1227            bail!("Malicious peer - Received a batch certificate from an unauthorized validator IP ({peer_ip})");
1228        }
1229        // Ensure storage does not already contain the certificate.
1230        if self.storage.contains_certificate(certificate.id()) {
1231            return Ok(());
1232        // Otherwise, ensure ephemeral storage contains the certificate.
1233        } else if !self.storage.contains_unprocessed_certificate(certificate.id()) {
1234            self.storage.insert_unprocessed_certificate(certificate.clone())?;
1235        }
1236
1237        // Retrieve the batch certificate author.
1238        let author = certificate.author();
1239        // Retrieve the batch certificate round.
1240        let certificate_round = certificate.round();
1241        // Retrieve the batch certificate committee ID.
1242        let committee_id = certificate.committee_id();
1243
1244        // Ensure the batch certificate is not from the current primary.
1245        if self.gateway.account().address() == author {
1246            bail!("Received a batch certificate for myself ({author})");
1247        }
1248
1249        // Ensure that the incoming certificate is valid.
1250        self.storage.check_incoming_certificate(&certificate)?;
1251
1252        // Store the certificate, after ensuring it is valid above.
1253        // The following call recursively fetches and stores
1254        // the previous certificates referenced from this certificate.
1255        // It is critical to make the following call this after validating the certificate above.
1256        // The reason is that a sequence of malformed certificates,
1257        // with references to previous certificates with non-decreasing rounds,
1258        // cause the recursive fetching of certificates to crash the validator due to resource exhaustion.
1259        // Note that if the following call, if not returning an error, guarantees the backward closure of the DAG
1260        // (i.e. that all the referenced previous certificates are in the DAG before storing this one),
1261        // then all the validity checks in [`Storage::check_certificate`] should be redundant.
1262        // TODO: eliminate those redundant checks
1263        self.sync_with_certificate_from_peer::<false>(peer_ip, certificate).await?;
1264
1265        // If there are enough certificates to reach quorum threshold for the certificate round,
1266        // then proceed to advance to the next round.
1267
1268        // Retrieve the committee lookback.
1269        let committee_lookback = self.ledger.get_committee_lookback_for_round(certificate_round)?;
1270
1271        // Retrieve the certificate authors.
1272        let authors = self.storage.get_certificate_authors_for_round(certificate_round);
1273        // Check if the certificates have reached the quorum threshold.
1274        let is_quorum = committee_lookback.is_quorum_threshold_reached(&authors);
1275
1276        // Ensure that the batch certificate's committee ID matches the expected committee ID.
1277        let expected_committee_id = committee_lookback.id();
1278        if expected_committee_id != committee_id {
1279            // Proceed to disconnect the validator.
1280            self.gateway.disconnect(peer_ip);
1281            bail!("Batch certificate has a different committee ID ({expected_committee_id} != {committee_id})");
1282        }
1283
1284        // Determine if we are currently proposing a round that is relevant.
1285        // Note: This is important, because while our peers have advanced,
1286        // they may not be proposing yet, and thus still able to sign our proposed batch.
1287        let should_advance = match &*self.latest_proposal_timestamp.read().await {
1288            // We advance if the proposal round is less than the current round that was just certified.
1289            Some((latest_round, _)) => *latest_round < certificate_round,
1290            // If there's no proposal, we consider advancing.
1291            None => true,
1292        };
1293
1294        // Retrieve the current round.
1295        let current_round = self.current_round();
1296
1297        // Determine whether to advance to the next round.
1298        if is_quorum && should_advance && certificate_round >= current_round {
1299            // If we have reached the quorum threshold and the round should advance, then proceed to the next round.
1300            self.round_increment_notify.notify_one();
1301        }
1302        Ok(())
1303    }
1304}
1305
1306impl<N: Network> Primary<N> {
1307    /// Starts the primary handlers.
1308    ///
1309    /// For each receiver in the `primary_receiver` struct, there will be a dedicated task
1310    /// that awaits new data and handles it accordingly.
1311    /// Additionally, this spawns a task that periodically issues PrimaryPings and one that
1312    /// tries to move to the next round when triggered (e.g. after a certificate is stored) or on a timeout.
1313    ///
1314    /// This function is called exactly once, in `Self::run()`.
1315    fn start_handlers(&self, primary_receiver: PrimaryReceiver<N>) {
1316        let PrimaryReceiver {
1317            mut rx_batch_propose,
1318            mut rx_batch_signature,
1319            mut rx_batch_certified,
1320            mut rx_primary_ping,
1321            mut rx_unconfirmed_solution,
1322            mut rx_unconfirmed_transaction,
1323        } = primary_receiver;
1324
1325        // Start the primary ping sender.
1326        let self_ = self.clone();
1327        self.spawn(async move {
1328            loop {
1329                // Sleep briefly.
1330                tokio::time::sleep(PRIMARY_PING_INTERVAL).await;
1331
1332                // Retrieve the block locators.
1333                let self__ = self_.clone();
1334                let block_locators = match spawn_blocking!(self__.sync.get_block_locators()) {
1335                    Ok(block_locators) => block_locators,
1336                    Err(e) => {
1337                        warn!("Failed to retrieve block locators - {e}");
1338                        continue;
1339                    }
1340                };
1341
1342                // Retrieve the latest certificate of the primary.
1343                let primary_certificate = {
1344                    // Retrieve the primary address.
1345                    let primary_address = self_.gateway.account().address();
1346
1347                    // Iterate backwards from the latest round to find the primary certificate.
1348                    let mut certificate = None;
1349                    let mut current_round = self_.current_round();
1350                    while certificate.is_none() {
1351                        // If the current round is 0, then break the while loop.
1352                        if current_round == 0 {
1353                            break;
1354                        }
1355                        // Retrieve the primary certificates.
1356                        if let Some(primary_certificate) =
1357                            self_.storage.get_certificate_for_round_with_author(current_round, primary_address)
1358                        {
1359                            certificate = Some(primary_certificate);
1360                        // If the primary certificate was not found, decrement the round.
1361                        } else {
1362                            current_round = current_round.saturating_sub(1);
1363                        }
1364                    }
1365
1366                    // Determine if the primary certificate was found.
1367                    match certificate {
1368                        Some(certificate) => certificate,
1369                        // Skip this iteration of the loop (do not send a primary ping).
1370                        None => continue,
1371                    }
1372                };
1373
1374                // Construct the primary ping.
1375                let primary_ping = PrimaryPing::from((<Event<N>>::VERSION, block_locators, primary_certificate));
1376                // Broadcast the event.
1377                self_.gateway.broadcast(Event::PrimaryPing(primary_ping));
1378            }
1379        });
1380
1381        // Start the primary ping handler.
1382        let self_ = self.clone();
1383        self.spawn(async move {
1384            while let Some((peer_ip, primary_certificate)) = rx_primary_ping.recv().await {
1385                // If the primary is not synced, then do not process the primary ping.
1386                if self_.sync.is_synced() {
1387                    trace!("Processing new primary ping from '{peer_ip}'");
1388                } else {
1389                    trace!("Skipping a primary ping from '{peer_ip}' {}", "(node is syncing)".dimmed());
1390                    continue;
1391                }
1392
1393                // Spawn a task to process the primary certificate.
1394                {
1395                    let self_ = self_.clone();
1396                    tokio::spawn(async move {
1397                        // Deserialize the primary certificate in the primary ping.
1398                        let Ok(primary_certificate) = spawn_blocking!(primary_certificate.deserialize_blocking())
1399                        else {
1400                            warn!("Failed to deserialize primary certificate in 'PrimaryPing' from '{peer_ip}'");
1401                            return;
1402                        };
1403                        // Process the primary certificate.
1404                        let id = fmt_id(primary_certificate.id());
1405                        let round = primary_certificate.round();
1406                        if let Err(e) = self_.process_batch_certificate_from_peer(peer_ip, primary_certificate).await {
1407                            warn!("Cannot process a primary certificate '{id}' at round {round} in a 'PrimaryPing' from '{peer_ip}' - {e}");
1408                        }
1409                    });
1410                }
1411            }
1412        });
1413
1414        // Start the worker ping(s).
1415        let self_ = self.clone();
1416        self.spawn(async move {
1417            loop {
1418                tokio::time::sleep(WORKER_PING_INTERVAL).await;
1419                // If the primary is not synced, then do not broadcast the worker ping(s).
1420                if !self_.sync.is_synced() {
1421                    trace!("Skipping worker ping(s) {}", "(node is syncing)".dimmed());
1422                    continue;
1423                }
1424                // Broadcast the worker ping(s).
1425                for worker in self_.workers() {
1426                    worker.broadcast_ping();
1427                }
1428            }
1429        });
1430
1431        // Start the batch proposal task.
1432        let proposal_task = self.proposal_task.clone();
1433        let self_ = self.clone();
1434        self.spawn(async move { proposal_task.run(self_).await });
1435
1436        // Start the proposed batch handler.
1437        let self_ = self.clone();
1438        self.spawn(async move {
1439            while let Some((peer_ip, batch_propose)) = rx_batch_propose.recv().await {
1440                // If the primary is not synced, then do not sign the batch.
1441                if !self_.sync.is_synced() {
1442                    trace!("Skipping a batch proposal from '{peer_ip}' {}", "(node is syncing)".dimmed());
1443                    continue;
1444                }
1445
1446                // Spawn a task to process the proposed batch.
1447                let self_ = self_.clone();
1448                tokio::spawn(async move {
1449                    // Process the batch proposal.
1450                    let round = batch_propose.round;
1451                    if let Err(err) = self_.process_batch_propose_from_peer(peer_ip, batch_propose).await {
1452                        let err = err.context(format!("Cannot sign a batch at round {round} from '{peer_ip}'"));
1453                        warn!("{}", flatten_error(err));
1454                    }
1455                });
1456            }
1457        });
1458
1459        // Start the batch signature handler.
1460        let self_ = self.clone();
1461        self.spawn(async move {
1462            while let Some((peer_ip, batch_signature)) = rx_batch_signature.recv().await {
1463                // If the primary is not synced, then do not store the signature.
1464                if !self_.sync.is_synced() {
1465                    trace!("Skipping a batch signature from '{peer_ip}' {}", "(node is syncing)".dimmed());
1466                    continue;
1467                }
1468                // Process the batch signature.
1469                // Note: Do NOT spawn a task around this function call. Processing signatures from peers
1470                // is a critical path, and we should only store the minimum required number of signatures.
1471                // In addition, spawning a task can cause concurrent processing of signatures (even with a lock),
1472                // which means the RwLock for the proposed batch must become a 'tokio::sync' to be safe.
1473                let id = fmt_id(batch_signature.batch_id);
1474                if let Err(err) = self_.process_batch_signature_from_peer(peer_ip, batch_signature).await {
1475                    let err = err.context(format!("Cannot store a signature for batch '{id}' from '{peer_ip}'"));
1476                    warn!("{}", flatten_error(err));
1477                }
1478            }
1479        });
1480
1481        // Start the certified batch handler.
1482        let self_ = self.clone();
1483        self.spawn(async move {
1484            while let Some((peer_ip, batch_certificate)) = rx_batch_certified.recv().await {
1485                // If the primary is not synced, then do not store the certificate.
1486                if !self_.sync.is_synced() {
1487                    trace!("Skipping a certified batch from '{peer_ip}' {}", "(node is syncing)".dimmed());
1488                    continue;
1489                }
1490                // Spawn a task to process the batch certificate.
1491                let self_ = self_.clone();
1492                tokio::spawn(async move {
1493                    // Deserialize the batch certificate.
1494                    let Ok(batch_certificate) = spawn_blocking!(batch_certificate.deserialize_blocking()) else {
1495                        warn!("Failed to deserialize the batch certificate from '{peer_ip}'");
1496                        return;
1497                    };
1498                    // Process the batch certificate.
1499                    let id = fmt_id(batch_certificate.id());
1500                    let round = batch_certificate.round();
1501                    if let Err(err) = self_.process_batch_certificate_from_peer(peer_ip, batch_certificate).await {
1502                        warn!(
1503                            "{}",
1504                            flatten_error(err.context(format!(
1505                                "Cannot store a certificate '{id}' for round {round} from '{peer_ip}'"
1506                            )))
1507                        );
1508                    }
1509                });
1510            }
1511        });
1512
1513        // This task tries to move to the next round when triggered (e.g. after a certificate is stored)
1514        // or after a timeout, so we are not stuck on a previous round despite having quorum.
1515        let self_ = self.clone();
1516        self.spawn(async move {
1517            loop {
1518                let round_start = Instant::now();
1519                let current_round = self_.current_round();
1520
1521                // Inner loop: wait and try to increment while we're still in the same round.
1522                while self_.current_round() == current_round {
1523                    let mut futures: Vec<Pin<Box<dyn Future<Output = ()> + Send>>> =
1524                        vec![Box::pin(self_.round_increment_notify.notified())];
1525
1526                    if let Some(remaining_delay) = MAX_BATCH_DELAY.checked_sub(round_start.elapsed())
1527                        && !remaining_delay.is_zero()
1528                    {
1529                        futures.push(Box::pin(tokio::time::sleep(remaining_delay)));
1530                    }
1531                    // Always ensure a wakeup no later than MAX_LEADER_CERTIFICATE_DELAY so that
1532                    // try_advance_to_next_round is called after the leader-certificate timer
1533                    // expires, even when no further certificates arrive (e.g. an even round where
1534                    // the elected leader was absent and quorum was reached without their cert).
1535                    futures.push(Box::pin(tokio::time::sleep(MAX_LEADER_CERTIFICATE_DELAY)));
1536                    if !self_.sync.is_synced() {
1537                        futures.push(Box::pin(self_.sync.wait_for_synced()));
1538                    }
1539                    let _ = futures::future::select_all(futures).await;
1540
1541                    if !self_.sync.is_synced() {
1542                        trace!("Skipping round increment {}", "(node is syncing)".dimmed());
1543                        continue;
1544                    }
1545
1546                    let next_round = current_round.saturating_add(1);
1547                    let is_quorum_threshold_reached = {
1548                        let authors = self_.storage.get_certificate_authors_for_round(current_round);
1549                        if authors.is_empty() {
1550                            continue;
1551                        }
1552                        let Ok(committee_lookback) = self_.ledger.get_committee_lookback_for_round(current_round)
1553                        else {
1554                            warn!("Failed to retrieve the committee lookback for round {current_round}");
1555                            continue;
1556                        };
1557                        committee_lookback.is_quorum_threshold_reached(&authors)
1558                    };
1559
1560                    if is_quorum_threshold_reached {
1561                        debug!("Quorum threshold reached for round {current_round}");
1562                        if let Err(err) = self_.try_increment_to_the_next_round(next_round).await {
1563                            warn!("{}", flatten_error(err.context("Failed to increment to the next round")));
1564                        }
1565                    }
1566                }
1567            }
1568        });
1569
1570        // Start a handler to process new unconfirmed solutions.
1571        let self_ = self.clone();
1572        self.spawn(async move {
1573            while let Some((solution_id, solution, callback)) = rx_unconfirmed_solution.recv().await {
1574                // Compute the checksum for the solution.
1575                let Ok(checksum) = solution.to_checksum::<N>() else {
1576                    error!("Failed to compute the checksum for the unconfirmed solution");
1577                    continue;
1578                };
1579                // Compute the worker ID.
1580                let Ok(worker_id) = assign_to_worker((solution_id, checksum), self_.num_workers()) else {
1581                    error!("Unable to determine the worker ID for the unconfirmed solution");
1582                    continue;
1583                };
1584                let self_ = self_.clone();
1585                tokio::spawn(async move {
1586                    // Retrieve the worker.
1587                    let worker = &self_.workers()[worker_id as usize];
1588                    // Process the unconfirmed solution.
1589                    let result = worker.process_unconfirmed_solution(solution_id, solution).await;
1590                    // Send the result to the callback.
1591                    callback.send(result).ok();
1592                });
1593            }
1594        });
1595
1596        // Start a handler to process new unconfirmed transactions.
1597        let self_ = self.clone();
1598        self.spawn(async move {
1599            while let Some((transaction_id, transaction, callback)) = rx_unconfirmed_transaction.recv().await {
1600                trace!("Primary - Received an unconfirmed transaction '{}'", fmt_id(transaction_id));
1601                // Compute the checksum for the transaction.
1602                let Ok(checksum) = transaction.to_checksum::<N>() else {
1603                    error!("Failed to compute the checksum for the unconfirmed transaction");
1604                    continue;
1605                };
1606                // Compute the worker ID.
1607                let Ok(worker_id) = assign_to_worker::<N>((&transaction_id, &checksum), self_.num_workers()) else {
1608                    error!("Unable to determine the worker ID for the unconfirmed transaction");
1609                    continue;
1610                };
1611                let self_ = self_.clone();
1612                tokio::spawn(async move {
1613                    // Retrieve the worker.
1614                    let worker = &self_.workers().get(worker_id as usize).expect("Invalid worker ID");
1615                    // Process the unconfirmed transaction.
1616                    let result = worker.process_unconfirmed_transaction(transaction_id, transaction).await;
1617                    // Send the result to the callback.
1618                    callback.send(result).ok();
1619                });
1620            }
1621        });
1622    }
1623
1624    /// Checks if the proposed batch is expired, and clears the proposed batch if it has expired.
1625    fn check_proposed_batch_for_expiration(&self) -> Result<()> {
1626        // Check if the proposed batch is timed out or stale.
1627        // A batch being certified is not considered expired.
1628        let is_expired = match &*self.proposed_batch.read() {
1629            ProposedBatchState::Certifying(proposal) => proposal.round() < self.current_round(),
1630            _ => false,
1631        };
1632        // If the batch is expired, clear the proposed batch.
1633        if is_expired {
1634            // Reset the proposed batch.
1635            let old = std::mem::replace(&mut *self.proposed_batch.write(), ProposedBatchState::None);
1636            if let ProposedBatchState::Certifying(proposal) = old {
1637                debug!("Cleared expired proposal for round {}", proposal.round());
1638                self.reinsert_transmissions_into_workers(proposal.into_transmissions())?;
1639            }
1640        }
1641        Ok(())
1642    }
1643
1644    /// Increments to the next round.
1645    async fn try_increment_to_the_next_round(&self, next_round: u64) -> Result<()> {
1646        // If the next round is within GC range, then iterate to the penultimate round.
1647        if self.current_round() + self.storage.max_gc_rounds() >= next_round {
1648            let mut fast_forward_round = self.current_round();
1649            // Iterate until the penultimate round is reached.
1650            while fast_forward_round < next_round.saturating_sub(1) {
1651                // Update to the next round in storage.
1652                fast_forward_round = self.storage.increment_to_next_round(fast_forward_round)?;
1653                // Clear the proposed batch.
1654                *self.proposed_batch.write() = ProposedBatchState::None;
1655            }
1656        }
1657
1658        // Retrieve the current round.
1659        let current_round = self.current_round();
1660        // Attempt to advance to the next round.
1661        if current_round < next_round {
1662            // If a BFT sender was provided, send the current round to the BFT.
1663            let is_ready = if let Some(cb) = self.primary_callback.get() {
1664                cb.try_advance_to_next_round(current_round)
1665            }
1666            // Otherwise, handle the Narwhal case.
1667            else {
1668                // Update to the next round in storage.
1669                self.storage.increment_to_next_round(current_round)?;
1670                // Set 'is_ready' to 'true'.
1671                true
1672            };
1673
1674            // Notify the proposal task if the new round is ready.
1675            if is_ready && self.is_synced() {
1676                debug!("Primary is ready to propose the next round");
1677                self.proposal_task.signal();
1678            } else {
1679                debug!("Primary is not ready to propose the next round");
1680            }
1681        }
1682        Ok(())
1683    }
1684
1685    /// Ensures the primary is signing for the specified batch round.
1686    /// This method is used to ensure: for a given round, as soon as the primary starts proposing,
1687    /// it will no longer sign for the previous round (as it has enough previous certificates to proceed).
1688    fn ensure_is_signing_round(&self, batch_round: u64) -> Result<()> {
1689        // Retrieve the current round.
1690        let current_round = self.current_round();
1691        // Ensure the batch round is within GC range of the current round.
1692        if current_round + self.storage.max_gc_rounds() <= batch_round {
1693            bail!("Round {batch_round} is too far in the future")
1694        }
1695        // Ensure the batch round is at or one before the current round.
1696        // Intuition: Our primary has moved on to the next round, but has not necessarily started proposing,
1697        // so we can still sign for the previous round. If we have started proposing, the next check will fail.
1698        if current_round > batch_round + 1 {
1699            bail!("Primary is on round {current_round}, and no longer signing for round {batch_round}")
1700        }
1701        // Check if the primary is still signing for the batch round.
1702        if let ProposedBatchState::Certifying(proposal) = &*self.proposed_batch.read()
1703            && proposal.round() > batch_round
1704        {
1705            bail!("Our primary at round {} is no longer signing for round {batch_round}", proposal.round())
1706        }
1707        Ok(())
1708    }
1709
1710    /// Ensure the primary is not creating batch proposals too frequently.
1711    /// This checks that the certificate timestamp for the previous round is within the expected range.
1712    fn check_peer_proposal_timestamp(&self, previous_round: u64, author: Address<N>, timestamp: i64) -> Result<()> {
1713        ensure!(author != self.gateway.account().address(), "Peer cannot propose a batch that is authored by myself");
1714
1715        // Retrieve the timestamp of the previous timestamp to check against.
1716        let previous_timestamp = match self.storage.get_certificate_for_round_with_author(previous_round, author) {
1717            // Ensure that the previous certificate was created at least `MIN_BATCH_DELAY` seconds ago.
1718            Some(certificate) => certificate.timestamp(),
1719            // If we do not see a previous certificate for the author, then proceed optimistically.
1720            None => return Ok(()),
1721        };
1722
1723        // Determine the elapsed time since the previous timestamp.
1724        let elapsed = timestamp
1725            .checked_sub(previous_timestamp)
1726            .ok_or_else(|| anyhow!("Timestamp cannot be before the previous certificate at round {previous_round}"))?;
1727        // Ensure that the previous certificate was created at least `MIN_BATCH_DELAY` seconds ago.
1728        match elapsed < MIN_BATCH_DELAY.as_secs() as i64 {
1729            true => bail!("Timestamp is too soon after the previous certificate at round {previous_round}"),
1730            false => Ok(()),
1731        }
1732    }
1733
1734    /// Ensure the primary is not creating batch proposals too frequently.
1735    /// This checks that the certificate timestamp for the previous round is within the expected range.
1736    ///
1737    /// # Returns
1738    /// - `Ok(true)` if the timestamp allows a new proposal.
1739    /// - `Ok(false)` if the timestamp is valid but too soon after the previous proposal.
1740    /// - `Err(err)` if an unexpected error occured, such as the timestamp being before the previous certificate.
1741    fn check_own_proposal_timestamp(
1742        &self,
1743        previous_round: u64,
1744        previous_timestamp: i64,
1745        timestamp: i64,
1746    ) -> Result<bool> {
1747        // Determine the elapsed time since the previous timestamp.
1748        let elapsed = timestamp
1749            .checked_sub(previous_timestamp)
1750            .ok_or_else(|| anyhow!("Timestamp cannot be before the previous certificate at round {previous_round}"))?;
1751
1752        Ok(elapsed >= MIN_BATCH_DELAY.as_secs() as i64)
1753    }
1754
1755    /// Stores the certified batch and broadcasts it to all validators, returning the certificate.
1756    async fn store_and_broadcast_certificate(&self, proposal: &Proposal<N>, committee: &Committee<N>) -> Result<()> {
1757        // Create the batch certificate and transmissions.
1758        let (certificate, transmissions) = tokio::task::block_in_place(|| proposal.to_certificate(committee))?;
1759
1760        // Convert the transmissions into a HashMap.
1761        // Note: Do not change the `Proposal` to use a HashMap. The ordering there is necessary for safety.
1762        let transmissions = transmissions.into_iter().collect::<HashMap<_, _>>();
1763
1764        // Store some metadata about the certified batch.
1765        let round = certificate.round();
1766        let num_transmissions = certificate.transmission_ids().len();
1767
1768        // Store the certified batch.
1769        let (storage, certificate_) = (self.storage.clone(), certificate.clone());
1770        spawn_blocking!(storage.insert_certificate(certificate_, transmissions, Default::default()))?;
1771        debug!("Stored a batch certificate for round {}", certificate.round());
1772        // The batch is now in storage, so late-arriving signatures can find it via contains_batch.
1773        // Transition from Certified back to None.
1774        *self.proposed_batch.write() = ProposedBatchState::None;
1775
1776        // If a BFT sender was provided, send the certificate to the BFT.
1777        if let Some(cb) = self.primary_callback.get() {
1778            // Await the callback to continue.
1779            cb.add_new_certificate(certificate.clone()).await.with_context(|| {
1780                format!("Failed to insert our newly certified batch for round {round} into the DAG")
1781            })?;
1782        }
1783        // Broadcast the certified batch to all validators.
1784        self.gateway.broadcast(Event::BatchCertified(certificate.into()));
1785
1786        // Log the certified batch.
1787        info!("Our batch with {num_transmissions} transmissions for round {round} was certified!");
1788
1789        // Record the certification latency (time from batch proposal to certification).
1790        #[cfg(feature = "metrics")]
1791        if let Some(start) = self.batch_propose_start.lock().take() {
1792            metrics::histogram(metrics::bft::BATCH_CERTIFICATION_LATENCY, start.elapsed().as_secs_f64());
1793        }
1794
1795        // Wake up the round increment task to re-check quorum.
1796        self.round_increment_notify.notify_one();
1797
1798        Ok(())
1799    }
1800
1801    /// Inserts the missing transmissions from the proposal into the workers.
1802    fn insert_missing_transmissions_into_workers(
1803        &self,
1804        peer_ip: SocketAddr,
1805        transmissions: impl Iterator<Item = (TransmissionID<N>, Transmission<N>)>,
1806    ) -> Result<()> {
1807        // Insert the transmissions into the workers.
1808        assign_to_workers(self.workers(), transmissions, |worker, transmission_id, transmission| {
1809            worker.process_transmission_from_peer(peer_ip, transmission_id, transmission);
1810        })
1811    }
1812
1813    /// Re-inserts the transmissions from the proposal into the workers.
1814    fn reinsert_transmissions_into_workers(
1815        &self,
1816        transmissions: IndexMap<TransmissionID<N>, Transmission<N>>,
1817    ) -> Result<()> {
1818        // Re-insert the transmissions into the workers.
1819        assign_to_workers(self.workers(), transmissions.into_iter(), |worker, transmission_id, transmission| {
1820            worker.reinsert(transmission_id, transmission);
1821        })
1822    }
1823
1824    /// Recursively stores a given batch certificate, after ensuring:
1825    ///   - Ensure the round matches the committee round.
1826    ///   - Ensure the address is a member of the committee.
1827    ///   - Ensure the timestamp is within range.
1828    ///   - Ensure we have all of the transmissions.
1829    ///   - Ensure we have all of the previous certificates.
1830    ///   - Ensure the previous certificates are for the previous round (i.e. round - 1).
1831    ///   - Ensure the previous certificates have reached the quorum threshold.
1832    ///   - Ensure we have not already signed the batch ID.
1833    #[async_recursion::async_recursion]
1834    async fn sync_with_certificate_from_peer<const IS_SYNCING: bool>(
1835        &self,
1836        peer_ip: SocketAddr,
1837        certificate: BatchCertificate<N>,
1838    ) -> Result<()> {
1839        // Retrieve the batch header.
1840        let batch_header = certificate.batch_header();
1841        // Retrieve the batch round.
1842        let batch_round = batch_header.round();
1843
1844        // If the certificate round is outdated, do not store it.
1845        if batch_round <= self.storage.gc_round() {
1846            return Ok(());
1847        }
1848        // If the certificate already exists in storage, return early.
1849        if self.storage.contains_certificate(certificate.id()) {
1850            return Ok(());
1851        }
1852
1853        // If node is not in sync mode and the node is not synced. Then return an error.
1854        if !IS_SYNCING && !self.is_synced() {
1855            bail!(
1856                "Failed to process certificate `{}` at round {batch_round} from '{peer_ip}' (node is syncing)",
1857                fmt_id(certificate.id())
1858            );
1859        }
1860
1861        // If the peer is ahead, use the batch header to sync up to the peer.
1862        let missing_transmissions =
1863            self.sync_with_batch_header_from_peer::<IS_SYNCING, false>(peer_ip, batch_header).await?;
1864
1865        // Check if the certificate needs to be stored.
1866        if !self.storage.contains_certificate(certificate.id()) {
1867            // Store the batch certificate.
1868            let (storage, certificate_) = (self.storage.clone(), certificate.clone());
1869            spawn_blocking!(storage.insert_certificate(certificate_, missing_transmissions, Default::default()))?;
1870            debug!("Stored a batch certificate for round {batch_round} from '{peer_ip}'");
1871            // If a BFT sender was provided, send the round and certificate to the BFT.
1872            if let Some(cb) = self.primary_callback.get() {
1873                cb.add_new_certificate(certificate).await.with_context(|| "Failed to update the DAG from sync")?;
1874            }
1875            // Wake the round-increment task to re-check quorum.
1876            self.round_increment_notify.notify_one();
1877        }
1878        Ok(())
1879    }
1880
1881    /// Recursively syncs using the given batch header.
1882    async fn sync_with_batch_header_from_peer<const IS_SYNCING: bool, const CHECK_PREVIOUS_CERTIFICATES: bool>(
1883        &self,
1884        peer_ip: SocketAddr,
1885        batch_header: &BatchHeader<N>,
1886    ) -> Result<HashMap<TransmissionID<N>, Transmission<N>>> {
1887        // Retrieve the batch round.
1888        let batch_round = batch_header.round();
1889
1890        // If the certificate round is outdated, do not store it.
1891        if batch_round <= self.storage.gc_round() {
1892            bail!("Round {batch_round} is too far in the past")
1893        }
1894
1895        // If node is not in sync mode and the node is not synced, then return an error.
1896        if !IS_SYNCING && !self.is_synced() {
1897            bail!(
1898                "Failed to process batch header `{}` at round {batch_round} from '{peer_ip}' (node is syncing)",
1899                fmt_id(batch_header.batch_id())
1900            );
1901        }
1902
1903        // Determine if quorum threshold is reached on the batch round.
1904        let is_quorum_threshold_reached = {
1905            let authors = self.storage.get_certificate_authors_for_round(batch_round);
1906            let committee_lookback = self.ledger.get_committee_lookback_for_round(batch_round)?;
1907            committee_lookback.is_quorum_threshold_reached(&authors)
1908        };
1909
1910        // Check if our primary should move to the next round.
1911        // Note: Checking that quorum threshold is reached is important for mitigating a race condition,
1912        // whereby Narwhal requires N-f, however the BFT only requires f+1. Without this check, the primary
1913        // will advance to the next round assuming f+1, not N-f, which can lead to a network stall.
1914        let is_behind_schedule = is_quorum_threshold_reached && batch_round > self.current_round();
1915        // Check if our primary is far behind the peer.
1916        let is_peer_far_in_future = batch_round > self.current_round() + self.storage.max_gc_rounds();
1917        // If our primary is far behind the peer, update our committee to the batch round.
1918        if is_behind_schedule || is_peer_far_in_future {
1919            // If the batch round is greater than the current committee round, update the committee.
1920            self.try_increment_to_the_next_round(batch_round)
1921                .await
1922                .with_context(|| "Failed to fast forward current round")?;
1923        }
1924
1925        // Ensure the primary has all of the transmissions.
1926        let missing_transmissions_handle = self.fetch_missing_transmissions(peer_ip, batch_header);
1927
1928        // Ensure the primary has all of the previous certificates.
1929        let missing_previous_certificates_handle = self.fetch_missing_previous_certificates(peer_ip, batch_header);
1930
1931        // Wait for the missing transmissions and previous certificates to be fetched.
1932        let (missing_transmissions, missing_previous_certificates) = tokio::try_join!(
1933            missing_transmissions_handle,
1934            missing_previous_certificates_handle,
1935        ).with_context(|| format!("Failed to fetch missing transmissions and previous certificates for round {batch_round} from '{peer_ip}"))?;
1936
1937        // Iterate through the missing previous certificates sequentially.
1938        // This is done sequentially to avoid requesting a large number of certificates from peers all at once.
1939        // TODO (raychu86): Optimize this by parallelizing requests, but avoiding duplicated requests since certificates are likely shared across batches.
1940        for batch_certificate in missing_previous_certificates {
1941            // Check if the missing previous certificate is valid. This is only
1942            // needed if we are processing an incoming batch header from a peer.
1943            // For incoming certificates, validity is assured by checking the
1944            // root certificate in `process_batch_certificate_from_peer`.
1945            if CHECK_PREVIOUS_CERTIFICATES {
1946                self.storage.check_incoming_certificate(&batch_certificate)?;
1947            }
1948            // Store the batch certificate (recursively fetching any missing previous certificates).
1949            self.sync_with_certificate_from_peer::<IS_SYNCING>(peer_ip, batch_certificate).await?;
1950        }
1951        Ok(missing_transmissions)
1952    }
1953
1954    /// Fetches any missing transmissions for the specified batch header.
1955    /// If a transmission does not exist, it will be fetched from the specified peer IP.
1956    async fn fetch_missing_transmissions(
1957        &self,
1958        peer_ip: SocketAddr,
1959        batch_header: &BatchHeader<N>,
1960    ) -> Result<HashMap<TransmissionID<N>, Transmission<N>>> {
1961        // If the round is <= the GC round, return early.
1962        if batch_header.round() <= self.storage.gc_round() {
1963            return Ok(Default::default());
1964        }
1965
1966        // Ensure this batch ID is new, otherwise return early.
1967        if self.storage.contains_batch(batch_header.batch_id()) {
1968            trace!("Batch for round {} from peer has already been processed", batch_header.round());
1969            return Ok(Default::default());
1970        }
1971
1972        // Retrieve the workers.
1973        let workers = self.workers.clone();
1974
1975        // Initialize a list for the transmissions.
1976        let mut fetch_transmissions = FuturesUnordered::new();
1977
1978        // Retrieve the number of workers.
1979        let num_workers = self.num_workers();
1980        // Iterate through the transmission IDs.
1981        for transmission_id in batch_header.transmission_ids() {
1982            // If the transmission does not exist in storage, proceed to fetch the transmission.
1983            if !self.storage.contains_transmission(*transmission_id) {
1984                // Determine the worker ID.
1985                let Ok(worker_id) = assign_to_worker(*transmission_id, num_workers) else {
1986                    bail!("Unable to assign transmission ID '{transmission_id}' to a worker")
1987                };
1988                // Retrieve the worker.
1989                let Some(worker) = workers.get().expect("No workers set").get(worker_id as usize) else {
1990                    bail!("Unable to find worker {worker_id}")
1991                };
1992                // Push the callback onto the list.
1993                fetch_transmissions.push(worker.get_or_fetch_transmission(peer_ip, *transmission_id));
1994            }
1995        }
1996
1997        // Initialize a set for the transmissions.
1998        let mut transmissions = HashMap::with_capacity(fetch_transmissions.len());
1999        // Wait for all of the transmissions to be fetched.
2000        while let Some(result) = fetch_transmissions.next().await {
2001            // Retrieve the transmission.
2002            let (transmission_id, transmission) = result?;
2003            // Insert the transmission into the set.
2004            transmissions.insert(transmission_id, transmission);
2005        }
2006        // Return the transmissions.
2007        Ok(transmissions)
2008    }
2009
2010    /// Fetches any missing previous certificates for the specified batch header from the specified peer.
2011    async fn fetch_missing_previous_certificates(
2012        &self,
2013        peer_ip: SocketAddr,
2014        batch_header: &BatchHeader<N>,
2015    ) -> Result<HashSet<BatchCertificate<N>>> {
2016        // Retrieve the round.
2017        let round = batch_header.round();
2018        // If the previous round is 0, or is <= the GC round, return early.
2019        if round == 1 || round <= self.storage.gc_round() + 1 {
2020            return Ok(Default::default());
2021        }
2022
2023        // Fetch the missing previous certificates.
2024        let missing_previous_certificates =
2025            self.fetch_missing_certificates(peer_ip, round, batch_header.previous_certificate_ids()).await?;
2026        if !missing_previous_certificates.is_empty() {
2027            debug!(
2028                "Fetched {} missing previous certificates for round {round} from '{peer_ip}'",
2029                missing_previous_certificates.len(),
2030            );
2031        }
2032        // Return the missing previous certificates.
2033        Ok(missing_previous_certificates)
2034    }
2035
2036    /// Fetches any missing certificates for the specified batch header from the specified peer.
2037    async fn fetch_missing_certificates(
2038        &self,
2039        peer_ip: SocketAddr,
2040        round: u64,
2041        certificate_ids: &IndexSet<Field<N>>,
2042    ) -> Result<HashSet<BatchCertificate<N>>> {
2043        // Initialize a list for the missing certificates.
2044        let mut fetch_certificates = FuturesUnordered::new();
2045        // Initialize a set for the missing certificates.
2046        let mut missing_certificates = HashSet::default();
2047        // Iterate through the certificate IDs.
2048        for certificate_id in certificate_ids {
2049            // Check if the certificate already exists in the ledger.
2050            if self.ledger.contains_certificate(certificate_id)? {
2051                continue;
2052            }
2053            // Check if the certificate already exists in storage.
2054            if self.storage.contains_certificate(*certificate_id) {
2055                continue;
2056            }
2057            // If we have not fully processed the certificate yet, store it.
2058            if let Some(certificate) = self.storage.get_unprocessed_certificate(*certificate_id) {
2059                missing_certificates.insert(certificate);
2060            } else {
2061                // If we do not have the certificate, request it.
2062                trace!("Primary - Found a new certificate ID for round {round} from '{peer_ip}'");
2063                // TODO (howardwu): Limit the number of open requests we send to a peer.
2064                // Send an certificate request to the peer.
2065                fetch_certificates.push(self.sync.send_certificate_request(peer_ip, *certificate_id));
2066            }
2067        }
2068
2069        // If there are no certificates to fetch, return early with the existing unprocessed certificates.
2070        match fetch_certificates.is_empty() {
2071            true => return Ok(missing_certificates),
2072            false => trace!(
2073                "Fetching {} missing certificates for round {round} from '{peer_ip}'...",
2074                fetch_certificates.len(),
2075            ),
2076        }
2077
2078        // Wait for all of the missing certificates to be fetched.
2079        while let Some(result) = fetch_certificates.next().await {
2080            // Insert the missing certificate into the set.
2081            missing_certificates.insert(result?);
2082        }
2083        // Return the missing certificates.
2084        Ok(missing_certificates)
2085    }
2086}
2087
2088impl<N: Network> Primary<N> {
2089    /// Spawns a task with the given future; it should only be used for long-running tasks.
2090    fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
2091        self.handles.lock().push(tokio::spawn(future));
2092    }
2093
2094    /// Shuts down the primary.
2095    pub async fn shut_down(&self) {
2096        info!("Shutting down the primary...");
2097        // Remove the callback.
2098        self.primary_callback.clear();
2099        // Shut down the sync service.
2100        self.sync.shut_down().await;
2101        // Shut down the workers.
2102        self.workers().iter().for_each(|worker| worker.shut_down());
2103        // Abort the tasks.
2104        self.handles.lock().drain(..).for_each(|handle| handle.abort());
2105        // Save the current proposal cache to disk.
2106        let proposal_cache = {
2107            // Only persist a Certifying batch; a Certified batch will appear in pending_certificates.
2108            // Note: it is guaranteed that there are no concurrent accesses to `proposed_batch` as all
2109            // background tasks already terminated at this point.
2110            let proposal = match std::mem::replace(&mut *self.proposed_batch.write(), ProposedBatchState::None) {
2111                ProposedBatchState::Certifying(p) => Some(*p),
2112                _ => None,
2113            };
2114            let signed_proposals = self.signed_proposals.read().clone();
2115            let latest_round = proposal
2116                .as_ref()
2117                .map(Proposal::round)
2118                .unwrap_or(self.latest_proposal_timestamp.read().await.map(|(round, _)| round).unwrap_or(0));
2119            let pending_certificates = self.storage.get_pending_certificates();
2120            ProposalCache::new(latest_round, proposal, signed_proposals, pending_certificates)
2121        };
2122        if let Err(err) = proposal_cache.store(&self.node_data_dir) {
2123            error!("{}", flatten_error(err.context("Failed to store the current proposal cache")));
2124        }
2125        // Close the gateway.
2126        self.gateway.shut_down().await;
2127    }
2128}
2129
2130#[cfg(test)]
2131mod tests {
2132    use super::{proposal_task::BatchPropose as _, *};
2133
2134    use snarkos_node_bft_ledger_service::MockLedgerService;
2135    use snarkos_node_bft_storage_service::BFTMemoryService;
2136    use snarkos_node_sync::{BlockSync, locators::test_helpers::sample_block_locators};
2137    use snarkvm::{
2138        ledger::{
2139            committee::{Committee, MIN_VALIDATOR_STAKE},
2140            test_helpers::sample_execution_transaction_with_fee,
2141        },
2142        prelude::{Address, Signature},
2143    };
2144
2145    use bytes::Bytes;
2146    use indexmap::IndexSet;
2147    use rand::RngExt;
2148
2149    type CurrentNetwork = snarkvm::prelude::MainnetV0;
2150
2151    fn sample_committee(rng: &mut TestRng) -> (Vec<(SocketAddr, Account<CurrentNetwork>)>, Committee<CurrentNetwork>) {
2152        // Create a committee containing the primary's account.
2153        const COMMITTEE_SIZE: usize = 4;
2154        let mut accounts = Vec::with_capacity(COMMITTEE_SIZE);
2155        let mut members = IndexMap::new();
2156
2157        for i in 0..COMMITTEE_SIZE {
2158            let socket_addr = format!("127.0.0.1:{}", 5000 + i).parse().unwrap();
2159            let account = Account::new(rng).unwrap();
2160
2161            members.insert(account.address(), (MIN_VALIDATOR_STAKE, true, rng.random_range(0..100)));
2162            accounts.push((socket_addr, account));
2163        }
2164
2165        (accounts, Committee::<CurrentNetwork>::new(1, members).unwrap())
2166    }
2167
2168    // Returns a primary and a list of accounts in the configured committee.
2169    fn primary_with_committee(
2170        account_index: usize,
2171        accounts: &[(SocketAddr, Account<CurrentNetwork>)],
2172        committee: Committee<CurrentNetwork>,
2173        height: u32,
2174    ) -> Primary<CurrentNetwork> {
2175        let ledger = Arc::new(MockLedgerService::new_at_height(committee, height));
2176        let storage = Storage::new(ledger.clone(), Arc::new(BFTMemoryService::new()), 10).unwrap();
2177
2178        // Initialize the primary.
2179        let account = accounts[account_index].1.clone();
2180        let block_sync = Arc::new(BlockSync::new(ledger.clone(), ConnectionMode::Gateway));
2181        let primary =
2182            Primary::new(account, storage, ledger, block_sync, None, &[], false, NodeDataDir::new_test(None), None)
2183                .unwrap();
2184
2185        // Construct a worker instance.
2186        let worker = Worker::new(
2187            0, // id
2188            Arc::new(primary.gateway.clone()),
2189            primary.storage.clone(),
2190            primary.ledger.clone(),
2191            primary.proposed_batch.clone(),
2192        )
2193        .unwrap();
2194        let _ = primary.workers.set(vec![worker]);
2195        for a in accounts.iter().skip(account_index) {
2196            primary.gateway.insert_connected_peer(a.0, a.0, a.1.address());
2197        }
2198
2199        primary
2200    }
2201
2202    fn primary_without_handlers(
2203        rng: &mut TestRng,
2204    ) -> (Primary<CurrentNetwork>, Vec<(SocketAddr, Account<CurrentNetwork>)>) {
2205        let (accounts, committee) = sample_committee(rng);
2206        let primary = primary_with_committee(
2207            0, // index of primary's account
2208            &accounts,
2209            committee,
2210            CurrentNetwork::CONSENSUS_HEIGHT(ConsensusVersion::V1).unwrap(),
2211        );
2212
2213        (primary, accounts)
2214    }
2215
2216    // Creates a mock solution.
2217    fn sample_unconfirmed_solution(rng: &mut TestRng) -> (SolutionID<CurrentNetwork>, Data<Solution<CurrentNetwork>>) {
2218        // Sample a random fake solution ID.
2219        let solution_id = rng.random::<u64>().into();
2220        // Vary the size of the solutions.
2221        let size = rng.random_range(1024..10 * 1024);
2222        // Sample random fake solution bytes.
2223        let vec: Vec<u8> = (0..size).map(|_| rng.random::<u8>()).collect();
2224        let solution = Data::Buffer(Bytes::from(vec));
2225        // Return the solution ID and solution.
2226        (solution_id, solution)
2227    }
2228
2229    // Samples a test transaction.
2230    fn sample_unconfirmed_transaction(
2231        rng: &mut TestRng,
2232    ) -> (<CurrentNetwork as Network>::TransactionID, Data<Transaction<CurrentNetwork>>) {
2233        let transaction = sample_execution_transaction_with_fee(false, rng, 0);
2234        let id = transaction.id();
2235
2236        (id, Data::Object(transaction))
2237    }
2238
2239    // Creates a batch proposal with one solution and one transaction.
2240    fn create_test_proposal(
2241        author: &Account<CurrentNetwork>,
2242        committee: Committee<CurrentNetwork>,
2243        round: u64,
2244        previous_certificate_ids: IndexSet<Field<CurrentNetwork>>,
2245        timestamp: i64,
2246        num_transactions: u64,
2247        rng: &mut TestRng,
2248    ) -> Proposal<CurrentNetwork> {
2249        let mut transmission_ids = IndexSet::new();
2250        let mut transmissions = IndexMap::new();
2251
2252        // Prepare the solution and insert into the sets.
2253        let (solution_id, solution) = sample_unconfirmed_solution(rng);
2254        let solution_checksum = solution.to_checksum::<CurrentNetwork>().unwrap();
2255        let solution_transmission_id = (solution_id, solution_checksum).into();
2256        transmission_ids.insert(solution_transmission_id);
2257        transmissions.insert(solution_transmission_id, Transmission::Solution(solution));
2258
2259        // Prepare the transactions and insert into the sets.
2260        for _ in 0..num_transactions {
2261            let (transaction_id, transaction) = sample_unconfirmed_transaction(rng);
2262            let transaction_checksum = transaction.to_checksum::<CurrentNetwork>().unwrap();
2263            let transaction_transmission_id = (&transaction_id, &transaction_checksum).into();
2264            transmission_ids.insert(transaction_transmission_id);
2265            transmissions.insert(transaction_transmission_id, Transmission::Transaction(transaction));
2266        }
2267
2268        // Retrieve the private key.
2269        let private_key = author.private_key();
2270        // Sign the batch header.
2271        let batch_header = BatchHeader::new(
2272            private_key,
2273            round,
2274            timestamp,
2275            committee.id(),
2276            transmission_ids,
2277            previous_certificate_ids,
2278            rng,
2279        )
2280        .unwrap();
2281        // Construct the proposal.
2282        Proposal::new(committee, batch_header, transmissions).unwrap()
2283    }
2284
2285    // Creates a signature of the primary's current proposal for each committee member (excluding
2286    // the primary).
2287    fn peer_signatures_for_proposal(
2288        primary: &Primary<CurrentNetwork>,
2289        accounts: &[(SocketAddr, Account<CurrentNetwork>)],
2290        rng: &mut TestRng,
2291    ) -> Vec<(SocketAddr, BatchSignature<CurrentNetwork>)> {
2292        // Each committee member signs the batch.
2293        let mut signatures = Vec::with_capacity(accounts.len() - 1);
2294        for (socket_addr, account) in accounts {
2295            if account.address() == primary.gateway.account().address() {
2296                continue;
2297            }
2298            let batch_id = primary.proposed_batch.read().as_proposal().unwrap().batch_id();
2299            let signature = account.sign(&[batch_id], rng).unwrap();
2300            signatures.push((*socket_addr, BatchSignature::new(batch_id, signature)));
2301        }
2302
2303        signatures
2304    }
2305
2306    /// Creates a signature of the batch ID for each committee member (excluding the primary).
2307    fn peer_signatures_for_batch(
2308        primary_address: Address<CurrentNetwork>,
2309        accounts: &[(SocketAddr, Account<CurrentNetwork>)],
2310        batch_id: Field<CurrentNetwork>,
2311        rng: &mut TestRng,
2312    ) -> IndexSet<Signature<CurrentNetwork>> {
2313        let mut signatures = IndexSet::new();
2314        for (_, account) in accounts {
2315            if account.address() == primary_address {
2316                continue;
2317            }
2318            let signature = account.sign(&[batch_id], rng).unwrap();
2319            signatures.insert(signature);
2320        }
2321        signatures
2322    }
2323
2324    // Creates a batch certificate.
2325    fn create_batch_certificate(
2326        primary_address: Address<CurrentNetwork>,
2327        accounts: &[(SocketAddr, Account<CurrentNetwork>)],
2328        round: u64,
2329        previous_certificate_ids: IndexSet<Field<CurrentNetwork>>,
2330        rng: &mut TestRng,
2331    ) -> (BatchCertificate<CurrentNetwork>, HashMap<TransmissionID<CurrentNetwork>, Transmission<CurrentNetwork>>) {
2332        let timestamp = now();
2333
2334        let author =
2335            accounts.iter().find(|&(_, acct)| acct.address() == primary_address).map(|(_, acct)| acct.clone()).unwrap();
2336        let private_key = author.private_key();
2337
2338        let committee_id = Field::rand(rng);
2339        let (solution_id, solution) = sample_unconfirmed_solution(rng);
2340        let (transaction_id, transaction) = sample_unconfirmed_transaction(rng);
2341        let solution_checksum = solution.to_checksum::<CurrentNetwork>().unwrap();
2342        let transaction_checksum = transaction.to_checksum::<CurrentNetwork>().unwrap();
2343
2344        let solution_transmission_id = (solution_id, solution_checksum).into();
2345        let transaction_transmission_id = (&transaction_id, &transaction_checksum).into();
2346
2347        let transmission_ids = [solution_transmission_id, transaction_transmission_id].into();
2348        let transmissions = [
2349            (solution_transmission_id, Transmission::Solution(solution)),
2350            (transaction_transmission_id, Transmission::Transaction(transaction)),
2351        ]
2352        .into();
2353
2354        let batch_header = BatchHeader::new(
2355            private_key,
2356            round,
2357            timestamp,
2358            committee_id,
2359            transmission_ids,
2360            previous_certificate_ids,
2361            rng,
2362        )
2363        .unwrap();
2364        let signatures = peer_signatures_for_batch(primary_address, accounts, batch_header.batch_id(), rng);
2365        let certificate = BatchCertificate::<CurrentNetwork>::from(batch_header, signatures).unwrap();
2366        (certificate, transmissions)
2367    }
2368
2369    // Create a certificate chain up to, but not including, the specified round in the primary storage.
2370    fn store_certificate_chain(
2371        primary: &Primary<CurrentNetwork>,
2372        accounts: &[(SocketAddr, Account<CurrentNetwork>)],
2373        round: u64,
2374        rng: &mut TestRng,
2375    ) -> IndexSet<Field<CurrentNetwork>> {
2376        let mut previous_certificates = IndexSet::<Field<CurrentNetwork>>::new();
2377        let mut next_certificates = IndexSet::<Field<CurrentNetwork>>::new();
2378        for cur_round in 1..round {
2379            for (_, account) in accounts.iter() {
2380                let (certificate, transmissions) = create_batch_certificate(
2381                    account.address(),
2382                    accounts,
2383                    cur_round,
2384                    previous_certificates.clone(),
2385                    rng,
2386                );
2387                next_certificates.insert(certificate.id());
2388                assert!(primary.storage.insert_certificate(certificate, transmissions, Default::default()).is_ok());
2389            }
2390
2391            assert!(primary.storage.increment_to_next_round(cur_round).is_ok());
2392            previous_certificates = next_certificates;
2393            next_certificates = IndexSet::<Field<CurrentNetwork>>::new();
2394        }
2395
2396        previous_certificates
2397    }
2398
2399    // Insert the account socket addresses into the resolver so that
2400    // they are recognized as "connected".
2401    fn map_account_addresses(primary: &Primary<CurrentNetwork>, accounts: &[(SocketAddr, Account<CurrentNetwork>)]) {
2402        // First account is primary, which doesn't need to resolve.
2403        for (addr, acct) in accounts.iter().skip(1) {
2404            primary.gateway.resolver().write().insert_peer(*addr, *addr, Some(acct.address()));
2405        }
2406    }
2407
2408    #[test_log::test(tokio::test)]
2409    async fn test_propose_batch() {
2410        let mut rng = TestRng::default();
2411        let (primary, _) = primary_without_handlers(&mut rng);
2412
2413        // Check there is no batch currently proposed.
2414        assert!(primary.proposed_batch.read().is_none());
2415
2416        // Generate a solution and a transaction.
2417        let (solution_id, solution) = sample_unconfirmed_solution(&mut rng);
2418        let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
2419
2420        // Store it on one of the workers.
2421        primary.workers()[0].process_unconfirmed_solution(solution_id, solution).await.unwrap();
2422        primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
2423
2424        // Try to propose a batch again. This time, it should succeed.
2425        assert!(primary.propose_batch().await.is_ok());
2426        assert!(primary.proposed_batch.read().is_proposed());
2427    }
2428
2429    #[test_log::test(tokio::test)]
2430    async fn test_propose_batch_with_no_transmissions() {
2431        let mut rng = TestRng::default();
2432        let (primary, _) = primary_without_handlers(&mut rng);
2433
2434        // Check there is no batch currently proposed.
2435        assert!(primary.proposed_batch.read().is_none());
2436
2437        // Try to propose a batch with no transmissions.
2438        assert!(primary.propose_batch().await.is_ok());
2439        assert!(primary.proposed_batch.read().is_proposed());
2440    }
2441
2442    #[test_log::test(tokio::test)]
2443    async fn test_propose_batch_in_round() {
2444        let round = 3;
2445        let mut rng = TestRng::default();
2446        let (primary, accounts) = primary_without_handlers(&mut rng);
2447
2448        // Fill primary storage.
2449        store_certificate_chain(&primary, &accounts, round, &mut rng);
2450
2451        // Sleep for a while to ensure the primary is ready to propose the next round.
2452        tokio::time::sleep(MIN_BATCH_DELAY).await;
2453
2454        // Generate a solution and a transaction.
2455        let (solution_id, solution) = sample_unconfirmed_solution(&mut rng);
2456        let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
2457
2458        // Store it on one of the workers.
2459        primary.workers()[0].process_unconfirmed_solution(solution_id, solution).await.unwrap();
2460        primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
2461
2462        // Propose a batch again. This time, it should succeed.
2463        assert!(primary.propose_batch().await.is_ok());
2464        assert!(primary.proposed_batch.read().is_proposed());
2465    }
2466
2467    #[test_log::test(tokio::test)]
2468    async fn test_propose_batch_skip_transmissions_from_previous_certificates() {
2469        let round = 3;
2470        let prev_round = round - 1;
2471        let mut rng = TestRng::default();
2472        let (primary, accounts) = primary_without_handlers(&mut rng);
2473        let peer_account = &accounts[1];
2474        let peer_ip = peer_account.0;
2475
2476        // Fill primary storage.
2477        store_certificate_chain(&primary, &accounts, round, &mut rng);
2478
2479        // Get transmissions from previous certificates.
2480        let previous_certificate_ids: IndexSet<_> = primary.storage.get_certificate_ids_for_round(prev_round);
2481
2482        // Track the number of transmissions in the previous round.
2483        let mut num_transmissions_in_previous_round = 0;
2484
2485        // Generate a solution and a transaction.
2486        let (solution_commitment, solution) = sample_unconfirmed_solution(&mut rng);
2487        let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
2488        let solution_checksum = solution.to_checksum::<CurrentNetwork>().unwrap();
2489        let transaction_checksum = transaction.to_checksum::<CurrentNetwork>().unwrap();
2490
2491        // Store it on one of the workers.
2492        primary.workers()[0].process_unconfirmed_solution(solution_commitment, solution).await.unwrap();
2493        primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
2494
2495        // Check that the worker has 2 transmissions.
2496        assert_eq!(primary.workers()[0].num_transmissions(), 2);
2497
2498        // Create certificates for the current round and add the transmissions to the worker before inserting the certificate to storage.
2499        for (_, account) in accounts.iter() {
2500            let (certificate, transmissions) = create_batch_certificate(
2501                account.address(),
2502                &accounts,
2503                round,
2504                previous_certificate_ids.clone(),
2505                &mut rng,
2506            );
2507
2508            // Add the transmissions to the worker.
2509            for (transmission_id, transmission) in transmissions.iter() {
2510                primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone());
2511            }
2512
2513            // Insert the certificate to storage.
2514            num_transmissions_in_previous_round += transmissions.len();
2515            primary.storage.insert_certificate(certificate, transmissions, Default::default()).unwrap();
2516        }
2517
2518        // Sleep for a while to ensure the primary is ready to propose the next round.
2519        tokio::time::sleep(MIN_BATCH_DELAY).await;
2520
2521        // Advance to the next round.
2522        assert!(primary.storage.increment_to_next_round(round).is_ok());
2523
2524        // Check that the worker has `num_transmissions_in_previous_round + 2` transmissions.
2525        assert_eq!(primary.workers()[0].num_transmissions(), num_transmissions_in_previous_round + 2);
2526
2527        // Propose the batch.
2528        assert!(primary.propose_batch().await.is_ok());
2529
2530        // Check that the proposal only contains the new transmissions that were not in previous certificates.
2531        let proposed_transmissions = primary.proposed_batch.read().as_proposal().unwrap().transmissions().clone();
2532        assert_eq!(proposed_transmissions.len(), 2);
2533        assert!(proposed_transmissions.contains_key(&TransmissionID::Solution(solution_commitment, solution_checksum)));
2534        assert!(
2535            proposed_transmissions.contains_key(&TransmissionID::Transaction(transaction_id, transaction_checksum))
2536        );
2537    }
2538
2539    #[test_log::test(tokio::test)]
2540    async fn test_propose_batch_over_spend_limit() {
2541        let mut rng = TestRng::default();
2542
2543        // Create a primary to test spend limit backwards compatibility with V4.
2544        let (accounts, committee) = sample_committee(&mut rng);
2545        let primary = primary_with_committee(
2546            0,
2547            &accounts,
2548            committee.clone(),
2549            CurrentNetwork::CONSENSUS_HEIGHT(ConsensusVersion::V4).unwrap(),
2550        );
2551
2552        // Check there is no batch currently proposed.
2553        assert!(primary.proposed_batch.read().is_none());
2554        // Check the workers are empty.
2555        primary.workers().iter().for_each(|worker| assert!(worker.transmissions().is_empty()));
2556
2557        // Generate a solution and transactions.
2558        let (solution_id, solution) = sample_unconfirmed_solution(&mut rng);
2559        primary.workers()[0].process_unconfirmed_solution(solution_id, solution).await.unwrap();
2560
2561        for _i in 0..5 {
2562            let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
2563            // Store it on one of the workers.
2564            primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
2565        }
2566
2567        // Try to propose a batch again. This time, it should succeed.
2568        assert!(primary.propose_batch().await.is_ok());
2569        // Expect 2/5 transactions to be included in the proposal in addition to the solution.
2570        assert_eq!(primary.proposed_batch.read().as_proposal().unwrap().transmissions().len(), 3);
2571        // Check the transmissions were correctly drained from the workers.
2572        assert_eq!(primary.workers().iter().map(|worker| worker.transmissions().len()).sum::<usize>(), 3);
2573    }
2574
2575    #[test_log::test(tokio::test)]
2576    async fn test_batch_propose_from_peer() {
2577        let mut rng = TestRng::default();
2578        let (primary, accounts) = primary_without_handlers(&mut rng);
2579
2580        // Create a valid proposal with an author that isn't the primary.
2581        let round = 1;
2582        let peer_account = &accounts[1];
2583        let peer_ip = peer_account.0;
2584        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2585        let proposal = create_test_proposal(
2586            &peer_account.1,
2587            primary.ledger.current_committee().unwrap(),
2588            round,
2589            Default::default(),
2590            timestamp,
2591            1,
2592            &mut rng,
2593        );
2594
2595        // Make sure the primary is aware of the transmissions in the proposal.
2596        for (transmission_id, transmission) in proposal.transmissions() {
2597            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2598        }
2599
2600        // The author must be known to resolver to pass propose checks.
2601        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2602
2603        // The primary will only consider itself synced if we received
2604        // block locators from a peer.
2605        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(20)).unwrap();
2606        primary.sync.testing_only_set_sync_height_testing_only(20);
2607
2608        // Try to process the batch proposal from the peer, should succeed.
2609        assert!(
2610            primary.process_batch_propose_from_peer(peer_ip, (*proposal.batch_header()).clone().into()).await.is_ok()
2611        );
2612    }
2613
2614    #[test_log::test(tokio::test)]
2615    async fn test_batch_propose_from_peer_when_not_synced() {
2616        let mut rng = TestRng::default();
2617        let (primary, accounts) = primary_without_handlers(&mut rng);
2618
2619        // Create a valid proposal with an author that isn't the primary.
2620        let round = 1;
2621        let peer_account = &accounts[1];
2622        let peer_ip = peer_account.0;
2623        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2624        let proposal = create_test_proposal(
2625            &peer_account.1,
2626            primary.ledger.current_committee().unwrap(),
2627            round,
2628            Default::default(),
2629            timestamp,
2630            1,
2631            &mut rng,
2632        );
2633
2634        // Make sure the primary is aware of the transmissions in the proposal.
2635        for (transmission_id, transmission) in proposal.transmissions() {
2636            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2637        }
2638
2639        // The author must be known to resolver to pass propose checks.
2640        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2641
2642        // Add a high block locator to indicate we are not synced.
2643        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(20)).unwrap();
2644
2645        // Try to process the batch proposal from the peer, should fail
2646        assert!(
2647            primary.process_batch_propose_from_peer(peer_ip, (*proposal.batch_header()).clone().into()).await.is_err()
2648        );
2649    }
2650
2651    #[test_log::test(tokio::test)]
2652    async fn test_batch_propose_from_peer_in_round() {
2653        let round = 2;
2654        let mut rng = TestRng::default();
2655        let (primary, accounts) = primary_without_handlers(&mut rng);
2656
2657        // Generate certificates.
2658        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
2659
2660        // Create a valid proposal with an author that isn't the primary.
2661        let peer_account = &accounts[1];
2662        let peer_ip = peer_account.0;
2663        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2664        let proposal = create_test_proposal(
2665            &peer_account.1,
2666            primary.ledger.current_committee().unwrap(),
2667            round,
2668            previous_certificates,
2669            timestamp,
2670            1,
2671            &mut rng,
2672        );
2673
2674        // Make sure the primary is aware of the transmissions in the proposal.
2675        for (transmission_id, transmission) in proposal.transmissions() {
2676            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2677        }
2678
2679        // The author must be known to resolver to pass propose checks.
2680        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2681
2682        // The primary will only consider itself synced if we received
2683        // block locators from a peer.
2684        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(20)).unwrap();
2685        primary.sync.testing_only_set_sync_height_testing_only(20);
2686
2687        // Try to process the batch proposal from the peer, should succeed.
2688        primary.process_batch_propose_from_peer(peer_ip, (*proposal.batch_header()).clone().into()).await.unwrap();
2689    }
2690
2691    #[test_log::test(tokio::test)]
2692    async fn test_batch_propose_from_peer_wrong_round() {
2693        let mut rng = TestRng::default();
2694        let (primary, accounts) = primary_without_handlers(&mut rng);
2695
2696        // Create a valid proposal with an author that isn't the primary.
2697        let round = 1;
2698        let peer_account = &accounts[1];
2699        let peer_ip = peer_account.0;
2700        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2701        let proposal = create_test_proposal(
2702            &peer_account.1,
2703            primary.ledger.current_committee().unwrap(),
2704            round,
2705            Default::default(),
2706            timestamp,
2707            1,
2708            &mut rng,
2709        );
2710
2711        // Make sure the primary is aware of the transmissions in the proposal.
2712        for (transmission_id, transmission) in proposal.transmissions() {
2713            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2714        }
2715
2716        // The author must be known to resolver to pass propose checks.
2717        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2718        // The primary must be considered synced.
2719        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(20)).unwrap();
2720        primary.sync.testing_only_set_sync_height_testing_only(20);
2721
2722        // Try to process the batch proposal from the peer, should error.
2723        assert!(
2724            primary
2725                .process_batch_propose_from_peer(peer_ip, BatchPropose {
2726                    round: round + 1,
2727                    batch_header: Data::Object(proposal.batch_header().clone())
2728                })
2729                .await
2730                .is_err()
2731        );
2732    }
2733
2734    #[test_log::test(tokio::test)]
2735    async fn test_batch_propose_from_peer_in_round_wrong_round() {
2736        let round = 4;
2737        let mut rng = TestRng::default();
2738        let (primary, accounts) = primary_without_handlers(&mut rng);
2739
2740        // Generate certificates.
2741        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
2742
2743        // Create a valid proposal with an author that isn't the primary.
2744        let peer_account = &accounts[1];
2745        let peer_ip = peer_account.0;
2746        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2747        let proposal = create_test_proposal(
2748            &peer_account.1,
2749            primary.ledger.current_committee().unwrap(),
2750            round,
2751            previous_certificates,
2752            timestamp,
2753            1,
2754            &mut rng,
2755        );
2756
2757        // Make sure the primary is aware of the transmissions in the proposal.
2758        for (transmission_id, transmission) in proposal.transmissions() {
2759            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2760        }
2761
2762        // The author must be known to resolver to pass propose checks.
2763        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2764        // The primary must be considered synced.
2765        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(0)).unwrap();
2766        primary.sync.testing_only_set_sync_height_testing_only(0);
2767
2768        // Try to process the batch proposal from the peer, should error.
2769        assert!(
2770            primary
2771                .process_batch_propose_from_peer(peer_ip, BatchPropose {
2772                    round: round + 1,
2773                    batch_header: Data::Object(proposal.batch_header().clone())
2774                })
2775                .await
2776                .is_err()
2777        );
2778    }
2779
2780    /// Tests that the minimum batch delay is enforced as expected, i.e., that proposals with timestamps that are too close to the previous proposal are rejected.
2781    #[test_log::test(tokio::test)]
2782    async fn test_batch_propose_from_peer_with_past_timestamp() {
2783        let round = 2;
2784        let mut rng = TestRng::default();
2785        let (primary, accounts) = primary_without_handlers(&mut rng);
2786
2787        // Generate certificates.
2788        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
2789
2790        // Create a valid proposal with an author that isn't the primary.
2791        let peer_account = &accounts[1];
2792        let peer_ip = peer_account.0;
2793
2794        // Use a timestamp that is too early.
2795        // Set it to something that is less than the minimum batch delay
2796        // Note, that the minimum delay is currently 1, so this will be equal to the last timestamp
2797        let last_timestamp = primary
2798            .storage
2799            .get_certificate_for_round_with_author(round - 1, peer_account.1.address())
2800            .expect("No previous proposal exists")
2801            .timestamp();
2802        let invalid_timestamp = last_timestamp + (MIN_BATCH_DELAY.as_secs() as i64) - 1;
2803
2804        let proposal = create_test_proposal(
2805            &peer_account.1,
2806            primary.ledger.current_committee().unwrap(),
2807            round,
2808            previous_certificates,
2809            invalid_timestamp,
2810            1,
2811            &mut rng,
2812        );
2813
2814        // Make sure the primary is aware of the transmissions in the proposal.
2815        for (transmission_id, transmission) in proposal.transmissions() {
2816            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone())
2817        }
2818
2819        // The author must be known to resolver to pass propose checks.
2820        primary.gateway.resolver().write().insert_peer(peer_ip, peer_ip, Some(peer_account.1.address()));
2821        // The primary must be considered synced.
2822        primary.sync.testing_only_update_peer_locators_testing_only(peer_ip, sample_block_locators(0)).unwrap();
2823        primary.sync.testing_only_set_sync_height_testing_only(0);
2824
2825        // Try to process the batch proposal from the peer, should error.
2826        assert!(
2827            primary.process_batch_propose_from_peer(peer_ip, (*proposal.batch_header()).clone().into()).await.is_err()
2828        );
2829    }
2830
2831    #[test_log::test(tokio::test)]
2832    async fn test_propose_batch_with_storage_round_behind_proposal_lock() {
2833        let round = 3;
2834        let mut rng = TestRng::default();
2835        let (primary, _) = primary_without_handlers(&mut rng);
2836
2837        // Check there is no batch currently proposed.
2838        assert!(primary.proposed_batch.read().is_none());
2839
2840        // Generate a solution and a transaction.
2841        let (solution_id, solution) = sample_unconfirmed_solution(&mut rng);
2842        let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
2843
2844        // Store it on one of the workers.
2845        primary.workers()[0].process_unconfirmed_solution(solution_id, solution).await.unwrap();
2846        primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
2847
2848        // Set the proposal lock to a round ahead of the storage.
2849        let (old_proposal_round, old_proposal_timestamp) = primary
2850            .latest_proposal_timestamp
2851            .read()
2852            .await
2853            .map(|(round, timestamp)| (round, timestamp))
2854            .unwrap_or((0, 0));
2855        *primary.latest_proposal_timestamp.write().await =
2856            Some((round + 1, old_proposal_timestamp + MIN_BATCH_DELAY.as_secs() as i64));
2857
2858        // Propose a batch and enforce that it fails.
2859        assert!(primary.propose_batch().await.is_ok());
2860        assert!(primary.proposed_batch.read().is_none());
2861
2862        // Set the proposal lock back to the old round.
2863        *primary.latest_proposal_timestamp.write().await = Some((old_proposal_round, old_proposal_timestamp));
2864
2865        // Try to propose a batch again. This time, it should succeed.
2866        assert!(primary.propose_batch().await.is_ok());
2867        assert!(primary.proposed_batch.read().is_proposed());
2868    }
2869
2870    #[test_log::test(tokio::test)]
2871    async fn test_propose_batch_with_storage_round_behind_proposal() {
2872        let round = 5;
2873        let mut rng = TestRng::default();
2874        let (primary, accounts) = primary_without_handlers(&mut rng);
2875
2876        // Generate previous certificates.
2877        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
2878
2879        // Create a valid proposal.
2880        let timestamp = now();
2881        let proposal = create_test_proposal(
2882            primary.gateway.account(),
2883            primary.ledger.current_committee().unwrap(),
2884            round + 1,
2885            previous_certificates,
2886            timestamp,
2887            1,
2888            &mut rng,
2889        );
2890
2891        // Store the proposal on the primary.
2892        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
2893
2894        // Try to propose a batch will terminate early because the storage is behind the proposal.
2895        assert!(primary.propose_batch().await.is_ok());
2896        assert!(primary.proposed_batch.read().is_proposed());
2897        assert!(primary.proposed_batch.read().as_proposal().unwrap().round() > primary.current_round());
2898    }
2899
2900    #[test_log::test(tokio::test(flavor = "multi_thread"))]
2901    async fn test_batch_signature_from_peer() {
2902        let mut rng = TestRng::default();
2903        let (primary, accounts) = primary_without_handlers(&mut rng);
2904        map_account_addresses(&primary, &accounts);
2905
2906        // Create a valid proposal.
2907        let round = 1;
2908        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2909        let proposal = create_test_proposal(
2910            primary.gateway.account(),
2911            primary.ledger.current_committee().unwrap(),
2912            round,
2913            Default::default(),
2914            timestamp,
2915            1,
2916            &mut rng,
2917        );
2918
2919        // Store the proposal on the primary.
2920        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
2921
2922        // Each committee member signs the batch.
2923        let signatures = peer_signatures_for_proposal(&primary, &accounts, &mut rng);
2924
2925        // Have the primary process the signatures.
2926        for (socket_addr, signature) in signatures {
2927            primary.process_batch_signature_from_peer(socket_addr, signature).await.unwrap();
2928        }
2929
2930        // Check the certificate was created and stored by the primary.
2931        assert!(primary.storage.contains_certificate_in_round_from(round, primary.gateway.account().address()));
2932        // Manually attempt round advancement (because the handler is not running).
2933        primary.try_increment_to_the_next_round(round + 1).await.unwrap();
2934        // Check the round was incremented.
2935        assert_eq!(primary.current_round(), round + 1);
2936    }
2937
2938    #[test_log::test(tokio::test(flavor = "multi_thread"))]
2939    async fn test_batch_signature_from_peer_in_round() {
2940        let round = 5;
2941        let mut rng = TestRng::default();
2942        let (primary, accounts) = primary_without_handlers(&mut rng);
2943        map_account_addresses(&primary, &accounts);
2944
2945        // Generate certificates.
2946        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
2947
2948        // Create a valid proposal.
2949        let timestamp = now();
2950        let proposal = create_test_proposal(
2951            primary.gateway.account(),
2952            primary.ledger.current_committee().unwrap(),
2953            round,
2954            previous_certificates,
2955            timestamp,
2956            1,
2957            &mut rng,
2958        );
2959
2960        // Store the proposal on the primary.
2961        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
2962
2963        // Each committee member signs the batch.
2964        let signatures = peer_signatures_for_proposal(&primary, &accounts, &mut rng);
2965
2966        // Have the primary process the signatures.
2967        for (socket_addr, signature) in signatures {
2968            primary.process_batch_signature_from_peer(socket_addr, signature).await.unwrap();
2969        }
2970
2971        // Check the certificate was created and stored by the primary.
2972        assert!(primary.storage.contains_certificate_in_round_from(round, primary.gateway.account().address()));
2973        // Manually attempt round advancement (because the handler is not running).
2974        primary.try_increment_to_the_next_round(round + 1).await.unwrap();
2975        // Check the round was incremented.
2976        assert_eq!(primary.current_round(), round + 1);
2977    }
2978
2979    #[test_log::test(tokio::test)]
2980    async fn test_batch_signature_from_peer_no_quorum() {
2981        let mut rng = TestRng::default();
2982        let (primary, accounts) = primary_without_handlers(&mut rng);
2983        map_account_addresses(&primary, &accounts);
2984
2985        // Create a valid proposal.
2986        let round = 1;
2987        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
2988        let proposal = create_test_proposal(
2989            primary.gateway.account(),
2990            primary.ledger.current_committee().unwrap(),
2991            round,
2992            Default::default(),
2993            timestamp,
2994            1,
2995            &mut rng,
2996        );
2997
2998        // Store the proposal on the primary.
2999        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
3000
3001        // Each committee member signs the batch.
3002        let signatures = peer_signatures_for_proposal(&primary, &accounts, &mut rng);
3003
3004        // Have the primary process only one signature, mimicking a lack of quorum.
3005        let (socket_addr, signature) = signatures.first().unwrap();
3006        primary.process_batch_signature_from_peer(*socket_addr, *signature).await.unwrap();
3007
3008        // Check the certificate was not created and stored by the primary.
3009        assert!(!primary.storage.contains_certificate_in_round_from(round, primary.gateway.account().address()));
3010        // Check the round was incremented.
3011        assert_eq!(primary.current_round(), round);
3012    }
3013
3014    #[test_log::test(tokio::test)]
3015    async fn test_batch_signature_from_peer_in_round_no_quorum() {
3016        let round = 7;
3017        let mut rng = TestRng::default();
3018        let (primary, accounts) = primary_without_handlers(&mut rng);
3019        map_account_addresses(&primary, &accounts);
3020
3021        // Generate certificates.
3022        let previous_certificates = store_certificate_chain(&primary, &accounts, round, &mut rng);
3023
3024        // Create a valid proposal.
3025        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
3026        let proposal = create_test_proposal(
3027            primary.gateway.account(),
3028            primary.ledger.current_committee().unwrap(),
3029            round,
3030            previous_certificates,
3031            timestamp,
3032            1,
3033            &mut rng,
3034        );
3035
3036        // Store the proposal on the primary.
3037        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(proposal));
3038
3039        // Each committee member signs the batch.
3040        let signatures = peer_signatures_for_proposal(&primary, &accounts, &mut rng);
3041
3042        // Have the primary process only one signature, mimicking a lack of quorum.
3043        let (socket_addr, signature) = signatures.first().unwrap();
3044        primary.process_batch_signature_from_peer(*socket_addr, *signature).await.unwrap();
3045
3046        // Check the certificate was not created and stored by the primary.
3047        assert!(!primary.storage.contains_certificate_in_round_from(round, primary.gateway.account().address()));
3048        // Check the round was incremented.
3049        assert_eq!(primary.current_round(), round);
3050    }
3051
3052    // Tests that a late-arriving signature for a batch that is currently being certified
3053    // (ProposedBatchState::Certified) is silently dropped without error.
3054    // This exercises the race condition where proposed_batch.take() has been called but
3055    // insert_certificate has not yet completed.
3056    #[test_log::test(tokio::test)]
3057    async fn test_batch_signature_from_peer_batch_being_certified() {
3058        let mut rng = TestRng::default();
3059        let (primary, accounts) = primary_without_handlers(&mut rng);
3060        map_account_addresses(&primary, &accounts);
3061
3062        // Create a valid proposal.
3063        let round = 1;
3064        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
3065        let proposal = create_test_proposal(
3066            primary.gateway.account(),
3067            primary.ledger.current_committee().unwrap(),
3068            round,
3069            Default::default(),
3070            timestamp,
3071            1,
3072            &mut rng,
3073        );
3074        let batch_id = proposal.batch_id();
3075
3076        // Simulate the race: the batch has been taken for certification but not yet stored.
3077        *primary.proposed_batch.write() = ProposedBatchState::Certified(batch_id);
3078
3079        // Send a late signature for the batch being certified.
3080        let (socket_addr, account) =
3081            accounts.iter().find(|(_, a)| a.address() != primary.gateway.account().address()).unwrap();
3082        let signature = account.sign(&[batch_id], &mut rng).unwrap();
3083        let batch_signature = BatchSignature::new(batch_id, signature);
3084
3085        // The signature should be accepted without error (silently dropped).
3086        assert!(primary.process_batch_signature_from_peer(*socket_addr, batch_signature).await.is_ok());
3087        // The batch state is unchanged (still BeingCertified — no new proposal was set).
3088        assert!(matches!(&*primary.proposed_batch.read(), ProposedBatchState::Certified(id) if *id == batch_id));
3089    }
3090
3091    // Tests that a signature for a completely unknown batch ID is rejected even when another
3092    // batch is being certified. The BeingCertified state only suppresses errors for its own ID.
3093    #[test_log::test(tokio::test)]
3094    async fn test_batch_signature_from_peer_unknown_id_while_certifying() {
3095        let mut rng = TestRng::default();
3096        let (primary, accounts) = primary_without_handlers(&mut rng);
3097        map_account_addresses(&primary, &accounts);
3098
3099        // Create two proposals so we have two distinct batch IDs.
3100        let round = 1;
3101        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
3102        let proposal_a = create_test_proposal(
3103            primary.gateway.account(),
3104            primary.ledger.current_committee().unwrap(),
3105            round,
3106            Default::default(),
3107            timestamp,
3108            1,
3109            &mut rng,
3110        );
3111        let proposal_b = create_test_proposal(
3112            primary.gateway.account(),
3113            primary.ledger.current_committee().unwrap(),
3114            round,
3115            Default::default(),
3116            timestamp,
3117            1,
3118            &mut rng,
3119        );
3120        let batch_id_a = proposal_a.batch_id();
3121        let batch_id_b = proposal_b.batch_id();
3122        assert_ne!(batch_id_a, batch_id_b);
3123
3124        // Simulate certifying batch A.
3125        *primary.proposed_batch.write() = ProposedBatchState::Certified(batch_id_a);
3126
3127        // Send a signature for batch B (a genuinely unknown ID).
3128        let (socket_addr, account) =
3129            accounts.iter().find(|(_, a)| a.address() != primary.gateway.account().address()).unwrap();
3130        let signature = account.sign(&[batch_id_b], &mut rng).unwrap();
3131        let batch_signature = BatchSignature::new(batch_id_b, signature);
3132
3133        // The signature is for a genuinely unknown ID — should be rejected with an error.
3134        assert!(primary.process_batch_signature_from_peer(*socket_addr, batch_signature).await.is_err());
3135    }
3136
3137    // Tests the "already certified" path: a signature arrives after the batch is fully in
3138    // storage and the primary has moved on to a new proposal.
3139    #[test_log::test(tokio::test(flavor = "multi_thread"))]
3140    async fn test_batch_signature_from_peer_already_certified() {
3141        let mut rng = TestRng::default();
3142        let (primary, accounts) = primary_without_handlers(&mut rng);
3143        map_account_addresses(&primary, &accounts);
3144
3145        // Create and certify a batch so it lands in storage.
3146        let round = 1;
3147        let timestamp = now() + MIN_BATCH_DELAY.as_secs() as i64;
3148        let old_proposal = create_test_proposal(
3149            primary.gateway.account(),
3150            primary.ledger.current_committee().unwrap(),
3151            round,
3152            Default::default(),
3153            timestamp,
3154            1,
3155            &mut rng,
3156        );
3157        let old_batch_id = old_proposal.batch_id();
3158        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(old_proposal));
3159        let signatures = peer_signatures_for_proposal(&primary, &accounts, &mut rng);
3160        for (socket_addr, signature) in signatures {
3161            primary.process_batch_signature_from_peer(socket_addr, signature).await.unwrap();
3162        }
3163        // The batch is now in storage.
3164        assert!(primary.storage.contains_certificate_in_round_from(round, primary.gateway.account().address()));
3165
3166        // Simulate a new proposal being active.
3167        let new_proposal = create_test_proposal(
3168            primary.gateway.account(),
3169            primary.ledger.current_committee().unwrap(),
3170            round,
3171            Default::default(),
3172            timestamp,
3173            1,
3174            &mut rng,
3175        );
3176        assert_ne!(new_proposal.batch_id(), old_batch_id);
3177        *primary.proposed_batch.write() = ProposedBatchState::Certifying(Box::new(new_proposal));
3178
3179        // Send a late signature for the already-certified old batch.
3180        let (socket_addr, account) =
3181            accounts.iter().find(|(_, a)| a.address() != primary.gateway.account().address()).unwrap();
3182        let signature = account.sign(&[old_batch_id], &mut rng).unwrap();
3183        let batch_signature = BatchSignature::new(old_batch_id, signature);
3184
3185        // Should be silently accepted (already certified path).
3186        assert!(primary.process_batch_signature_from_peer(*socket_addr, batch_signature).await.is_ok());
3187    }
3188
3189    #[test_log::test(tokio::test)]
3190    async fn test_insert_certificate_with_aborted_transmissions() {
3191        let round = 3;
3192        let prev_round = round - 1;
3193        let mut rng = TestRng::default();
3194        let (primary, accounts) = primary_without_handlers(&mut rng);
3195        let peer_account = &accounts[1];
3196        let peer_ip = peer_account.0;
3197
3198        // Fill primary storage.
3199        store_certificate_chain(&primary, &accounts, round, &mut rng);
3200
3201        // Get transmissions from previous certificates.
3202        let previous_certificate_ids: IndexSet<_> = primary.storage.get_certificate_ids_for_round(prev_round);
3203
3204        // Generate a solution and a transaction.
3205        let (solution_commitment, solution) = sample_unconfirmed_solution(&mut rng);
3206        let (transaction_id, transaction) = sample_unconfirmed_transaction(&mut rng);
3207
3208        // Store it on one of the workers.
3209        primary.workers()[0].process_unconfirmed_solution(solution_commitment, solution).await.unwrap();
3210        primary.workers()[0].process_unconfirmed_transaction(transaction_id, transaction).await.unwrap();
3211
3212        // Check that the worker has 2 transmissions.
3213        assert_eq!(primary.workers()[0].num_transmissions(), 2);
3214
3215        // Create certificates for the current round.
3216        let account = accounts[0].1.clone();
3217        let (certificate, transmissions) =
3218            create_batch_certificate(account.address(), &accounts, round, previous_certificate_ids.clone(), &mut rng);
3219        let certificate_id = certificate.id();
3220
3221        // Randomly abort some of the transmissions.
3222        let mut aborted_transmissions = HashSet::new();
3223        let mut transmissions_without_aborted = HashMap::new();
3224        for (transmission_id, transmission) in transmissions.clone() {
3225            match rng.random::<bool>() || aborted_transmissions.is_empty() {
3226                true => {
3227                    // Insert the aborted transmission.
3228                    aborted_transmissions.insert(transmission_id);
3229                }
3230                false => {
3231                    // Insert the transmission without the aborted transmission.
3232                    transmissions_without_aborted.insert(transmission_id, transmission);
3233                }
3234            };
3235        }
3236
3237        // Add the non-aborted transmissions to the worker.
3238        for (transmission_id, transmission) in transmissions_without_aborted.iter() {
3239            primary.workers()[0].process_transmission_from_peer(peer_ip, *transmission_id, transmission.clone());
3240        }
3241
3242        // Check that inserting the transmission with missing transmissions fails.
3243        assert!(
3244            primary
3245                .storage
3246                .check_certificate(&certificate, transmissions_without_aborted.clone(), Default::default())
3247                .is_err()
3248        );
3249        assert!(
3250            primary
3251                .storage
3252                .insert_certificate(certificate.clone(), transmissions_without_aborted.clone(), Default::default())
3253                .is_err()
3254        );
3255
3256        // Insert the certificate to storage.
3257        primary
3258            .storage
3259            .insert_certificate(certificate, transmissions_without_aborted, aborted_transmissions.clone())
3260            .unwrap();
3261
3262        // Ensure the certificate exists in storage.
3263        assert!(primary.storage.contains_certificate(certificate_id));
3264        // Ensure that the aborted transmission IDs exist in storage.
3265        for aborted_transmission_id in aborted_transmissions {
3266            assert!(primary.storage.contains_transmission(aborted_transmission_id));
3267            assert!(primary.storage.get_transmission(aborted_transmission_id).is_none());
3268        }
3269    }
3270
3271    // -----------------------------------------------------------------------
3272    // add_signature_to_batch
3273    // -----------------------------------------------------------------------
3274
3275    /// State is `None` and the batch is not in storage — returns an error, state stays `None`.
3276    #[test]
3277    fn test_add_signature_to_batch_none_state() {
3278        let mut rng = TestRng::default();
3279        let (primary, accounts) = primary_without_handlers(&mut rng);
3280
3281        let peer_ip = accounts[1].0;
3282        let batch_id = Field::rand(&mut rng);
3283        let signature = accounts[1].1.sign(&[batch_id], &mut rng).unwrap();
3284
3285        let (result, new_state) =
3286            primary.add_signature_to_batch(ProposedBatchState::None, peer_ip, batch_id, signature);
3287
3288        assert!(result.is_err());
3289        assert_eq!(new_state, ProposedBatchState::None);
3290    }
3291
3292    /// State is `Certified` with a matching batch ID — silently dropped, state restored.
3293    #[test]
3294    fn test_add_signature_to_batch_certified_matching_id() {
3295        let mut rng = TestRng::default();
3296        let (primary, accounts) = primary_without_handlers(&mut rng);
3297
3298        let peer_ip = accounts[1].0;
3299        let batch_id = Field::rand(&mut rng);
3300        let signature = accounts[1].1.sign(&[batch_id], &mut rng).unwrap();
3301
3302        let (result, new_state) =
3303            primary.add_signature_to_batch(ProposedBatchState::Certified(batch_id), peer_ip, batch_id, signature);
3304
3305        assert!(result.unwrap().is_none());
3306        assert_eq!(new_state, ProposedBatchState::Certified(batch_id));
3307    }
3308
3309    /// State is `Certified` with a *different* batch ID — error returned, state becomes `None`.
3310    #[test]
3311    fn test_add_signature_to_batch_certified_different_id() {
3312        let mut rng = TestRng::default();
3313        let (primary, accounts) = primary_without_handlers(&mut rng);
3314
3315        let peer_ip = accounts[1].0;
3316        let certified_id = Field::rand(&mut rng);
3317        let other_id = Field::rand(&mut rng);
3318        let signature = accounts[1].1.sign(&[other_id], &mut rng).unwrap();
3319
3320        let (result, new_state) =
3321            primary.add_signature_to_batch(ProposedBatchState::Certified(certified_id), peer_ip, other_id, signature);
3322
3323        assert!(result.is_err());
3324        assert_eq!(new_state, ProposedBatchState::Certified(certified_id));
3325    }
3326
3327    /// State is `Certifying` for a *different* batch ID that **is already in storage** — silently
3328    /// dropped, state restored.
3329    #[tokio::test(flavor = "multi_thread")]
3330    async fn test_add_signature_to_batch_certifying_different_id_in_storage() {
3331        let round = 1;
3332        let mut rng = TestRng::default();
3333        let (primary, accounts) = primary_without_handlers(&mut rng);
3334        map_account_addresses(&primary, &accounts);
3335
3336        // Create a proposal owned by the primary.
3337        let proposal = create_test_proposal(
3338            primary.gateway.account(),
3339            primary.ledger.current_committee().unwrap(),
3340            round,
3341            Default::default(),
3342            now(),
3343            0,
3344            &mut rng,
3345        );
3346        let proposal_batch_id = proposal.batch_id();
3347
3348        // Create and store a *different* certificate so `contains_batch` returns true for it.
3349        let (certificate, transmissions) =
3350            create_batch_certificate(accounts[1].1.address(), &accounts, round, Default::default(), &mut rng);
3351        let stored_batch_id = certificate.batch_id();
3352        primary.storage.insert_certificate(certificate, transmissions, Default::default()).unwrap();
3353
3354        let peer_ip = accounts[1].0;
3355        let signature = accounts[1].1.sign(&[stored_batch_id], &mut rng).unwrap();
3356
3357        let (result, new_state) = primary.add_signature_to_batch(
3358            ProposedBatchState::Certifying(Box::new(proposal)),
3359            peer_ip,
3360            stored_batch_id,
3361            signature,
3362        );
3363
3364        assert!(result.unwrap().is_none());
3365        // State is restored with the original proposal.
3366        assert_eq!(new_state.as_proposal().unwrap().batch_id(), proposal_batch_id);
3367    }
3368
3369    /// State is `Certifying` for a *different* batch ID that is **not in storage** — error
3370    /// returned, state restored.
3371    #[test]
3372    fn test_add_signature_to_batch_certifying_different_id_unknown() {
3373        let mut rng = TestRng::default();
3374        let (primary, accounts) = primary_without_handlers(&mut rng);
3375
3376        let proposal = create_test_proposal(
3377            primary.gateway.account(),
3378            primary.ledger.current_committee().unwrap(),
3379            1,
3380            Default::default(),
3381            now(),
3382            0,
3383            &mut rng,
3384        );
3385        let proposal_batch_id = proposal.batch_id();
3386
3387        let peer_ip = accounts[1].0;
3388        let unknown_id = Field::rand(&mut rng);
3389        let signature = accounts[1].1.sign(&[unknown_id], &mut rng).unwrap();
3390
3391        let (result, new_state) = primary.add_signature_to_batch(
3392            ProposedBatchState::Certifying(Box::new(proposal)),
3393            peer_ip,
3394            unknown_id,
3395            signature,
3396        );
3397
3398        assert!(result.is_err());
3399        assert_eq!(new_state.as_proposal().unwrap().batch_id(), proposal_batch_id);
3400    }
3401
3402    /// Matching batch ID, valid signature, quorum **not yet** reached — state stays `Certifying`.
3403    #[test]
3404    fn test_add_signature_to_batch_certifying_matching_no_quorum() {
3405        let mut rng = TestRng::default();
3406        let (primary, accounts) = primary_without_handlers(&mut rng);
3407        map_account_addresses(&primary, &accounts);
3408
3409        let proposal = create_test_proposal(
3410            primary.gateway.account(),
3411            primary.ledger.current_committee().unwrap(),
3412            1,
3413            Default::default(),
3414            now(),
3415            0,
3416            &mut rng,
3417        );
3418        let batch_id = proposal.batch_id();
3419
3420        // Only one peer signs — not enough for quorum.
3421        let peer_ip = accounts[1].0;
3422        let signature = accounts[1].1.sign(&[batch_id], &mut rng).unwrap();
3423
3424        let (result, new_state) = primary.add_signature_to_batch(
3425            ProposedBatchState::Certifying(Box::new(proposal)),
3426            peer_ip,
3427            batch_id,
3428            signature,
3429        );
3430
3431        assert!(result.unwrap().is_none());
3432        assert_eq!(new_state.as_proposal().unwrap().batch_id(), batch_id);
3433    }
3434
3435    /// Matching batch ID, all peers sign — quorum reached, proposal extracted and state becomes
3436    /// `Certified`.
3437    #[test]
3438    fn test_add_signature_to_batch_certifying_matching_quorum_reached() {
3439        let mut rng = TestRng::default();
3440        let (primary, accounts) = primary_without_handlers(&mut rng);
3441        map_account_addresses(&primary, &accounts);
3442
3443        let proposal = create_test_proposal(
3444            primary.gateway.account(),
3445            primary.ledger.current_committee().unwrap(),
3446            1,
3447            Default::default(),
3448            now(),
3449            0,
3450            &mut rng,
3451        );
3452        let batch_id = proposal.batch_id();
3453
3454        // Add all peer signatures one by one until quorum is reached.
3455        let peers: Vec<_> =
3456            accounts.iter().filter(|(_, a)| a.address() != primary.gateway.account().address()).collect();
3457        let mut state = ProposedBatchState::Certifying(Box::new(proposal));
3458        let mut final_result = None;
3459
3460        for (peer_ip, peer_account) in &peers {
3461            let signature = peer_account.sign(&[batch_id], &mut rng).unwrap();
3462            let (result, new_state) = primary.add_signature_to_batch(state, *peer_ip, batch_id, signature);
3463            state = new_state;
3464            if result.as_ref().unwrap().is_some() {
3465                final_result = Some(result);
3466                break;
3467            }
3468        }
3469
3470        // Quorum must have been reached with the committee's peers.
3471        let proposal = final_result.expect("quorum should be reached").unwrap().unwrap();
3472        assert_eq!(proposal.batch_id(), batch_id);
3473        assert_eq!(state, ProposedBatchState::Certified(batch_id));
3474    }
3475}