diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 578a2f14e50..e60efa5c196 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -474,7 +474,7 @@ impl PeerState { self.outbound_channels_by_intercept_scid.insert(intercept_scid, channel); } - fn peer_disconnected(&mut self) { + fn prune_expired_request_state(&mut self) { self.pending_requests.retain(|_, entry| { match entry { LSPS2Request::GetInfo(_) => false, @@ -495,6 +495,11 @@ impl PeerState { true }); } + + fn is_prunable(&self) -> bool { + // Return whether the entire state is empty. + self.pending_requests.is_empty() && self.outbound_channels_by_intercept_scid.is_empty() + } } /// The main object allowing to send and receive LSPS2 messages. @@ -1270,12 +1275,29 @@ where } pub(crate) fn peer_disconnected(&self, counterparty_node_id: PublicKey) { - let outer_state_lock = self.per_peer_state.write().unwrap(); - if let Some(inner_state_lock) = outer_state_lock.get(&counterparty_node_id) { - let mut peer_state_lock = inner_state_lock.lock().unwrap(); - peer_state_lock.peer_disconnected(); + let mut outer_state_lock = self.per_peer_state.write().unwrap(); + let is_prunable = + if let Some(inner_state_lock) = outer_state_lock.get(&counterparty_node_id) { + let mut peer_state_lock = inner_state_lock.lock().unwrap(); + peer_state_lock.prune_expired_request_state(); + peer_state_lock.is_prunable() + } else { + return; + }; + if is_prunable { + outer_state_lock.remove(&counterparty_node_id); } } + + #[allow(clippy::bool_comparison)] + pub(crate) fn prune_peer_state(&self) { + let mut outer_state_lock = self.per_peer_state.write().unwrap(); + outer_state_lock.retain(|_, inner_state_lock| { + let mut peer_state_lock = inner_state_lock.lock().unwrap(); + peer_state_lock.prune_expired_request_state(); + peer_state_lock.is_prunable() == false + }); + } } impl ProtocolMessageHandler for LSPS2ServiceHandler diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index a7e2a7913a1..0c03e5128f8 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -684,6 +684,9 @@ where fn best_block_updated(&self, _header: &bitcoin::block::Header, _height: u32) { // TODO: Call best_block_updated on all sub-modules that require it, e.g., LSPS1MessageHandler. + if let Some(lsps2_service_handler) = self.lsps2_service_handler.as_ref() { + lsps2_service_handler.prune_peer_state(); + } } fn get_relevant_txids(&self) -> Vec<(bitcoin::Txid, u32, Option)> {