dusk_node/
chain.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7mod acceptor;
8mod consensus;
9mod fallback;
10mod fsm;
11mod genesis;
12
13mod header_validation;
14mod metrics;
15
16use std::ops::Deref;
17use std::sync::Arc;
18use std::time::Duration;
19
20use anyhow::Result;
21use async_trait::async_trait;
22use dusk_consensus::config::is_emergency_block;
23use dusk_consensus::errors::ConsensusError;
24use dusk_core::signatures::bls::PublicKey as BlsPublicKey;
25pub use header_validation::verify_att;
26use node_data::events::Event;
27use node_data::ledger::{to_str, BlockWithLabel, Label};
28use node_data::message::payload::RatificationResult;
29use node_data::message::{AsyncQueue, Payload, Topics};
30use tokio::sync::mpsc::Sender;
31use tokio::sync::RwLock;
32use tokio::time::{sleep_until, Instant};
33use tracing::{debug, error, info, warn};
34
35use self::acceptor::Acceptor;
36use self::fsm::SimpleFSM;
37#[cfg(feature = "archive")]
38use crate::archive::Archive;
39use crate::database::rocksdb::MD_HASH_KEY;
40use crate::database::{Ledger, Metadata};
41use crate::{database, vm, LongLivedService, Message, Network};
42
43const TOPICS: &[u8] = &[
44    Topics::Block as u8,
45    Topics::Candidate as u8,
46    Topics::Validation as u8,
47    Topics::Ratification as u8,
48    Topics::Quorum as u8,
49    Topics::ValidationQuorum as u8,
50];
51
52const HEARTBEAT_SEC: Duration = Duration::from_secs(3);
53
54pub struct ChainSrv<N: Network, DB: database::DB, VM: vm::VMExecution> {
55    /// Inbound wire messages queue
56    inbound: AsyncQueue<Message>,
57    keys_path: String,
58    acceptor: Option<Arc<RwLock<Acceptor<N, DB, VM>>>>,
59    max_consensus_queue_size: usize,
60    /// Sender channel for sending out RUES events
61    event_sender: Sender<Event>,
62    genesis_timestamp: u64,
63    dusk_key: BlsPublicKey,
64    finality_activation: u64,
65    #[cfg(feature = "archive")]
66    archive: Archive,
67}
68
69#[async_trait]
70impl<N: Network, DB: database::DB, VM: vm::VMExecution>
71    LongLivedService<N, DB, VM> for ChainSrv<N, DB, VM>
72{
73    async fn initialize(
74        &mut self,
75        network: Arc<RwLock<N>>,
76        db: Arc<RwLock<DB>>,
77        vm: Arc<RwLock<VM>>,
78    ) -> anyhow::Result<()> {
79        let tip = Self::load_tip(
80            db.read().await.deref(),
81            vm.read().await.deref(),
82            self.genesis_timestamp,
83        )
84        .await?;
85
86        let state_hash = tip.inner().header().state_hash;
87        let provisioners_list = vm.read().await.get_provisioners(state_hash)?;
88
89        // Initialize Acceptor
90        let acc = Acceptor::init_consensus(
91            &self.keys_path,
92            tip,
93            provisioners_list,
94            db,
95            network,
96            vm,
97            #[cfg(feature = "archive")]
98            self.archive.clone(),
99            self.max_consensus_queue_size,
100            self.event_sender.clone(),
101            self.dusk_key,
102            self.finality_activation,
103        )
104        .await?;
105
106        self.acceptor = Some(Arc::new(RwLock::new(acc)));
107
108        Ok(())
109    }
110
111    async fn execute(
112        &mut self,
113        network: Arc<RwLock<N>>,
114        _db: Arc<RwLock<DB>>,
115        _vm: Arc<RwLock<VM>>,
116    ) -> anyhow::Result<usize> {
117        // Register routes
118        LongLivedService::<N, DB, VM>::add_routes(
119            self,
120            TOPICS,
121            self.inbound.clone(),
122            &network,
123        )
124        .await?;
125
126        let acc = self.acceptor.as_mut().expect("initialize is called");
127        acc.write().await.spawn_task().await;
128
129        // Start-up FSM instance
130        let mut fsm = SimpleFSM::new(acc.clone(), network.clone()).await;
131
132        let outbound_chan = acc.read().await.get_outbound_chan().await;
133        let result_chan = acc.read().await.get_result_chan().await;
134
135        let mut heartbeat = Instant::now().checked_add(HEARTBEAT_SEC).unwrap();
136
137        // Message loop for Chain context
138        loop {
139            tokio::select! {
140                biased;
141                // Receives results from the upper layer
142                recv = result_chan.recv() => {
143                    match recv? {
144                        Err(ConsensusError::Canceled(round)) => {
145                            debug!(event = "consensus canceled", round);
146                        }
147                        Err(err) => {
148                            // Internal consensus execution has terminated with an error
149                            error!(event = "failed_consensus", ?err);
150                            fsm.on_failed_consensus().await;
151                        }
152                        _ => {}
153                    }
154                },
155                // Handles any inbound wire.
156                recv = self.inbound.recv() => {
157                    let msg = recv?;
158
159                    match msg.payload {
160                        Payload::Candidate(_)
161                        | Payload::Validation(_)
162                        | Payload::Ratification(_)
163                        | Payload::ValidationQuorum(_) => {
164                            self.reroute_acceptor(msg).await;
165                        }
166
167                        Payload::Quorum(ref q) => {
168                            fsm.on_quorum(q, msg.metadata.as_ref()).await;
169                            self.reroute_acceptor(msg).await;
170
171                        }
172
173                        Payload::Block(blk) => {
174                            info!(
175                                event = "New block",
176                                src = "Block msg",
177                                height = blk.header().height,
178                                iter = blk.header().iteration,
179                                hash = to_str(&blk.header().hash),
180                                metadata = ?msg.metadata,
181                            );
182
183                            // Handle a block that originates from a network peer.
184                            // By disabling block broadcast, a block may be received
185                            // from a peer only after explicit request (on demand).
186                            match fsm.on_block_event(*blk, msg.metadata.clone()).await {
187                                Ok(res) => {
188                                    if let Some(accepted_blk) = res {
189                                        // Repropagate Emergency Blocks
190                                        // We already know it's valid because we accepted it
191                                        if is_emergency_block(accepted_blk.header().iteration){
192                                            // We build a new `msg` to avoid cloning `blk` when
193                                            // passing it to `on_block_event`.
194                                            // We copy the metadata to keep the original ray_id.
195                                            let mut eb_msg = Message::from(accepted_blk);
196                                            eb_msg.metadata = msg.metadata;
197                                            if let Err(e) = network.read().await.broadcast(&eb_msg).await {
198                                                warn!("Unable to re-broadcast Emergency Block: {e}");
199                                            }
200                                        }
201                                    }
202                                }
203                                Err(err) => {
204                                    error!(event = "fsm::on_event failed", src = "wire", err = ?err);
205                                }
206                            }
207                        }
208
209                        _ => {
210                            warn!("invalid inbound message");
211                        },
212                    }
213
214                },
215                // Re-routes messages originated from Consensus (upper) layer to the network layer.
216                recv = outbound_chan.recv() => {
217                    let msg = recv?;
218
219                    // Handle quorum messages from Consensus layer.
220                    // If the associated candidate block already exists,
221                    // the winner block will be compiled and redirected to the Acceptor.
222                    if let Payload::Quorum(quorum) = &msg.payload {
223                      if let RatificationResult::Success(_) = quorum.att.result {
224                          fsm.on_success_quorum(quorum, msg.metadata.clone()).await;
225                      }
226                    }
227
228                    if let Payload::GetResource(res) = &msg.payload {
229                        if let Err(e) = network.read().await.flood_request(res.get_inv(), None, 16).await {
230                            warn!("Unable to re-route message {e}");
231                        }
232                    } else if let Err(e) = network.read().await.broadcast(&msg).await {
233                            warn!("Unable to broadcast message {e}");
234                    }
235
236                },
237                 // Handles heartbeat event
238                _ = sleep_until(heartbeat) => {
239                    if let Err(err) = fsm.on_heartbeat_event().await {
240                        error!(event = "heartbeat_failed", ?err);
241                    }
242
243                    heartbeat = Instant::now().checked_add(HEARTBEAT_SEC).unwrap();
244                },
245            }
246        }
247    }
248
249    /// Returns service name.
250    fn name(&self) -> &'static str {
251        "chain"
252    }
253}
254
255impl<N: Network, DB: database::DB, VM: vm::VMExecution> ChainSrv<N, DB, VM> {
256    pub fn new(
257        keys_path: String,
258        max_inbound_size: usize,
259        event_sender: Sender<Event>,
260        genesis_timestamp: u64,
261        dusk_key: BlsPublicKey,
262        finality_activation: u64,
263        #[cfg(feature = "archive")] archive: Archive,
264    ) -> Self {
265        info!(
266            "ChainSrv::new with keys_path: {}, max_inbound_size: {}",
267            keys_path, max_inbound_size
268        );
269
270        Self {
271            inbound: AsyncQueue::bounded(max_inbound_size, "chain_inbound"),
272            keys_path,
273            acceptor: None,
274            max_consensus_queue_size: max_inbound_size,
275            event_sender,
276            genesis_timestamp,
277            dusk_key,
278            finality_activation,
279            #[cfg(feature = "archive")]
280            archive,
281        }
282    }
283
284    /// Load both the chain tip and last finalized block from persisted ledger.
285    ///
286    /// Panics
287    ///
288    /// If register entry is read but block is not found.
289    async fn load_tip(
290        db: &DB,
291        vm: &VM,
292        genesis_timestamp: u64,
293    ) -> Result<BlockWithLabel> {
294        let stored_block = db.view(|t| {
295            anyhow::Ok(t.op_read(MD_HASH_KEY)?.and_then(|tip_hash| {
296                t.block(&tip_hash[..])
297                    .expect("block to be found if metadata is set")
298            }))
299        })?;
300
301        let block = match stored_block {
302            Some(blk) => {
303                let (_, label) = db
304                    .view(|t| t.block_label_by_height(blk.header().height))?
305                    .unwrap();
306
307                BlockWithLabel::new_with_label(blk, label)
308            }
309            None => {
310                // Lack of register record means the loaded database is
311                // either malformed or empty.
312                let state = vm.get_state_root()?;
313                let genesis_blk =
314                    genesis::generate_block(state, genesis_timestamp);
315                db.update(|t| {
316                    // Persist genesis block
317                    t.store_block(
318                        genesis_blk.header(),
319                        &[],
320                        &[],
321                        Label::Final(0),
322                    )
323                })?;
324
325                BlockWithLabel::new_with_label(genesis_blk, Label::Final(0))
326            }
327        };
328
329        let block_header = block.inner().header();
330
331        tracing::info!(
332            event = "Ledger block loaded",
333            height = block_header.height,
334            hash = hex::encode(block_header.hash),
335            state_root = hex::encode(block_header.state_hash),
336            label = ?block.label()
337        );
338
339        Ok(block)
340    }
341
342    pub async fn revert_last_final(&self) -> anyhow::Result<()> {
343        self.acceptor
344            .as_ref()
345            .expect("Chain to be initialized")
346            .read()
347            .await
348            .try_revert(acceptor::RevertTarget::LastFinalizedState)
349            .await
350    }
351
352    async fn reroute_acceptor(&self, msg: Message) {
353        debug!(
354            event = "Consensus message received",
355            topic = ?msg.topic(),
356            info = ?msg.header,
357            metadata = ?msg.metadata,
358        );
359
360        // Re-route message to the Consensus
361        let acc = self.acceptor.as_ref().expect("initialize is called");
362        if let Err(e) = acc.read().await.reroute_msg(msg).await {
363            warn!("Could not reroute msg to Consensus: {}", e);
364        }
365    }
366}