snarkos_node/validator/
mod.rs

1// Copyright (c) 2019-2025 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 router;
17
18use crate::traits::NodeInterface;
19
20use snarkos_account::Account;
21use snarkos_node_bft::{ledger_service::CoreLedgerService, spawn_blocking};
22use snarkos_node_cdn::CdnBlockSync;
23use snarkos_node_consensus::Consensus;
24use snarkos_node_rest::Rest;
25use snarkos_node_router::{
26    Heartbeat,
27    Inbound,
28    Outbound,
29    Router,
30    Routing,
31    messages::{NodeType, PuzzleResponse, UnconfirmedSolution, UnconfirmedTransaction},
32};
33use snarkos_node_sync::{BlockSync, Ping};
34use snarkos_node_tcp::{
35    P2P,
36    protocols::{Disconnect, Handshake, OnConnect, Reading},
37};
38use snarkvm::prelude::{
39    Ledger,
40    Network,
41    block::{Block, Header},
42    puzzle::Solution,
43    store::ConsensusStorage,
44};
45
46use aleo_std::StorageMode;
47use anyhow::Result;
48use core::future::Future;
49#[cfg(feature = "locktick")]
50use locktick::parking_lot::Mutex;
51#[cfg(not(feature = "locktick"))]
52use parking_lot::Mutex;
53use std::{
54    net::SocketAddr,
55    sync::{Arc, atomic::AtomicBool},
56    time::Duration,
57};
58use tokio::task::JoinHandle;
59
60/// A validator is a full node, capable of validating blocks.
61#[derive(Clone)]
62pub struct Validator<N: Network, C: ConsensusStorage<N>> {
63    /// The ledger of the node.
64    ledger: Ledger<N, C>,
65    /// The consensus module of the node.
66    consensus: Consensus<N>,
67    /// The router of the node.
68    router: Router<N>,
69    /// The REST server of the node.
70    rest: Option<Rest<N, C, Self>>,
71    /// The block synchronization logic (used in the Router impl).
72    sync: Arc<BlockSync<N>>,
73    /// The spawned handles.
74    handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
75    /// The shutdown signal.
76    shutdown: Arc<AtomicBool>,
77    /// Keeps track of sending pings.
78    ping: Arc<Ping<N>>,
79}
80
81impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
82    /// Initializes a new validator node.
83    pub async fn new(
84        node_ip: SocketAddr,
85        bft_ip: Option<SocketAddr>,
86        rest_ip: Option<SocketAddr>,
87        rest_rps: u32,
88        account: Account<N>,
89        trusted_peers: &[SocketAddr],
90        trusted_validators: &[SocketAddr],
91        genesis: Block<N>,
92        cdn: Option<String>,
93        storage_mode: StorageMode,
94        allow_external_peers: bool,
95        dev_txs: bool,
96        shutdown: Arc<AtomicBool>,
97    ) -> Result<Self> {
98        // Initialize the signal handler.
99        let signal_node = Self::handle_signals(shutdown.clone());
100
101        // Initialize the ledger.
102        let ledger = Ledger::load(genesis, storage_mode.clone())?;
103
104        // Initialize the ledger service.
105        let ledger_service = Arc::new(CoreLedgerService::new(ledger.clone(), shutdown.clone()));
106
107        // Determine if the validator should rotate external peers.
108        let rotate_external_peers = false;
109
110        // Initialize the node router.
111        let router = Router::new(
112            node_ip,
113            NodeType::Validator,
114            account.clone(),
115            ledger_service.clone(),
116            trusted_peers,
117            Self::MAXIMUM_NUMBER_OF_PEERS as u16,
118            rotate_external_peers,
119            allow_external_peers,
120            matches!(storage_mode, StorageMode::Development(_)),
121        )
122        .await?;
123
124        // Initialize the block synchronization logic.
125        let sync = Arc::new(BlockSync::new(ledger_service.clone()));
126        let locators = sync.get_block_locators()?;
127        let ping = Arc::new(Ping::new(router.clone(), locators));
128
129        // Initialize the consensus layer.
130        let consensus = Consensus::new(
131            account.clone(),
132            ledger_service.clone(),
133            sync.clone(),
134            bft_ip,
135            trusted_validators,
136            storage_mode.clone(),
137            ping.clone(),
138        )
139        .await?;
140
141        // Initialize the node.
142        let mut node = Self {
143            ledger: ledger.clone(),
144            consensus: consensus.clone(),
145            router,
146            rest: None,
147            sync: sync.clone(),
148            ping,
149            handles: Default::default(),
150            shutdown: shutdown.clone(),
151        };
152
153        // Perform sync with CDN (if enabled).
154        let cdn_sync = cdn.map(|base_url| Arc::new(CdnBlockSync::new(base_url, ledger.clone(), shutdown)));
155
156        // Initialize the transaction pool.
157        node.initialize_transaction_pool(storage_mode.clone(), dev_txs)?;
158
159        // Initialize the REST server.
160        if let Some(rest_ip) = rest_ip {
161            node.rest = Some(
162                Rest::start(
163                    rest_ip,
164                    rest_rps,
165                    Some(consensus),
166                    ledger.clone(),
167                    Arc::new(node.clone()),
168                    cdn_sync.clone(),
169                    sync,
170                )
171                .await?,
172            );
173        }
174
175        // Set up everything else after CDN sync is done.
176        if let Some(cdn_sync) = cdn_sync {
177            if let Err(error) = cdn_sync.wait().await {
178                crate::log_clean_error(&storage_mode);
179                node.shut_down().await;
180                return Err(error);
181            }
182        }
183
184        // Initialize the routing.
185        node.initialize_routing().await;
186        // Initialize the notification message loop.
187        node.handles.lock().push(crate::start_notification_message_loop());
188        // Pass the node to the signal handler.
189        let _ = signal_node.set(node.clone());
190        // Return the node.
191        Ok(node)
192    }
193
194    /// Returns the ledger.
195    pub fn ledger(&self) -> &Ledger<N, C> {
196        &self.ledger
197    }
198
199    /// Returns the REST server.
200    pub fn rest(&self) -> &Option<Rest<N, C, Self>> {
201        &self.rest
202    }
203}
204
205impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
206    // /// Initialize the transaction pool.
207    // fn initialize_transaction_pool(&self, dev: Option<u16>) -> Result<()> {
208    //     use snarkvm::{
209    //         console::{
210    //             account::ViewKey,
211    //             program::{Identifier, Literal, Plaintext, ProgramID, Record, Value},
212    //             types::U64,
213    //         },
214    //         ledger::block::transition::Output,
215    //     };
216    //     use std::str::FromStr;
217    //
218    //     // Initialize the locator.
219    //     let locator = (ProgramID::from_str("credits.aleo")?, Identifier::from_str("split")?);
220    //     // Initialize the record name.
221    //     let record_name = Identifier::from_str("credits")?;
222    //
223    //     /// Searches the genesis block for the mint record.
224    //     fn search_genesis_for_mint<N: Network>(
225    //         block: Block<N>,
226    //         view_key: &ViewKey<N>,
227    //     ) -> Option<Record<N, Plaintext<N>>> {
228    //         for transition in block.transitions().filter(|t| t.is_mint()) {
229    //             if let Output::Record(_, _, Some(ciphertext)) = &transition.outputs()[0] {
230    //                 if ciphertext.is_owner(view_key) {
231    //                     match ciphertext.decrypt(view_key) {
232    //                         Ok(record) => return Some(record),
233    //                         Err(error) => {
234    //                             error!("Failed to decrypt the mint output record - {error}");
235    //                             return None;
236    //                         }
237    //                     }
238    //                 }
239    //             }
240    //         }
241    //         None
242    //     }
243    //
244    //     /// Searches the block for the split record.
245    //     fn search_block_for_split<N: Network>(
246    //         block: Block<N>,
247    //         view_key: &ViewKey<N>,
248    //     ) -> Option<Record<N, Plaintext<N>>> {
249    //         let mut found = None;
250    //         // TODO (howardwu): Switch to the iterator when DoubleEndedIterator is supported.
251    //         // block.transitions().rev().for_each(|t| {
252    //         let splits = block.transitions().filter(|t| t.is_split()).collect::<Vec<_>>();
253    //         splits.iter().rev().for_each(|t| {
254    //             if found.is_some() {
255    //                 return;
256    //             }
257    //             let Output::Record(_, _, Some(ciphertext)) = &t.outputs()[1] else {
258    //                 error!("Failed to find the split output record");
259    //                 return;
260    //             };
261    //             if ciphertext.is_owner(view_key) {
262    //                 match ciphertext.decrypt(view_key) {
263    //                     Ok(record) => found = Some(record),
264    //                     Err(error) => {
265    //                         error!("Failed to decrypt the split output record - {error}");
266    //                     }
267    //                 }
268    //             }
269    //         });
270    //         found
271    //     }
272    //
273    //     let self_ = self.clone();
274    //     self.spawn(async move {
275    //         // Retrieve the view key.
276    //         let view_key = self_.view_key();
277    //         // Initialize the record.
278    //         let mut record = {
279    //             let mut found = None;
280    //             let mut height = self_.ledger.latest_height();
281    //             while found.is_none() && height > 0 {
282    //                 // Retrieve the block.
283    //                 let Ok(block) = self_.ledger.get_block(height) else {
284    //                     error!("Failed to get block at height {}", height);
285    //                     break;
286    //                 };
287    //                 // Search for the latest split record.
288    //                 if let Some(record) = search_block_for_split(block, view_key) {
289    //                     found = Some(record);
290    //                 }
291    //                 // Decrement the height.
292    //                 height = height.saturating_sub(1);
293    //             }
294    //             match found {
295    //                 Some(record) => record,
296    //                 None => {
297    //                     // Retrieve the genesis block.
298    //                     let Ok(block) = self_.ledger.get_block(0) else {
299    //                         error!("Failed to get the genesis block");
300    //                         return;
301    //                     };
302    //                     // Search the genesis block for the mint record.
303    //                     if let Some(record) = search_genesis_for_mint(block, view_key) {
304    //                         found = Some(record);
305    //                     }
306    //                     found.expect("Failed to find the split output record")
307    //                 }
308    //             }
309    //         };
310    //         info!("Starting transaction pool...");
311    //         // Start the transaction loop.
312    //         loop {
313    //             tokio::time::sleep(Duration::from_secs(1)).await;
314    //             // If the node is running in development mode, only generate if you are allowed.
315    //             if let Some(dev) = dev {
316    //                 if dev != 0 {
317    //                     continue;
318    //                 }
319    //             }
320    //
321    //             // Prepare the inputs.
322    //             let inputs = [Value::from(record.clone()), Value::from(Literal::U64(U64::new(1)))].into_iter();
323    //             // Execute the transaction.
324    //             let transaction = match self_.ledger.vm().execute(
325    //                 self_.private_key(),
326    //                 locator,
327    //                 inputs,
328    //                 None,
329    //                 None,
330    //                 &mut rand::thread_rng(),
331    //             ) {
332    //                 Ok(transaction) => transaction,
333    //                 Err(error) => {
334    //                     error!("Transaction pool encountered an execution error - {error}");
335    //                     continue;
336    //                 }
337    //             };
338    //             // Retrieve the transition.
339    //             let Some(transition) = transaction.transitions().next() else {
340    //                 error!("Transaction pool encountered a missing transition");
341    //                 continue;
342    //             };
343    //             // Retrieve the second output.
344    //             let Output::Record(_, _, Some(ciphertext)) = &transition.outputs()[1] else {
345    //                 error!("Transaction pool encountered a missing output");
346    //                 continue;
347    //             };
348    //             // Save the second output record.
349    //             let Ok(next_record) = ciphertext.decrypt(view_key) else {
350    //                 error!("Transaction pool encountered a decryption error");
351    //                 continue;
352    //             };
353    //             // Broadcast the transaction.
354    //             if self_
355    //                 .unconfirmed_transaction(
356    //                     self_.router.local_ip(),
357    //                     UnconfirmedTransaction::from(transaction.clone()),
358    //                     transaction.clone(),
359    //                 )
360    //                 .await
361    //             {
362    //                 info!("Transaction pool broadcasted the transaction");
363    //                 let commitment = next_record.to_commitment(&locator.0, &record_name).unwrap();
364    //                 while !self_.ledger.contains_commitment(&commitment).unwrap_or(false) {
365    //                     tokio::time::sleep(Duration::from_secs(1)).await;
366    //                 }
367    //                 info!("Transaction accepted by the ledger");
368    //             }
369    //             // Save the record.
370    //             record = next_record;
371    //         }
372    //     });
373    //     Ok(())
374    // }
375
376    /// Initialize the transaction pool.
377    fn initialize_transaction_pool(&self, storage_mode: StorageMode, dev_txs: bool) -> Result<()> {
378        use snarkvm::console::{
379            program::{Identifier, Literal, ProgramID, Value},
380            types::U64,
381        };
382        use std::str::FromStr;
383
384        // Initialize the locator.
385        let locator = (ProgramID::from_str("credits.aleo")?, Identifier::from_str("transfer_public")?);
386
387        // Determine whether to start the loop.
388        match storage_mode {
389            // If the node is running in development mode, only generate if you are allowed.
390            StorageMode::Development(id) => {
391                // If the node is not the first node, or if we should not create dev traffic, do not start the loop.
392                if id != 0 || !dev_txs {
393                    return Ok(());
394                }
395            }
396            // If the node is not running in development mode, do not generate dev traffic.
397            _ => return Ok(()),
398        }
399
400        let self_ = self.clone();
401        self.spawn(async move {
402            tokio::time::sleep(Duration::from_secs(3)).await;
403            info!("Starting transaction pool...");
404
405            // Start the transaction loop.
406            loop {
407                tokio::time::sleep(Duration::from_millis(500)).await;
408
409                // Prepare the inputs.
410                let inputs = [Value::from(Literal::Address(self_.address())), Value::from(Literal::U64(U64::new(1)))];
411                // Execute the transaction.
412                let self__ = self_.clone();
413                let transaction = match spawn_blocking!(self__.ledger.vm().execute(
414                    self__.private_key(),
415                    locator,
416                    inputs.into_iter(),
417                    None,
418                    10_000,
419                    None,
420                    &mut rand::thread_rng(),
421                )) {
422                    Ok(transaction) => transaction,
423                    Err(error) => {
424                        error!("Transaction pool encountered an execution error - {error}");
425                        continue;
426                    }
427                };
428                // Broadcast the transaction.
429                if self_
430                    .unconfirmed_transaction(
431                        self_.router.local_ip(),
432                        UnconfirmedTransaction::from(transaction.clone()),
433                        transaction.clone(),
434                    )
435                    .await
436                {
437                    info!("Transaction pool broadcasted the transaction");
438                }
439            }
440        });
441        Ok(())
442    }
443
444    /// Spawns a task with the given future; it should only be used for long-running tasks.
445    pub fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
446        self.handles.lock().push(tokio::spawn(future));
447    }
448}
449
450#[async_trait]
451impl<N: Network, C: ConsensusStorage<N>> NodeInterface<N> for Validator<N, C> {
452    /// Shuts down the node.
453    async fn shut_down(&self) {
454        info!("Shutting down...");
455
456        // Shut down the node.
457        trace!("Shutting down the node...");
458        self.shutdown.store(true, std::sync::atomic::Ordering::Release);
459
460        // Abort the tasks.
461        trace!("Shutting down the validator...");
462        self.handles.lock().iter().for_each(|handle| handle.abort());
463
464        // Shut down the router.
465        self.router.shut_down().await;
466
467        // Shut down consensus.
468        trace!("Shutting down consensus...");
469        self.consensus.shut_down().await;
470
471        info!("Node has shut down.");
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use snarkvm::prelude::{
479        MainnetV0,
480        VM,
481        store::{ConsensusStore, helpers::memory::ConsensusMemory},
482    };
483
484    use anyhow::bail;
485    use rand::SeedableRng;
486    use rand_chacha::ChaChaRng;
487    use std::str::FromStr;
488
489    type CurrentNetwork = MainnetV0;
490
491    /// Use `RUST_MIN_STACK=67108864 cargo test --release profiler --features timer` to run this test.
492    #[ignore]
493    #[tokio::test]
494    async fn test_profiler() -> Result<()> {
495        // Specify the node attributes.
496        let node = SocketAddr::from_str("0.0.0.0:4130").unwrap();
497        let rest = SocketAddr::from_str("0.0.0.0:3030").unwrap();
498        let storage_mode = StorageMode::Development(0);
499        let dev_txs = true;
500
501        // Initialize an (insecure) fixed RNG.
502        let mut rng = ChaChaRng::seed_from_u64(1234567890u64);
503        // Initialize the account.
504        let account = Account::<CurrentNetwork>::new(&mut rng).unwrap();
505        // Initialize a new VM.
506        let vm = VM::from(ConsensusStore::<CurrentNetwork, ConsensusMemory<CurrentNetwork>>::open(
507            StorageMode::new_test(None),
508        )?)?;
509        // Initialize the genesis block.
510        let genesis = vm.genesis_beacon(account.private_key(), &mut rng)?;
511
512        println!("Initializing validator node...");
513
514        let validator = Validator::<CurrentNetwork, ConsensusMemory<CurrentNetwork>>::new(
515            node,
516            None,
517            Some(rest),
518            10,
519            account,
520            &[],
521            &[],
522            genesis,
523            None,
524            storage_mode,
525            false,
526            dev_txs,
527            Default::default(),
528        )
529        .await
530        .unwrap();
531
532        println!("Loaded validator node with {} blocks", validator.ledger.latest_height(),);
533
534        bail!("\n\nRemember to #[ignore] this test!\n\n")
535    }
536}