Skip to content

Commit

Permalink
Merge pull request AleoNet#2515 from ljedrz/perf/faster_max_height
Browse files Browse the repository at this point in the history
[Perf] Speed up the fetching of the latest block height
  • Loading branch information
zosorock authored Oct 22, 2024
2 parents 36b4ef4 + 6730aa9 commit b118ea2
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 23 deletions.
6 changes: 3 additions & 3 deletions ledger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
const NUM_BLOCKS: usize = 10;
// Retrieve the latest height.
let latest_height = ledger.current_block.read().height();
debug_assert_eq!(latest_height, *ledger.vm.block_store().heights().max().unwrap(), "Mismatch in latest height");
debug_assert_eq!(latest_height, ledger.vm.block_store().max_height().unwrap(), "Mismatch in latest height");
// Sample random block heights.
let block_heights: Vec<u32> =
(0..=latest_height).choose_multiple(&mut OsRng, (latest_height as usize).min(NUM_BLOCKS));
Expand Down Expand Up @@ -170,15 +170,15 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
};

// If the block store is empty, initialize the genesis block.
if ledger.vm.block_store().heights().max().is_none() {
if ledger.vm.block_store().max_height().is_none() {
// Add the genesis block.
ledger.advance_to_next_block(&genesis_block)?;
}
lap!(timer, "Initialize genesis");

// Retrieve the latest height.
let latest_height =
*ledger.vm.block_store().heights().max().ok_or_else(|| anyhow!("Failed to load blocks from the ledger"))?;
ledger.vm.block_store().max_height().ok_or_else(|| anyhow!("Failed to load blocks from the ledger"))?;
// Fetch the latest block.
let block = ledger
.get_block(latest_height)
Expand Down
32 changes: 19 additions & 13 deletions ledger/store/src/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1009,16 +1009,19 @@ impl<N: Network, B: BlockStorage<N>> BlockStore<N, B> {

// Compute the block tree.
let tree = {
// Prepare an iterator over the block heights.
let heights = storage.id_map().keys_confirmed();
// Find the maximum block height.
let max_height = storage.id_map().len_confirmed().checked_sub(1).map(u32::try_from);
// Prepare the leaves of the block tree.
let hashes = match heights.max() {
Some(height) => cfg_into_iter!(0..=cow_to_copied!(height))
.map(|height| match storage.get_block_hash(height)? {
Some(hash) => Ok(hash.to_bits_le()),
None => bail!("Missing block hash for block {height}"),
})
.collect::<Result<Vec<Vec<bool>>>>()?,
let hashes = match max_height {
Some(height) => {
let height = height?;
cfg_into_iter!(0..=height)
.map(|height| match storage.get_block_hash(height)? {
Some(hash) => Ok(hash.to_bits_le()),
None => bail!("Missing block hash for block {height}"),
})
.collect::<Result<Vec<Vec<bool>>>>()?
}
None => vec![],
};
// Construct the block tree.
Expand Down Expand Up @@ -1070,10 +1073,8 @@ impl<N: Network, B: BlockStorage<N>> BlockStore<N, B> {
let mut tree = self.tree.write();

// Determine the block heights to remove.
let heights = match self.storage.id_map().keys_confirmed().max() {
Some(height) => {
// Determine the end block height to remove.
let end_height = cow_to_copied!(height);
let heights = match self.max_height() {
Some(end_height) => {
// Determine the start block height to remove.
let start_height = end_height
.checked_sub(n - 1)
Expand Down Expand Up @@ -1355,6 +1356,11 @@ impl<N: Network, B: BlockStorage<N>> BlockStore<N, B> {
self.storage.id_map().keys_confirmed()
}

/// Returns the height of the latest block in the storage.
pub fn max_height(&self) -> Option<u32> {
self.storage.id_map().len_confirmed().checked_sub(1)?.try_into().ok()
}

/// Returns an iterator over the block hashes, for all blocks in `self`.
pub fn hashes(&self) -> impl '_ + Iterator<Item = Cow<'_, N::BlockHash>> {
self.storage.reverse_id_map().keys_confirmed()
Expand Down
4 changes: 1 addition & 3 deletions synthesizer/src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,6 @@ pub(crate) mod test_helpers {

use indexmap::IndexMap;
use once_cell::sync::OnceCell;
use std::borrow::Borrow;
#[cfg(feature = "rocks")]
use std::path::Path;
use synthesizer_snark::VerifyingKey;
Expand Down Expand Up @@ -761,8 +760,7 @@ function compute:
rng: &mut R,
) -> Result<Block<MainnetV0>> {
// Get the most recent block.
let block_hash =
vm.block_store().get_block_hash(*vm.block_store().heights().max().unwrap().borrow()).unwrap().unwrap();
let block_hash = vm.block_store().get_block_hash(vm.block_store().max_height().unwrap()).unwrap().unwrap();
let previous_block = vm.block_store().get_block(&block_hash).unwrap().unwrap();

// Construct the new block header.
Expand Down
6 changes: 2 additions & 4 deletions synthesizer/tests/test_vm_execute_and_finalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ use anyhow::Result;
use console::account::Address;
use indexmap::IndexMap;
use rayon::prelude::*;
use std::borrow::Borrow;
use utilities::*;

#[test]
Expand Down Expand Up @@ -458,8 +457,7 @@ fn construct_next_block<C: ConsensusStorage<CurrentNetwork>, R: Rng + CryptoRng>
rng: &mut R,
) -> Result<Block<CurrentNetwork>> {
// Get the most recent block.
let block_hash =
vm.block_store().get_block_hash(*vm.block_store().heights().max().unwrap().borrow()).unwrap().unwrap();
let block_hash = vm.block_store().get_block_hash(vm.block_store().max_height().unwrap()).unwrap().unwrap();
let previous_block = vm.block_store().get_block(&block_hash).unwrap().unwrap();

// Construct the metadata associated with the block.
Expand Down Expand Up @@ -524,7 +522,7 @@ fn construct_finalize_global_state<C: ConsensusStorage<CurrentNetwork>>(
vm: &VM<CurrentNetwork, C>,
) -> FinalizeGlobalState {
// Retrieve the latest block.
let block_height = *vm.block_store().heights().max().unwrap().clone();
let block_height = vm.block_store().max_height().unwrap();
let latest_block_hash = vm.block_store().get_block_hash(block_height).unwrap().unwrap();
let latest_block = vm.block_store().get_block(&latest_block_hash).unwrap().unwrap();
// Retrieve the latest round.
Expand Down

0 comments on commit b118ea2

Please sign in to comment.