1#![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
62const CAPACITY_FOR_DEPLOYMENTS: usize = 1 << 10;
65const CAPACITY_FOR_EXECUTIONS: usize = 1 << 10;
68const CAPACITY_FOR_SOLUTIONS: usize = 1 << 10;
71const MAX_DEPLOYMENTS_PER_INTERVAL: usize = 1;
74
75struct 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 ledger: Arc<dyn LedgerService<N>>,
94 bft: BFT<N>,
96 primary_sender: Arc<OnceCell<PrimarySender<N>>>,
98 solutions_queue: Arc<Mutex<LruCache<SolutionID<N>, Solution<N>>>>,
100 transactions_queue: Arc<Mutex<TransactionsQueue<N>>>,
102 seen_solutions: Arc<Mutex<LruCache<SolutionID<N>, ()>>>,
104 seen_transactions: Arc<Mutex<LruCache<N::TransactionID, ()>>>,
106 #[cfg(feature = "metrics")]
107 transmissions_queue_timestamps: Arc<Mutex<HashMap<TransmissionID<N>, i64>>>,
108 handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
110}
111
112impl<N: Network> Consensus<N> {
113 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 let transmissions = Arc::new(BFTPersistentStorage::open(storage_mode.clone())?);
122 let storage = NarwhalStorage::new(ledger.clone(), transmissions, BatchHeader::<N>::MAX_GC_ROUNDS as u64);
124 let bft = BFT::new(account, storage, keep_state, storage_mode, ledger.clone())?;
126 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 pub async fn run(&mut self, primary_sender: PrimarySender<N>, primary_receiver: PrimaryReceiver<N>) -> Result<()> {
143 info!("Starting the consensus instance...");
144 self.primary_sender.set(primary_sender.clone()).expect("Primary sender already set");
146
147 let (consensus_sender, consensus_receiver) = init_consensus_channels();
149 self.start_handlers(consensus_receiver);
151 self.bft.run(Some(consensus_sender), primary_sender, primary_receiver).await?;
153 Ok(())
154 }
155
156 pub const fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
158 &self.ledger
159 }
160
161 pub const fn bft(&self) -> &BFT<N> {
163 &self.bft
164 }
165
166 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 pub fn num_unconfirmed_transmissions(&self) -> usize {
175 self.bft.num_unconfirmed_transmissions()
176 }
177
178 pub fn num_unconfirmed_ratifications(&self) -> usize {
180 self.bft.num_unconfirmed_ratifications()
181 }
182
183 pub fn num_unconfirmed_solutions(&self) -> usize {
185 self.bft.num_unconfirmed_solutions()
186 }
187
188 pub fn num_unconfirmed_transactions(&self) -> usize {
190 self.bft.num_unconfirmed_transactions()
191 }
192}
193
194impl<N: Network> Consensus<N> {
195 pub fn unconfirmed_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
197 self.worker_transmission_ids().chain(self.inbound_transmission_ids())
198 }
199
200 pub fn unconfirmed_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
202 self.worker_transmissions().chain(self.inbound_transmissions())
203 }
204
205 pub fn unconfirmed_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
207 self.worker_solutions().chain(self.inbound_solutions())
208 }
209
210 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 pub fn worker_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
219 self.bft.worker_transmission_ids()
220 }
221
222 pub fn worker_transmissions(&self) -> impl '_ + Iterator<Item = (TransmissionID<N>, Transmission<N>)> {
224 self.bft.worker_transmissions()
225 }
226
227 pub fn worker_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
229 self.bft.worker_solutions()
230 }
231
232 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 pub fn inbound_transmission_ids(&self) -> impl '_ + Iterator<Item = TransmissionID<N>> {
241 self.inbound_transmissions().map(|(id, _)| id)
242 }
243
244 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 pub fn inbound_solutions(&self) -> impl '_ + Iterator<Item = (SolutionID<N>, Data<Solution<N>>)> {
263 self.solutions_queue.lock().clone().into_iter().map(|(id, solution)| (id, Data::Object(solution)))
265 }
266
267 pub fn inbound_transactions(&self) -> impl '_ + Iterator<Item = (N::TransactionID, Data<Transaction<N>>)> {
269 let tx_queue = self.transactions_queue.lock();
271 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 pub async fn add_unconfirmed_solution(&self, solution: Solution<N>) -> Result<()> {
284 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 {
296 let solution_id = solution.id();
297
298 if self.seen_solutions.lock().put(solution_id, ()).is_some() {
300 return Ok(());
302 }
303 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 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 self.process_unconfirmed_solutions().await
316 }
317
318 pub async fn process_unconfirmed_solutions(&self) -> Result<()> {
320 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 let solutions = {
330 let capacity = N::MAX_SOLUTIONS.saturating_sub(num_unconfirmed_solutions);
332 let mut queue = self.solutions_queue.lock();
334 let num_solutions = queue.len().min(capacity);
336 (0..num_solutions).filter_map(|_| queue.pop_lru().map(|(_, solution)| solution)).collect::<Vec<_>>()
338 };
339 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 if let Err(e) = self.primary_sender().send_unconfirmed_solution(solution_id, Data::Object(solution)).await {
345 if self.bft.is_synced() {
347 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 pub async fn add_unconfirmed_transaction(&self, transaction: Transaction<N>) -> Result<()> {
359 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 {
371 let transaction_id = transaction.id();
372
373 if transaction.is_fee() {
375 bail!("Transaction '{}' is a fee transaction {}", fmt_id(transaction_id), "(skipping)".dimmed());
376 }
377 if self.seen_transactions.lock().put(transaction_id, ()).is_some() {
379 return Ok(());
381 }
382 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 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 self.process_unconfirmed_transactions().await
398 }
399 }
400
401 pub async fn process_unconfirmed_transactions(&self) -> Result<()> {
403 let num_unconfirmed_transmissions = self.num_unconfirmed_transmissions();
405 if num_unconfirmed_transmissions >= Primary::<N>::MAX_TRANSMISSIONS_TOLERANCE {
406 return Ok(());
407 }
408 let transactions = {
410 let capacity = Primary::<N>::MAX_TRANSMISSIONS_TOLERANCE.saturating_sub(num_unconfirmed_transmissions);
412 let mut tx_queue = self.transactions_queue.lock();
414 let num_deployments = tx_queue.deployments.len().min(capacity).min(MAX_DEPLOYMENTS_PER_INTERVAL);
416 let num_executions = tx_queue.executions.len().min(capacity.saturating_sub(num_deployments));
418 let selector_iter = (0..num_deployments).map(|_| true).interleave((0..num_executions).map(|_| false));
421 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 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 if let Err(e) =
438 self.primary_sender().send_unconfirmed_transaction(transaction_id, Data::Object(transaction)).await
439 {
440 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 fn start_handlers(&self, consensus_receiver: ConsensusReceiver<N>) {
456 let ConsensusReceiver { mut rx_consensus_subdag } = consensus_receiver;
457
458 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 let self_ = self.clone();
468 self.spawn(async move {
469 loop {
470 tokio::time::sleep(Duration::from_millis(MAX_BATCH_DELAY_IN_MS)).await;
472 if let Err(e) = self_.process_unconfirmed_transactions().await {
474 warn!("Cannot process unconfirmed transactions - {e}");
475 }
476 if let Err(e) = self_.process_unconfirmed_solutions().await {
478 warn!("Cannot process unconfirmed solutions - {e}");
479 }
480 }
481 });
482 }
483
484 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 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 let Err(e) = &result {
498 error!("Unable to advance to the next block - {e}");
499 self.reinsert_transmissions(transmissions).await;
501 }
502 callback.send(result).ok();
505 }
506
507 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 let next_block = self.ledger.prepare_advance_to_next_quorum_block(subdag, transmissions)?;
522
523 self.ledger.advance_to_next_block(&next_block)?;
531
532 if next_block.height() % N::NUM_BLOCKS_PER_EPOCH == 0 {
534 self.solutions_queue.lock().clear();
536 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 async fn reinsert_transmissions(&self, transmissions: IndexMap<TransmissionID<N>, Transmission<N>>) {
563 for (transmission_id, transmission) in transmissions.into_iter() {
565 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 async fn reinsert_transmission(
578 &self,
579 transmission_id: TransmissionID<N>,
580 transmission: Transmission<N>,
581 ) -> Result<()> {
582 let (callback, callback_receiver) = oneshot::channel();
584 match (transmission_id, transmission) {
586 (TransmissionID::Ratification, Transmission::Ratification) => return Ok(()),
587 (TransmissionID::Solution(solution_id, _), Transmission::Solution(solution)) => {
588 self.primary_sender().tx_unconfirmed_solution.send((solution_id, solution, callback)).await?;
590 }
591 (TransmissionID::Transaction(transaction_id, _), Transmission::Transaction(transaction)) => {
592 self.primary_sender().tx_unconfirmed_transaction.send((transaction_id, transaction, callback)).await?;
594 }
595 _ => bail!("Mismatching `(transmission_id, transmission)` pair in consensus"),
596 }
597 callback_receiver.await?
599 }
600
601 fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
603 self.handles.lock().push(tokio::spawn(future));
604 }
605
606 pub async fn shut_down(&self) {
608 info!("Shutting down consensus...");
609 self.bft.shut_down().await;
611 self.handles.lock().iter().for_each(|handle| handle.abort());
613 }
614}