feat(chain): impl PartialEq on CheckPoint

We impl `PartialEq` on `CheckPoint` instead of directly on `LocalChain`.
We also made the implementation more efficient.
This commit is contained in:
志宇 2024-03-25 12:30:31 +08:00
parent 9a62d56900
commit 2d1d95a685
No known key found for this signature in database
GPG Key ID: F6345C9837C2BDE8

View File

@ -6,7 +6,6 @@ use core::ops::RangeBounds;
use crate::collections::BTreeMap; use crate::collections::BTreeMap;
use crate::{BlockId, ChainOracle}; use crate::{BlockId, ChainOracle};
use alloc::sync::Arc; use alloc::sync::Arc;
use alloc::vec::Vec;
use bitcoin::block::Header; use bitcoin::block::Header;
use bitcoin::BlockHash; use bitcoin::BlockHash;
@ -36,6 +35,14 @@ struct CPInner {
prev: Option<Arc<CPInner>>, prev: Option<Arc<CPInner>>,
} }
impl PartialEq for CheckPoint {
fn eq(&self, other: &Self) -> bool {
let self_cps = self.iter().map(|cp| cp.block_id());
let other_cps = other.iter().map(|cp| cp.block_id());
self_cps.eq(other_cps)
}
}
impl CheckPoint { impl CheckPoint {
/// Construct a new base block at the front of a linked list. /// Construct a new base block at the front of a linked list.
pub fn new(block: BlockId) -> Self { pub fn new(block: BlockId) -> Self {
@ -220,7 +227,7 @@ impl IntoIterator for CheckPoint {
/// Script-pubkey based syncing mechanisms may not introduce transactions in a chronological order /// 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 /// so some updates require introducing older blocks (to anchor older transactions). For
/// script-pubkey based syncing, `introduce_older_blocks` would typically be `true`. /// script-pubkey based syncing, `introduce_older_blocks` would typically be `true`.
#[derive(Debug, Clone)] #[derive(Debug, Clone, PartialEq)]
pub struct Update { pub struct Update {
/// The update chain's new tip. /// The update chain's new tip.
pub tip: CheckPoint, pub tip: CheckPoint,
@ -234,23 +241,11 @@ pub struct Update {
} }
/// This is a local implementation of [`ChainOracle`]. /// This is a local implementation of [`ChainOracle`].
#[derive(Debug, Clone)] #[derive(Debug, Clone, PartialEq)]
pub struct LocalChain { pub struct LocalChain {
tip: CheckPoint, 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 // TODO: Figure out whether we can get rid of this
impl From<LocalChain> for BTreeMap<u32, BlockHash> { impl From<LocalChain> for BTreeMap<u32, BlockHash> {
fn from(value: LocalChain) -> Self { fn from(value: LocalChain) -> Self {