From 86965c188e29191b60da51ce7d998157e1d50f77 Mon Sep 17 00:00:00 2001 From: Michael Mallan Date: Sun, 8 Sep 2024 17:12:36 +0100 Subject: [PATCH] electrum: common ancestor is before first changed block --- src/bitcoin/electrum/mod.rs | 7 ++++++- src/bitcoin/electrum/wallet.rs | 15 +++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/bitcoin/electrum/mod.rs b/src/bitcoin/electrum/mod.rs index af14c586..5f72ceb8 100644 --- a/src/bitcoin/electrum/mod.rs +++ b/src/bitcoin/electrum/mod.rs @@ -212,7 +212,12 @@ impl Electrum { None } else { log::info!("Block chain reorganization detected."); - Some(self.bdk_wallet.find_block_at_or_before_height(height)) + // We can assume height is positive as genesis block will not have changed. + Some( + self.bdk_wallet + .find_block_before_height(height) + .expect("height of first change is greater than 0"), + ) }; } Some((_, None)) => continue, diff --git a/src/bitcoin/electrum/wallet.rs b/src/bitcoin/electrum/wallet.rs index 2e467f21..cea08c9c 100644 --- a/src/bitcoin/electrum/wallet.rs +++ b/src/bitcoin/electrum/wallet.rs @@ -295,17 +295,20 @@ impl BdkWallet { }) } - /// Find the first block in the local chain whose height is less than or equal to this. - pub fn find_block_at_or_before_height(&self, height: u32) -> BlockChainTip { + /// Find the highest block in the local chain whose height is below `height`. + /// + /// As the local chain will always contain the genesis block, this returns + /// `None` only if `height` is 0. + pub fn find_block_before_height(&self, height: u32) -> Option { for cp in self.local_chain.iter_checkpoints() { - if cp.height() <= height { - return BlockChainTip { + if cp.height() < height { + return Some(BlockChainTip { height: height_i32_from_u32(cp.height()), hash: cp.hash(), - }; + }); } } - unreachable!("There must be at least the genesis block.") + None } /// Apply an update to the local chain.