Skip to content

Commit 2970b83

Browse files
committed
fix(core): calling CheckPoint::insert with existing block must succeed
Previously, we were panicking when the caller tried to insert a block at height 0. However, this should succeed if the block hash does not change.
1 parent 8760653 commit 2970b83

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

crates/core/src/checkpoint.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -173,15 +173,14 @@ impl CheckPoint {
173173
/// passed in. Of course, if the `block_id` was already present then this just returns `self`.
174174
#[must_use]
175175
pub fn insert(self, block_id: BlockId) -> Self {
176-
assert_ne!(block_id.height, 0, "cannot insert the genesis block");
177-
178176
let mut cp = self.clone();
179177
let mut tail = vec![];
180178
let base = loop {
181179
if cp.height() == block_id.height {
182180
if cp.hash() == block_id.hash {
183181
return self;
184182
}
183+
assert_ne!(cp.height(), 0, "cannot replace genesis block");
185184
// if we have a conflict we just return the inserted block because the tail is by
186185
// implication invalid.
187186
tail = vec![];

crates/core/tests/common.rs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#[allow(unused_macros)]
2+
macro_rules! block_id {
3+
($height:expr, $hash:literal) => {{
4+
bdk_chain::BlockId {
5+
height: $height,
6+
hash: bitcoin::hashes::Hash::hash($hash.as_bytes()),
7+
}
8+
}};
9+
}

crates/core/tests/test_checkpoint.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#[macro_use]
2+
mod common;
3+
4+
use bdk_core::CheckPoint;
5+
6+
/// Inserting a block that already exists in the checkpoint chain must always succeed.
7+
#[test]
8+
fn checkpoint_insert_existing() {
9+
let blocks = &[
10+
block_id!(0, "genesis"),
11+
block_id!(1, "A"),
12+
block_id!(2, "B"),
13+
block_id!(3, "C"),
14+
];
15+
16+
// Index `i` allows us to test with chains of different length.
17+
// Index `j` allows us to test inserting different block heights.
18+
for i in 0..blocks.len() {
19+
let cp_chain = CheckPoint::from_block_ids(blocks[..=i].iter().copied())
20+
.expect("must construct valid chain");
21+
22+
for j in 0..i {
23+
let block_to_insert = cp_chain
24+
.get(j as u32)
25+
.expect("cp of height must exist")
26+
.block_id();
27+
let new_cp_chain = cp_chain.clone().insert(block_to_insert);
28+
29+
assert_eq!(
30+
new_cp_chain, cp_chain,
31+
"must not divert from original chain"
32+
);
33+
assert!(new_cp_chain.eq_ptr(&cp_chain), "pointers must still match");
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)