amareleo_node_consensus/
lib.rs

1// Copyright 2024 Aleo Network Foundation
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
16#![forbid(unsafe_code)]
17
18#[macro_use]
19extern crate tracing;
20
21use amareleo_chain_account::Account;
22use amareleo_node_bft::{
23    BFT,
24    MAX_BATCH_DELAY_IN_MS,
25    Primary,
26    helpers::{
27        ConsensusReceiver,
28        PrimaryReceiver,
29        PrimarySender,
30        Storage as NarwhalStorage,
31        fmt_id,
32        init_consensus_channels,
33    },
34    spawn_blocking,
35};
36use amareleo_node_bft_ledger_service::LedgerService;
37use amareleo_node_bft_storage_service::BFTPersistentStorage;
38use snarkvm::{
39    ledger::{
40        block::Transaction,
41        narwhal::{BatchHeader, Data, Subdag, Transmission, TransmissionID},
42        puzzle::{Solution, SolutionID},
43    },
44    prelude::*,
45};
46
47use aleo_std::StorageMode;
48use anyhow::Result;
49use colored::Colorize;
50use indexmap::IndexMap;
51use lru::LruCache;
52use parking_lot::Mutex;
53use std::{future::Future, num::NonZeroUsize, sync::Arc, time::Duration};
54use tokio::{
55    sync::{OnceCell, oneshot},
56    task::JoinHandle,
57};
58
59#[cfg(feature = "metrics")]
60use std::collections::HashMap;
61
62/// The capacity of the queue reserved for deployments.
63/// Note: This is an inbound queue capacity, not a Narwhal-enforced capacity.
64const CAPACITY_FOR_DEPLOYMENTS: usize = 1 << 10;
65/// The capacity of the queue reserved for executions.
66/// Note: This is an inbound queue capacity, not a Narwhal-enforced capacity.
67const CAPACITY_FOR_EXECUTIONS: usize = 1 << 10;
68/// The capacity of the queue reserved for solutions.
69/// Note: This is an inbound queue capacity, not a Narwhal-enforced capacity.
70const CAPACITY_FOR_SOLUTIONS: usize = 1 << 10;
71/// The **suggested** maximum number of deployments in each interval.
72/// Note: This is an inbound queue limit, not a Narwhal-enforced limit.
73const MAX_DEPLOYMENTS_PER_INTERVAL: usize = 1;
74
75/// Helper struct to track incoming transactions.
76struct TransactionsQueue<N: Network> {
77    pub deployments: LruCache<N::TransactionID, Transaction<N>>,
78    pub executions: LruCache<N::TransactionID, Transaction<N>>,
79}
80
81impl<N: Network> Default for TransactionsQueue<N> {
82    fn default() -> Self {
83        Self {
84            deployments: LruCache::new(NonZeroUsize::new(CAPACITY_FOR_DEPLOYMENTS).unwrap()),
85            executions: LruCache::new(NonZeroUsize::new(CAPACITY_FOR_EXECUTIONS).unwrap()),
86        }
87    }
88}
89
90#[derive(Clone)]
91pub struct Consensus<N: Network> {
92    /// The ledger.
93    ledger: Arc<dyn LedgerService<N>>,
94    /// The BFT.
95    bft: BFT<N>,
96    /// The primary sender.
97    primary_sender: Arc<OnceCell<PrimarySender<N>>>,
98    /// The unconfirmed solutions queue.
99    solutions_queue: Arc<Mutex<LruCache<SolutionID<N>, Solution<N>>>>,
100    /// The unconfirmed transactions queue.
101    transactions_queue: Arc<Mutex<TransactionsQueue<N>>>,
102    /// The recently-seen unconfirmed solutions.
103    seen_solutions: Arc<Mutex<LruCache<SolutionID<N>, ()>>>,
104    /// The recently-seen unconfirmed transactions.
105    seen_transactions: Arc<Mutex<LruCache<N::TransactionID, ()>>>,
106    #[cfg(feature = "metrics")]
107    transmissions_queue_timestamps: Arc<Mutex<HashMap<TransmissionID<N>, i64>>>,
108    /// The spawned handles.
109    handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
110}
111
112impl<N: Network> Consensus<N> {
113    /// Initializes a new instance of consensus.
114    pub fn new(
115        account: Account<N>,
116        ledger: Arc<dyn LedgerService<N>>,
117        keep_state: bool,
118        storage_mode: StorageMode,
119    ) -> Result<Self> {
120        // Initialize the Narwhal transmissions.
121        let transmissions = Arc::new(BFTPersistentStorage::open(storage_mode.clone())?);
122        // Initialize the Narwhal storage.
123        let storage = NarwhalStorage::new(ledger.clone(), transmissions, BatchHeader::<N>::MAX_GC_ROUNDS as u64);
124        // Initialize the BFT.
125        let bft = BFT::new(account, storage, keep_state, storage_mode, ledger.clone())?;
126        // Return the consensus.
127        Ok(Self {
128            ledger,
129            bft,
130            primary_sender: Default::default(),
131            solutions_queue: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(CAPACITY_FOR_SOLUTIONS).unwrap()))),
132            transactions_queue: Default::default(),
133            seen_solutions: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1 << 16).unwrap()))),
134            seen_transactions: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1 << 16).unwrap()))),
135            #[cfg(feature = "metrics")]
136            transmissions_queue_timestamps: Default::default(),
137            handles: Default::default(),
138        })
139    }
140
141    /// Run the consensus instance.
142    pub async fn run(&mut self, primary_sender: PrimarySender<N>, primary_receiver: PrimaryReceiver<N>) -> Result<()> {
143        info!("Starting the consensus instance...");
144        // Set the primary sender.
145        self.primary_sender.set(primary_sender.clone()).expect("Primary sender already set");
146
147        // First, initialize the consensus channels.
148        let (consensus_sender, consensus_receiver) = init_consensus_channels();
149        // Then, start the consensus handlers.
150        self.start_handlers(consensus_receiver);
151        // Lastly, the consensus.
152        self.bft.run(Some(consensus_sender), primary_sender, primary_receiver).await?;
153        Ok(())
154    }
155
156    /// Returns the ledger.
157    pub const fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
158        &self.ledger
159    }
160
161    /// Returns the BFT.
162    pub const fn bft(&self) -> &BFT<N> {
163        &self.bft
164    }
165
166    /// Returns the primary sender.
167    pub fn primary_sender(&self) -> &PrimarySender<N> {
168        self.primary_sender.get().expect("Primary sender not set")
169    }
170}
171
172impl<N: Network> Consensus<N> {
173    /// Returns the number of unconfirmed transmissions.
174    pub fn num_unconfirmed_transmissions(&self) -> usize {
175        self.bft.num_unconfirmed_transmissions()
176    }
177
178    /// Returns the number of unconfirmed ratifications.
179    pub fn num_unconfirmed_ratifications(&self) -> usize {
180        self.bft.num_unconfirmed_ratifications()
181    }
182
183    /// Returns the number of solutions.
184    pub fn num_unconfirmed_solutions(&self) -> usize {
185        self.bft.num_unconfirmed_solutions()
186    }
187
188    /// Returns the number of unconfirmed transactions.
189    pub fn num_unconfirmed_transactions(&self) -> usize {
190        self.bft.num_unconfirmed_transactions()
191    }
192}
193
194impl<N: Network> Consensus<N> {
195    /// Returns the unconfirmed transmission IDs.
196    pub fn unconfirmed_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
197        self.worker_transmission_ids().chain(self.inbound_transmission_ids())
198    }
199
200    /// Returns the unconfirmed transmissions.
201    pub fn unconfirmed_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
202        self.worker_transmissions().chain(self.inbound_transmissions())
203    }
204
205    /// Returns the unconfirmed solutions.
206    pub fn unconfirmed_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
207        self.worker_solutions().chain(self.inbound_solutions())
208    }
209
210    /// Returns the unconfirmed transactions.
211    pub fn unconfirmed_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
212        self.worker_transactions().chain(self.inbound_transactions())
213    }
214}
215
216impl<N: Network> Consensus<N> {
217    /// Returns the worker transmission IDs.
218    pub fn worker_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
219        self.bft.worker_transmission_ids()
220    }
221
222    /// Returns the worker transmissions.
223    pub fn worker_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
224        self.bft.worker_transmissions()
225    }
226
227    /// Returns the worker solutions.
228    pub fn worker_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
229        self.bft.worker_solutions()
230    }
231
232    /// Returns the worker transactions.
233    pub fn worker_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
234        self.bft.worker_transactions()
235    }
236}
237
238impl<N: Network> Consensus<N> {
239    /// Returns the transmission IDs in the inbound queue.
240    pub fn inbound_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
241        self.inbound_transmissions().map(|(id, _)| id)
242    }
243
244    /// Returns the transmissions in the inbound queue.
245    pub fn inbound_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
246        self.inbound_transactions()
247            .map(|(id, tx)| {
248                (
249                    TransmissionID::Transaction(id, tx.to_checksum::<N>().unwrap_or_default()),
250                    Transmission::Transaction(tx),
251                )
252            })
253            .chain(self.inbound_solutions().map(|(id, solution)| {
254                (
255                    TransmissionID::Solution(id, solution.to_checksum::<N>().unwrap_or_default()),
256                    Transmission::Solution(solution),
257                )
258            }))
259    }
260
261    /// Returns the solutions in the inbound queue.
262    pub fn inbound_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
263        // Return an iterator over the solutions in the inbound queue.
264        self.solutions_queue.lock().clone().into_iter().map(|(id, solution)| (id, Data::Object(solution)))
265    }
266
267    /// Returns the transactions in the inbound queue.
268    pub fn inbound_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
269        // Acquire the lock on the transactions queue.
270        let tx_queue = self.transactions_queue.lock();
271        // Return an iterator over the deployment and execution transactions in the inbound queue.
272        tx_queue
273            .deployments
274            .clone()
275            .into_iter()
276            .chain(tx_queue.executions.clone())
277            .map(|(id, tx)| (id, Data::Object(tx)))
278    }
279}
280
281impl<N: Network> Consensus<N> {
282    /// Adds the given unconfirmed solution to the memory pool.
283    pub async fn add_unconfirmed_solution(&self, solution: Solution<N>) -> Result<()> {
284        // Calculate the transmission checksum.
285        let checksum = Data::<Solution<N>>::Buffer(solution.to_bytes_le()?.into()).to_checksum::<N>()?;
286        #[cfg(feature = "metrics")]
287        {
288            metrics::increment_gauge(metrics::consensus::UNCONFIRMED_SOLUTIONS, 1f64);
289            let timestamp = amareleo_node_bft::helpers::now();
290            self.transmissions_queue_timestamps
291                .lock()
292                .insert(TransmissionID::Solution(solution.id(), checksum), timestamp);
293        }
294        // Queue the unconfirmed solution.
295        {
296            let solution_id = solution.id();
297
298            // Check if the transaction was recently seen.
299            if self.seen_solutions.lock().put(solution_id, ()).is_some() {
300                // If the transaction was recently seen, return early.
301                return Ok(());
302            }
303            // Check if the solution already exists in the ledger.
304            if self.ledger.contains_transmission(&TransmissionID::Solution(solution_id, checksum))? {
305                bail!("Solution '{}' exists in the ledger {}", fmt_id(solution_id), "(skipping)".dimmed());
306            }
307            // Add the solution to the memory pool.
308            trace!("Received unconfirmed solution '{}' in the queue", fmt_id(solution_id));
309            if self.solutions_queue.lock().put(solution_id, solution).is_some() {
310                bail!("Solution '{}' exists in the memory pool", fmt_id(solution_id));
311            }
312        }
313
314        // Try to process the unconfirmed solutions in the memory pool.
315        self.process_unconfirmed_solutions().await
316    }
317
318    /// Processes unconfirmed transactions in the memory pool.
319    pub async fn process_unconfirmed_solutions(&self) -> Result<()> {
320        // If the memory pool of this node is full, return early.
321        let num_unconfirmed_solutions = self.num_unconfirmed_solutions();
322        let num_unconfirmed_transmissions = self.num_unconfirmed_transmissions();
323        if num_unconfirmed_solutions >= N::MAX_SOLUTIONS
324            || num_unconfirmed_transmissions >= Primary::<N>::MAX_TRANSMISSIONS_TOLERANCE
325        {
326            return Ok(());
327        }
328        // Retrieve the solutions.
329        let solutions = {
330            // Determine the available capacity.
331            let capacity = N::MAX_SOLUTIONS.saturating_sub(num_unconfirmed_solutions);
332            // Acquire the lock on the queue.
333            let mut queue = self.solutions_queue.lock();
334            // Determine the number of solutions to send.
335            let num_solutions = queue.len().min(capacity);
336            // Drain the solutions from the queue.
337            (0..num_solutions).filter_map(|_| queue.pop_lru().map(|(_, solution)| solution)).collect::<Vec<_>>()
338        };
339        // Iterate over the solutions.
340        for solution in solutions.into_iter() {
341            let solution_id = solution.id();
342            trace!("Adding unconfirmed solution '{}' to the memory pool...", fmt_id(solution_id));
343            // Send the unconfirmed solution to the primary.
344            if let Err(e) = self.primary_sender().send_unconfirmed_solution(solution_id, Data::Object(solution)).await {
345                // If the BFT is synced, then log the warning.
346                if self.bft.is_synced() {
347                    // If error occurs after the first 10 blocks of the epoch, log it as a warning, otherwise ignore.
348                    if self.ledger().latest_block_height() % N::NUM_BLOCKS_PER_EPOCH > 10 {
349                        warn!("Failed to add unconfirmed solution '{}' to the memory pool - {e}", fmt_id(solution_id))
350                    };
351                }
352            }
353        }
354        Ok(())
355    }
356
357    /// Adds the given unconfirmed transaction to the memory pool.
358    pub async fn add_unconfirmed_transaction(&self, transaction: Transaction<N>) -> Result<()> {
359        // Calculate the transmission checksum.
360        let checksum = Data::<Transaction<N>>::Buffer(transaction.to_bytes_le()?.into()).to_checksum::<N>()?;
361        #[cfg(feature = "metrics")]
362        {
363            metrics::increment_gauge(metrics::consensus::UNCONFIRMED_TRANSACTIONS, 1f64);
364            let timestamp = amareleo_node_bft::helpers::now();
365            self.transmissions_queue_timestamps
366                .lock()
367                .insert(TransmissionID::Transaction(transaction.id(), checksum), timestamp);
368        }
369        // Queue the unconfirmed transaction.
370        {
371            let transaction_id = transaction.id();
372
373            // Check that the transaction is not a fee transaction.
374            if transaction.is_fee() {
375                bail!("Transaction '{}' is a fee transaction {}", fmt_id(transaction_id), "(skipping)".dimmed());
376            }
377            // Check if the transaction was recently seen.
378            if self.seen_transactions.lock().put(transaction_id, ()).is_some() {
379                // If the transaction was recently seen, return early.
380                return Ok(());
381            }
382            // Check if the transaction already exists in the ledger.
383            if self.ledger.contains_transmission(&TransmissionID::Transaction(transaction_id, checksum))? {
384                bail!("Transaction '{}' exists in the ledger {}", fmt_id(transaction_id), "(skipping)".dimmed());
385            }
386            // Add the transaction to the memory pool.
387            trace!("Received unconfirmed transaction '{}' in the queue", fmt_id(transaction_id));
388            if transaction.is_deploy() {
389                if self.transactions_queue.lock().deployments.put(transaction_id, transaction).is_some() {
390                    bail!("Transaction '{}' exists in the memory pool", fmt_id(transaction_id));
391                }
392            } else if self.transactions_queue.lock().executions.put(transaction_id, transaction).is_some() {
393                bail!("Transaction '{}' exists in the memory pool", fmt_id(transaction_id));
394            }
395
396            // Try to process the unconfirmed transactions in the memory pool.
397            self.process_unconfirmed_transactions().await
398        }
399    }
400
401    /// Processes unconfirmed transactions in the memory pool.
402    pub async fn process_unconfirmed_transactions(&self) -> Result<()> {
403        // If the memory pool of this node is full, return early.
404        let num_unconfirmed_transmissions = self.num_unconfirmed_transmissions();
405        if num_unconfirmed_transmissions >= Primary::<N>::MAX_TRANSMISSIONS_TOLERANCE {
406            return Ok(());
407        }
408        // Retrieve the transactions.
409        let transactions = {
410            // Determine the available capacity.
411            let capacity = Primary::<N>::MAX_TRANSMISSIONS_TOLERANCE.saturating_sub(num_unconfirmed_transmissions);
412            // Acquire the lock on the transactions queue.
413            let mut tx_queue = self.transactions_queue.lock();
414            // Determine the number of deployments to send.
415            let num_deployments = tx_queue.deployments.len().min(capacity).min(MAX_DEPLOYMENTS_PER_INTERVAL);
416            // Determine the number of executions to send.
417            let num_executions = tx_queue.executions.len().min(capacity.saturating_sub(num_deployments));
418            // Create an iterator which will select interleaved deployments and executions within the capacity.
419            // Note: interleaving ensures we will never have consecutive invalid deployments blocking the queue.
420            let selector_iter = (0..num_deployments).map(|_| true).interleave((0..num_executions).map(|_| false));
421            // Drain the transactions from the queue, interleaving deployments and executions.
422            selector_iter
423                .filter_map(|select_deployment| {
424                    if select_deployment {
425                        tx_queue.deployments.pop_lru().map(|(_, tx)| tx)
426                    } else {
427                        tx_queue.executions.pop_lru().map(|(_, tx)| tx)
428                    }
429                })
430                .collect_vec()
431        };
432        // Iterate over the transactions.
433        for transaction in transactions.into_iter() {
434            let transaction_id = transaction.id();
435            trace!("Adding unconfirmed transaction '{}' to the memory pool...", fmt_id(transaction_id));
436            // Send the unconfirmed transaction to the primary.
437            if let Err(e) =
438                self.primary_sender().send_unconfirmed_transaction(transaction_id, Data::Object(transaction)).await
439            {
440                // If the BFT is synced, then log the warning.
441                if self.bft.is_synced() {
442                    warn!(
443                        "Failed to add unconfirmed transaction '{}' to the memory pool - {e}",
444                        fmt_id(transaction_id)
445                    );
446                }
447            }
448        }
449        Ok(())
450    }
451}
452
453impl<N: Network> Consensus<N> {
454    /// Starts the consensus handlers.
455    fn start_handlers(&self, consensus_receiver: ConsensusReceiver<N>) {
456        let ConsensusReceiver { mut rx_consensus_subdag } = consensus_receiver;
457
458        // Process the committed subdag and transmissions from the BFT.
459        let self_ = self.clone();
460        self.spawn(async move {
461            while let Some((committed_subdag, transmissions, callback)) = rx_consensus_subdag.recv().await {
462                self_.process_bft_subdag(committed_subdag, transmissions, callback).await;
463            }
464        });
465
466        // Process the unconfirmed transactions in the memory pool.
467        let self_ = self.clone();
468        self.spawn(async move {
469            loop {
470                // Sleep briefly.
471                tokio::time::sleep(Duration::from_millis(MAX_BATCH_DELAY_IN_MS)).await;
472                // Process the unconfirmed transactions in the memory pool.
473                if let Err(e) = self_.process_unconfirmed_transactions().await {
474                    warn!("Cannot process unconfirmed transactions - {e}");
475                }
476                // Process the unconfirmed solutions in the memory pool.
477                if let Err(e) = self_.process_unconfirmed_solutions().await {
478                    warn!("Cannot process unconfirmed solutions - {e}");
479                }
480            }
481        });
482    }
483
484    /// Processes the committed subdag and transmissions from the BFT.
485    async fn process_bft_subdag(
486        &self,
487        subdag: Subdag<N>,
488        transmissions: IndexMap<TransmissionID<N>, Transmission<N>>,
489        callback: oneshot::Sender<Result<()>>,
490    ) {
491        // Try to advance to the next block.
492        let self_ = self.clone();
493        let transmissions_ = transmissions.clone();
494        let result = spawn_blocking! { self_.try_advance_to_next_block(subdag, transmissions_) };
495
496        // If the block failed to advance, reinsert the transmissions into the memory pool.
497        if let Err(e) = &result {
498            error!("Unable to advance to the next block - {e}");
499            // On failure, reinsert the transmissions into the memory pool.
500            self.reinsert_transmissions(transmissions).await;
501        }
502        // Send the callback **after** advancing to the next block.
503        // Note: We must await the block to be advanced before sending the callback.
504        callback.send(result).ok();
505    }
506
507    /// Attempts to advance to the next block.
508    fn try_advance_to_next_block(
509        &self,
510        subdag: Subdag<N>,
511        transmissions: IndexMap<TransmissionID<N>, Transmission<N>>,
512    ) -> Result<()> {
513        #[cfg(feature = "metrics")]
514        let start = subdag.leader_certificate().batch_header().timestamp();
515        #[cfg(feature = "metrics")]
516        let num_committed_certificates = subdag.values().map(|c| c.len()).sum::<usize>();
517        #[cfg(feature = "metrics")]
518        let current_block_timestamp = self.ledger.latest_block().header().metadata().timestamp();
519
520        // Create the candidate next block.
521        let next_block = self.ledger.prepare_advance_to_next_quorum_block(subdag, transmissions)?;
522
523        // AlexZ: Disabling block validation since this would catch our
524        //        cheating in always assigning the same leader.
525        //        Validation is within SnarkVM which we don't want to touch.
526        // Check that the block is well-formed.
527        // self.ledger.check_next_block(&next_block)?;
528
529        // Advance to the next block.
530        self.ledger.advance_to_next_block(&next_block)?;
531
532        // If the next block starts a new epoch, clear the existing solutions.
533        if next_block.height() % N::NUM_BLOCKS_PER_EPOCH == 0 {
534            // Clear the solutions queue.
535            self.solutions_queue.lock().clear();
536            // Clear the worker solutions.
537            self.bft.primary().clear_worker_solutions();
538        }
539
540        #[cfg(feature = "metrics")]
541        {
542            let elapsed = std::time::Duration::from_secs((amareleo_node_bft::helpers::now() - start) as u64);
543            let next_block_timestamp = next_block.header().metadata().timestamp();
544            let block_latency = next_block_timestamp - current_block_timestamp;
545            let proof_target = next_block.header().proof_target();
546            let coinbase_target = next_block.header().coinbase_target();
547            let cumulative_proof_target = next_block.header().cumulative_proof_target();
548
549            metrics::add_transmission_latency_metric(&self.transmissions_queue_timestamps, &next_block);
550
551            metrics::gauge(metrics::consensus::COMMITTED_CERTIFICATES, num_committed_certificates as f64);
552            metrics::histogram(metrics::consensus::CERTIFICATE_COMMIT_LATENCY, elapsed.as_secs_f64());
553            metrics::histogram(metrics::consensus::BLOCK_LATENCY, block_latency as f64);
554            metrics::gauge(metrics::blocks::PROOF_TARGET, proof_target as f64);
555            metrics::gauge(metrics::blocks::COINBASE_TARGET, coinbase_target as f64);
556            metrics::gauge(metrics::blocks::CUMULATIVE_PROOF_TARGET, cumulative_proof_target as f64);
557        }
558        Ok(())
559    }
560
561    /// Reinserts the given transmissions into the memory pool.
562    async fn reinsert_transmissions(&self, transmissions: IndexMap<TransmissionID<N>, Transmission<N>>) {
563        // Iterate over the transmissions.
564        for (transmission_id, transmission) in transmissions.into_iter() {
565            // Reinsert the transmission into the memory pool.
566            if let Err(e) = self.reinsert_transmission(transmission_id, transmission).await {
567                warn!(
568                    "Unable to reinsert transmission {}.{} into the memory pool - {e}",
569                    fmt_id(transmission_id),
570                    fmt_id(transmission_id.checksum().unwrap_or_default()).dimmed()
571                );
572            }
573        }
574    }
575
576    /// Reinserts the given transmission into the memory pool.
577    async fn reinsert_transmission(
578        &self,
579        transmission_id: TransmissionID<N>,
580        transmission: Transmission<N>,
581    ) -> Result<()> {
582        // Initialize a callback sender and receiver.
583        let (callback, callback_receiver) = oneshot::channel();
584        // Send the transmission to the primary.
585        match (transmission_id, transmission) {
586            (TransmissionID::Ratification, Transmission::Ratification) => return Ok(()),
587            (TransmissionID::Solution(solution_id, _), Transmission::Solution(solution)) => {
588                // Send the solution to the primary.
589                self.primary_sender().tx_unconfirmed_solution.send((solution_id, solution, callback)).await?;
590            }
591            (TransmissionID::Transaction(transaction_id, _), Transmission::Transaction(transaction)) => {
592                // Send the transaction to the primary.
593                self.primary_sender().tx_unconfirmed_transaction.send((transaction_id, transaction, callback)).await?;
594            }
595            _ => bail!("Mismatching `(transmission_id, transmission)` pair in consensus"),
596        }
597        // Await the callback.
598        callback_receiver.await?
599    }
600
601    /// Spawns a task with the given future; it should only be used for long-running tasks.
602    fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
603        self.handles.lock().push(tokio::spawn(future));
604    }
605
606    /// Shuts down the BFT.
607    pub async fn shut_down(&self) {
608        info!("Shutting down consensus...");
609        // Shut down the BFT.
610        self.bft.shut_down().await;
611        // Abort the tasks.
612        self.handles.lock().iter().for_each(|handle| handle.abort());
613    }
614}