Skip to content
Open
13 changes: 9 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@
an LSP when an inbound payment is received through an LSPS2 just-in-time channel.
- The Bitcoin Core RPC and REST chain-source builder methods now accept an optional
`wallet_rescan_from_height` argument. Passing a height lets fresh wallets rescan from a known
birthday block instead of checkpointing at the current tip, which is useful when restoring a
wallet on a pruned node where the full history is unavailable but the wallet birthday height is
known. Existing wallets are not rewound, and future heights fail the build. Passing `Some(0)`
rescans from genesis; passing `None` keeps the default current-tip checkpoint behavior. (#884)
birthday block, which is useful when restoring a wallet on a pruned node where the full history
is unavailable but the wallet birthday height is known. Existing wallets are not rewound, and
future heights fail the build. Passing `Some(0)` rescans from genesis; passing `None` checkpoints
12 blocks behind the current tip, or at genesis on shorter chains. (#884)
- `EsploraSyncConfig` and `ElectrumSyncConfig` now support `force_wallet_full_scan`. When set,
the on-chain wallet keeps using BDK `full_scan` instead of incremental sync until a full scan
succeeds, allowing restored wallets to rediscover funds sent to previously-unknown addresses.
Expand All @@ -97,6 +97,11 @@
transaction.

## Bug Fixes and Improvements
- New Bitcoin Core RPC/REST wallets default to a checkpoint 12 blocks behind the chain tip
(or genesis on shorter chains), allowing reorgs within that window to be replayed. This adds
up to 12 blocks of initial scanning. Explicit rescan heights scan at least this window as well
as all requested history. Existing wallets are unchanged. Deeper reorgs that remove the
birthday checkpoint can still prevent wallet synchronization and require recovery.
- `Node::bump_channel_funding_fee` can now fee-bump a splice made with
`Node::splice_in_with_all` without spending the anchor reserve or failing for lack of a change
output. The splice now spends the wallet's confirmed UTXOs in full, so a bump is paid by adding
Expand Down
126 changes: 78 additions & 48 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use bitcoin::Network;
use bitcoin_payment_instructions::dns_resolver::DNSHrnResolver;
#[cfg(feature = "unified-payments")]
use bitcoin_payment_instructions::onion_message_resolver::LDKOnionMessageDNSSECHrnResolver;
use lightning::chain::channelmonitor::ANTI_REORG_DELAY;
use lightning::chain::{chainmonitor, BlockLocator};
use lightning::ln::channelmanager::{self, ChainParameters, ChannelManagerReadArgs};
use lightning::ln::msgs::{RoutingMessageHandler, SocketAddress};
Expand Down Expand Up @@ -121,6 +122,9 @@ use crate::{Node, NodeMetrics, PersistedNodeMetrics};

const LSPS_HARDENED_CHILD_INDEX: u32 = 577;
const PERSISTER_MAX_PENDING_UPDATES: u64 = 100;
// Match the ancestor-history capacity of LDK's BlockLocator. Keeping the initial sparse
// checkpoint behind the tip allows reorgs within this window to be replayed.
const WALLET_BIRTHDAY_BLOCK_BUFFER: u32 = ANTI_REORG_DELAY * 2;

#[derive(Debug, Clone)]
enum ChainDataSourceConfig {
Expand Down Expand Up @@ -233,12 +237,11 @@ pub enum BuildError {
AsyncPaymentsConfigMismatch,
/// An attempt to setup a DNS Resolver failed.
DNSResolverSetupFailed,
/// We failed to determine the current chain tip on first startup.
/// We failed to fetch the current tip hash or the wallet birthday hash on first startup.
///
/// Returned when a fresh node is built against a Bitcoin Core RPC or REST chain source that
/// is unreachable or misconfigured, so we cannot learn the tip height/hash to use as the
/// wallet birthday. Falling back to genesis would silently force a full-history rescan on
/// the next successful startup, so we abort instead.
/// Returned when a fresh node's Bitcoin Core RPC or REST chain source fails to provide the
/// current tip hash or the wallet birthday hash. Falling back to genesis would silently
/// force a full-history rescan on the next successful startup, so we abort instead.
ChainTipFetchFailed,
/// The configured wallet rescan height is above the current chain tip.
WalletRescanHeightTooHigh,
Expand Down Expand Up @@ -283,7 +286,7 @@ impl fmt::Display for BuildError {
Self::ChainTipFetchFailed => {
write!(
f,
"Failed to determine the current chain tip on first startup. Verify the chain data source is reachable and correctly configured."
"Failed to fetch the current tip hash or the wallet birthday hash on first startup. Verify the chain data source is reachable and correctly configured."
)
},
Self::WalletRescanHeightTooHigh => {
Expand Down Expand Up @@ -453,7 +456,12 @@ impl NodeBuilder {
/// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on
/// first startup, before wallet state exists. Existing wallets are not rewound. The height
/// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None`
/// checkpoints at the current tip.
/// checkpoints 12 blocks behind the current tip, or at genesis on shorter chains. Explicit
/// heights also scan at least this window, starting earlier if needed to include the
/// requested height.
///
/// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the
/// birthday checkpoint, the wallet may stop synchronizing and require recovery.
#[cfg(feature = "chain-bitcoind")]
pub fn set_chain_source_bitcoind_rpc(
&mut self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String,
Expand Down Expand Up @@ -482,7 +490,12 @@ impl NodeBuilder {
/// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on
/// first startup, before wallet state exists. Existing wallets are not rewound. The height
/// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None`
/// checkpoints at the current tip.
/// checkpoints 12 blocks behind the current tip, or at genesis on shorter chains. Explicit
/// heights also scan at least this window, starting earlier if needed to include the
/// requested height.
///
/// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the
/// birthday checkpoint, the wallet may stop synchronizing and require recovery.
#[cfg(feature = "chain-bitcoind")]
pub fn set_chain_source_bitcoind_rest(
&mut self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16,
Expand Down Expand Up @@ -1127,7 +1140,12 @@ impl Builder {
/// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on
/// first startup, before wallet state exists. Existing wallets are not rewound. The height
/// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None`
/// checkpoints at the current tip.
/// checkpoints 12 blocks behind the current tip, or at genesis on shorter chains. Explicit
/// heights also scan at least this window, starting earlier if needed to include the
/// requested height.
///
/// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the
/// birthday checkpoint, the wallet may stop synchronizing and require recovery.
pub fn set_chain_source_bitcoind_rpc(
&self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String,
wallet_rescan_from_height: Option<u32>,
Expand All @@ -1153,7 +1171,12 @@ impl Builder {
/// * `wallet_rescan_from_height` - Optional wallet birthday height to rescan from (inclusive) on
/// first startup, before wallet state exists. Existing wallets are not rewound. The height
/// must be at or below the current tip. Passing `Some(0)` rescans from genesis; passing `None`
/// checkpoints at the current tip.
/// checkpoints 12 blocks behind the current tip, or at genesis on shorter chains. Explicit
/// heights also scan at least this window, starting earlier if needed to include the
/// requested height.
///
/// This margin does not guarantee recovery from deeper reorgs. If a reorg removes the
/// birthday checkpoint, the wallet may stop synchronizing and require recovery.
pub fn set_chain_source_bitcoind_rest(
&self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16,
rpc_user: String, rpc_password: String, wallet_rescan_from_height: Option<u32>,
Expand Down Expand Up @@ -1853,6 +1876,7 @@ fn build_with_store_internal(
// if we are creating a new wallet but failed to learn the current chain tip from
// a Bitcoin Core RPC/REST backend, we'd otherwise persist fresh wallet state
// pinned at height 0 and force a full-history rescan once the backend comes back.
// Explicit rescan heights also need the tip to enforce the birthday margin.
// Abort cleanly instead so the misconfiguration surfaces on the first startup.
// Esplora/Electrum backends currently never return a tip at build time, so they
// retain their existing behavior.
Expand All @@ -1862,7 +1886,7 @@ fn build_with_store_internal(
#[cfg(not(feature = "chain-bitcoind"))]
let uses_bitcoind = false;

if wallet_rescan_from_height.is_none() && chain_tip_opt.is_none() && uses_bitcoind {
if chain_tip_opt.is_none() && uses_bitcoind {
log_error!(
logger,
"Failed to determine chain tip on first startup. Aborting to avoid pinning the wallet birthday to genesis."
Expand All @@ -1880,60 +1904,66 @@ fn build_with_store_internal(
BuildError::WalletSetupFailed
})?;

// Decide which block (if any) to insert as the initial BDK checkpoint. If the
// bitcoind config provides a wallet rescan height, use the preceding block as the
// checkpoint so synchronization includes the requested height. Otherwise, use the
// current chain tip to avoid any rescan.
let checkpoint_block = match wallet_rescan_from_height {
None => chain_tip_opt,
// Default to a checkpoint behind the tip so a reorg does not immediately invalidate
// the wallet's sparse birthday checkpoint. Scan at least the requested history and
// at least the birthday margin, even when an explicit rescan height is supplied.
let checkpoint_height = if let Some(chain_tip) = chain_tip_opt {
let mut height = chain_tip.height.saturating_sub(WALLET_BIRTHDAY_BLOCK_BUFFER);
if let Some(rescan_height) = wallet_rescan_from_height {
if rescan_height > chain_tip.height {
log_error!(
logger,
"Wallet rescan height {} is above current chain tip {}.",
rescan_height,
chain_tip.height
);
return Err(BuildError::WalletRescanHeightTooHigh);
}
// Synchronization connects blocks strictly above the checkpoint.
height = height.min(rescan_height.saturating_sub(1));
}
Some(height)
} else {
None
};
let checkpoint_block: Option<BlockLocator> = match checkpoint_height {
None => None,
#[cfg(feature = "chain-bitcoind")]
Some(height) => {
if let Some(chain_tip) = chain_tip_opt {
if height > chain_tip.height {
log_error!(
logger,
"Wallet rescan height {} is above current chain tip {}.",
height,
chain_tip.height
);
return Err(BuildError::WalletRescanHeightTooHigh);
}
}
// `synchronize_listeners` connects blocks strictly above each listener's
// checkpoint. The genesis block is already BDK's initial checkpoint, so
// saturating subtraction also handles a requested height of zero.
let checkpoint_height = height.saturating_sub(1);

let utxo_source = chain_source.as_utxo_source().ok_or_else(|| {
log_error!(
logger,
"Wallet rescan height requested but the chain source does not support block-by-height lookups.",
"Wallet checkpoint requested but the chain source does not support block-by-height lookups."
);
BuildError::WalletSetupFailed
})?;
let hash_res = runtime.block_on(async {
lightning_block_sync::gossip::UtxoSource::get_block_hash_by_height(
&utxo_source,
checkpoint_height,
let hash = match runtime.block_on(async {
tokio::time::timeout(
std::time::Duration::from_secs(
crate::chain::bitcoind::CHAIN_POLLING_TIMEOUT_SECS,
),
lightning_block_sync::gossip::UtxoSource::get_block_hash_by_height(
&utxo_source,
height,
),
)
.await
});
match hash_res {
Ok(hash) => Some(BlockLocator::new(hash, checkpoint_height)),
Err(e) => {
}) {
Ok(Ok(hash)) => hash,
failure => {
log_error!(
logger,
"Failed to resolve checkpoint block hash at height {} for wallet rescan from height {}: {:?}",
checkpoint_height,
"Failed to resolve the wallet birthday hash at height {}: {:?}",
height,
e,
failure
);
return Err(BuildError::WalletSetupFailed);
return Err(BuildError::ChainTipFetchFailed);
},
}
};
Some(BlockLocator::new(hash, height))
},
#[cfg(not(feature = "chain-bitcoind"))]
Some(_) => unreachable!("wallet rescans require the chain-bitcoind feature"),
Some(_) => unreachable!("wallet checkpoints require the chain-bitcoind feature"),
};

if let Some(best_block) = checkpoint_block {
Expand Down
2 changes: 1 addition & 1 deletion src/chain/bitcoind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use crate::types::{Broadcaster, ChainMonitor, ChannelManager, DynStore, Sweeper,
use crate::{Error, PersistedNodeMetrics};

const CHAIN_POLLING_INTERVAL_SECS: u64 = 2;
const CHAIN_POLLING_TIMEOUT_SECS: u64 = 10;
pub(crate) const CHAIN_POLLING_TIMEOUT_SECS: u64 = 10;

type BitcoindSpvClient =
SpvClient<ChainPoller<Arc<BitcoindClient>, BitcoindClient>, Arc<ChainListener>>;
Expand Down
Loading
Loading