Merge PR 'Refuse to persist fresh monitors that alias archived monitors' (#5645)
What changed, and why it matters
This change prevents a Lightning node from accidentally overwriting an archived copy of a channel's security monitor with a brand-new one that happens to use the same identifier. In the old code, if a new channel reused the same identifier as a previously closed and archived channel, the new monitor could be saved on top of the archived one. Later, when the new channel closed, its archived copy would overwrite the old archived copy, permanently destroying the historical record needed to detect cheating or recover funds. The fix makes the node refuse to save a new monitor when an archived one already exists under the same key, leaving the new channel 'stuck' instead of silently destroying data. This is a safety improvement rather than a remote-exploitable bug.
Treat this as a defensive hardening commit. Users running nodes should upgrade to ensure archived channel monitors are protected from accidental overwrite. Operators encountering the new log error should investigate why a new channel is reusing a funding outpoint that already has an archived monitor and resolve the key collision before the channel can make progress.
Security signals we found
Data-loss prevention: stops archived ChannelMonitor from being overwritten by a later channel with the same key
Safety guard added to both sync and async persistence paths
Persistence refusal surfaces as InProgress/UnrecoverableError rather than silent overwrite
Tests added to enforce the new refusal behavior
No cryptographic or network-level exploit vector; risk is state-corruption/data-loss
Evidence from the diff
The commit hardens channel-monitor persistence in rust-lightning. Channel monitors for closed channels can be moved to an ‘archived’ namespace keyed by the funding outpoint. Because the funding outpoint is chosen by the channel funder, a later channel can reuse the same outpoint and thus the same persistence key. Previously, persist_new_channel would write the fresh monitor into the live namespace without checking the archived namespace. When that fresh channel was later archived, the archived write would overwrite the prior archived monitor, and any stale updates left behind could also be replayed onto the fresh monitor on restart. The patch adds a check in both the sync Persist blanket implementation and the async MonitorUpdatingPersister paths: before writing a new monitor, list the archived namespace and, if the key already exists, return ChannelMonitorUpdateStatus::InProgress (sync) or abort the spawned task (async), log an error, and never queue the write. Tests are added to verify the refusal and that the archived bytes remain untouched.
Changed components
lightning/src/util/persist.rslightning/src/ln/chanmon_update_fail_tests.rsPersist blanket implementation for KVStoreSyncMonitorUpdatingPersister and MonitorUpdatingPersisterAsyncChannel monitor archival and persistence logicInspect captured patch +298 / −33
### lightning/src/ln/chanmon_update_fail_tests.rs
@@ -36,13 +36,16 @@ use crate::sign::NodeSigner;
use crate::types::string::UntrustedString;
use crate::util::native_async::FutureQueue;
use crate::util::persist::{
- MonitorName, MonitorUpdatingPersisterAsync, CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
- CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ KVStoreSync, MonitorName, MonitorUpdatingPersisterAsync,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
};
use crate::util::ser::{ReadableArgs, Writeable};
use crate::util::test_channel_signer::TestChannelSigner;
use crate::util::test_utils::TestBroadcaster;
+use crate::util::wakers::Notifier;
use bitcoin::constants::genesis_block;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::Network;
@@ -5345,6 +5348,18 @@ fn native_async_persist() {
Arc::clone(&tx_broadcaster),
Arc::clone(&fee_estimator),
);
+ // A second persister over the same store, used below to spawn persistence operations directly
+ // once `native_async_persister` has been moved into the `ChainMonitor`.
+ let direct_persister = MonitorUpdatingPersisterAsync::new(
+ Arc::clone(&kv_store),
+ Arc::clone(&persist_futures),
+ Arc::clone(&logger),
+ 42,
+ Arc::clone(&keys_manager),
+ Arc::clone(&keys_manager),
+ Arc::clone(&tx_broadcaster),
+ Arc::clone(&fee_estimator),
+ );
let chain_source = test_utils::TestChainSource::new(Network::Testnet);
let async_chain_monitor = ChainMonitor::new_async_beta(
Some(&chain_source),
@@ -5361,6 +5376,7 @@ fn native_async_persist() {
// isn't returned until the write is completed (via `complete_all_async_writes`) and the future
// is `poll`ed (which a background spawn should do automatically in production, but which is
// needed to get the future completion through to the `ChainMonitor`).
+ let monitor_alias = monitor.clone();
let write_status = async_chain_monitor.watch_channel(chan_id, monitor).unwrap();
assert_eq!(write_status, ChannelMonitorUpdateStatus::InProgress);
@@ -5492,6 +5508,35 @@ fn native_async_persist() {
} else {
panic!();
}
+
+ // Finally, confirm that a fresh monitor is refused from persisting under a key which has an
+ // archived monitor, leaving the persistence in progress forever rather than aliasing the
+ // archived monitor. `native_async_persister` was moved into the `ChainMonitor` above, so a
+ // second persister over the same store is used to spawn the persistence directly.
+ let monitor_name = MonitorName::V1Channel(funding_txo);
+ KVStoreSync::write(
+ &*kv_store,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &key,
+ monitor_alias.encode(),
+ )
+ .unwrap();
+
+ direct_persister.spawn_async_persist_new_channel(
+ monitor_name,
+ &monitor_alias,
+ Arc::new(Notifier::new()),
+ );
+ persist_futures.poll_futures();
+ assert_eq!(persist_futures.pending_futures(), 0);
+ assert!(kv_store
+ .list_pending_async_writes(
+ CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &key,
+ )
+ .is_empty());
}
#[test]
### lightning/src/util/persist.rs
@@ -892,10 +892,25 @@ impl<ChannelSigner: EcdsaChannelSigner, K: KVStoreSync + ?Sized> Persist<Channel
fn persist_new_channel(
&self, monitor_name: MonitorName, monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
+ // As in the `MonitorUpdatingPersister` implementations, a fresh monitor must not be
+ // written under a key which has an archived monitor: archiving the fresh monitor would
+ // overwrite the archived one.
+ let monitor_key = monitor_name.to_key();
+ match self.list(
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ ) {
+ Ok(archived_keys) => {
+ if archived_keys.iter().any(|key| key == monitor_key.as_str()) {
+ return chain::ChannelMonitorUpdateStatus::InProgress;
+ }
+ },
+ Err(_) => return chain::ChannelMonitorUpdateStatus::UnrecoverableError,
+ }
match self.write(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
- monitor_name.to_key().as_str(),
+ monitor_key.as_str(),
monitor.encode(),
) {
Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
@@ -1218,7 +1233,32 @@ where
fn persist_new_channel(
&self, monitor_name: MonitorName, monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
- let res = poll_sync_future(self.0 .0.persist_new_channel(monitor_name, monitor));
+ let monitor_key = monitor_name.to_key();
+ match poll_sync_future(self.0 .0.has_archived_monitor(monitor_key.as_str())) {
+ Ok(false) => {},
+ Ok(true) => {
+ log_error!(
+ self.0 .0.logger,
+ "Refusing to persist new ChannelMonitor {}: an archived ChannelMonitor is \
+ stored under the same key. Persistence will be left in progress forever and \
+ the channel will not be able to make progress.",
+ monitor_name
+ );
+ return chain::ChannelMonitorUpdateStatus::InProgress;
+ },
+ Err(e) => {
+ log_error!(
+ self.0 .0.logger,
+ "Failed to check for archived ChannelMonitors prior to persisting new \
+ ChannelMonitor {}, reason: {}",
+ monitor_name,
+ e
+ );
+ return chain::ChannelMonitorUpdateStatus::UnrecoverableError;
+ },
+ }
+ let monitor_bytes = serialize_full_monitor(monitor, self.0 .0.maximum_pending_updates);
+ let res = poll_sync_future(self.0 .0.write_new_monitor(monitor_name, monitor_bytes));
match res {
Ok(_) => chain::ChannelMonitorUpdateStatus::Completed,
Err(e) => {
@@ -1440,13 +1480,39 @@ where
notifier: Arc<Notifier>,
) {
let inner = Arc::clone(&self.0);
- // Note that `persist_new_channel` is a sync method which calls all the way through to the
- // sync KVStore::write method (which returns a future) to ensure writes are well-ordered.
- let future = inner.persist_new_channel(monitor_name, monitor);
+ let monitor_key = monitor_name.to_key();
let channel_id = monitor.channel_id();
let completion = (monitor.channel_id(), monitor.get_latest_update_id());
+ let monitor_bytes = serialize_full_monitor(monitor, self.0.maximum_pending_updates);
let _runs_free = self.0.future_spawner.spawn(async move {
- match future.await {
+ // The write is only queued once the check for an archived monitor under the same key
+ // completes, as a fresh monitor must never be written over an archived one. Unlike
+ // `spawn_async_update_channel`, which queues its write on the calling thread to ensure
+ // writes are well-ordered, this write is queued from the spawned task, so a
+ // chain-sync full-monitor write for the same key (e.g. triggered by a block
+ // connection racing in the between-spawn-and-poll window) could theoretically be
+ // queued first, in which case the watch-time monitor serialized above would win on
+ // disk. The window is narrow and a regressed monitor is repaired by replaying blocks
+ // on restart; the `ChannelManager` will not queue monitor updates for the channel
+ // until this persistence completes.
+ match inner.has_archived_monitor(monitor_key.as_str()).await {
+ Ok(false) => {},
+ Ok(true) => {
+ log_error!(
+ inner.logger,
+ "Refusing to persist new ChannelMonitor {channel_id}: an archived ChannelMonitor is stored under the same key. Persistence will be left in progress forever and the channel will not be able to make progress."
+ );
+ return;
+ },
+ Err(e) => {
+ log_error!(
+ inner.logger,
+ "Failed to check for archived ChannelMonitors prior to persisting new ChannelMonitor {channel_id}, reason: {e}. The node will now likely stall as this channel will not be able to make progress. You should restart as soon as possible."
+ );
+ return;
+ },
+ }
+ match inner.write_new_monitor(monitor_name, monitor_bytes).await {
Ok(()) => {
inner.async_completed_updates.lock().unwrap().push(completion);
notifier.notify();
@@ -1507,6 +1573,24 @@ where
trait MaybeSendableFuture: Future<Output = Result<(), io::Error>> + MaybeSend {}
impl<F: Future<Output = Result<(), io::Error>> + MaybeSend> MaybeSendableFuture for F {}
+// Serializes a full `ChannelMonitor` snapshot for persistence, prepending the sentinel unless
+// monitor updates are disabled entirely.
+fn serialize_full_monitor<ChannelSigner: EcdsaChannelSigner>(
+ monitor: &ChannelMonitor<ChannelSigner>, maximum_pending_updates: u64,
+) -> Vec<u8> {
+ let mut monitor_bytes = Vec::with_capacity(
+ MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() + monitor.serialized_length(),
+ );
+ // If `maximum_pending_updates` is zero, we aren't actually writing monitor updates at all.
+ // Thus, there's no need to add the sentinel prefix as the monitor can be read directly from
+ // disk without issue.
+ if maximum_pending_updates != 0 {
+ monitor_bytes.extend_from_slice(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL);
+ }
+ monitor.write(&mut monitor_bytes).unwrap();
+ monitor_bytes
+}
+
impl<
K: KVStore,
S: FutureSpawner,
@@ -1793,22 +1877,24 @@ impl<
Ok(())
}
- fn persist_new_channel<'a, ChannelSigner: EcdsaChannelSigner>(
- &'a self, monitor_name: MonitorName, monitor: &'a ChannelMonitor<ChannelSigner>,
+ // Returns whether an archived `ChannelMonitor` is stored under the given key.
+ //
+ // A fresh monitor must never be persisted under a key which has an archived monitor: when
+ // the fresh monitor is ultimately archived, it would overwrite the archived monitor,
+ // defeating the purpose of archiving.
+ async fn has_archived_monitor(&self, monitor_key: &str) -> Result<bool, io::Error> {
+ let primary = ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE;
+ let secondary = ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE;
+ let archived_monitor_keys = self.kv_store.list(primary, secondary).await?;
+ Ok(archived_monitor_keys.iter().any(|key| key == monitor_key))
+ }
+
+ // Queues a write of the given serialized `ChannelMonitor` under the key for `monitor_name`,
+ // returning a future for the completion of the write.
+ fn write_new_monitor(
+ &self, monitor_name: MonitorName, monitor_bytes: Vec<u8>,
) -> Pin<Box<dyn MaybeSendableFuture<Output = Result<(), io::Error>> + 'static>> {
- // Determine the proper key for this monitor
let monitor_key = monitor_name.to_key();
- // Serialize and write the new monitor
- let mut monitor_bytes = Vec::with_capacity(
- MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() + monitor.serialized_length(),
- );
- // If `maximum_pending_updates` is zero, we aren't actually writing monitor updates at all.
- // Thus, there's no need to add the sentinel prefix as the monitor can be read directly
- // from disk without issue.
- if self.maximum_pending_updates != 0 {
- monitor_bytes.extend_from_slice(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL);
- }
- monitor.write(&mut monitor_bytes).unwrap();
// Note that this is NOT an async function, but rather calls the *sync* KVStore write
// method, allowing it to do its queueing immediately, and then return a future for the
// completion of the write. This ensures monitor persistence ordering is preserved.
@@ -1855,7 +1941,8 @@ impl<
// write method, allowing it to do its queueing immediately, and then return a
// future for the completion of the write. This ensures monitor persistence
// ordering is preserved. This, thus, must happen before any await we do below.
- let write_fut = self.persist_new_channel(monitor_name, monitor);
+ let monitor_bytes = serialize_full_monitor(monitor, self.maximum_pending_updates);
+ let write_fut = self.write_new_monitor(monitor_name, monitor_bytes);
let latest_update_id = monitor.get_latest_update_id();
res_b = Some(async move {
@@ -1884,7 +1971,8 @@ impl<
// Note that this is NOT an async function, but rather calls the *sync* KVStore write
// method, allowing it to do its queueing immediately, and then return a future for the
// completion of the write. This ensures monitor persistence ordering is preserved.
- res_c = Some(self.persist_new_channel(monitor_name, monitor));
+ let monitor_bytes = serialize_full_monitor(monitor, self.maximum_pending_updates);
+ res_c = Some(self.write_new_monitor(monitor_name, monitor_bytes));
}
async move {
// Complete any pending future(s). Note that to keep one return type we have to end
@@ -1930,15 +2018,14 @@ impl<
e
);
}
- // The archived monitor has all stored updates applied, so drop them too. The key of a v1
- // channel is its funding outpoint, which the funder picks, so a new monitor may later be
- // persisted under this key starting at `update_id` 0, and any updates we leave behind
- // would be replayed onto it when it is read. The removal here is lazy, as any updates
- // left behind when it is lost are removed by `cleanup_archived_monitor_updates` on the
- // next startup, which the non-lazy removal above keeps a stale live monitor from
- // blocking. A failure here is only logged.
- // `ChainMonitor` will not persist a monitor under this key while it is being archived, so
- // no lock is needed beyond that.
+ // The archived monitor has all stored updates applied, so drop them too, rather than
+ // leaving them orphaned under the key. The removal here is lazy, as any updates left
+ // behind when it is lost are removed by `cleanup_archived_monitor_updates` on the next
+ // startup, which the non-lazy removal above keeps a stale live monitor from blocking. A
+ // failure here is only logged.
+ // Note that once the archived write above completes, `persist_new_channel` will refuse to
+ // persist a fresh monitor under this key, so the updates removed here cannot be replayed
+ // onto a fresh monitor.
if let Err(e) = self.cleanup_stale_updates_for_monitor_to(key, u64::MAX, true).await {
log_error!(
self.logger,
@@ -2817,6 +2904,139 @@ mod tests {
assert!(update_list.is_empty());
}
+ // Confirm that persisting a new monitor under a key which has an archived monitor is refused,
+ // leaving the persistence in progress forever: the fresh monitor would alias the archived
+ // one, and archiving the fresh monitor later would overwrite the archived monitor.
+ #[test]
+ fn refuses_new_monitor_aliasing_archived_monitor() {
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let kv_store = TestStore::new(false);
+ let persister = MonitorUpdatingPersister::new(
+ &kv_store,
+ &chanmon_cfgs[0].logger,
+ 100,
+ &chanmon_cfgs[0].keys_manager,
+ &chanmon_cfgs[0].keys_manager,
+ &chanmon_cfgs[0].tx_broadcaster,
+ &chanmon_cfgs[0].fee_estimator,
+ );
+ let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let chain_mon_0 = test_utils::TestChainMonitor::new(
+ Some(&chanmon_cfgs[0].chain_source),
+ &chanmon_cfgs[0].tx_broadcaster,
+ &chanmon_cfgs[0].logger,
+ &chanmon_cfgs[0].fee_estimator,
+ &persister,
+ &chanmon_cfgs[0].keys_manager,
+ );
+ node_cfgs[0].chain_monitor = chain_mon_0;
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+ let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
+ send_payment(&nodes[0], &vec![&nodes[1]][..], 8_000_000);
+
+ let persisted_chan_data = persister.read_all_channel_monitors_with_updates().unwrap();
+ assert_eq!(persisted_chan_data.len(), 1);
+ let (_, monitor) = &persisted_chan_data[0];
+ let monitor_name = monitor.persistence_key();
+ let monitor_key = monitor_name.to_string();
+
+ Persist::<TestChannelSigner>::archive_persisted_channel(&persister, monitor_name);
+ let archived_monitor_bytes = KVStoreSync::read(
+ &kv_store,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &monitor_key,
+ )
+ .unwrap();
+
+ let status =
+ Persist::<TestChannelSigner>::persist_new_channel(&persister, monitor_name, monitor);
+ assert_eq!(status, ChannelMonitorUpdateStatus::InProgress);
+ assert!(KVStoreSync::read(
+ &kv_store,
+ CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &monitor_key,
+ )
+ .is_err());
+ assert_eq!(
+ KVStoreSync::read(
+ &kv_store,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &monitor_key,
+ )
+ .unwrap(),
+ archived_monitor_bytes
+ );
+ }
+
+ // Confirm that the default `Persist` implementation over a `KVStoreSync` also refuses to
+ // persist a new monitor under a key which has an archived monitor.
+ #[test]
+ fn default_persister_refuses_new_monitor_aliasing_archived_monitor() {
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let kv_store = TestStore::new(false);
+ let persister = MonitorUpdatingPersister::new(
+ &kv_store,
+ &chanmon_cfgs[0].logger,
+ 100,
+ &chanmon_cfgs[0].keys_manager,
+ &chanmon_cfgs[0].keys_manager,
+ &chanmon_cfgs[0].tx_broadcaster,
+ &chanmon_cfgs[0].fee_estimator,
+ );
+ let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let chain_mon_0 = test_utils::TestChainMonitor::new(
+ Some(&chanmon_cfgs[0].chain_source),
+ &chanmon_cfgs[0].tx_broadcaster,
+ &chanmon_cfgs[0].logger,
+ &chanmon_cfgs[0].fee_estimator,
+ &persister,
+ &chanmon_cfgs[0].keys_manager,
+ );
+ node_cfgs[0].chain_monitor = chain_mon_0;
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+ let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
+ send_payment(&nodes[0], &vec![&nodes[1]][..], 8_000_000);
+
+ let persisted_chan_data = persister.read_all_channel_monitors_with_updates().unwrap();
+ assert_eq!(persisted_chan_data.len(), 1);
+ let (_, monitor) = &persisted_chan_data[0];
+ let monitor_name = monitor.persistence_key();
+ let monitor_key = monitor_name.to_string();
+
+ // The blanket `Persist` implementation is exercised on a separate store, as the monitor
+ // was persisted to `kv_store` above.
+ let blanket_impl_store = TestStore::new(false);
+ KVStoreSync::write(
+ &blanket_impl_store,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &monitor_key,
+ monitor.encode(),
+ )
+ .unwrap();
+
+ let status = Persist::<TestChannelSigner>::persist_new_channel(
+ &blanket_impl_store,
+ monitor_name,
+ monitor,
+ );
+ assert_eq!(status, ChannelMonitorUpdateStatus::InProgress);
+ assert!(KVStoreSync::read(
+ &blanket_impl_store,
+ CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ &monitor_key,
+ )
+ .is_err());
+ }
+
// Confirm that reading all monitors removes updates left behind for already-archived monitors
// by a prior version, as a new monitor may later be persisted under the same key and must not
// have the archived channel's updates replayed onto it.Why this scored 54/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.