|
| 1 | +use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier}; |
| 2 | +use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader}; |
| 3 | + |
| 4 | +use bitcoin::blockdata::block::{Block, BlockHeader}; |
| 5 | +use bitcoin::hash_types::BlockHash; |
| 6 | +use bitcoin::network::constants::Network; |
| 7 | + |
| 8 | +use lightning::chain; |
| 9 | + |
| 10 | +/// Performs a one-time sync of chain listeners using a single *trusted* block source, bringing each |
| 11 | +/// listener's view of the chain from its paired block hash to `block_source`'s best chain tip. |
| 12 | +/// |
| 13 | +/// Upon success, the returned header can be used to initialize [`SpvClient`]. In the case of |
| 14 | +/// failure, each listener may be left at a different block hash than the one it was originally |
| 15 | +/// paired with. |
| 16 | +/// |
| 17 | +/// Useful during startup to bring the [`ChannelManager`] and each [`ChannelMonitor`] in sync before |
| 18 | +/// switching to [`SpvClient`]. For example: |
| 19 | +/// |
| 20 | +/// ``` |
| 21 | +/// use bitcoin::hash_types::BlockHash; |
| 22 | +/// use bitcoin::network::constants::Network; |
| 23 | +/// |
| 24 | +/// use lightning::chain; |
| 25 | +/// use lightning::chain::Watch; |
| 26 | +/// use lightning::chain::chainmonitor::ChainMonitor; |
| 27 | +/// use lightning::chain::channelmonitor; |
| 28 | +/// use lightning::chain::channelmonitor::ChannelMonitor; |
| 29 | +/// use lightning::chain::chaininterface::BroadcasterInterface; |
| 30 | +/// use lightning::chain::chaininterface::FeeEstimator; |
| 31 | +/// use lightning::chain::keysinterface; |
| 32 | +/// use lightning::chain::keysinterface::KeysInterface; |
| 33 | +/// use lightning::ln::channelmanager::ChannelManager; |
| 34 | +/// use lightning::ln::channelmanager::ChannelManagerReadArgs; |
| 35 | +/// use lightning::util::config::UserConfig; |
| 36 | +/// use lightning::util::logger::Logger; |
| 37 | +/// use lightning::util::ser::ReadableArgs; |
| 38 | +/// |
| 39 | +/// use lightning_block_sync::*; |
| 40 | +/// |
| 41 | +/// use std::cell::RefCell; |
| 42 | +/// use std::io::Cursor; |
| 43 | +/// |
| 44 | +/// async fn init_sync< |
| 45 | +/// B: BlockSource, |
| 46 | +/// K: KeysInterface<Signer = S>, |
| 47 | +/// S: keysinterface::Sign, |
| 48 | +/// T: BroadcasterInterface, |
| 49 | +/// F: FeeEstimator, |
| 50 | +/// L: Logger, |
| 51 | +/// C: chain::Filter, |
| 52 | +/// P: channelmonitor::Persist<S>, |
| 53 | +/// >( |
| 54 | +/// block_source: &mut B, |
| 55 | +/// chain_monitor: &ChainMonitor<S, &C, &T, &F, &L, &P>, |
| 56 | +/// config: UserConfig, |
| 57 | +/// keys_manager: &K, |
| 58 | +/// tx_broadcaster: &T, |
| 59 | +/// fee_estimator: &F, |
| 60 | +/// logger: &L, |
| 61 | +/// persister: &P, |
| 62 | +/// ) { |
| 63 | +/// // Read a serialized channel monitor paired with the block hash when it was persisted. |
| 64 | +/// let serialized_monitor = "..."; |
| 65 | +/// let (monitor_block_hash, mut monitor) = <(BlockHash, ChannelMonitor<S>)>::read( |
| 66 | +/// &mut Cursor::new(&serialized_monitor), keys_manager).unwrap(); |
| 67 | +/// |
| 68 | +/// // Read the channel manager paired with the block hash when it was persisted. |
| 69 | +/// let serialized_manager = "..."; |
| 70 | +/// let (manager_block_hash, mut manager) = { |
| 71 | +/// let read_args = ChannelManagerReadArgs::new( |
| 72 | +/// keys_manager, |
| 73 | +/// fee_estimator, |
| 74 | +/// chain_monitor, |
| 75 | +/// tx_broadcaster, |
| 76 | +/// logger, |
| 77 | +/// config, |
| 78 | +/// vec![&mut monitor], |
| 79 | +/// ); |
| 80 | +/// <(BlockHash, ChannelManager<S, &ChainMonitor<S, &C, &T, &F, &L, &P>, &T, &K, &F, &L>)>::read( |
| 81 | +/// &mut Cursor::new(&serialized_manager), read_args).unwrap() |
| 82 | +/// }; |
| 83 | +/// |
| 84 | +/// // Synchronize any channel monitors and the channel manager to be on the best block. |
| 85 | +/// let mut cache = UnboundedCache::new(); |
| 86 | +/// let mut monitor_listener = (RefCell::new(monitor), &*tx_broadcaster, &*fee_estimator, &*logger); |
| 87 | +/// let listeners = vec![ |
| 88 | +/// (monitor_block_hash, &mut monitor_listener as &mut dyn chain::Listen), |
| 89 | +/// (manager_block_hash, &mut manager as &mut dyn chain::Listen), |
| 90 | +/// ]; |
| 91 | +/// let chain_tip = init::synchronize_listeners( |
| 92 | +/// block_source, Network::Bitcoin, &mut cache, listeners).await.unwrap(); |
| 93 | +/// |
| 94 | +/// // Allow the chain monitor to watch any channels. |
| 95 | +/// let monitor = monitor_listener.0.into_inner(); |
| 96 | +/// chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor); |
| 97 | +/// |
| 98 | +/// // Create an SPV client to notify the chain monitor and channel manager of block events. |
| 99 | +/// let chain_poller = poll::ChainPoller::new(block_source, Network::Bitcoin); |
| 100 | +/// let mut chain_listener = (chain_monitor, &manager); |
| 101 | +/// let spv_client = SpvClient::new(chain_tip, chain_poller, &mut cache, &chain_listener); |
| 102 | +/// } |
| 103 | +/// ``` |
| 104 | +/// |
| 105 | +/// [`SpvClient`]: ../struct.SpvClient.html |
| 106 | +/// [`ChannelManager`]: ../../lightning/ln/channelmanager/struct.ChannelManager.html |
| 107 | +/// [`ChannelMonitor`]: ../../lightning/chain/channelmonitor/struct.ChannelMonitor.html |
| 108 | +pub async fn synchronize_listeners<B: BlockSource, C: Cache>( |
| 109 | + block_source: &mut B, |
| 110 | + network: Network, |
| 111 | + header_cache: &mut C, |
| 112 | + mut chain_listeners: Vec<(BlockHash, &mut dyn chain::Listen)>, |
| 113 | +) -> BlockSourceResult<ValidatedBlockHeader> { |
| 114 | + let (best_block_hash, best_block_height) = block_source.get_best_block().await?; |
| 115 | + let best_header = block_source |
| 116 | + .get_header(&best_block_hash, best_block_height).await? |
| 117 | + .validate(best_block_hash)?; |
| 118 | + |
| 119 | + // Fetch the header for the block hash paired with each listener. |
| 120 | + let mut chain_listeners_with_old_headers = Vec::new(); |
| 121 | + for (old_block_hash, chain_listener) in chain_listeners.drain(..) { |
| 122 | + let old_header = match header_cache.look_up(&old_block_hash) { |
| 123 | + Some(header) => *header, |
| 124 | + None => block_source |
| 125 | + .get_header(&old_block_hash, None).await? |
| 126 | + .validate(old_block_hash)? |
| 127 | + }; |
| 128 | + chain_listeners_with_old_headers.push((old_header, chain_listener)) |
| 129 | + } |
| 130 | + |
| 131 | + // Find differences and disconnect blocks for each listener individually. |
| 132 | + let mut chain_poller = ChainPoller::new(block_source, network); |
| 133 | + let mut chain_listeners_at_height = Vec::new(); |
| 134 | + let mut most_common_ancestor = None; |
| 135 | + let mut most_connected_blocks = Vec::new(); |
| 136 | + for (old_header, chain_listener) in chain_listeners_with_old_headers.drain(..) { |
| 137 | + // Disconnect any stale blocks, but keep them in the cache for the next iteration. |
| 138 | + let header_cache = &mut ReadOnlyCache(header_cache); |
| 139 | + let (common_ancestor, connected_blocks) = { |
| 140 | + let chain_listener = &DynamicChainListener(chain_listener); |
| 141 | + let mut chain_notifier = ChainNotifier { header_cache, chain_listener }; |
| 142 | + let difference = |
| 143 | + chain_notifier.find_difference(best_header, &old_header, &mut chain_poller).await?; |
| 144 | + chain_notifier.disconnect_blocks(difference.disconnected_blocks); |
| 145 | + (difference.common_ancestor, difference.connected_blocks) |
| 146 | + }; |
| 147 | + |
| 148 | + // Keep track of the most common ancestor and all blocks connected across all listeners. |
| 149 | + chain_listeners_at_height.push((common_ancestor.height, chain_listener)); |
| 150 | + if connected_blocks.len() > most_connected_blocks.len() { |
| 151 | + most_common_ancestor = Some(common_ancestor); |
| 152 | + most_connected_blocks = connected_blocks; |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // Connect new blocks for all listeners at once to avoid re-fetching blocks. |
| 157 | + if let Some(common_ancestor) = most_common_ancestor { |
| 158 | + let chain_listener = &ChainListenerSet(chain_listeners_at_height); |
| 159 | + let mut chain_notifier = ChainNotifier { header_cache, chain_listener }; |
| 160 | + chain_notifier.connect_blocks(common_ancestor, most_connected_blocks, &mut chain_poller) |
| 161 | + .await.or_else(|(e, _)| Err(e))?; |
| 162 | + } |
| 163 | + |
| 164 | + Ok(best_header) |
| 165 | +} |
| 166 | + |
| 167 | +/// A wrapper to make a cache read-only. |
| 168 | +/// |
| 169 | +/// Used to prevent losing headers that may be needed to disconnect blocks common to more than one |
| 170 | +/// listener. |
| 171 | +struct ReadOnlyCache<'a, C: Cache>(&'a mut C); |
| 172 | + |
| 173 | +impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> { |
| 174 | + fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> { |
| 175 | + self.0.look_up(block_hash) |
| 176 | + } |
| 177 | + |
| 178 | + fn block_connected(&mut self, _block_hash: BlockHash, _block_header: ValidatedBlockHeader) { |
| 179 | + unreachable!() |
| 180 | + } |
| 181 | + |
| 182 | + fn block_disconnected(&mut self, _block_hash: &BlockHash) -> Option<ValidatedBlockHeader> { |
| 183 | + None |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/// Wrapper for supporting dynamically sized chain listeners. |
| 188 | +struct DynamicChainListener<'a>(&'a mut dyn chain::Listen); |
| 189 | + |
| 190 | +impl<'a> chain::Listen for DynamicChainListener<'a> { |
| 191 | + fn block_connected(&self, _block: &Block, _height: u32) { |
| 192 | + unreachable!() |
| 193 | + } |
| 194 | + |
| 195 | + fn block_disconnected(&self, header: &BlockHeader, height: u32) { |
| 196 | + self.0.block_disconnected(header, height) |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +/// A set of dynamically sized chain listeners, each paired with a starting block height. |
| 201 | +struct ChainListenerSet<'a>(Vec<(u32, &'a mut dyn chain::Listen)>); |
| 202 | + |
| 203 | +impl<'a> chain::Listen for ChainListenerSet<'a> { |
| 204 | + fn block_connected(&self, block: &Block, height: u32) { |
| 205 | + for (starting_height, chain_listener) in self.0.iter() { |
| 206 | + if height > *starting_height { |
| 207 | + chain_listener.block_connected(block, height); |
| 208 | + } |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + fn block_disconnected(&self, _header: &BlockHeader, _height: u32) { |
| 213 | + unreachable!() |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +#[cfg(test)] |
| 218 | +mod tests { |
| 219 | + use crate::test_utils::{Blockchain, MockChainListener}; |
| 220 | + use super::*; |
| 221 | + |
| 222 | + use bitcoin::network::constants::Network; |
| 223 | + |
| 224 | + #[tokio::test] |
| 225 | + async fn sync_from_same_chain() { |
| 226 | + let mut chain = Blockchain::default().with_height(4); |
| 227 | + |
| 228 | + let mut listener_1 = MockChainListener::new() |
| 229 | + .expect_block_connected(*chain.at_height(2)) |
| 230 | + .expect_block_connected(*chain.at_height(3)) |
| 231 | + .expect_block_connected(*chain.at_height(4)); |
| 232 | + let mut listener_2 = MockChainListener::new() |
| 233 | + .expect_block_connected(*chain.at_height(3)) |
| 234 | + .expect_block_connected(*chain.at_height(4)); |
| 235 | + let mut listener_3 = MockChainListener::new() |
| 236 | + .expect_block_connected(*chain.at_height(4)); |
| 237 | + |
| 238 | + let listeners = vec![ |
| 239 | + (chain.at_height(1).block_hash, &mut listener_1 as &mut dyn chain::Listen), |
| 240 | + (chain.at_height(2).block_hash, &mut listener_2 as &mut dyn chain::Listen), |
| 241 | + (chain.at_height(3).block_hash, &mut listener_3 as &mut dyn chain::Listen), |
| 242 | + ]; |
| 243 | + let mut cache = chain.header_cache(0..=4); |
| 244 | + match synchronize_listeners(&mut chain, Network::Bitcoin, &mut cache, listeners).await { |
| 245 | + Ok(header) => assert_eq!(header, chain.tip()), |
| 246 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 247 | + } |
| 248 | + } |
| 249 | + |
| 250 | + #[tokio::test] |
| 251 | + async fn sync_from_different_chains() { |
| 252 | + let mut main_chain = Blockchain::default().with_height(4); |
| 253 | + let fork_chain_1 = main_chain.fork_at_height(1); |
| 254 | + let fork_chain_2 = main_chain.fork_at_height(2); |
| 255 | + let fork_chain_3 = main_chain.fork_at_height(3); |
| 256 | + |
| 257 | + let mut listener_1 = MockChainListener::new() |
| 258 | + .expect_block_disconnected(*fork_chain_1.at_height(4)) |
| 259 | + .expect_block_disconnected(*fork_chain_1.at_height(3)) |
| 260 | + .expect_block_disconnected(*fork_chain_1.at_height(2)) |
| 261 | + .expect_block_connected(*main_chain.at_height(2)) |
| 262 | + .expect_block_connected(*main_chain.at_height(3)) |
| 263 | + .expect_block_connected(*main_chain.at_height(4)); |
| 264 | + let mut listener_2 = MockChainListener::new() |
| 265 | + .expect_block_disconnected(*fork_chain_2.at_height(4)) |
| 266 | + .expect_block_disconnected(*fork_chain_2.at_height(3)) |
| 267 | + .expect_block_connected(*main_chain.at_height(3)) |
| 268 | + .expect_block_connected(*main_chain.at_height(4)); |
| 269 | + let mut listener_3 = MockChainListener::new() |
| 270 | + .expect_block_disconnected(*fork_chain_3.at_height(4)) |
| 271 | + .expect_block_connected(*main_chain.at_height(4)); |
| 272 | + |
| 273 | + let listeners = vec![ |
| 274 | + (fork_chain_1.tip().block_hash, &mut listener_1 as &mut dyn chain::Listen), |
| 275 | + (fork_chain_2.tip().block_hash, &mut listener_2 as &mut dyn chain::Listen), |
| 276 | + (fork_chain_3.tip().block_hash, &mut listener_3 as &mut dyn chain::Listen), |
| 277 | + ]; |
| 278 | + let mut cache = fork_chain_1.header_cache(2..=4); |
| 279 | + cache.extend(fork_chain_2.header_cache(3..=4)); |
| 280 | + cache.extend(fork_chain_3.header_cache(4..=4)); |
| 281 | + match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await { |
| 282 | + Ok(header) => assert_eq!(header, main_chain.tip()), |
| 283 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 284 | + } |
| 285 | + } |
| 286 | + |
| 287 | + #[tokio::test] |
| 288 | + async fn sync_from_overlapping_chains() { |
| 289 | + let mut main_chain = Blockchain::default().with_height(4); |
| 290 | + let fork_chain_1 = main_chain.fork_at_height(1); |
| 291 | + let fork_chain_2 = fork_chain_1.fork_at_height(2); |
| 292 | + let fork_chain_3 = fork_chain_2.fork_at_height(3); |
| 293 | + |
| 294 | + let mut listener_1 = MockChainListener::new() |
| 295 | + .expect_block_disconnected(*fork_chain_1.at_height(4)) |
| 296 | + .expect_block_disconnected(*fork_chain_1.at_height(3)) |
| 297 | + .expect_block_disconnected(*fork_chain_1.at_height(2)) |
| 298 | + .expect_block_connected(*main_chain.at_height(2)) |
| 299 | + .expect_block_connected(*main_chain.at_height(3)) |
| 300 | + .expect_block_connected(*main_chain.at_height(4)); |
| 301 | + let mut listener_2 = MockChainListener::new() |
| 302 | + .expect_block_disconnected(*fork_chain_2.at_height(4)) |
| 303 | + .expect_block_disconnected(*fork_chain_2.at_height(3)) |
| 304 | + .expect_block_disconnected(*fork_chain_2.at_height(2)) |
| 305 | + .expect_block_connected(*main_chain.at_height(2)) |
| 306 | + .expect_block_connected(*main_chain.at_height(3)) |
| 307 | + .expect_block_connected(*main_chain.at_height(4)); |
| 308 | + let mut listener_3 = MockChainListener::new() |
| 309 | + .expect_block_disconnected(*fork_chain_3.at_height(4)) |
| 310 | + .expect_block_disconnected(*fork_chain_3.at_height(3)) |
| 311 | + .expect_block_disconnected(*fork_chain_3.at_height(2)) |
| 312 | + .expect_block_connected(*main_chain.at_height(2)) |
| 313 | + .expect_block_connected(*main_chain.at_height(3)) |
| 314 | + .expect_block_connected(*main_chain.at_height(4)); |
| 315 | + |
| 316 | + let listeners = vec![ |
| 317 | + (fork_chain_1.tip().block_hash, &mut listener_1 as &mut dyn chain::Listen), |
| 318 | + (fork_chain_2.tip().block_hash, &mut listener_2 as &mut dyn chain::Listen), |
| 319 | + (fork_chain_3.tip().block_hash, &mut listener_3 as &mut dyn chain::Listen), |
| 320 | + ]; |
| 321 | + let mut cache = fork_chain_1.header_cache(2..=4); |
| 322 | + cache.extend(fork_chain_2.header_cache(3..=4)); |
| 323 | + cache.extend(fork_chain_3.header_cache(4..=4)); |
| 324 | + match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await { |
| 325 | + Ok(header) => assert_eq!(header, main_chain.tip()), |
| 326 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 327 | + } |
| 328 | + } |
| 329 | + |
| 330 | + #[tokio::test] |
| 331 | + async fn cache_connected_and_keep_disconnected_blocks() { |
| 332 | + let mut main_chain = Blockchain::default().with_height(2); |
| 333 | + let fork_chain = main_chain.fork_at_height(1); |
| 334 | + let new_tip = main_chain.tip(); |
| 335 | + let old_tip = fork_chain.tip(); |
| 336 | + |
| 337 | + let mut listener = MockChainListener::new() |
| 338 | + .expect_block_disconnected(*old_tip) |
| 339 | + .expect_block_connected(*new_tip); |
| 340 | + |
| 341 | + let listeners = vec![(old_tip.block_hash, &mut listener as &mut dyn chain::Listen)]; |
| 342 | + let mut cache = fork_chain.header_cache(2..=2); |
| 343 | + match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await { |
| 344 | + Ok(_) => { |
| 345 | + assert!(cache.contains_key(&new_tip.block_hash)); |
| 346 | + assert!(cache.contains_key(&old_tip.block_hash)); |
| 347 | + }, |
| 348 | + Err(e) => panic!("Unexpected error: {:?}", e), |
| 349 | + } |
| 350 | + } |
| 351 | +} |
0 commit comments