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