amareleo_node_bft/sync/
mod.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
16use crate::helpers::{BFTSender, Storage};
17use amareleo_node_bft_ledger_service::LedgerService;
18use amareleo_node_sync::locators::{BlockLocators, CHECKPOINT_INTERVAL, NUM_RECENT_BLOCKS};
19use snarkvm::{
20    console::network::Network,
21    ledger::authority::Authority,
22    prelude::{cfg_into_iter, cfg_iter},
23};
24
25use anyhow::{Result, bail};
26use indexmap::IndexMap;
27use rayon::prelude::*;
28use std::{collections::HashMap, sync::Arc};
29use tokio::sync::OnceCell;
30
31use std::sync::atomic::{AtomicBool, Ordering};
32
33#[derive(Clone)]
34pub struct Sync<N: Network> {
35    /// The storage.
36    storage: Storage<N>,
37    /// The ledger service.
38    ledger: Arc<dyn LedgerService<N>>,
39    /// The BFT sender.
40    bft_sender: Arc<OnceCell<BFTSender<N>>>,
41    /// The boolean indicator of whether the node is synced up to the latest block (within the given tolerance).
42    is_block_synced: Arc<AtomicBool>,
43}
44
45impl<N: Network> Sync<N> {
46    /// Initializes a new sync instance.
47    pub fn new(storage: Storage<N>, ledger: Arc<dyn LedgerService<N>>) -> Self {
48        // Return the sync instance.
49        Self { storage, ledger, bft_sender: Default::default(), is_block_synced: Default::default() }
50    }
51
52    /// Initializes the sync module and sync the storage with the ledger at bootup.
53    pub async fn initialize(&self, bft_sender: Option<BFTSender<N>>) -> Result<()> {
54        // If a BFT sender was provided, set it.
55        if let Some(bft_sender) = bft_sender {
56            self.bft_sender.set(bft_sender).expect("BFT sender already set in gateway");
57        }
58
59        info!("Syncing storage with the ledger...");
60
61        // Sync the storage with the ledger.
62        self.sync_storage_with_ledger_at_bootup().await
63    }
64
65    /// Starts the sync module.
66    pub async fn run(&self) -> Result<()> {
67        info!("Starting the sync module...");
68
69        // Update the sync status.
70        self.is_block_synced.store(true, Ordering::SeqCst);
71
72        // Update the `IS_SYNCED` metric.
73        #[cfg(feature = "metrics")]
74        metrics::gauge(metrics::bft::IS_SYNCED, true);
75
76        Ok(())
77    }
78}
79
80// Methods to manage storage.
81impl<N: Network> Sync<N> {
82    /// Syncs the storage with the ledger at bootup.
83    async fn sync_storage_with_ledger_at_bootup(&self) -> Result<()> {
84        // Retrieve the latest block in the ledger.
85        let latest_block = self.ledger.latest_block();
86
87        // Retrieve the block height.
88        let block_height = latest_block.height();
89        // Determine the number of maximum number of blocks that would have been garbage collected.
90        let max_gc_blocks = u32::try_from(self.storage.max_gc_rounds())?.saturating_div(2);
91        // Determine the earliest height, conservatively set to the block height minus the max GC rounds.
92        // By virtue of the BFT protocol, we can guarantee that all GC range blocks will be loaded.
93        let gc_height = block_height.saturating_sub(max_gc_blocks);
94        // Retrieve the blocks.
95        let blocks = self.ledger.get_blocks(gc_height..block_height.saturating_add(1))?;
96
97        debug!("Syncing storage with the ledger from block {} to {}...", gc_height, block_height.saturating_add(1));
98
99        /* Sync storage */
100
101        // Sync the height with the block.
102        self.storage.sync_height_with_block(latest_block.height());
103        // Sync the round with the block.
104        self.storage.sync_round_with_block(latest_block.round());
105        // Perform GC on the latest block round.
106        self.storage.garbage_collect_certificates(latest_block.round());
107        // Iterate over the blocks.
108        for block in &blocks {
109            // If the block authority is a subdag, then sync the batch certificates with the block.
110            if let Authority::Quorum(subdag) = block.authority() {
111                // Reconstruct the unconfirmed transactions.
112                let unconfirmed_transactions = cfg_iter!(block.transactions())
113                    .filter_map(|tx| {
114                        tx.to_unconfirmed_transaction().map(|unconfirmed| (unconfirmed.id(), unconfirmed)).ok()
115                    })
116                    .collect::<HashMap<_, _>>();
117
118                // Iterate over the certificates.
119                for certificates in subdag.values().cloned() {
120                    cfg_into_iter!(certificates).for_each(|certificate| {
121                        self.storage.sync_certificate_with_block(block, certificate, &unconfirmed_transactions);
122                    });
123                }
124            }
125        }
126
127        /* Sync the BFT DAG */
128
129        // Construct a list of the certificates.
130        let certificates = blocks
131            .iter()
132            .flat_map(|block| {
133                match block.authority() {
134                    // If the block authority is a beacon, then skip the block.
135                    Authority::Beacon(_) => None,
136                    // If the block authority is a subdag, then retrieve the certificates.
137                    Authority::Quorum(subdag) => Some(subdag.values().flatten().cloned().collect::<Vec<_>>()),
138                }
139            })
140            .flatten()
141            .collect::<Vec<_>>();
142
143        // If a BFT sender was provided, send the certificates to the BFT.
144        if let Some(bft_sender) = self.bft_sender.get() {
145            // Await the callback to continue.
146            if let Err(e) = bft_sender.tx_sync_bft_dag_at_bootup.send(certificates).await {
147                bail!("Failed to update the BFT DAG from sync: {e}");
148            }
149        }
150
151        Ok(())
152    }
153}
154
155// Methods to assist with the block sync module.
156impl<N: Network> Sync<N> {
157    /// Returns `true` if the node is synced and has connected peers.
158    pub fn is_synced(&self) -> bool {
159        self.is_block_synced.load(Ordering::SeqCst)
160    }
161
162    /// Returns the number of blocks the node is behind the greatest peer height.
163    pub fn num_blocks_behind(&self) -> u32 {
164        0u32
165    }
166
167    /// Returns `true` if the node is in gateway mode.
168    pub const fn is_gateway_mode(&self) -> bool {
169        true
170    }
171
172    /// Returns the current block locators of the node.
173    pub fn get_block_locators(&self) -> Result<BlockLocators<N>> {
174        // Retrieve the latest block height.
175        let latest_height = self.ledger.latest_block_height();
176
177        // Initialize the recents map.
178        let mut recents = IndexMap::with_capacity(NUM_RECENT_BLOCKS);
179        // Retrieve the recent block hashes.
180        for height in latest_height.saturating_sub((NUM_RECENT_BLOCKS - 1) as u32)..=latest_height {
181            recents.insert(height, self.ledger.get_block_hash(height)?);
182        }
183
184        // Initialize the checkpoints map.
185        let mut checkpoints = IndexMap::with_capacity((latest_height / CHECKPOINT_INTERVAL + 1).try_into()?);
186        // Retrieve the checkpoint block hashes.
187        for height in (0..=latest_height).step_by(CHECKPOINT_INTERVAL as usize) {
188            checkpoints.insert(height, self.ledger.get_block_hash(height)?);
189        }
190
191        // Construct the block locators.
192        BlockLocators::new(recents, checkpoints)
193    }
194}