Skip to content

Commit

Permalink
feat(chain): impl PartialEq on CheckPoint
Browse files Browse the repository at this point in the history
We impl `PartialEq` on `CheckPoint` instead of directly on `LocalChain`.
We also made the implementation more efficient.
  • Loading branch information
evanlinjin committed Mar 25, 2024
1 parent 99c1865 commit aa84ecf
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions crates/chain/src/local_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use core::convert::Infallible;
use crate::collections::BTreeMap;
use crate::{BlockId, ChainOracle};
use alloc::sync::Arc;
use alloc::vec::Vec;
use bitcoin::block::Header;
use bitcoin::BlockHash;

Expand Down Expand Up @@ -35,6 +34,20 @@ struct CPInner {
prev: Option<Arc<CPInner>>,
}

impl PartialEq for CheckPoint {
fn eq(&self, other: &Self) -> bool {
let mut self_cps = self.iter().map(|cp| cp.block_id());
let mut other_cps = other.iter().map(|cp| cp.block_id());
loop {
match (self_cps.next(), other_cps.next()) {
(Some(self_cp), Some(other_cp)) if self_cp == other_cp => continue,
(None, None) => break true,
_ => break false,
}
}
}
}

impl CheckPoint {
/// Construct a new base block at the front of a linked list.
pub fn new(block: BlockId) -> Self {
Expand Down Expand Up @@ -206,7 +219,7 @@ impl IntoIterator for CheckPoint {
/// Script-pubkey based syncing mechanisms may not introduce transactions in a chronological order
/// so some updates require introducing older blocks (to anchor older transactions). For
/// script-pubkey based syncing, `introduce_older_blocks` would typically be `true`.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq)]
pub struct Update {
/// The update chain's new tip.
pub tip: CheckPoint,
Expand All @@ -220,23 +233,11 @@ pub struct Update {
}

/// This is a local implementation of [`ChainOracle`].
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq)]
pub struct LocalChain {
tip: CheckPoint,
}

impl PartialEq for LocalChain {
fn eq(&self, other: &Self) -> bool {
self.iter_checkpoints()
.map(|cp| cp.block_id())
.collect::<Vec<_>>()
== other
.iter_checkpoints()
.map(|cp| cp.block_id())
.collect::<Vec<_>>()
}
}

// TODO: Figure out whether we can get rid of this
impl From<LocalChain> for BTreeMap<u32, BlockHash> {
fn from(value: LocalChain) -> Self {
Expand Down

0 comments on commit aa84ecf

Please sign in to comment.