Skip to content

Commit

Permalink
perf: calculate the main chain height more efficiently (#237)
Browse files Browse the repository at this point in the history
The Bitcoin testnet's metrics endpoint ran out of cycles because it had
a large number of unstable blocks, and computing the main chain height
under those conditions was very expensive.

This commit makes that computation more efficient. Prior to this change,
the `get_metrics` benchmark took `163_059_419` cycles. Now it takes
`8_102_095`.
  • Loading branch information
ielashi authored Jul 26, 2023
1 parent 6c5dfda commit 32bf6fc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion canister/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ pub fn ingest_stable_blocks_into_utxoset(state: &mut State) -> bool {
}

pub fn main_chain_height(state: &State) -> Height {
unstable_blocks::get_main_chain(&state.unstable_blocks).len() as u32 + state.utxos.next_height()
unstable_blocks::get_main_chain_length(&state.unstable_blocks) as u32
+ state.utxos.next_height()
- 1
}

Expand Down
16 changes: 16 additions & 0 deletions canister/src/unstable_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,22 @@ pub fn get_main_chain(blocks: &UnstableBlocks) -> BlockChain {
main_chain
}

/// Returns the length of the "main chain".
/// See `get_main_chain` for what defines a main chain.
pub fn get_main_chain_length(blocks: &UnstableBlocks) -> usize {
let blocks_by_height = blocks.blocks_with_depths_by_heights();

// Traverse the heights in reverse order. The highest height with a single block corresponds to
// the tip of the main chain.
for height in (0..blocks_by_height.len()).rev() {
if blocks_by_height[height].len() == 1 {
return height + 1;
}
}

unreachable!("There must be at least one height with exactly one block.");
}

pub fn get_blocks(blocks: &UnstableBlocks) -> Vec<&Block> {
blocktree::blockchains(&blocks.tree)
.into_iter()
Expand Down

0 comments on commit 32bf6fc

Please sign in to comment.