#![forbid(unsafe_code)]
#![warn(clippy::cast_possible_truncation)]
#[macro_use]
extern crate tracing;
pub use ledger_authority as authority;
pub use ledger_block as block;
pub use ledger_committee as committee;
pub use ledger_narwhal as narwhal;
pub use ledger_puzzle as puzzle;
pub use ledger_query as query;
pub use ledger_store as store;
pub use crate::block::*;
#[cfg(feature = "test-helpers")]
pub use ledger_test_helpers;
mod helpers;
pub use helpers::*;
mod advance;
mod check_next_block;
mod check_transaction_basic;
mod contains;
mod find;
mod get;
mod iterators;
#[cfg(test)]
mod tests;
use console::{
account::{Address, GraphKey, PrivateKey, ViewKey},
network::prelude::*,
program::{Ciphertext, Entry, Identifier, Literal, Plaintext, ProgramID, Record, StatePath, Value},
types::{Field, Group},
};
use ledger_authority::Authority;
use ledger_committee::Committee;
use ledger_narwhal::{BatchCertificate, Subdag, Transmission, TransmissionID};
use ledger_puzzle::{Puzzle, PuzzleSolutions, Solution, SolutionID};
use ledger_query::Query;
use ledger_store::{ConsensusStorage, ConsensusStore};
use synthesizer::{
program::{FinalizeGlobalState, Program},
vm::VM,
};
use aleo_std::{
StorageMode,
prelude::{finish, lap, timer},
};
use anyhow::Result;
use core::ops::Range;
use indexmap::IndexMap;
use parking_lot::RwLock;
use rand::{prelude::IteratorRandom, rngs::OsRng};
use std::{borrow::Cow, sync::Arc};
use time::OffsetDateTime;
#[cfg(not(feature = "serial"))]
use rayon::prelude::*;
pub type RecordMap<N> = IndexMap<Field<N>, Record<N, Plaintext<N>>>;
#[derive(Copy, Clone, Debug)]
pub enum RecordsFilter<N: Network> {
All,
Spent,
Unspent,
SlowSpent(PrivateKey<N>),
SlowUnspent(PrivateKey<N>),
}
#[derive(Clone)]
pub struct Ledger<N: Network, C: ConsensusStorage<N>> {
vm: VM<N, C>,
genesis_block: Block<N>,
current_epoch_hash: Arc<RwLock<Option<N::BlockHash>>>,
current_committee: Arc<RwLock<Option<Committee<N>>>>,
current_block: Arc<RwLock<Block<N>>>,
}
impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
pub fn load(genesis_block: Block<N>, storage_mode: StorageMode) -> Result<Self> {
let timer = timer!("Ledger::load");
let genesis_hash = genesis_block.hash();
let ledger = Self::load_unchecked(genesis_block, storage_mode)?;
if !ledger.contains_block_hash(&genesis_hash)? {
bail!("Incorrect genesis block (run 'snarkos clean' and try again)")
}
const NUM_BLOCKS: usize = 10;
let latest_height = ledger.current_block.read().height();
debug_assert_eq!(latest_height, ledger.vm.block_store().max_height().unwrap(), "Mismatch in latest height");
let block_heights: Vec<u32> =
(0..=latest_height).choose_multiple(&mut OsRng, (latest_height as usize).min(NUM_BLOCKS));
cfg_into_iter!(block_heights).try_for_each(|height| {
ledger.get_block(height)?;
Ok::<_, Error>(())
})?;
lap!(timer, "Check existence of {NUM_BLOCKS} random blocks");
finish!(timer);
Ok(ledger)
}
pub fn load_unchecked(genesis_block: Block<N>, storage_mode: StorageMode) -> Result<Self> {
let timer = timer!("Ledger::load_unchecked");
info!("Loading the ledger from storage...");
let store = match ConsensusStore::<N, C>::open(storage_mode) {
Ok(store) => store,
Err(e) => bail!("Failed to load ledger (run 'snarkos clean' and try again)\n\n{e}\n"),
};
lap!(timer, "Load consensus store");
let vm = VM::from(store)?;
lap!(timer, "Initialize a new VM");
let current_committee = vm.finalize_store().committee_store().current_committee().ok();
let mut ledger = Self {
vm,
genesis_block: genesis_block.clone(),
current_epoch_hash: Default::default(),
current_committee: Arc::new(RwLock::new(current_committee)),
current_block: Arc::new(RwLock::new(genesis_block.clone())),
};
if ledger.vm.block_store().max_height().is_none() {
ledger.advance_to_next_block(&genesis_block)?;
}
lap!(timer, "Initialize genesis");
let latest_height =
ledger.vm.block_store().max_height().ok_or_else(|| anyhow!("Failed to load blocks from the ledger"))?;
let block = ledger
.get_block(latest_height)
.map_err(|_| anyhow!("Failed to load block {latest_height} from the ledger"))?;
ledger.current_block = Arc::new(RwLock::new(block));
ledger.current_committee = Arc::new(RwLock::new(Some(ledger.latest_committee()?)));
ledger.current_epoch_hash = Arc::new(RwLock::new(Some(ledger.get_epoch_hash(latest_height)?)));
finish!(timer, "Initialize ledger");
Ok(ledger)
}
pub const fn vm(&self) -> &VM<N, C> {
&self.vm
}
pub const fn puzzle(&self) -> &Puzzle<N> {
self.vm.puzzle()
}
pub fn latest_committee(&self) -> Result<Committee<N>> {
match self.current_committee.read().as_ref() {
Some(committee) => Ok(committee.clone()),
None => self.vm.finalize_store().committee_store().current_committee(),
}
}
pub fn latest_state_root(&self) -> N::StateRoot {
self.vm.block_store().current_state_root()
}
pub fn latest_epoch_number(&self) -> u32 {
self.current_block.read().height() / N::NUM_BLOCKS_PER_EPOCH
}
pub fn latest_epoch_hash(&self) -> Result<N::BlockHash> {
match self.current_epoch_hash.read().as_ref() {
Some(epoch_hash) => Ok(*epoch_hash),
None => self.get_epoch_hash(self.latest_height()),
}
}
pub fn latest_block(&self) -> Block<N> {
self.current_block.read().clone()
}
pub fn latest_round(&self) -> u64 {
self.current_block.read().round()
}
pub fn latest_height(&self) -> u32 {
self.current_block.read().height()
}
pub fn latest_hash(&self) -> N::BlockHash {
self.current_block.read().hash()
}
pub fn latest_header(&self) -> Header<N> {
*self.current_block.read().header()
}
pub fn latest_cumulative_weight(&self) -> u128 {
self.current_block.read().cumulative_weight()
}
pub fn latest_cumulative_proof_target(&self) -> u128 {
self.current_block.read().cumulative_proof_target()
}
pub fn latest_solutions_root(&self) -> Field<N> {
self.current_block.read().header().solutions_root()
}
pub fn latest_coinbase_target(&self) -> u64 {
self.current_block.read().coinbase_target()
}
pub fn latest_proof_target(&self) -> u64 {
self.current_block.read().proof_target()
}
pub fn last_coinbase_target(&self) -> u64 {
self.current_block.read().last_coinbase_target()
}
pub fn last_coinbase_timestamp(&self) -> i64 {
self.current_block.read().last_coinbase_timestamp()
}
pub fn latest_timestamp(&self) -> i64 {
self.current_block.read().timestamp()
}
pub fn latest_transactions(&self) -> Transactions<N> {
self.current_block.read().transactions().clone()
}
}
impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
pub fn find_unspent_credits_records(&self, view_key: &ViewKey<N>) -> Result<RecordMap<N>> {
let microcredits = Identifier::from_str("microcredits")?;
Ok(self
.find_records(view_key, RecordsFilter::Unspent)?
.filter(|(_, record)| {
match record.data().get(µcredits) {
Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) => !amount.is_zero(),
_ => false,
}
})
.collect::<IndexMap<_, _>>())
}
pub fn create_deploy<R: Rng + CryptoRng>(
&self,
private_key: &PrivateKey<N>,
program: &Program<N>,
priority_fee_in_microcredits: u64,
query: Option<Query<N, C::BlockStorage>>,
rng: &mut R,
) -> Result<Transaction<N>> {
let records = self.find_unspent_credits_records(&ViewKey::try_from(private_key)?)?;
ensure!(!records.len().is_zero(), "The Aleo account has no records to spend.");
let mut records = records.values();
let fee_record = Some(records.next().unwrap().clone());
self.vm.deploy(private_key, program, fee_record, priority_fee_in_microcredits, query, rng)
}
pub fn create_transfer<R: Rng + CryptoRng>(
&self,
private_key: &PrivateKey<N>,
to: Address<N>,
amount_in_microcredits: u64,
priority_fee_in_microcredits: u64,
query: Option<Query<N, C::BlockStorage>>,
rng: &mut R,
) -> Result<Transaction<N>> {
let records = self.find_unspent_credits_records(&ViewKey::try_from(private_key)?)?;
ensure!(!records.len().is_zero(), "The Aleo account has no records to spend.");
let mut records = records.values();
let inputs = [
Value::Record(records.next().unwrap().clone()),
Value::from_str(&format!("{to}"))?,
Value::from_str(&format!("{amount_in_microcredits}u64"))?,
];
let fee_record = Some(records.next().unwrap().clone());
self.vm.execute(
private_key,
("credits.aleo", "transfer_private"),
inputs.iter(),
fee_record,
priority_fee_in_microcredits,
query,
rng,
)
}
}
#[cfg(test)]
pub(crate) mod test_helpers {
use crate::Ledger;
use aleo_std::StorageMode;
use console::{
account::{Address, PrivateKey, ViewKey},
network::MainnetV0,
prelude::*,
};
use ledger_block::Block;
use ledger_store::ConsensusStore;
use snarkvm_circuit::network::AleoV0;
use synthesizer::vm::VM;
pub(crate) type CurrentNetwork = MainnetV0;
pub(crate) type CurrentAleo = AleoV0;
#[cfg(not(feature = "rocks"))]
pub(crate) type CurrentLedger =
Ledger<CurrentNetwork, ledger_store::helpers::memory::ConsensusMemory<CurrentNetwork>>;
#[cfg(feature = "rocks")]
pub(crate) type CurrentLedger = Ledger<CurrentNetwork, ledger_store::helpers::rocksdb::ConsensusDB<CurrentNetwork>>;
#[cfg(not(feature = "rocks"))]
pub(crate) type CurrentConsensusStore =
ConsensusStore<CurrentNetwork, ledger_store::helpers::memory::ConsensusMemory<CurrentNetwork>>;
#[cfg(feature = "rocks")]
pub(crate) type CurrentConsensusStore =
ConsensusStore<CurrentNetwork, ledger_store::helpers::rocksdb::ConsensusDB<CurrentNetwork>>;
#[allow(dead_code)]
pub(crate) struct TestEnv {
pub ledger: CurrentLedger,
pub private_key: PrivateKey<CurrentNetwork>,
pub view_key: ViewKey<CurrentNetwork>,
pub address: Address<CurrentNetwork>,
}
pub(crate) fn sample_test_env(rng: &mut (impl Rng + CryptoRng)) -> TestEnv {
let private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
let view_key = ViewKey::try_from(&private_key).unwrap();
let address = Address::try_from(&private_key).unwrap();
let ledger = sample_ledger(private_key, rng);
TestEnv { ledger, private_key, view_key, address }
}
pub(crate) fn sample_genesis_block() -> Block<CurrentNetwork> {
Block::<CurrentNetwork>::from_bytes_le(CurrentNetwork::genesis_bytes()).unwrap()
}
pub(crate) fn sample_ledger(
private_key: PrivateKey<CurrentNetwork>,
rng: &mut (impl Rng + CryptoRng),
) -> CurrentLedger {
let store = CurrentConsensusStore::open(None).unwrap();
let genesis = VM::from(store).unwrap().genesis_beacon(&private_key, rng).unwrap();
let ledger = CurrentLedger::load(genesis.clone(), StorageMode::Production).unwrap();
assert_eq!(genesis, ledger.get_block(0).unwrap());
ledger
}
}