Skip to content

Commit

Permalink
chain: add helper methods on CheckPoint
Browse files Browse the repository at this point in the history
* `CheckPoint::from_header` allows us to construct a checkpoint from
  block header.
* `CheckPoint::into_update` transforms the cp into a
  `local_chain::Update`.
  • Loading branch information
evanlinjin committed Oct 9, 2023
1 parent b3db5ca commit 43bc813
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions crates/chain/src/local_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,41 @@ impl CheckPoint {
Self(Arc::new(CPInner { block, prev: None }))
}

/// Construct a checkpoint from the given `header` and block `height`.
///
/// If `header` is of the genesis block, the checkpoint won't have a [`prev`] node. Otherwise,
/// we return a checkpoint linked with the previous block.
///
/// [`prev`]: CheckPoint::prev
pub fn from_header(header: &bitcoin::block::Header, height: u32) -> Self {
let hash = header.block_hash();
let this_block_id = BlockId { height, hash };

let prev_height = match height.checked_sub(1) {
Some(h) => h,
None => return Self::new(this_block_id),
};

let prev_block_id = BlockId {
height: prev_height,
hash: header.prev_blockhash,
};

CheckPoint::new(prev_block_id)
.push(this_block_id)
.expect("must construct checkpoint")
}

/// Convenience method to convert the [`CheckPoint`] into an [`Update`].
///
/// For more information, refer to [`Update`].
pub fn into_update(self, introduce_older_blocks: bool) -> Update {
Update {
tip: self,
introduce_older_blocks,
}
}

/// Puts another checkpoint onto the linked list representing the blockchain.
///
/// Returns an `Err(self)` if the block you are pushing on is not at a greater height that the one you
Expand Down

0 comments on commit 43bc813

Please sign in to comment.