From dcba68d2a86cd67fc565ab0fbebb60582dc051dd Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Thu, 23 Apr 2026 17:59:21 +0000 Subject: [PATCH] Rename `BestBlock` to `BlockLocator` `BestBlock` is now really a pointer to a block rather than just a block itself, so its weird to still call it `BestBlock`. Here we rename it to `BlockLocator`. Co-Authored-By: Claude Opus 4.7 (1M context) --- fuzz/src/chanmon_consistency.rs | 10 +-- fuzz/src/chanmon_deser.rs | 6 +- fuzz/src/full_stack.rs | 6 +- fuzz/src/lsps_message.rs | 4 +- lightning-background-processor/src/lib.rs | 10 +-- lightning-block-sync/src/init.rs | 18 +++--- lightning-block-sync/src/lib.rs | 12 ++-- lightning-block-sync/src/poll.rs | 8 +-- lightning-block-sync/src/test_utils.rs | 14 ++--- lightning/src/chain/chainmonitor.rs | 4 +- lightning/src/chain/channelmonitor.rs | 40 ++++++------ lightning/src/chain/mod.rs | 62 ++++++++++--------- lightning/src/ln/chanmon_update_fail_tests.rs | 4 +- lightning/src/ln/channel.rs | 30 ++++----- lightning/src/ln/channelmanager.rs | 49 ++++++++------- lightning/src/ln/functional_test_utils.rs | 16 ++--- lightning/src/ln/functional_tests.rs | 8 +-- lightning/src/ln/reload_tests.rs | 10 +-- lightning/src/offers/flow.rs | 8 +-- lightning/src/util/persist.rs | 24 +++---- lightning/src/util/sweep.rs | 22 +++---- lightning/src/util/test_utils.rs | 8 +-- 22 files changed, 189 insertions(+), 184 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index 5b5c6391b4b..371fcc1a17f 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -44,7 +44,7 @@ use lightning::chain::chaininterface::{ use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent}; use lightning::chain::transaction::OutPoint; use lightning::chain::{ - chainmonitor, channelmonitor, BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch, + chainmonitor, channelmonitor, BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch, }; use lightning::events; use lightning::ln::channel::{ @@ -332,7 +332,7 @@ impl chain::Watch for TestChainMonitor { .map(|(_, data)| data) .unwrap_or(&map_entry.persisted_monitor); let deserialized_monitor = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut &latest_monitor_data[..], (&*self.keys, &*self.keys), ) @@ -958,7 +958,7 @@ pub fn do_test(data: &[u8], out: Out) { } let network = Network::Bitcoin; let best_block_timestamp = genesis_block(network).header.time; - let params = ChainParameters { network, best_block: BestBlock::from_network(network) }; + let params = ChainParameters { network, best_block: BlockLocator::from_network(network) }; ( ChannelManager::new( $fee_estimator.clone(), @@ -1039,7 +1039,7 @@ pub fn do_test(data: &[u8], out: Out) { // Use a different value of `use_old_mons` if we have another monitor (only for node B) // by shifting `use_old_mons` one in base-3. use_old_mons /= 3; - let mon = <(BestBlock, ChannelMonitor)>::read( + let mon = <(BlockLocator, ChannelMonitor)>::read( &mut &serialized_mon[..], (&**keys, &**keys), ) @@ -1074,7 +1074,7 @@ pub fn do_test(data: &[u8], out: Out) { }; let manager = - <(BestBlock, ChanMan)>::read(&mut &ser[..], read_args).expect("Failed to read manager"); + <(BlockLocator, ChanMan)>::read(&mut &ser[..], read_args).expect("Failed to read manager"); let res = (manager.1, chain_monitor.clone()); for (channel_id, mon) in monitors.drain() { assert_eq!( diff --git a/fuzz/src/chanmon_deser.rs b/fuzz/src/chanmon_deser.rs index be9ffe8f026..3206db0b143 100644 --- a/fuzz/src/chanmon_deser.rs +++ b/fuzz/src/chanmon_deser.rs @@ -1,7 +1,7 @@ // This file is auto-generated by gen_target.sh based on msg_target_template.txt // To modify it, modify msg_target_template.txt and run gen_target.sh instead. -use lightning::chain::{channelmonitor, BestBlock}; +use lightning::chain::{channelmonitor, BlockLocator}; use lightning::util::ser::{ReadableArgs, Writeable, Writer}; use lightning::util::test_channel_signer::TestChannelSigner; use lightning::util::test_utils::OnlyReadsKeysInterface; @@ -21,14 +21,14 @@ impl Writer for VecWriter { #[inline] pub fn do_test(data: &[u8], _out: Out) { if let Ok((latest_block_hash, monitor)) = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut Cursor::new(data), (&OnlyReadsKeysInterface {}, &OnlyReadsKeysInterface {}), ) { let mut w = VecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let deserialized_copy = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut Cursor::new(&w.0), (&OnlyReadsKeysInterface {}, &OnlyReadsKeysInterface {}), ) diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 1f1cf425c92..405d615e6f0 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -39,7 +39,7 @@ use lightning::chain::chaininterface::{ }; use lightning::chain::chainmonitor; use lightning::chain::transaction::OutPoint; -use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen}; +use lightning::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Listen}; use lightning::events::Event; use lightning::ln::channel_state::ChannelDetails; use lightning::ln::channelmanager::{ChainParameters, ChannelManager, InterceptId, PaymentId}; @@ -354,7 +354,7 @@ impl<'a> MoneyLossDetector<'a> { self.header_hashes[self.height - 1].0, self.header_hashes[self.height].1, ); - let best_block = BestBlock::new(header.prev_blockhash, self.height as u32 - 1); + let best_block = BlockLocator::new(header.prev_blockhash, self.height as u32 - 1); self.manager.blocks_disconnected(best_block); self.monitor.blocks_disconnected(best_block); self.height -= 1; @@ -606,7 +606,7 @@ pub fn do_test(mut data: &[u8], logger: &Arc let network = Network::Bitcoin; let best_block_timestamp = genesis_block(network).header.time; - let params = ChainParameters { network, best_block: BestBlock::from_network(network) }; + let params = ChainParameters { network, best_block: BlockLocator::from_network(network) }; let channelmanager = Arc::new(ChannelManager::new( fee_est.clone(), monitor.clone(), diff --git a/fuzz/src/lsps_message.rs b/fuzz/src/lsps_message.rs index 8ff85d0fc24..83fa5ddab6d 100644 --- a/fuzz/src/lsps_message.rs +++ b/fuzz/src/lsps_message.rs @@ -6,7 +6,7 @@ use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use bitcoin::Network; use lightning::chain::Filter; -use lightning::chain::{chainmonitor, BestBlock}; +use lightning::chain::{chainmonitor, BlockLocator}; use lightning::ln::channelmanager::{ChainParameters, ChannelManager}; use lightning::ln::peer_handler::CustomMessageHandler; use lightning::ln::wire::CustomMessageReader; @@ -61,7 +61,7 @@ pub fn do_test(data: &[u8]) { keys_manager.get_peer_storage_key(), false, )); - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let params = ChainParameters { network, best_block }; let manager = Arc::new(ChannelManager::new( Arc::clone(&fee_estimator), diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index c796c53a031..8ab20d5a1f3 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -1937,7 +1937,7 @@ mod tests { use lightning::chain::chainmonitor; use lightning::chain::channelmonitor::ANTI_REORG_DELAY; use lightning::chain::transaction::OutPoint; - use lightning::chain::{BestBlock, Confirm}; + use lightning::chain::{BlockLocator, Confirm}; use lightning::events::{Event, PathFailure, ReplayEvent}; use lightning::ln::channelmanager; use lightning::ln::channelmanager::{ @@ -2121,7 +2121,7 @@ mod tests { tx_broadcaster: Arc, network_graph: Arc>>, logger: Arc, - best_block: BestBlock, + best_block: BlockLocator, scorer: Arc>, sweeper: Arc< OutputSweeperSync< @@ -2484,7 +2484,7 @@ mod tests { keys_manager.get_peer_storage_key(), true, )); - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let params = ChainParameters { network, best_block }; let mut config = UserConfig::default(); config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; @@ -2726,7 +2726,7 @@ mod tests { let height = node.best_block.height + 1; let header = create_dummy_header(prev_blockhash, height); let txdata = vec![(0, tx)]; - node.best_block = BestBlock::new(header.block_hash(), height); + node.best_block = BlockLocator::new(header.block_hash(), height); match i { 1 => { node.node.transactions_confirmed(&header, &txdata, height); @@ -2753,7 +2753,7 @@ mod tests { let prev_blockhash = node.best_block.block_hash; let height = node.best_block.height + 1; let header = create_dummy_header(prev_blockhash, height); - node.best_block = BestBlock::new(header.block_hash(), height); + node.best_block = BlockLocator::new(header.block_hash(), height); if i == num_blocks { // We need the TestBroadcaster to know about the new height so that it doesn't think // we're violating the time lock requirements of transactions broadcasted at that diff --git a/lightning-block-sync/src/init.rs b/lightning-block-sync/src/init.rs index 07c9f230be3..b41489e0a28 100644 --- a/lightning-block-sync/src/init.rs +++ b/lightning-block-sync/src/init.rs @@ -9,7 +9,7 @@ use bitcoin::block::Header; use bitcoin::network::Network; use lightning::chain; -use lightning::chain::BestBlock; +use lightning::chain::BlockLocator; use std::ops::Deref; @@ -46,7 +46,7 @@ where /// use bitcoin::network::Network; /// /// use lightning::chain; -/// use lightning::chain::{BestBlock, Watch}; +/// use lightning::chain::{BlockLocator, Watch}; /// use lightning::chain::chainmonitor; /// use lightning::chain::chainmonitor::ChainMonitor; /// use lightning::chain::channelmonitor::ChannelMonitor; @@ -93,7 +93,7 @@ where /// ) { /// // Read a serialized channel monitor paired with the best block when it was persisted. /// let serialized_monitor = "..."; -/// let (monitor_best_block, mut monitor) = <(BestBlock, ChannelMonitor)>::read( +/// let (monitor_best_block, mut monitor) = <(BlockLocator, ChannelMonitor)>::read( /// &mut Cursor::new(&serialized_monitor), (entropy_source, signer_provider)).unwrap(); /// /// // Read the channel manager paired with the best block when it was persisted. @@ -112,7 +112,7 @@ where /// config, /// vec![&mut monitor], /// ); -/// <(BestBlock, ChannelManager<&ChainMonitor, &T, &ES, &NS, &SP, &F, &R, &MR, &L>)>::read( +/// <(BlockLocator, ChannelManager<&ChainMonitor, &T, &ES, &NS, &SP, &F, &R, &MR, &L>)>::read( /// &mut Cursor::new(&serialized_manager), read_args).unwrap() /// }; /// @@ -140,7 +140,7 @@ where /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor pub async fn synchronize_listeners( - block_source: B, network: Network, mut chain_listeners: Vec<(BestBlock, &L)>, + block_source: B, network: Network, mut chain_listeners: Vec<(BlockLocator, &L)>, ) -> BlockSourceResult<(HeaderCache, ValidatedBlockHeader)> where B::Target: BlockSource, @@ -242,7 +242,7 @@ impl<'a, L: chain::Listen + ?Sized> chain::Listen for DynamicChainListener<'a, L unreachable!() } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { self.0.blocks_disconnected(fork_point) } } @@ -266,9 +266,9 @@ mod tests { let listener_3 = MockChainListener::new().expect_block_connected(*chain.at_height(4)); let listeners = vec![ - (chain.best_block_at_height(1), &listener_1 as &dyn chain::Listen), - (chain.best_block_at_height(2), &listener_2 as &dyn chain::Listen), - (chain.best_block_at_height(3), &listener_3 as &dyn chain::Listen), + (chain.block_locator_at_height(1), &listener_1 as &dyn chain::Listen), + (chain.block_locator_at_height(2), &listener_2 as &dyn chain::Listen), + (chain.block_locator_at_height(3), &listener_3 as &dyn chain::Listen), ]; match synchronize_listeners(&chain, Network::Bitcoin, listeners).await { Ok((cache, header)) => { diff --git a/lightning-block-sync/src/lib.rs b/lightning-block-sync/src/lib.rs index 8e2c5b500f6..b5d76e3bd06 100644 --- a/lightning-block-sync/src/lib.rs +++ b/lightning-block-sync/src/lib.rs @@ -54,7 +54,7 @@ use bitcoin::hash_types::BlockHash; use bitcoin::pow::Work; use lightning::chain; -use lightning::chain::BestBlock; +use lightning::chain::BlockLocator; use std::future::Future; use std::ops::Deref; @@ -372,7 +372,7 @@ impl<'a, L: chain::Listen + ?Sized> ChainNotifier<'a, L> { /// Updates the header cache as it goes, tracking headers needed to find the diff to reuse for /// other objects that might need similar headers. async fn find_difference_from_best_block( - &mut self, current_header: ValidatedBlockHeader, prev_best_block: BestBlock, + &mut self, current_header: ValidatedBlockHeader, prev_best_block: BlockLocator, chain_poller: &mut P, ) -> BlockSourceResult { // Try to resolve the header for the previous best block. First try the block_hash, @@ -393,7 +393,9 @@ impl<'a, L: chain::Listen + ?Sized> ChainNotifier<'a, L> { break; } let height = prev_best_block.height.checked_sub(height_diff).ok_or( - BlockSourceError::persistent("BestBlock had more previous_blocks than its height"), + BlockSourceError::persistent( + "BlockLocator had more previous_blocks than its height", + ), )?; if let Ok(header) = chain_poller.get_header(block_hash, Some(height)).await { found_header = Some(header); @@ -402,7 +404,7 @@ impl<'a, L: chain::Listen + ?Sized> ChainNotifier<'a, L> { } } let found_header = found_header.ok_or_else(|| { - BlockSourceError::persistent("could not resolve any block from BestBlock") + BlockSourceError::persistent("could not resolve any block from BlockLocator") })?; self.find_difference_from_header(current_header, &found_header, chain_poller).await @@ -456,7 +458,7 @@ impl<'a, L: chain::Listen + ?Sized> ChainNotifier<'a, L> { /// Notifies the chain listeners of disconnected blocks. fn disconnect_blocks(&mut self, fork_point: ValidatedBlockHeader) { self.header_cache.blocks_disconnected(&fork_point); - let best_block = BestBlock::new(fork_point.block_hash, fork_point.height); + let best_block = BlockLocator::new(fork_point.block_hash, fork_point.height); self.chain_listener.blocks_disconnected(best_block); } diff --git a/lightning-block-sync/src/poll.rs b/lightning-block-sync/src/poll.rs index fd8c546c56f..5637be174cc 100644 --- a/lightning-block-sync/src/poll.rs +++ b/lightning-block-sync/src/poll.rs @@ -4,7 +4,7 @@ use crate::{BlockData, BlockHeaderData, BlockSource, BlockSourceError, BlockSour use bitcoin::hash_types::BlockHash; use bitcoin::network::Network; -use lightning::chain::BestBlock; +use lightning::chain::BlockLocator; use std::future::Future; use std::ops::Deref; @@ -160,7 +160,7 @@ impl ValidatedBlockHeader { Ok(()) } - /// Returns the [`BestBlock`] corresponding to this validated block header, which can be passed + /// Returns the [`BlockLocator`] corresponding to this validated block header, which can be passed /// into [`ChannelManager::new`] as part of its [`ChainParameters`]. Useful for ensuring that /// the [`SpvClient`] and [`ChannelManager`] are initialized to the same block during a fresh /// start. @@ -169,8 +169,8 @@ impl ValidatedBlockHeader { /// [`ChainParameters`]: lightning::ln::channelmanager::ChainParameters /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager /// [`ChannelManager::new`]: lightning::ln::channelmanager::ChannelManager::new - pub fn to_best_block(&self) -> BestBlock { - BestBlock::new(self.block_hash, self.inner.height) + pub fn to_block_locator(&self) -> BlockLocator { + BlockLocator::new(self.block_hash, self.inner.height) } } diff --git a/lightning-block-sync/src/test_utils.rs b/lightning-block-sync/src/test_utils.rs index 01da431c243..20ed6f0545e 100644 --- a/lightning-block-sync/src/test_utils.rs +++ b/lightning-block-sync/src/test_utils.rs @@ -12,7 +12,7 @@ use bitcoin::transaction; use bitcoin::Transaction; use lightning::chain; -use lightning::chain::BestBlock; +use lightning::chain::BlockLocator; use std::cell::RefCell; use std::collections::VecDeque; @@ -104,12 +104,12 @@ impl Blockchain { block_header.validate(block_hash).unwrap() } - pub fn best_block_at_height(&self, height: usize) -> BestBlock { + pub fn block_locator_at_height(&self, height: usize) -> BlockLocator { let mut previous_blocks = [None; 12]; for (i, height) in (0..height).rev().take(12).enumerate() { previous_blocks[i] = Some(self.blocks[height].block_hash()); } - BestBlock { + BlockLocator { height: height as u32, block_hash: self.blocks[height].block_hash(), previous_blocks, @@ -135,9 +135,9 @@ impl Blockchain { self.at_height(self.blocks.len() - 1) } - pub fn best_block(&self) -> BestBlock { + pub fn best_block(&self) -> BlockLocator { assert!(!self.blocks.is_empty()); - self.best_block_at_height(self.blocks.len() - 1) + self.block_locator_at_height(self.blocks.len() - 1) } pub fn disconnect_tip(&mut self) -> Option { @@ -223,7 +223,7 @@ impl chain::Listen for NullChainListener { &self, _header: &Header, _txdata: &chain::transaction::TransactionData, _height: u32, ) { } - fn blocks_disconnected(&self, _fork_point: BestBlock) {} + fn blocks_disconnected(&self, _fork_point: BlockLocator) {} } pub struct MockChainListener { @@ -284,7 +284,7 @@ impl chain::Listen for MockChainListener { } } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { match self.expected_blocks_disconnected.borrow_mut().pop_front() { None => { panic!( diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index ca01e95c054..b3b69096997 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -37,7 +37,7 @@ use crate::chain::channelmonitor::{ WithChannelMonitor, }; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, WatchedOutput}; +use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, WatchedOutput}; use crate::events::{self, Event, EventHandler, ReplayEvent}; use crate::ln::channel_state::ChannelDetails; #[cfg(peer_storage)] @@ -1473,7 +1473,7 @@ where self.event_notifier.notify(); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { let monitor_states = self.monitors.read().unwrap(); log_debug!( self.logger, diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 810de80da95..c3e20ef5e6f 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -42,7 +42,7 @@ use crate::chain::package::{ HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedHTLCOutput, RevokedOutput, }; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::{BestBlock, WatchedOutput}; +use crate::chain::{BlockLocator, WatchedOutput}; use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent}; use crate::events::{ClosureReason, Event, EventHandler, ReplayEvent}; use crate::ln::chan_utils::{ @@ -505,7 +505,7 @@ impl OnchainEventEntry { conf_threshold } - fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool { + fn has_reached_confirmation_threshold(&self, best_block: &BlockLocator) -> bool { best_block.height >= self.confirmation_threshold() } } @@ -1058,15 +1058,15 @@ impl Readable for IrrevocablyResolvedHTLC { /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date /// information and are actively monitoring the chain. /// -/// Like the [`ChannelManager`], deserialization is implemented for `(BestBlock, ChannelMonitor)`, -/// providing you with the last block hash which was connected before shutting down. You must begin -/// syncing the chain from that point, disconnecting and connecting blocks as required to get to -/// the best chain on startup. Note that all [`ChannelMonitor`]s passed to a [`ChainMonitor`] must +/// Like the [`ChannelManager`], deserialization is implemented for `(BlockLocator, ChannelMonitor)`, +/// providing a locator for the best chain as of the last write before shutting down. You must +/// begin syncing the chain from that locator, disconnecting and connecting blocks as required to +/// get to the best chain on startup. Note that all [`ChannelMonitor`]s passed to a [`ChainMonitor`] must /// by synced as of the same block, so syncing must happen prior to [`ChainMonitor`] /// initialization. /// /// For those loading potentially-ancient [`ChannelMonitor`]s, deserialization is also implemented -/// for `Option<(BestBlock, ChannelMonitor)>`. LDK can no longer deserialize a [`ChannelMonitor`] +/// for `Option<(BlockLocator, ChannelMonitor)>`. LDK can no longer deserialize a [`ChannelMonitor`] /// that was first created in LDK prior to 0.0.110 and last updated prior to LDK 0.0.119. In such /// cases, the `Option<(..)>` deserialization option may return `Ok(None)` rather than failing to /// deserialize, allowing you to differentiate between the two cases. @@ -1354,7 +1354,7 @@ pub(crate) struct ChannelMonitorImpl { // (we do *not*, however, update them in update_monitor to ensure any local user copies keep // their best_block from its state and not based on updated copies that didn't run through // the full block_connected). - best_block: BestBlock, + best_block: BlockLocator, /// The node_id of our counterparty counterparty_node_id: PublicKey, @@ -1858,7 +1858,7 @@ impl ChannelMonitor { on_counterparty_tx_csv: u16, destination_script: &Script, channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool, commitment_transaction_number_obscure_factor: u64, - initial_holder_commitment_tx: HolderCommitmentTransaction, best_block: BestBlock, + initial_holder_commitment_tx: HolderCommitmentTransaction, best_block: BlockLocator, counterparty_node_id: PublicKey, channel_id: ChannelId, is_manual_broadcast: bool, ) -> ChannelMonitor { @@ -2379,7 +2379,7 @@ impl ChannelMonitor { /// Determines if the disconnected block contained any transactions of interest and updates /// appropriately. pub fn blocks_disconnected( - &self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &L, + &self, fork_point: BlockLocator, broadcaster: B, fee_estimator: F, logger: &L, ) { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); @@ -2472,7 +2472,7 @@ impl ChannelMonitor { /// Gets the latest best block which was connected either via the [`chain::Listen`] or /// [`chain::Confirm`] interfaces. - pub fn current_best_block(&self) -> BestBlock { + pub fn current_best_block(&self) -> BlockLocator { self.inner.lock().unwrap().best_block.clone() } @@ -5414,7 +5414,7 @@ impl ChannelMonitorImpl { log_trace!(logger, "Connecting new block {} at height {}", block_hash, height); self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger) } else if block_hash != self.best_block.block_hash { - self.best_block = BestBlock::new(block_hash, height); + self.best_block = BlockLocator::new(block_hash, height); log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height); self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height); let conf_target = self.closure_conf_target(); @@ -5931,7 +5931,7 @@ impl ChannelMonitorImpl { #[rustfmt::skip] fn blocks_disconnected( - &mut self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &WithContext + &mut self, fork_point: BlockLocator, broadcaster: B, fee_estimator: F, logger: &WithContext ) { let new_height = fork_point.height; log_trace!(logger, "Block(s) disconnected to height {}", new_height); @@ -6440,7 +6440,7 @@ impl ReadableArgs<(&'a ES, &'b SP)> - for (BestBlock, ChannelMonitor) + for (BlockLocator, ChannelMonitor) { fn read(reader: &mut R, args: (&'a ES, &'b SP)) -> Result { match >::read(reader, args) { @@ -6482,7 +6482,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP } impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)> - for Option<(BestBlock, ChannelMonitor)> + for Option<(BlockLocator, ChannelMonitor)> { #[rustfmt::skip] fn read(reader: &mut R, args: (&'a ES, &'b SP)) -> Result { @@ -6645,7 +6645,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP } } - let mut best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?); + let mut best_block = BlockLocator::new(Readable::read(reader)?, Readable::read(reader)?); let waiting_threshold_conf_len: u64 = Readable::read(reader)?; let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128)); @@ -6966,7 +6966,7 @@ pub(super) fn dummy_monitor( channel_value_satoshis: 0, }; let shutdown_script = crate::ln::script::ShutdownScript::new_p2wpkh_from_pubkey(dummy_key); - let best_block = BestBlock::from_network(Network::Testnet); + let best_block = BlockLocator::from_network(Network::Testnet); let signer = wrap_signer(keys); ChannelMonitor::new( secp_ctx, @@ -7014,7 +7014,7 @@ mod tests { weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT, }; use crate::chain::transaction::OutPoint; - use crate::chain::{BestBlock, Confirm}; + use crate::chain::{BlockLocator, Confirm}; use crate::io; use crate::ln::chan_utils::{self, HTLCOutputInCommitment, HolderCommitmentTransaction}; use crate::ln::channel_keys::{ @@ -7081,7 +7081,7 @@ mod tests { nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header, &[(0, broadcast_tx)], conf_height); - let (_, pre_update_monitor) = <(BestBlock, ChannelMonitor<_>)>::read( + let (_, pre_update_monitor) = <(BlockLocator, ChannelMonitor<_>)>::read( &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()), (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap(); diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index 9692558cf7c..d72d58b3149 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -38,36 +38,38 @@ pub(crate) mod onchaintx; pub(crate) mod package; pub mod transaction; -/// The best known block as identified by its hash and height. +/// Identifies a position in the chain by its block hash and height, along with recent ancestor +/// hashes used to locate the fork point of a reorg. #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] -pub struct BestBlock { - /// The block's hash +pub struct BlockLocator { + /// The block's hash. pub block_hash: BlockHash, - /// The height at which the block was confirmed. + /// The block's height. pub height: u32, - /// Previous blocks immediately before [`Self::block_hash`], in reverse chronological order. + /// Ancestor block hashes immediately before [`Self::block_hash`], in reverse chronological + /// order. /// /// These ensure we can find the fork point of a reorg if our block source no longer has the - /// previous best tip after a restart. + /// previous tip after a restart. pub previous_blocks: [Option; ANTI_REORG_DELAY as usize * 2], } -impl BestBlock { - /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given +impl BlockLocator { + /// Constructs a `BlockLocator` that represents the genesis block at height 0 of the given /// network. pub fn from_network(network: Network) -> Self { let block_hash = genesis_block(network).header.block_hash(); let previous_blocks = [None; ANTI_REORG_DELAY as usize * 2]; - BestBlock { block_hash, height: 0, previous_blocks } + BlockLocator { block_hash, height: 0, previous_blocks } } - /// Returns a `BestBlock` as identified by the given block hash and height. + /// Returns a `BlockLocator` as identified by the given block hash and height. /// /// This is not exported to bindings users directly as the bindings auto-generate an /// equivalent `new`. pub fn new(block_hash: BlockHash, height: u32) -> Self { let previous_blocks = [None; ANTI_REORG_DELAY as usize * 2]; - BestBlock { block_hash, height, previous_blocks } + BlockLocator { block_hash, height, previous_blocks } } /// Advances to a new block at height [`Self::height`] + 1. @@ -85,14 +87,14 @@ impl BestBlock { self.height += 1; } - /// Updates this object for a new best-block, either delegating to [`Self::advance`] if the new + /// Updates this locator for a new chain tip, either delegating to [`Self::advance`] if the new /// block is simply one higher than the current tip and wiping [`Self::previous_blocks`] if a /// few blocks have been skipped. pub fn update_for_new_tip(&mut self, new_tip_hash: BlockHash, new_tip_height: u32) { if new_tip_height == self.height + 1 { self.advance(new_tip_hash); } else { - *self = BestBlock::new(new_tip_hash, new_tip_height); + *self = BlockLocator::new(new_tip_hash, new_tip_height); } } @@ -115,12 +117,12 @@ impl BestBlock { } } - /// Find the most recent common ancestor between two BestBlocks by searching their block hash - /// histories. + /// Finds the most recent common ancestor between two [`BlockLocator`]s by searching their + /// ancestor hash histories. /// /// Returns the common block hash and height, or None if no common block is found in the /// available histories. - pub fn find_common_ancestor(&self, other: &BestBlock) -> Option<(BlockHash, u32)> { + pub fn find_common_ancestor(&self, other: &BlockLocator) -> Option<(BlockHash, u32)> { // First check if either tip matches if self.block_hash == other.block_hash && self.height == other.height { return Some((self.block_hash, self.height)); @@ -141,11 +143,11 @@ impl BestBlock { } } -impl_writeable_tlv_based!(BestBlock, { +impl_writeable_tlv_based!(BlockLocator, { (0, block_hash, required), // Note that any change to the previous_blocks array length will change the serialization // format and thus it is specified without constants here. - (1, previous_blocks_read, (legacy, [Option; 6 * 2], |_| Ok(()), |us: &BestBlock| Some(us.previous_blocks))), + (1, previous_blocks_read, (legacy, [Option; 6 * 2], |_| Ok(()), |us: &BlockLocator| Some(us.previous_blocks))), (2, height, required), (unused, previous_blocks, (static_value, previous_blocks_read.unwrap_or([None; 6 * 2]))), }); @@ -177,8 +179,8 @@ impl_writeable_tlv_based!(BestBlock, { /// /// # Object Birthday /// -/// Note that most implementations take a [`BestBlock`] on construction and blocks only need to be -/// applied starting from that point. +/// Note that most implementations take a [`BlockLocator`] on construction identifying the best +/// block at that time, and blocks only need to be applied starting from that point. pub trait Listen { /// Notifies the listener that a block was added at the given height, with the transaction data /// possibly filtered. @@ -192,11 +194,11 @@ pub trait Listen { /// Notifies the listener that one or more blocks were removed in anticipation of a reorg. /// - /// The provided [`BestBlock`] is the new best block after disconnecting blocks in the reorg - /// but before connecting new ones (i.e. the "fork point" block). For backwards compatibility, - /// you may instead walk the chain backwards, calling `blocks_disconnected` for each block - /// that is disconnected in a reorg. - fn blocks_disconnected(&self, fork_point_block: BestBlock); + /// The provided [`BlockLocator`] identifies the new best block after disconnecting blocks in + /// the reorg but before connecting new ones (i.e. the "fork point" block). For backwards + /// compatibility, you may instead walk the chain backwards, calling `blocks_disconnected` for + /// each block that is disconnected in a reorg. + fn blocks_disconnected(&self, fork_point_block: BlockLocator); } /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on @@ -532,7 +534,7 @@ impl Listen for dyn core::ops::Deref { (**self).filtered_block_connected(header, txdata, height); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { (**self).blocks_disconnected(fork_point); } } @@ -547,7 +549,7 @@ where self.1.filtered_block_connected(header, txdata, height); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { self.0.blocks_disconnected(fork_point); self.1.blocks_disconnected(fork_point); } @@ -584,8 +586,8 @@ mod tests { #[test] fn test_best_block() { let hash1 = BlockHash::from_slice(&[1; 32]).unwrap(); - let mut chain_a = BestBlock::new(hash1, 100); - let mut chain_b = BestBlock::new(hash1, 100); + let mut chain_a = BlockLocator::new(hash1, 100); + let mut chain_b = BlockLocator::new(hash1, 100); // Test get_hash_at_height on initial block assert_eq!(chain_a.get_hash_at_height(100), Some(hash1)); @@ -613,7 +615,7 @@ mod tests { // Test find_common_ancestor with no common history let hash_other = BlockHash::from_slice(&[99; 32]).unwrap(); - let chain_c = BestBlock::new(hash_other, 200); + let chain_c = BlockLocator::new(hash_other, 200); assert_eq!(chain_a.find_common_ancestor(&chain_c), None); } } diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index af4d1569d0c..9633800db08 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -16,7 +16,7 @@ use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::chainmonitor::ChainMonitor; use crate::chain::channelmonitor::{ChannelMonitor, MonitorEvent, ANTI_REORG_DELAY}; use crate::chain::transaction::OutPoint; -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; +use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentPurpose}; use crate::ln::channel::AnnouncementSigsState; use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, TrustedChannelFeatures}; @@ -90,7 +90,7 @@ fn test_monitor_and_persister_update_fail() { let chain_mon = { let new_monitor = { let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(chan.2).unwrap(); - let (_, new_monitor) = <(BestBlock, ChannelMonitor)>::read( + let (_, new_monitor) = <(BlockLocator, ChannelMonitor)>::read( &mut &monitor.encode()[..], (nodes[0].keys_manager, nodes[0].keys_manager), ) diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 10801edef01..fbf2a4caa9f 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -35,7 +35,7 @@ use crate::chain::channelmonitor::{ LATENCY_GRACE_PERIOD_BLOCKS, }; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::BestBlock; +use crate::chain::BlockLocator; use crate::events::{ClosureReason, FundingInfo}; use crate::ln::chan_utils; use crate::ln::chan_utils::{ @@ -2053,7 +2053,7 @@ where #[rustfmt::skip] pub fn funding_signed( - &mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, logger: &L + &mut self, msg: &msgs::FundingSigned, best_block: BlockLocator, signer_provider: &SP, logger: &L ) -> Result<(&mut FundedChannel, ChannelMonitor), ChannelError> { let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined); let result = if let ChannelPhase::UnfundedOutboundV1(chan) = phase { @@ -2326,7 +2326,7 @@ where #[rustfmt::skip] pub fn commitment_signed( - &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, fee_estimator: &LowerBoundedFeeEstimator, logger: &L + &mut self, msg: &msgs::CommitmentSigned, best_block: BlockLocator, signer_provider: &SP, fee_estimator: &LowerBoundedFeeEstimator, logger: &L ) -> Result<(Option>, Option), ChannelError> { let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined); match phase { @@ -3542,7 +3542,7 @@ trait InitialRemoteCommitmentReceiver { #[rustfmt::skip] fn initial_commitment_signed( &mut self, channel_id: ChannelId, counterparty_signature: Signature, holder_commitment_point: &mut HolderCommitmentPoint, - best_block: BestBlock, signer_provider: &SP, logger: &L, + best_block: BlockLocator, signer_provider: &SP, logger: &L, ) -> Result<(ChannelMonitor, CommitmentTransaction), ChannelError> { let initial_commitment_tx = match self.check_counterparty_commitment_signature(&counterparty_signature, holder_commitment_point, logger) { Ok(res) => res, @@ -7837,7 +7837,7 @@ where #[rustfmt::skip] pub fn channel_ready( &mut self, msg: &msgs::ChannelReady, node_signer: &NS, chain_hash: ChainHash, - user_config: &UserConfig, best_block: &BestBlock, logger: &L + user_config: &UserConfig, best_block: &BlockLocator, logger: &L ) -> Result, ChannelError> { if self.context.channel_state.is_peer_disconnected() { self.context.workaround_lnd_bug_4006 = Some(msg.clone()); @@ -8244,7 +8244,7 @@ where } pub fn initial_commitment_signed_v2( - &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, + &mut self, msg: &msgs::CommitmentSigned, best_block: BlockLocator, signer_provider: &SP, logger: &L, ) -> Result, ChannelError> { if let Some(signing_session) = self.context.interactive_tx_signing_session.as_ref() { @@ -10237,7 +10237,7 @@ where #[rustfmt::skip] pub fn channel_reestablish( &mut self, msg: &msgs::ChannelReestablish, logger: &L, node_signer: &NS, - chain_hash: ChainHash, user_config: &UserConfig, best_block: &BestBlock, + chain_hash: ChainHash, user_config: &UserConfig, best_block: &BlockLocator, path_for_release_htlc: CBP, ) -> Result where @@ -14572,7 +14572,7 @@ impl OutboundV1Channel { /// Handles a funding_signed message from the remote end. /// If this call is successful, broadcast the funding transaction (and not before!) pub fn funding_signed( - mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, + mut self, msg: &msgs::FundingSigned, best_block: BlockLocator, signer_provider: &SP, logger: &L, ) -> Result< (FundedChannel, ChannelMonitor), @@ -14866,7 +14866,7 @@ impl InboundV1Channel { } pub fn funding_created( - mut self, msg: &msgs::FundingCreated, best_block: BestBlock, signer_provider: &SP, + mut self, msg: &msgs::FundingCreated, best_block: BlockLocator, signer_provider: &SP, logger: &L, ) -> Result< (FundedChannel, Option, ChannelMonitor), @@ -16801,7 +16801,7 @@ pub(crate) fn hold_time_since(send_timestamp: Option) -> Option { mod tests { use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::transaction::OutPoint; - use crate::chain::BestBlock; + use crate::chain::BlockLocator; use crate::ln::chan_utils::{self, commit_tx_fee_sat, ChannelTransactionParameters}; use crate::ln::channel::{ AwaitingChannelReadyFlags, ChannelState, FundedChannel, HTLCUpdateAwaitingACK, @@ -17000,7 +17000,7 @@ mod tests { let network = Network::Testnet; let keys_provider = TestKeysInterface::new(&seed, network); let logger = TestLogger::new(); - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); // Go through the flow of opening a channel between two nodes, making sure // they have different dust limits. @@ -17146,7 +17146,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let seed = [42; 32]; let network = Network::Testnet; - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let chain_hash = ChainHash::using_genesis_block(network); let keys_provider = TestKeysInterface::new(&seed, network); @@ -17382,7 +17382,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let seed = [42; 32]; let network = Network::Testnet; - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let chain_hash = ChainHash::using_genesis_block(network); let keys_provider = TestKeysInterface::new(&seed, network); @@ -17460,7 +17460,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let seed = [42; 32]; let network = Network::Testnet; - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let keys_provider = TestKeysInterface::new(&seed, network); let node_b_node_id = @@ -19115,7 +19115,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let seed = [42; 32]; let network = Network::Testnet; - let best_block = BestBlock::from_network(network); + let best_block = BlockLocator::from_network(network); let chain_hash = ChainHash::using_genesis_block(network); let keys_provider = TestKeysInterface::new(&seed, network); diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 73d9a67f50f..570639d8995 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -48,7 +48,7 @@ use crate::chain::channelmonitor::{ LATENCY_GRACE_PERIOD_BLOCKS, MAX_BLOCKS_FOR_CONF, }; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch}; +use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch}; use crate::events::{ self, ClosureReason, Event, EventHandler, EventsProvider, HTLCHandlingFailureType, InboundChannelFunds, PaymentFailureReason, ReplayEvent, @@ -2126,7 +2126,7 @@ impl< /// /// ``` /// use bitcoin::network::Network; -/// use lightning::chain::BestBlock; +/// use lightning::chain::BlockLocator; /// # use lightning::chain::channelmonitor::ChannelMonitor; /// use lightning::ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs}; /// # use lightning::routing::gossip::NetworkGraph; @@ -2152,7 +2152,7 @@ impl< /// # entropy_source: &ES, /// # node_signer: &dyn lightning::sign::NodeSigner, /// # signer_provider: &lightning::sign::DynSignerProvider, -/// # best_block: lightning::chain::BestBlock, +/// # best_block: lightning::chain::BlockLocator, /// # current_timestamp: u32, /// # mut reader: R, /// # ) -> Result<(), lightning::ln::msgs::DecodeError> { @@ -2174,7 +2174,7 @@ impl< /// router, message_router, logger, config, channel_monitors.iter().collect(), /// ); /// let (best_block, channel_manager) = -/// <(BestBlock, ChannelManager<_, _, _, _, _, _, _, _, _>)>::read(&mut reader, args)?; +/// <(BlockLocator, ChannelManager<_, _, _, _, _, _, _, _, _>)>::read(&mut reader, args)?; /// /// // Update the ChannelManager and ChannelMonitors with the latest chain data /// // ... @@ -2741,9 +2741,10 @@ impl< /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds /// will be lost (modulo on-chain transaction fees). /// -/// Note that the deserializer is only implemented for `(`[`BestBlock`]`, `[`ChannelManager`]`)`, which -/// tells you the last block hash which was connected. You should get the best block tip before using the manager. -/// See [`chain::Listen`] and [`chain::Confirm`] for more details. +/// Note that the deserializer is only implemented for `(`[`BlockLocator`]`, `[`ChannelManager`]`)`, +/// which provides a locator for the best chain as of the last write. You should sync to the +/// current best chain tip before using the manager. See [`chain::Listen`] and [`chain::Confirm`] +/// for more details. /// /// # `ChannelUpdate` Messages /// @@ -2835,9 +2836,9 @@ pub struct ChannelManager< flow: OffersMessageFlow, #[cfg(any(test, feature = "_test_utils"))] - pub(super) best_block: RwLock, + pub(super) best_block: RwLock, #[cfg(not(any(test, feature = "_test_utils")))] - best_block: RwLock, + best_block: RwLock, pub(super) secp_ctx: Secp256k1, /// The session_priv bytes and retry metadata of outbound payments which are pending resolution. @@ -3045,7 +3046,7 @@ pub struct ChainParameters { /// The hash and height of the latest block successfully connected. /// /// Used to track on-chain channel funding outputs and send payments with reliable timelocks. - pub best_block: BestBlock, + pub best_block: BlockLocator, } #[derive(Copy, Clone, PartialEq)] @@ -3673,7 +3674,7 @@ impl< /// /// [`block_connected`]: chain::Listen::block_connected /// [`blocks_disconnected`]: chain::Listen::blocks_disconnected - /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash + /// [`params.best_block.block_hash`]: chain::BlockLocator::block_hash #[rustfmt::skip] pub fn new( fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, message_router: MR, logger: L, @@ -15934,7 +15935,7 @@ impl< self.best_block_updated(header, height); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify_skipping_background_events( self, @@ -16431,7 +16432,7 @@ impl< /// Gets the latest best block which was connected either via the [`chain::Listen`] or /// [`chain::Confirm`] interfaces. - pub fn current_best_block(&self) -> BestBlock { + pub fn current_best_block(&self) -> BlockLocator { self.best_block.read().unwrap().clone() } @@ -18372,7 +18373,7 @@ impl Readable for AmountlessClaimablePaymentHTLCOnion { // This is an internal DTO used in the two-stage deserialization process. pub(super) struct ChannelManagerData { chain_hash: ChainHash, - best_block: BestBlock, + best_block: BlockLocator, channels: Vec>, claimable_payments: HashMap, peer_init_features: Vec<(PublicKey, InitFeatures)>, @@ -18694,7 +18695,7 @@ impl<'a, ES: EntropySource, SP: SignerProvider, L: Logger> Ok(ChannelManagerData { chain_hash, - best_block: BestBlock { + best_block: BlockLocator { block_hash: best_block_hash, height: best_block_height, previous_blocks: best_block_previous_blocks.unwrap_or([None; 12]), @@ -18731,7 +18732,7 @@ impl<'a, ES: EntropySource, SP: SignerProvider, L: Logger> /// is: /// 1) Deserialize all stored [`ChannelMonitor`]s. /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling: -/// `<(BestBlock, ChannelManager)>::read(reader, args)` +/// `<(BlockLocator, ChannelManager)>::read(reader, args)` /// This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored /// [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted. /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the @@ -18932,13 +18933,13 @@ impl< MR: MessageRouter, L: Logger + Clone, > ReadableArgs> - for (BestBlock, Arc>) + for (BlockLocator, Arc>) { fn read( reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>, ) -> Result { let (best_block, chan_manager) = - <(BestBlock, ChannelManager)>::read(reader, args)?; + <(BlockLocator, ChannelManager)>::read(reader, args)?; Ok((best_block, Arc::new(chan_manager))) } } @@ -18955,7 +18956,7 @@ impl< MR: MessageRouter, L: Logger + Clone, > ReadableArgs> - for (BestBlock, ChannelManager) + for (BlockLocator, ChannelManager) { fn read( reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>, @@ -18999,7 +19000,7 @@ impl< pub(super) fn from_channel_manager_data( data: ChannelManagerData, mut args: ChannelManagerReadArgs<'_, M, T, ES, NS, SP, F, R, MR, L>, - ) -> Result<(BestBlock, Self), DecodeError> { + ) -> Result<(BlockLocator, Self), DecodeError> { let ChannelManagerData { chain_hash, best_block, @@ -21804,7 +21805,7 @@ pub mod bench { use crate::chain::Listen; use crate::events::Event; use crate::ln::channelmanager::{ - BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentId, PaymentPreimage, + BlockLocator, ChainParameters, ChannelManager, PaymentHash, PaymentId, PaymentPreimage, RecipientOnionFields, Retry, }; use crate::ln::functional_test_utils::*; @@ -21891,7 +21892,7 @@ pub mod bench { let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a, &keys_manager_a, keys_manager_a.get_peer_storage_key(), false); let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &router, &message_router, &logger_a, &keys_manager_a, &keys_manager_a, &keys_manager_a, config.clone(), ChainParameters { network, - best_block: BestBlock::from_network(network), + best_block: BlockLocator::from_network(network), }, genesis_block.header.time); let node_a_holder = ANodeHolder { node: &node_a }; @@ -21901,7 +21902,7 @@ pub mod bench { let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b, &keys_manager_b, keys_manager_b.get_peer_storage_key(), false); let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &router, &message_router, &logger_b, &keys_manager_b, &keys_manager_b, &keys_manager_b, config.clone(), ChainParameters { network, - best_block: BestBlock::from_network(network), + best_block: BlockLocator::from_network(network), }, genesis_block.header.time); let node_b_holder = ANodeHolder { node: &node_b }; @@ -21955,7 +21956,7 @@ pub mod bench { assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]); - let block = create_dummy_block(BestBlock::from_network(network).block_hash, 42, vec![tx]); + let block = create_dummy_block(BlockLocator::from_network(network).block_hash, 42, vec![tx]); Listen::block_connected(&node_a, &block, 1); Listen::block_connected(&node_b, &block, 1); diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index c1923730a3d..b48d76d646d 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -15,7 +15,7 @@ use crate::blinded_path::payment::{ }; use crate::chain::channelmonitor::{ChannelMonitor, HTLC_FAIL_BACK_BUFFER}; use crate::chain::transaction::OutPoint; -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; +use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::events::bump_transaction::sync::BumpTransactionEventHandlerSync; use crate::events::bump_transaction::BumpTransactionEvent; use crate::events::{ @@ -447,13 +447,13 @@ pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) match *node.connect_style.borrow() { ConnectStyle::FullBlockViaListen => { - let best_block = BestBlock::new(orig.0.header.prev_blockhash, orig.1 - 1); + let best_block = BlockLocator::new(orig.0.header.prev_blockhash, orig.1 - 1); node.chain_monitor.chain_monitor.blocks_disconnected(best_block); Listen::blocks_disconnected(node.node, best_block); }, ConnectStyle::FullBlockDisconnectionsSkippingViaListen => { if i == count - 1 { - let best_block = BestBlock::new(orig.0.header.prev_blockhash, orig.1 - 1); + let best_block = BlockLocator::new(orig.0.header.prev_blockhash, orig.1 - 1); node.chain_monitor.chain_monitor.blocks_disconnected(best_block); Listen::blocks_disconnected(node.node, best_block); } @@ -848,7 +848,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mon = self.chain_monitor.chain_monitor.get_monitor(channel_id).unwrap(); mon.write(&mut w).unwrap(); let (_, deserialized_monitor) = - <(BestBlock, ChannelMonitor)>::read( + <(BlockLocator, ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager), ) @@ -877,7 +877,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); self.node.write(&mut w).unwrap(); <( - BestBlock, + BlockLocator, ChannelManager< &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, @@ -1312,7 +1312,7 @@ pub fn _reload_node<'a, 'b, 'c>( let mut monitors_read = Vec::with_capacity(monitors_encoded.len()); for encoded in monitors_encoded { let mut monitor_read = &encoded[..]; - let (_, monitor) = <(BestBlock, ChannelMonitor)>::read( + let (_, monitor) = <(BlockLocator, ChannelMonitor)>::read( &mut monitor_read, (node.keys_manager, node.keys_manager), ) @@ -1327,7 +1327,7 @@ pub fn _reload_node<'a, 'b, 'c>( for monitor in monitors_read.iter() { assert!(channel_monitors.insert(monitor.channel_id(), monitor).is_none()); } - <(BestBlock, TestChannelManager<'b, 'c>)>::read( + <(BlockLocator, TestChannelManager<'b, 'c>)>::read( &mut node_read, ChannelManagerReadArgs { config, @@ -4716,7 +4716,7 @@ pub fn create_node_chanmgrs<'a, 'b>( for i in 0..node_count { let network = Network::Testnet; let genesis_block = bitcoin::constants::genesis_block(network); - let params = ChainParameters { network, best_block: BestBlock::from_network(network) }; + let params = ChainParameters { network, best_block: BlockLocator::from_network(network) }; let node = ChannelManager::new( cfgs[i].fee_estimator, &cfgs[i].chain_monitor, diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index 8d9df062868..c8ecb40fa6d 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -19,7 +19,7 @@ use crate::chain::channelmonitor::{ LATENCY_GRACE_PERIOD_BLOCKS, }; use crate::chain::transaction::OutPoint; -use crate::chain::BestBlock; +use crate::chain::BlockLocator; use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::events::{ ClosureReason, Event, HTLCHandlingFailureType, PathFailure, PaymentFailureReason, @@ -7378,7 +7378,7 @@ pub fn test_update_err_monitor_lockdown() { let new_monitor = { let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(chan_1.2).unwrap(); let new_monitor = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager), ) @@ -7486,7 +7486,7 @@ pub fn test_concurrent_monitor_claim() { let new_monitor = { let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(chan_1.2).unwrap(); let new_monitor = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager), ) @@ -7536,7 +7536,7 @@ pub fn test_concurrent_monitor_claim() { let new_monitor = { let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(chan_1.2).unwrap(); let new_monitor = - <(BestBlock, channelmonitor::ChannelMonitor)>::read( + <(BlockLocator, channelmonitor::ChannelMonitor)>::read( &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager), ) diff --git a/lightning/src/ln/reload_tests.rs b/lightning/src/ln/reload_tests.rs index 9e992467ecd..16ba896685e 100644 --- a/lightning/src/ln/reload_tests.rs +++ b/lightning/src/ln/reload_tests.rs @@ -11,7 +11,7 @@ //! Functional tests which test for correct behavior across node restarts. -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Watch}; +use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Watch}; use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateStep}; use crate::routing::router::{PaymentParameters, RouteParameters}; @@ -411,7 +411,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut node_0_stale_monitors = Vec::new(); for serialized in node_0_stale_monitors_serialized.iter() { let mut read = &serialized[..]; - let (_, monitor) = <(BestBlock, ChannelMonitor)>::read(&mut read, (keys_manager, keys_manager)).unwrap(); + let (_, monitor) = <(BlockLocator, ChannelMonitor)>::read(&mut read, (keys_manager, keys_manager)).unwrap(); assert!(read.is_empty()); node_0_stale_monitors.push(monitor); } @@ -419,14 +419,14 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut node_0_monitors = Vec::new(); for serialized in node_0_monitors_serialized.iter() { let mut read = &serialized[..]; - let (_, monitor) = <(BestBlock, ChannelMonitor)>::read(&mut read, (keys_manager, keys_manager)).unwrap(); + let (_, monitor) = <(BlockLocator, ChannelMonitor)>::read(&mut read, (keys_manager, keys_manager)).unwrap(); assert!(read.is_empty()); node_0_monitors.push(monitor); } let mut nodes_0_read = &nodes_0_serialized[..]; if let Err(msgs::DecodeError::DangerousValue) = - <(BestBlock, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestMessageRouter, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockLocator, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestMessageRouter, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { config: UserConfig::default(), entropy_source: keys_manager, node_signer: keys_manager, @@ -445,7 +445,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut nodes_0_read = &nodes_0_serialized[..]; let (_, nodes_0_deserialized_tmp) = - <(BestBlock, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestMessageRouter, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockLocator, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestMessageRouter, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { config: UserConfig::default(), entropy_source: keys_manager, node_signer: keys_manager, diff --git a/lightning/src/offers/flow.rs b/lightning/src/offers/flow.rs index 2edcbc8aba8..6c1b7a5befe 100644 --- a/lightning/src/offers/flow.rs +++ b/lightning/src/offers/flow.rs @@ -29,7 +29,7 @@ use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS; #[allow(unused_imports)] use crate::prelude::*; -use crate::chain::BestBlock; +use crate::chain::BlockLocator; use crate::ln::channel_state::ChannelDetails; use crate::ln::channelmanager::{InterceptId, PaymentId, CLTV_FAR_FAR_AWAY}; use crate::ln::inbound_payment; @@ -69,7 +69,7 @@ use crate::util::ser::Writeable; /// for finding message paths when initiating and retrying onion messages. pub struct OffersMessageFlow { chain_hash: ChainHash, - best_block: RwLock, + best_block: RwLock, our_network_pubkey: PublicKey, highest_seen_timestamp: AtomicUsize, @@ -94,7 +94,7 @@ pub struct OffersMessageFlow { impl OffersMessageFlow { /// Creates a new [`OffersMessageFlow`] pub fn new( - chain_hash: ChainHash, best_block: BestBlock, our_network_pubkey: PublicKey, + chain_hash: ChainHash, best_block: BlockLocator, our_network_pubkey: PublicKey, current_timestamp: u32, inbound_payment_key: inbound_payment::ExpandedKey, receive_auth_key: ReceiveAuthKey, secp_ctx: Secp256k1, message_router: MR, logger: L, @@ -189,7 +189,7 @@ impl OffersMessageFlow { // Note that we deliberately don't use `update_for_new_tip` as we dont rely on receiving // disconnection information instead expecting to simply "jump" to the new tip. - *self.best_block.write().unwrap() = BestBlock::new(header.block_hash(), height); + *self.best_block.write().unwrap() = BlockLocator::new(header.block_hash(), height); loop { // Update timestamp to be the max of its current value and the block diff --git a/lightning/src/util/persist.rs b/lightning/src/util/persist.rs index 68359636f6b..95d6032e130 100644 --- a/lightning/src/util/persist.rs +++ b/lightning/src/util/persist.rs @@ -33,7 +33,7 @@ use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use crate::chain::chainmonitor::Persist; use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate}; use crate::chain::transaction::OutPoint; -use crate::chain::BestBlock; +use crate::chain::BlockLocator; use crate::ln::types::ChannelId; use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider}; use crate::sync::Mutex; @@ -654,7 +654,7 @@ impl Persist( kv_store: K, entropy_source: ES, signer_provider: SP, -) -> Result)>, io::Error> +) -> Result)>, io::Error> where K::Target: KVStoreSync, { @@ -664,7 +664,7 @@ where CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, )? { - match )>>::read( + match )>>::read( &mut io::Cursor::new(kv_store.read( CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, @@ -857,7 +857,7 @@ where /// Reads all stored channel monitors, along with any stored updates for them. pub fn read_all_channel_monitors_with_updates( &self, - ) -> Result)>, io::Error> { + ) -> Result)>, io::Error> { poll_sync_future(self.0.read_all_channel_monitors_with_updates()) } @@ -878,7 +878,7 @@ where /// function to accomplish this. Take care to limit the number of parallel readers. pub fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BestBlock, ChannelMonitor), io::Error> { + ) -> Result<(BlockLocator, ChannelMonitor), io::Error> { poll_sync_future(self.0.read_channel_monitor_with_updates(monitor_key)) } @@ -1045,7 +1045,7 @@ impl< /// deserialization as well. pub async fn read_all_channel_monitors_with_updates( &self, - ) -> Result)>, io::Error> { + ) -> Result)>, io::Error> { let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; let monitor_list = self.0.kv_store.list(primary, secondary).await?; @@ -1076,7 +1076,7 @@ impl< /// `Arc` that can live for `'static` and be sent and accessed across threads. pub async fn read_all_channel_monitors_with_updates_parallel( self: &Arc, - ) -> Result)>, io::Error> + ) -> Result)>, io::Error> where K: MaybeSend + MaybeSync + 'static, L: MaybeSend + MaybeSync + 'static, @@ -1126,7 +1126,7 @@ impl< /// function to accomplish this. Take care to limit the number of parallel readers. pub async fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BestBlock, ChannelMonitor), io::Error> { + ) -> Result<(BlockLocator, ChannelMonitor), io::Error> { self.0.read_channel_monitor_with_updates(monitor_key).await } @@ -1237,7 +1237,7 @@ impl< { pub async fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BestBlock, ChannelMonitor), io::Error> { + ) -> Result<(BlockLocator, ChannelMonitor), io::Error> { match self.maybe_read_channel_monitor_with_updates(monitor_key).await? { Some(res) => Ok(res), None => Err(io::Error::new( @@ -1254,7 +1254,7 @@ impl< async fn maybe_read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result)>, io::Error> { + ) -> Result)>, io::Error> { let monitor_name = MonitorName::from_str(monitor_key)?; let read_future = pin!(self.maybe_read_monitor(&monitor_name, monitor_key)); let list_future = pin!(self @@ -1298,7 +1298,7 @@ impl< /// Read a channel monitor. async fn maybe_read_monitor( &self, monitor_name: &MonitorName, monitor_key: &str, - ) -> Result)>, io::Error> { + ) -> Result)>, io::Error> { let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; let monitor_bytes = self.kv_store.read(primary, secondary, monitor_key).await?; @@ -1307,7 +1307,7 @@ impl< if monitor_cursor.get_ref().starts_with(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL) { monitor_cursor.set_position(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() as u64); } - match )>>::read( + match )>>::read( &mut monitor_cursor, (&self.entropy_source, &self.signer_provider), ) { diff --git a/lightning/src/util/sweep.rs b/lightning/src/util/sweep.rs index bbaaf2905ee..e66cb9c63bd 100644 --- a/lightning/src/util/sweep.rs +++ b/lightning/src/util/sweep.rs @@ -12,7 +12,7 @@ use crate::chain::chaininterface::{ BroadcasterInterface, ConfirmationTarget, FeeEstimator, TransactionType, }; use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ARCHIVAL_DELAY_BLOCKS}; -use crate::chain::{self, BestBlock, Confirm, Filter, Listen, WatchedOutput}; +use crate::chain::{self, BlockLocator, Confirm, Filter, Listen, WatchedOutput}; use crate::io; use crate::ln::msgs::DecodeError; use crate::ln::types::ChannelId; @@ -386,7 +386,7 @@ where /// If chain data is provided via the [`Confirm`] interface or via filtered blocks, users also /// need to register their [`Filter`] implementation via the given `chain_data_source`. pub fn new( - best_block: BestBlock, broadcaster: B, fee_estimator: E, chain_data_source: Option, + best_block: BlockLocator, broadcaster: B, fee_estimator: E, chain_data_source: Option, output_spender: O, change_destination_source: D, kv_store: K, logger: L, ) -> Self { let outputs = Vec::new(); @@ -472,7 +472,7 @@ where /// Gets the latest best block which was connected either via the [`Listen`] or /// [`Confirm`] interfaces. - pub fn current_best_block(&self) -> BestBlock { + pub fn current_best_block(&self) -> BlockLocator { self.sweeper_state.lock().unwrap().best_block } @@ -766,7 +766,7 @@ where self.best_block_updated_internal(&mut state_lock, header, height); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { let mut state_lock = self.sweeper_state.lock().unwrap(); assert!(state_lock.best_block.height > fork_point.height, @@ -854,7 +854,7 @@ where #[derive(Debug, Clone)] struct SweeperState { outputs: Vec, - best_block: BestBlock, + best_block: BlockLocator, dirty: bool, } @@ -889,7 +889,7 @@ impl< K: KVStore, L: Logger, O: OutputSpender, - > ReadableArgs<(B, E, Option, O, D, K, L)> for (BestBlock, OutputSweeper) + > ReadableArgs<(B, E, Option, O, D, K, L)> for (BlockLocator, OutputSweeper) where D::Target: ChangeDestinationSource, { @@ -986,7 +986,7 @@ where /// If chain data is provided via the [`Confirm`] interface or via filtered blocks, users also /// need to register their [`Filter`] implementation via the given `chain_data_source`. pub fn new( - best_block: BestBlock, broadcaster: B, fee_estimator: E, chain_data_source: Option, + best_block: BlockLocator, broadcaster: B, fee_estimator: E, chain_data_source: Option, output_spender: O, change_destination_source: D, kv_store: K, logger: L, ) -> Self { let change_destination_source = @@ -1054,7 +1054,7 @@ where /// Gets the latest best block which was connected either via [`Listen`] or [`Confirm`] /// interfaces. - pub fn current_best_block(&self) -> BestBlock { + pub fn current_best_block(&self) -> BlockLocator { self.sweeper.current_best_block() } @@ -1111,7 +1111,7 @@ where self.sweeper.filtered_block_connected(header, txdata, height); } - fn blocks_disconnected(&self, fork_point: BestBlock) { + fn blocks_disconnected(&self, fork_point: BlockLocator) { self.sweeper.blocks_disconnected(fork_point); } } @@ -1157,7 +1157,7 @@ impl< L: Logger, O: OutputSpender, > ReadableArgs<(B, E, Option, O, D, K, L)> - for (BestBlock, OutputSweeperSync) + for (BlockLocator, OutputSweeperSync) where D::Target: ChangeDestinationSourceSync, K::Target: KVStoreSync, @@ -1172,7 +1172,7 @@ where let kv_store = KVStoreSyncWrapper(kv_store); let args = (a, b, c, d, change_destination_source, kv_store, e); let (best_block, sweeper) = - <(BestBlock, OutputSweeper<_, _, _, _, _, _, _>)>::read(reader, args)?; + <(BlockLocator, OutputSweeper<_, _, _, _, _, _, _>)>::read(reader, args)?; Ok((best_block, OutputSweeperSync { sweeper })) } } diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 57f9ba6b22f..d7320ff2ba9 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -20,7 +20,7 @@ use crate::chain::channelmonitor::{ ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent, }; use crate::chain::transaction::OutPoint; -use crate::chain::BestBlock; +use crate::chain::BlockLocator; use crate::chain::WatchedOutput; #[cfg(any(test, feature = "_externalize_tests"))] use crate::ln::chan_utils::CommitmentTransaction; @@ -606,7 +606,7 @@ impl<'a> TestChainMonitor<'a> { // underlying `ChainMonitor`. let mut w = TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BestBlock, ChannelMonitor)>::read( + let new_monitor = <(BlockLocator, ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager), ) @@ -643,7 +643,7 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { // monitor to a serialized copy and get he same one back. let mut w = TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BestBlock, ChannelMonitor)>::read( + let new_monitor = <(BlockLocator, ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager), ) @@ -699,7 +699,7 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { let monitor = self.chain_monitor.get_monitor(channel_id).unwrap(); w.0.clear(); monitor.write(&mut w).unwrap(); - let new_monitor = <(BestBlock, ChannelMonitor)>::read( + let new_monitor = <(BlockLocator, ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager), )