Skip to content

Commit b2ccba3

Browse files
fix(electrum): fixed chain sync issue
* Fixed a logic error in `construct_update_tip` that caused the local chain tip to always be a block behind the actual tip. * Docs are added to clarify the `construct_update_tip` logic. * `ASSUME_FINAL_DEPTH` is renamed to `MAX_REPRG_DEPTH`. Testing: This is tested manually (we need to add a proper test framework in the near future). `example_electrum scan` can detect incoming transactions when unconfirmed, and detect that is becomes confirm in later calls. `exampl_electrum sync` can do that same. Co-authored-by: Wei Chen <[email protected]>
1 parent 38d69c9 commit b2ccba3

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

crates/electrum/src/electrum_ext.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use std::{
1111
str::FromStr,
1212
};
1313

14-
/// We assume that a block of this depth and deeper cannot be reorged.
15-
const ASSUME_FINAL_DEPTH: u32 = 8;
14+
/// We assume that a blocks deeper than this depth cannot be reorged.
15+
const MAX_REORG_DEPTH: u32 = 6;
1616

1717
/// Represents updates fetched from an Electrum server, but excludes full transactions.
1818
///
@@ -302,12 +302,20 @@ fn construct_update_tip(
302302
}
303303
}
304304

305-
// Atomically fetch the latest `ASSUME_FINAL_DEPTH` count of blocks from Electrum. We use this
305+
// Atomically fetch the latest `MAX_REOG_DEPTH + 1` count of blocks from Electrum. We use this
306306
// to construct our checkpoint update.
307+
//
308+
// The reason why we fetch multiple blocks in an atomic/batched call is to ensure consistency
309+
// between the fetched blocks (as there is a still a slim chance that a reorg happens when we
310+
// are fetching blocks individually).
311+
//
312+
// The reason why we want to fetch `MAX_REORG_DEPTH + 1` number of blocks in the batch call, is
313+
// because we want to at least include one block which is "final". This is beneficial if we
314+
// anchor transactions to the lowest-possible block.
307315
let mut new_blocks = {
308-
let start_height = new_tip_height.saturating_sub(ASSUME_FINAL_DEPTH);
316+
let start_height = new_tip_height.saturating_sub(MAX_REORG_DEPTH);
309317
let hashes = client
310-
.block_headers(start_height as _, ASSUME_FINAL_DEPTH as _)?
318+
.block_headers(start_height as _, (MAX_REORG_DEPTH + 1) as _)?
311319
.headers
312320
.into_iter()
313321
.map(|h| h.block_hash());

0 commit comments

Comments
 (0)