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