From 9ab24d55f26701087b43d2a8931f27a99b121d91 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 13:22:39 +0100 Subject: [PATCH 1/9] fix: fence a replaced vss store's writes VSS puts are unconditional, so a write of a stopped node that is still retrying, or one its detached work starts later, could overwrite what a node rebuilt on the same store wrote since, including a channel monitor. Building a VssStore now starts a new generation for its VSS store and waits for the write requests of earlier generations still on the wire, failing after 60 s. Writes retry in fenced_retry, which checks the generation before each attempt and drops the write once the store has been replaced. Verified: cargo test --lib (139 passed), cargo clippy --all-targets (no new findings), vss_test cfg compiles (not run: no auth-free VSS server here) --- CHANGELOG.md | 1 + src/io/vss_store.rs | 508 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 475 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 766076acac..3c52ff534a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Bug Fixes +- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for the earlier store's write requests still in flight, fails with `KVStoreSetupFailed` if they have not ended after 60 s, and drops the earlier store's writes from then on. - Prevent the native SIGABRT `A Tokio 1.x context was found, but it is being shutdown.` when a node is released while background work is still stuck, e.g. in a VSS write after a timed-out stop: the runtime is now kept alive until that work ends instead of being shut down under it. - Bump `lightning`, `lightning-liquidity`, `lightning-persister` and `lightning-transaction-sync` to 0.2.8 and `lightning-invoice` to 0.34.2. - `bump_fee_by_rbf` now only replaces transactions this wallet built and broadcast itself, and returns `TransactionNotBroadcastByWallet` for any other txid. diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index bca3779455..bc319f64d1 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -12,8 +12,9 @@ use std::future::Future; use std::panic::RefUnwindSafe; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Condvar, LazyLock, Mutex}; use std::time::Duration; +use std::{error, fmt}; use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; use lightning::impl_writeable_tlv_based_enum; @@ -31,7 +32,7 @@ use vss_client::types::{ }; use vss_client::util::key_obfuscator::KeyObfuscator; use vss_client::util::retry::{ - ExponentialBackoffRetryPolicy, FilteredRetryPolicy, JitteredRetryPolicy, + retry, ExponentialBackoffRetryPolicy, FilteredRetryPolicy, JitteredRetryPolicy, MaxAttemptsRetryPolicy, MaxTotalDelayRetryPolicy, RetryPolicy, }; use vss_client::util::storable_builder::{EntropySource, StorableBuilder}; @@ -46,6 +47,15 @@ type CustomRetryPolicy = FilteredRetryPolicy< Box bool + 'static + Send + Sync>, >; +type WriteRetryPolicy = FilteredRetryPolicy< + JitteredRetryPolicy< + MaxTotalDelayRetryPolicy< + MaxAttemptsRetryPolicy>, + >, + >, + Box bool + 'static + Send + Sync>, +>; + #[derive(Debug, PartialEq)] enum VssSchemaVersion { // The initial schema version. @@ -64,6 +74,167 @@ impl_writeable_tlv_based_enum!(VssSchemaVersion, const VSS_SCHEMA_VERSION_KEY: &str = "vss_schema_version"; +// How long a new store waits for writes of the store it replaces to end. A write retries for +// minutes while VSS is unreachable (see `retry_policy`), so building fails after this rather than +// letting such a write land after the new store's writes. +const REPLACED_WRITES_TIMEOUT: Duration = Duration::from_secs(60); + +static STORE_FENCES: LazyLock = LazyLock::new(StoreFences::default); + +/// Fences the writes of a [`VssStore`] once another one is built for the same VSS store. +/// +/// VSS writes are unconditional puts, so a write of a stopped node that is still retrying, or one +/// its detached work starts later, would overwrite what a node rebuilt on the same store wrote +/// since, e.g. a newer channel monitor. Building a store therefore starts a new generation for its +/// VSS store and waits for the write requests of earlier generations still on the wire. From then +/// on, an earlier generation's writes are dropped before their next attempt (see `fenced_retry`). +/// +/// A request whose task is cancelled, e.g. by `VssStore`'s runtime shutting down, stops counting +/// at once, although the server may still apply it shortly after. +#[derive(Default)] +struct StoreFences { + stores: Mutex>, + writes_ended: Condvar, +} + +#[derive(Default)] +struct FenceState { + generation: u64, + writes_in_flight: usize, +} + +impl StoreFences { + fn start_generation(&self, store: &(String, String), timeout: Duration) -> io::Result { + let mut stores = self.stores.lock().unwrap(); + let state = stores.entry(store.clone()).or_default(); + state.generation += 1; + let generation = state.generation; + // Wakes an earlier store still waiting here, which has now been replaced itself. + self.writes_ended.notify_all(); + let (stores, result) = self + .writes_ended + .wait_timeout_while(stores, timeout, |stores| { + stores.get(store).is_some_and(|state| { + state.generation == generation && state.writes_in_flight > 0 + }) + }) + .unwrap(); + if stores.get(store).is_none_or(|state| state.generation != generation) { + let msg = "VSS store was replaced while being built"; + return Err(Error::new(ErrorKind::Other, msg)); + } + if result.timed_out() { + let msg = "Writes of a replaced store to this VSS store are still in flight"; + return Err(Error::new(ErrorKind::TimedOut, msg)); + } + Ok(generation) + } + + fn is_current(&self, store: &(String, String), generation: u64) -> bool { + self.stores.lock().unwrap().get(store).is_some_and(|state| state.generation == generation) + } + + /// Returns `None` if the store of `generation` has been replaced. + fn begin_write<'a>( + &'a self, store: &'a (String, String), generation: u64, + ) -> Option> { + let mut stores = self.stores.lock().unwrap(); + let state = stores.get_mut(store).filter(|state| state.generation == generation)?; + state.writes_in_flight += 1; + Some(WriteGuard { fences: self, store }) + } +} + +/// Counts one write request as in flight until it ends or its future is dropped. +struct WriteGuard<'a> { + fences: &'a StoreFences, + store: &'a (String, String), +} + +impl Drop for WriteGuard<'_> { + fn drop(&mut self) { + let mut stores = self.fences.stores.lock().unwrap(); + if let Some(state) = stores.get_mut(self.store) { + state.writes_in_flight -= 1; + if state.writes_in_flight == 0 { + self.fences.writes_ended.notify_all(); + } + } + } +} + +/// A [`VssStore`]'s place in [`STORE_FENCES`]. +#[derive(Clone)] +struct StoreFence { + store: (String, String), + generation: u64, +} + +#[derive(Debug)] +enum FencedWriteError { + Replaced, + Vss(VssError), +} + +impl fmt::Display for FencedWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Replaced => write!(f, "VSS store was replaced"), + Self::Vss(e) => e.fmt(f), + } + } +} + +impl error::Error for FencedWriteError {} + +/// Runs `attempt` with `policy`'s retries while the store of `fence` is current, counting each +/// attempt as in flight. Returns `Ok` without writing once the store has been replaced: its node +/// is gone, and a failed write would make LDK treat a monitor update as unrecoverable and panic. +async fn fenced_retry( + fence: &StoreFence, policy: &WriteRetryPolicy, mut attempt: F, +) -> Result<(), VssError> +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let res = retry( + || { + let write = fence.begin_write(); + let request = write.as_ref().map(|_| attempt()); + async move { + let (Some(_write), Some(request)) = (write, request) else { + return Err(FencedWriteError::Replaced); + }; + // Once replaced, a failed attempt is not retried after a backoff either. + request.await.map_err(|e| { + if fence.is_current() { + FencedWriteError::Vss(e) + } else { + FencedWriteError::Replaced + } + }) + } + }, + policy, + ) + .await; + match res { + Ok(()) | Err(FencedWriteError::Replaced) => Ok(()), + Err(FencedWriteError::Vss(_)) if !fence.is_current() => Ok(()), + Err(FencedWriteError::Vss(e)) => Err(e), + } +} + +impl StoreFence { + fn is_current(&self) -> bool { + STORE_FENCES.is_current(&self.store, self.generation) + } + + fn begin_write(&self) -> Option> { + STORE_FENCES.begin_write(&self.store, self.generation) + } +} + // We set this to a small number of threads that would still allow to make some progress if one // would hit a blocking case const INTERNAL_RUNTIME_WORKERS: usize = 2; @@ -83,6 +254,12 @@ impl VssStore { base_url: String, store_id: String, vss_seed: [u8; 32], header_provider: Arc, ) -> io::Result { + let store = (base_url.trim_end_matches('/').to_string(), store_id.clone()); + let generation = tokio::task::block_in_place(|| { + STORE_FENCES.start_generation(&store, REPLACED_WRITES_TIMEOUT) + })?; + let fence = StoreFence { store, generation }; + let next_version = AtomicU64::new(1); let internal_runtime = Arc::new(StoreRuntime::new("ldk-node-vss-runtime", INTERNAL_RUNTIME_WORKERS, "VSS")?); @@ -100,6 +277,7 @@ impl VssStore { let runtime_handle = internal_runtime.handle(); let schema_version = tokio::task::block_in_place(|| { + // Not fenced: the schema version it may write is the same for every store. runtime_handle.block_on(async { determine_and_write_schema_version( &blocking_client, @@ -110,16 +288,33 @@ impl VssStore { .await }) })?; + if !fence.is_current() { + return Err(Error::new(ErrorKind::Other, "VSS store was replaced while being built")); + } let async_retry_policy = retry_policy(); - let async_client = - VssClient::new_with_headers(base_url, async_retry_policy, header_provider); + let async_client = VssClient::new_with_headers( + base_url.clone(), + async_retry_policy, + header_provider.clone(), + ); + // Writes retry in `fenced_retry`, so that each attempt is fenced. + let blocking_write_client = VssClient::new_with_headers( + base_url.clone(), + no_retry_policy(), + header_provider.clone(), + ); + let async_write_client = + VssClient::new_with_headers(base_url, no_retry_policy(), header_provider); let inner = Arc::new(VssStoreInner::new( schema_version, blocking_client, async_client, + blocking_write_client, + async_write_client, store_id, + fence, data_encryption_key, key_obfuscator, )); @@ -196,7 +391,7 @@ impl KVStoreSync for VssStore { let fut = async move { inner .write_internal( - &inner.blocking_client, + &inner.blocking_write_client, inner_lock_ref, locking_key, version, @@ -227,7 +422,7 @@ impl KVStoreSync for VssStore { let fut = async move { inner .remove_internal( - &inner.blocking_client, + &inner.blocking_write_client, inner_lock_ref, locking_key, version, @@ -297,7 +492,7 @@ impl KVStore for VssStore { let task = runtime.spawn(async move { inner .write_internal( - &inner.async_client, + &inner.async_write_client, inner_lock_ref, locking_key, version, @@ -326,7 +521,7 @@ impl KVStore for VssStore { let fut = async move { inner .remove_internal( - &inner.async_client, + &inner.async_write_client, inner_lock_ref, locking_key, version, @@ -386,7 +581,12 @@ struct VssStoreInner { // A secondary client that will only be used for async persistence via `KVStore`, to ensure TCP // connections aren't shared between our outer and the internal runtime. async_client: VssClient, + // Clients for writes and removes, which `fenced_retry` retries. + blocking_write_client: VssClient, + async_write_client: VssClient, + write_retry_policy: WriteRetryPolicy, store_id: String, + fence: StoreFence, data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, // Per-key locks that ensures that we don't have concurrent writes to the same namespace/key. @@ -395,9 +595,12 @@ struct VssStoreInner { } impl VssStoreInner { + #[allow(clippy::too_many_arguments)] pub(crate) fn new( schema_version: VssSchemaVersion, blocking_client: VssClient, - async_client: VssClient, store_id: String, + async_client: VssClient, + blocking_write_client: VssClient, + async_write_client: VssClient, store_id: String, fence: StoreFence, data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, ) -> Self { let locks = Mutex::new(HashMap::new()); @@ -405,7 +608,11 @@ impl VssStoreInner { schema_version, blocking_client, async_client, + blocking_write_client, + async_write_client, + write_retry_policy: write_retry_policy(), store_id, + fence, data_encryption_key, key_obfuscator, locks, @@ -566,15 +773,20 @@ impl VssStoreInner { }; self.execute_locked_write(inner_lock_ref, locking_key, version, async move || { - client.put_object(&request).await.map_err(|e| { - let msg = format!( - "Failed to write to key {}/{}/{}: {}", - primary_namespace, secondary_namespace, key, e - ); - Error::new(ErrorKind::Other, msg) - })?; - - Ok(()) + let res = fenced_retry(&self.fence, &self.write_retry_policy, || async { + client.put_object(&request).await.map(|_| ()) + }) + .await; + match res { + Ok(()) => Ok(()), + Err(e) => { + let msg = format!( + "Failed to write to key {}/{}/{}: {}", + primary_namespace, secondary_namespace, key, e + ); + Err(Error::new(ErrorKind::Other, msg)) + }, + } }) .await } @@ -599,15 +811,20 @@ impl VssStoreInner { let request = DeleteObjectRequest { store_id: self.store_id.clone(), key_value: Some(key_value) }; - client.delete_object(&request).await.map_err(|e| { - let msg = format!( - "Failed to delete key {}/{}/{}: {}", - primary_namespace, secondary_namespace, key, e - ); - Error::new(ErrorKind::Other, msg) - })?; - - Ok(()) + let res = fenced_retry(&self.fence, &self.write_retry_policy, || async { + client.delete_object(&request).await.map(|_| ()) + }) + .await; + match res { + Ok(()) => Ok(()), + Err(e) => { + let msg = format!( + "Failed to delete key {}/{}/{}: {}", + primary_namespace, secondary_namespace, key, e + ); + Err(Error::new(ErrorKind::Other, msg)) + }, + } }) .await } @@ -695,13 +912,35 @@ fn retry_policy() -> CustomRetryPolicy { .with_max_attempts(100) .with_max_total_delay(Duration::from_secs(180)) .with_max_jitter(Duration::from_millis(100)) - .skip_retry_on_error(Box::new(|e: &VssError| { - matches!( - e, - VssError::NoSuchKeyError(..) - | VssError::InvalidRequestError(..) - | VssError::ConflictError(..) - ) + .skip_retry_on_error(Box::new(|e: &VssError| is_permanent(e)) as _) +} + +fn is_permanent(e: &VssError) -> bool { + matches!( + e, + VssError::NoSuchKeyError(..) + | VssError::InvalidRequestError(..) + | VssError::ConflictError(..) + ) +} + +fn no_retry_policy() -> CustomRetryPolicy { + ExponentialBackoffRetryPolicy::new(Duration::ZERO) + .with_max_attempts(1) + .with_max_total_delay(Duration::ZERO) + .with_max_jitter(Duration::ZERO) + .skip_retry_on_error(Box::new(|_: &VssError| true) as _) +} + +// The same retries as `retry_policy`, for `fenced_retry`. +fn write_retry_policy() -> WriteRetryPolicy { + ExponentialBackoffRetryPolicy::new(Duration::from_millis(10)) + .with_max_attempts(100) + .with_max_total_delay(Duration::from_secs(180)) + .with_max_jitter(Duration::from_millis(100)) + .skip_retry_on_error(Box::new(|e: &FencedWriteError| match e { + FencedWriteError::Replaced => true, + FencedWriteError::Vss(e) => is_permanent(e), }) as _) } @@ -822,6 +1061,183 @@ impl EntropySource for RandEntropySource { #[cfg(test)] impl RefUnwindSafe for VssStore {} +#[cfg(test)] +mod store_fences_tests { + use super::*; + + fn store() -> (String, String) { + ("https://vss.example".to_string(), "store".to_string()) + } + + #[test] + fn each_store_starts_a_new_generation() { + let fences = StoreFences::default(); + let first = fences.start_generation(&store(), Duration::ZERO).unwrap(); + let second = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(second > first); + } + + #[test] + fn a_store_replaced_while_waiting_stops_waiting() { + let fences = Arc::new(StoreFences::default()); + let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); + let key = store(); + let write = fences.begin_write(&key, replaced).unwrap(); + let waiting = { + let fences = Arc::clone(&fences); + std::thread::spawn(move || fences.start_generation(&store(), Duration::from_secs(10))) + }; + while fences.is_current(&key, replaced) { + std::thread::yield_now(); + } + let err = fences.start_generation(&key, Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert_eq!(waiting.join().unwrap().unwrap_err().kind(), ErrorKind::Other); + drop(write); + } + + #[test] + fn a_replaced_store_cannot_begin_writes() { + let fences = StoreFences::default(); + let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.begin_write(&store(), replaced).is_some()); + let current = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.begin_write(&store(), replaced).is_none()); + assert!(!fences.is_current(&store(), replaced)); + assert!(fences.begin_write(&store(), current).is_some()); + } + + #[test] + fn a_new_store_waits_for_writes_of_the_replaced_one() { + let fences = Arc::new(StoreFences::default()); + let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let writer = { + let fences = Arc::clone(&fences); + std::thread::spawn(move || { + let store = store(); + let _write = fences.begin_write(&store, replaced).unwrap(); + started_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }) + }; + started_rx.recv().unwrap(); + let builder = { + let fences = Arc::clone(&fences); + std::thread::spawn(move || fences.start_generation(&store(), Duration::from_secs(10))) + }; + std::thread::sleep(Duration::from_millis(50)); + assert!(!builder.is_finished(), "new store did not wait for the in-flight write"); + release_tx.send(()).unwrap(); + writer.join().unwrap(); + builder.join().unwrap().unwrap(); + } + + #[test] + fn a_new_store_fails_but_still_fences_while_a_write_stays_in_flight() { + let fences = StoreFences::default(); + let store = store(); + let replaced = fences.start_generation(&store, Duration::ZERO).unwrap(); + let _write = fences.begin_write(&store, replaced).unwrap(); + let err = fences.start_generation(&store, Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fences.begin_write(&store, replaced).is_none()); + } + + #[test] + fn dropping_an_unfinished_write_future_ends_the_write() { + let fences = StoreFences::default(); + let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); + let store = store(); + let write = fences.begin_write(&store, replaced).unwrap(); + let fut = async move { + let _write = write; + std::future::pending::<()>().await; + }; + drop(fut); + fences.start_generation(&store, Duration::ZERO).unwrap(); + } + + fn current_fence(store_id: &str) -> StoreFence { + let store = ("https://vss.example".to_string(), store_id.to_string()); + let generation = STORE_FENCES.start_generation(&store, Duration::ZERO).unwrap(); + StoreFence { store, generation } + } + + fn server_error() -> VssError { + VssError::InternalServerError("unavailable".to_string()) + } + + #[tokio::test] + async fn fenced_retry_retries_until_a_write_succeeds() { + let fence = current_fence("retries"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + let res = fenced_retry(&fence, &write_retry_policy(), || async { + if attempts.fetch_add(1, Ordering::SeqCst) < 2 { + Err(server_error()) + } else { + Ok(()) + } + }) + .await; + assert!(res.is_ok()); + assert_eq!(attempts.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn fenced_retry_returns_permanent_errors_without_retrying() { + let fence = current_fence("permanent"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + let res = fenced_retry(&fence, &write_retry_policy(), || async { + attempts.fetch_add(1, Ordering::SeqCst); + Err(VssError::ConflictError("conflict".to_string())) + }) + .await; + assert!(matches!(res, Err(VssError::ConflictError(..)))); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn fenced_retry_drops_writes_of_a_replaced_store() { + let fence = current_fence("replaced"); + current_fence("replaced"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + let res = fenced_retry(&fence, &write_retry_policy(), || async { + attempts.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + .await; + assert!(res.is_ok()); + assert_eq!(attempts.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn fenced_retry_stops_retrying_once_the_store_is_replaced() { + let fence = current_fence("replaced-between-attempts"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + let res = fenced_retry(&fence, &write_retry_policy(), || async { + attempts.fetch_add(1, Ordering::SeqCst); + // A new store starts its generation now; it times out waiting for this attempt. + let _ = STORE_FENCES.start_generation(&fence.store, Duration::ZERO); + Err(server_error()) + }) + .await; + assert!(res.is_ok()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[test] + fn stores_fence_only_their_own_writes() { + let fences = StoreFences::default(); + let other = ("https://vss.example".to_string(), "other".to_string()); + let other_generation = fences.start_generation(&other, Duration::ZERO).unwrap(); + let _write = fences.begin_write(&other, other_generation).unwrap(); + fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.begin_write(&other, other_generation).is_some()); + } +} + #[cfg(test)] #[cfg(vss_test)] mod tests { @@ -861,4 +1277,28 @@ mod tests { do_read_write_remove_list_persist(&vss_store); drop(vss_store) } + + #[test] + fn vss_writes_of_a_replaced_store_are_dropped() { + let vss_base_url = std::env::var("TEST_VSS_BASE_URL").unwrap(); + let mut rng = rng(); + let rand_store_id: String = (0..7).map(|_| rng.sample(Alphanumeric) as char).collect(); + let mut vss_seed = [0u8; 32]; + rng.fill_bytes(&mut vss_seed); + let header_provider = Arc::new(FixedHeaders::new(HashMap::new())); + let replaced = VssStore::new( + vss_base_url.clone(), + rand_store_id.clone(), + vss_seed, + header_provider.clone(), + ) + .unwrap(); + let current = + VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider).unwrap(); + + KVStoreSync::write(¤t, "ns", "", "key", vec![2]).unwrap(); + KVStoreSync::write(&replaced, "ns", "", "key", vec![1]).unwrap(); + KVStoreSync::remove(&replaced, "ns", "", "key", false).unwrap(); + assert_eq!(KVStoreSync::read(¤t, "ns", "", "key").unwrap(), vec![2]); + } } From 3e494b3d6911f39d33ba0b41126fd24dec4a001d Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 14:37:19 +0100 Subject: [PATCH 2/9] fix: keep a running node's vss store from being replaced Scope the write fence to one wallet and to stopped nodes: - The fence key adds a hash of the store's obfuscation key, so stores of other wallets on the same URL and store id stay unaffected. - A node marks its store live from start() until the end of stop(). Building a store waits up to 60 s for a live store's node to stop and fails without replacing it, so a running node's writes are never dropped. - start() refuses a store that has been replaced, e.g. after a failed rebuild, with PersistenceFailed. - A dropped write is logged, each write attempt ends after 30 s (the LNURL-auth JWT fetch has no timeout), and the docs state that a request ended on the client may still land. Verified: cargo test --lib (144 passed), cargo clippy --lib (no new findings), vss_test targets compile; VSS integration tests not run locally. --- CHANGELOG.md | 2 +- src/builder.rs | 17 +- src/io/vss_store.rs | 327 +++++++++++++++++++++++++-------- src/lib.rs | 27 +++ tests/integration_tests_vss.rs | 31 ++++ 5 files changed, 324 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c52ff534a..ec8891a76b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Bug Fixes -- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for the earlier store's write requests still in flight, fails with `KVStoreSetupFailed` if they have not ended after 60 s, and drops the earlier store's writes from then on. +- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for the earlier store's write requests to end, fails with `KVStoreSetupFailed` if they have not after 60 s, and drops the earlier store's writes from then on; a node whose store has been replaced fails to start with `PersistenceFailed`. - Prevent the native SIGABRT `A Tokio 1.x context was found, but it is being shutdown.` when a node is released while background work is still stuck, e.g. in a VSS write after a timed-out stop: the runtime is now kept alive until that work ends instead of being shut down under it. - Bump `lightning`, `lightning-liquidity`, `lightning-persister` and `lightning-transaction-sync` to 0.2.8 and `lightning-invoice` to 0.34.2. - `bump_fee_by_rbf` now only replaces transactions this wallet built and broadcast itself, and returns `TransactionNotBroadcastByWallet` for any other txid. diff --git a/src/builder.rs b/src/builder.rs index 67cb9afec8..762b118c5c 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -65,7 +65,7 @@ use crate::io::utils::{ read_network_graph, read_node_metrics, read_payments_async, write_node_metrics, EXTERNAL_PATHFINDING_SCORES_CACHE_KEY, }; -use crate::io::vss_store::VssStore; +use crate::io::vss_store::{StoreFence, VssStore}; use crate::io::{ self, EVENT_QUEUE_PERSISTENCE_KEY, EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE, EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, @@ -830,10 +830,12 @@ impl NodeBuilder { let vss_seed_bytes: [u8; 32] = vss_xprv.private_key.secret_bytes(); let vss_store = - VssStore::new(vss_url, store_id, vss_seed_bytes, header_provider).map_err(|e| { - log_error!(logger, "Failed to setup VSS store: {}", e); - BuildError::KVStoreSetupFailed - })?; + VssStore::new(vss_url, store_id, vss_seed_bytes, header_provider, Arc::clone(&logger)) + .map_err(|e| { + log_error!(logger, "Failed to setup VSS store: {}", e); + BuildError::KVStoreSetupFailed + })?; + let vss_store_fence = vss_store.fence(); build_with_store_internal( config, @@ -846,6 +848,7 @@ impl NodeBuilder { runtime, logger, Arc::new(vss_store), + Some(vss_store_fence), self.channel_data_migration.as_ref(), ) } @@ -881,6 +884,7 @@ impl NodeBuilder { runtime, logger, kv_store, + None, self.channel_data_migration.as_ref(), ) } @@ -1726,7 +1730,7 @@ fn build_with_store_internal( liquidity_source_config: Option<&LiquiditySourceConfig>, pathfinding_scores_sync_config: Option<&PathfindingScoresSyncConfig>, async_payments_role: Option, seed_bytes: [u8; 64], runtime: Runtime, - logger: Arc, kv_store: Arc, + logger: Arc, kv_store: Arc, vss_store_fence: Option, channel_data_migration: Option<&ChannelDataMigration>, ) -> Result { optionally_install_rustls_cryptoprovider(); @@ -2600,6 +2604,7 @@ fn build_with_store_internal( pathfinding_scores_sync_url, liquidity_source, kv_store, + vss_store_fence, logger, _router: router, scorer, diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index bc319f64d1..1641df803d 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -13,14 +13,14 @@ use std::panic::RefUnwindSafe; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; use std::{error, fmt}; use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; -use lightning::impl_writeable_tlv_based_enum; use lightning::io::{self, Error, ErrorKind}; use lightning::util::persist::{KVStore, KVStoreSync}; use lightning::util::ser::{Readable, Writeable}; +use lightning::{impl_writeable_tlv_based_enum, log_warn}; use prost::Message; use rand::RngCore; use vss_client::client::VssClient; @@ -38,6 +38,7 @@ use vss_client::util::retry::{ use vss_client::util::storable_builder::{EntropySource, StorableBuilder}; use crate::io::utils::check_namespace_key_validity; +use crate::logger::{LdkLogger, Logger}; use crate::runtime::StoreRuntime; type CustomRetryPolicy = FilteredRetryPolicy< @@ -74,46 +75,71 @@ impl_writeable_tlv_based_enum!(VssSchemaVersion, const VSS_SCHEMA_VERSION_KEY: &str = "vss_schema_version"; -// How long a new store waits for writes of the store it replaces to end. A write retries for -// minutes while VSS is unreachable (see `retry_policy`), so building fails after this rather than -// letting such a write land after the new store's writes. +// How long building a store waits for a node still running on the same VSS store to stop, and +// then for the write requests of that store to end. A replaced store starts no further attempt, +// so the second wait covers at most one attempt, which `WRITE_ATTEMPT_TIMEOUT` bounds. const REPLACED_WRITES_TIMEOUT: Duration = Duration::from_secs(60); +// Bounds one write attempt, the header fetch included: the VSS client times a request out after +// 10 s, but the LNURL-auth JWT fetch has no timeout of its own. +const WRITE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(30); + static STORE_FENCES: LazyLock = LazyLock::new(StoreFences::default); +/// Identifies a VSS store by URL, store id and wallet, as the server separates stores by the +/// authenticated user as well as by store id. The wallet part is a hash of the store's +/// obfuscation key, so no key material is kept here. +type StoreKey = (String, String, [u8; 32]); + /// Fences the writes of a [`VssStore`] once another one is built for the same VSS store. /// /// VSS writes are unconditional puts, so a write of a stopped node that is still retrying, or one /// its detached work starts later, would overwrite what a node rebuilt on the same store wrote -/// since, e.g. a newer channel monitor. Building a store therefore starts a new generation for its -/// VSS store and waits for the write requests of earlier generations still on the wire. From then -/// on, an earlier generation's writes are dropped before their next attempt (see `fenced_retry`). +/// since, e.g. a newer channel monitor. Building a store therefore waits until no node runs on +/// the VSS store (see [`StoreFence::mark_live`]), starts a new generation for it and waits for the +/// write requests of earlier generations to end. From then on, an earlier generation's writes are +/// dropped before their next attempt (see `fenced_retry`), and its node refuses to start. /// -/// A request whose task is cancelled, e.g. by `VssStore`'s runtime shutting down, stops counting -/// at once, although the server may still apply it shortly after. +/// A request stops counting once its attempt ends, also when it times out on the client or its +/// task is cancelled, e.g. by `VssStore`'s runtime shutting down. The server may still apply such +/// a request shortly after; ruling that out needs conditional writes. #[derive(Default)] struct StoreFences { - stores: Mutex>, - writes_ended: Condvar, + stores: Mutex>, + changed: Condvar, } #[derive(Default)] struct FenceState { generation: u64, + // Whether a node runs on the current generation's store. + live: bool, writes_in_flight: usize, } impl StoreFences { - fn start_generation(&self, store: &(String, String), timeout: Duration) -> io::Result { - let mut stores = self.stores.lock().unwrap(); + fn start_generation(&self, store: &StoreKey, timeout: Duration) -> io::Result { + let deadline = Instant::now() + timeout; + let stores = self.stores.lock().unwrap(); + let (mut stores, result) = self + .changed + .wait_timeout_while(stores, timeout, |stores| { + stores.get(store).is_some_and(|state| state.live) + }) + .unwrap(); + if result.timed_out() { + let msg = "A node using this VSS store is still running"; + return Err(Error::new(ErrorKind::TimedOut, msg)); + } let state = stores.entry(store.clone()).or_default(); state.generation += 1; let generation = state.generation; // Wakes an earlier store still waiting here, which has now been replaced itself. - self.writes_ended.notify_all(); + self.changed.notify_all(); + let remaining = deadline.saturating_duration_since(Instant::now()); let (stores, result) = self - .writes_ended - .wait_timeout_while(stores, timeout, |stores| { + .changed + .wait_timeout_while(stores, remaining, |stores| { stores.get(store).is_some_and(|state| { state.generation == generation && state.writes_in_flight > 0 }) @@ -130,14 +156,31 @@ impl StoreFences { Ok(generation) } - fn is_current(&self, store: &(String, String), generation: u64) -> bool { + fn is_current(&self, store: &StoreKey, generation: u64) -> bool { self.stores.lock().unwrap().get(store).is_some_and(|state| state.generation == generation) } + fn mark_live(&self, store: &StoreKey, generation: u64) -> bool { + let mut stores = self.stores.lock().unwrap(); + match stores.get_mut(store).filter(|state| state.generation == generation) { + Some(state) => { + state.live = true; + true + }, + None => false, + } + } + + fn clear_live(&self, store: &StoreKey, generation: u64) { + let mut stores = self.stores.lock().unwrap(); + if let Some(state) = stores.get_mut(store).filter(|state| state.generation == generation) { + state.live = false; + self.changed.notify_all(); + } + } + /// Returns `None` if the store of `generation` has been replaced. - fn begin_write<'a>( - &'a self, store: &'a (String, String), generation: u64, - ) -> Option> { + fn begin_write<'a>(&'a self, store: &'a StoreKey, generation: u64) -> Option> { let mut stores = self.stores.lock().unwrap(); let state = stores.get_mut(store).filter(|state| state.generation == generation)?; state.writes_in_flight += 1; @@ -148,7 +191,7 @@ impl StoreFences { /// Counts one write request as in flight until it ends or its future is dropped. struct WriteGuard<'a> { fences: &'a StoreFences, - store: &'a (String, String), + store: &'a StoreKey, } impl Drop for WriteGuard<'_> { @@ -157,19 +200,41 @@ impl Drop for WriteGuard<'_> { if let Some(state) = stores.get_mut(self.store) { state.writes_in_flight -= 1; if state.writes_in_flight == 0 { - self.fences.writes_ended.notify_all(); + self.fences.changed.notify_all(); } } } } -/// A [`VssStore`]'s place in [`STORE_FENCES`]. +/// A [`VssStore`]'s place in the process-wide fences of its VSS store. #[derive(Clone)] -struct StoreFence { - store: (String, String), +pub(crate) struct StoreFence { + store: StoreKey, generation: u64, } +impl StoreFence { + /// Marks the store as used by a running node, so that building another store for the same VSS + /// store waits until [`Self::clear_live`]. Returns `false` if the store has been replaced, as + /// its writes are then dropped and its node must not run. + pub(crate) fn mark_live(&self) -> bool { + STORE_FENCES.mark_live(&self.store, self.generation) + } + + /// Marks the store's node as stopped. + pub(crate) fn clear_live(&self) { + STORE_FENCES.clear_live(&self.store, self.generation) + } + + fn is_current(&self) -> bool { + STORE_FENCES.is_current(&self.store, self.generation) + } + + fn begin_write(&self) -> Option> { + STORE_FENCES.begin_write(&self.store, self.generation) + } +} + #[derive(Debug)] enum FencedWriteError { Replaced, @@ -187,12 +252,21 @@ impl fmt::Display for FencedWriteError { impl error::Error for FencedWriteError {} +#[derive(Debug, PartialEq, Eq)] +enum WriteOutcome { + Written, + // The store was replaced, so the write was not sent or its failure ended the attempts. + Dropped, +} + /// Runs `attempt` with `policy`'s retries while the store of `fence` is current, counting each -/// attempt as in flight. Returns `Ok` without writing once the store has been replaced: its node -/// is gone, and a failed write would make LDK treat a monitor update as unrecoverable and panic. +/// attempt as in flight and ending it after `attempt_timeout`. Once the store has been +/// replaced, returns [`WriteOutcome::Dropped`] without writing: its node has stopped and cannot +/// start again, and a failed write would make LDK treat a monitor update as unrecoverable and +/// panic in the node's detached work. async fn fenced_retry( - fence: &StoreFence, policy: &WriteRetryPolicy, mut attempt: F, -) -> Result<(), VssError> + fence: &StoreFence, policy: &WriteRetryPolicy, attempt_timeout: Duration, mut attempt: F, +) -> Result where F: FnMut() -> Fut, Fut: Future>, @@ -200,13 +274,16 @@ where let res = retry( || { let write = fence.begin_write(); - let request = write.as_ref().map(|_| attempt()); + let request = write.as_ref().map(|_| tokio::time::timeout(attempt_timeout, attempt())); async move { let (Some(_write), Some(request)) = (write, request) else { return Err(FencedWriteError::Replaced); }; + let res = request.await.unwrap_or_else(|_| { + Err(VssError::InternalError("VSS write attempt timed out".to_string())) + }); // Once replaced, a failed attempt is not retried after a backoff either. - request.await.map_err(|e| { + res.map_err(|e| { if fence.is_current() { FencedWriteError::Vss(e) } else { @@ -219,22 +296,13 @@ where ) .await; match res { - Ok(()) | Err(FencedWriteError::Replaced) => Ok(()), - Err(FencedWriteError::Vss(_)) if !fence.is_current() => Ok(()), + Ok(()) => Ok(WriteOutcome::Written), + Err(FencedWriteError::Replaced) => Ok(WriteOutcome::Dropped), + Err(FencedWriteError::Vss(_)) if !fence.is_current() => Ok(WriteOutcome::Dropped), Err(FencedWriteError::Vss(e)) => Err(e), } } -impl StoreFence { - fn is_current(&self) -> bool { - STORE_FENCES.is_current(&self.store, self.generation) - } - - fn begin_write(&self) -> Option> { - STORE_FENCES.begin_write(&self.store, self.generation) - } -} - // We set this to a small number of threads that would still allow to make some progress if one // would hit a blocking case const INTERNAL_RUNTIME_WORKERS: usize = 2; @@ -252,9 +320,14 @@ pub struct VssStore { impl VssStore { pub(crate) fn new( base_url: String, store_id: String, vss_seed: [u8; 32], - header_provider: Arc, + header_provider: Arc, logger: Arc, ) -> io::Result { - let store = (base_url.trim_end_matches('/').to_string(), store_id.clone()); + let (data_encryption_key, obfuscation_master_key) = + derive_data_encryption_and_obfuscation_keys(&vss_seed); + let wallet = sha256::Hash::hash(&obfuscation_master_key).to_byte_array(); + let key_obfuscator = KeyObfuscator::new(obfuscation_master_key); + + let store = (base_url.trim_end_matches('/').to_string(), store_id.clone(), wallet); let generation = tokio::task::block_in_place(|| { STORE_FENCES.start_generation(&store, REPLACED_WRITES_TIMEOUT) })?; @@ -264,10 +337,6 @@ impl VssStore { let internal_runtime = Arc::new(StoreRuntime::new("ldk-node-vss-runtime", INTERNAL_RUNTIME_WORKERS, "VSS")?); - let (data_encryption_key, obfuscation_master_key) = - derive_data_encryption_and_obfuscation_keys(&vss_seed); - let key_obfuscator = KeyObfuscator::new(obfuscation_master_key); - let sync_retry_policy = retry_policy(); let blocking_client = VssClient::new_with_headers( base_url.clone(), @@ -317,11 +386,17 @@ impl VssStore { fence, data_encryption_key, key_obfuscator, + logger, )); Ok(Self { inner, next_version, internal_runtime: Some(internal_runtime) }) } + /// The store's fence, for its node to mark the store as live while running. + pub(crate) fn fence(&self) -> StoreFence { + self.inner.fence.clone() + } + fn internal_runtime(&self) -> Arc { Arc::clone(self.internal_runtime.as_ref().expect("VSS runtime must be available")) } @@ -589,6 +664,7 @@ struct VssStoreInner { fence: StoreFence, data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, + logger: Arc, // Per-key locks that ensures that we don't have concurrent writes to the same namespace/key. // The lock also encapsulates the latest written version per key. locks: Mutex>>>, @@ -601,7 +677,7 @@ impl VssStoreInner { async_client: VssClient, blocking_write_client: VssClient, async_write_client: VssClient, store_id: String, fence: StoreFence, - data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, + data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, logger: Arc, ) -> Self { let locks = Mutex::new(HashMap::new()); Self { @@ -615,6 +691,7 @@ impl VssStoreInner { fence, data_encryption_key, key_obfuscator, + logger, locks, } } @@ -773,12 +850,25 @@ impl VssStoreInner { }; self.execute_locked_write(inner_lock_ref, locking_key, version, async move || { - let res = fenced_retry(&self.fence, &self.write_retry_policy, || async { - client.put_object(&request).await.map(|_| ()) - }) + let res = fenced_retry( + &self.fence, + &self.write_retry_policy, + WRITE_ATTEMPT_TIMEOUT, + || async { client.put_object(&request).await.map(|_| ()) }, + ) .await; match res { - Ok(()) => Ok(()), + Ok(WriteOutcome::Written) => Ok(()), + Ok(WriteOutcome::Dropped) => { + log_warn!( + self.logger, + "Dropped write of key {}/{}/{}: another node was built on this VSS store", + primary_namespace, + secondary_namespace, + key + ); + Ok(()) + }, Err(e) => { let msg = format!( "Failed to write to key {}/{}/{}: {}", @@ -811,12 +901,25 @@ impl VssStoreInner { let request = DeleteObjectRequest { store_id: self.store_id.clone(), key_value: Some(key_value) }; - let res = fenced_retry(&self.fence, &self.write_retry_policy, || async { - client.delete_object(&request).await.map(|_| ()) - }) + let res = fenced_retry( + &self.fence, + &self.write_retry_policy, + WRITE_ATTEMPT_TIMEOUT, + || async { client.delete_object(&request).await.map(|_| ()) }, + ) .await; match res { - Ok(()) => Ok(()), + Ok(WriteOutcome::Written) => Ok(()), + Ok(WriteOutcome::Dropped) => { + log_warn!( + self.logger, + "Dropped removal of key {}/{}/{}: another node was built on this VSS store", + primary_namespace, + secondary_namespace, + key + ); + Ok(()) + }, Err(e) => { let msg = format!( "Failed to delete key {}/{}/{}: {}", @@ -1065,8 +1168,8 @@ impl RefUnwindSafe for VssStore {} mod store_fences_tests { use super::*; - fn store() -> (String, String) { - ("https://vss.example".to_string(), "store".to_string()) + fn store() -> StoreKey { + ("https://vss.example".to_string(), "store".to_string(), [1; 32]) } #[test] @@ -1160,7 +1263,7 @@ mod store_fences_tests { } fn current_fence(store_id: &str) -> StoreFence { - let store = ("https://vss.example".to_string(), store_id.to_string()); + let store = ("https://vss.example".to_string(), store_id.to_string(), [1; 32]); let generation = STORE_FENCES.start_generation(&store, Duration::ZERO).unwrap(); StoreFence { store, generation } } @@ -1173,7 +1276,7 @@ mod store_fences_tests { async fn fenced_retry_retries_until_a_write_succeeds() { let fence = current_fence("retries"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), || async { + let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { if attempts.fetch_add(1, Ordering::SeqCst) < 2 { Err(server_error()) } else { @@ -1181,7 +1284,7 @@ mod store_fences_tests { } }) .await; - assert!(res.is_ok()); + assert_eq!(res.unwrap(), WriteOutcome::Written); assert_eq!(attempts.load(Ordering::SeqCst), 3); } @@ -1189,7 +1292,7 @@ mod store_fences_tests { async fn fenced_retry_returns_permanent_errors_without_retrying() { let fence = current_fence("permanent"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), || async { + let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { attempts.fetch_add(1, Ordering::SeqCst); Err(VssError::ConflictError("conflict".to_string())) }) @@ -1203,12 +1306,12 @@ mod store_fences_tests { let fence = current_fence("replaced"); current_fence("replaced"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), || async { + let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { attempts.fetch_add(1, Ordering::SeqCst); Ok(()) }) .await; - assert!(res.is_ok()); + assert_eq!(res.unwrap(), WriteOutcome::Dropped); assert_eq!(attempts.load(Ordering::SeqCst), 0); } @@ -1216,26 +1319,96 @@ mod store_fences_tests { async fn fenced_retry_stops_retrying_once_the_store_is_replaced() { let fence = current_fence("replaced-between-attempts"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), || async { + let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { attempts.fetch_add(1, Ordering::SeqCst); // A new store starts its generation now; it times out waiting for this attempt. let _ = STORE_FENCES.start_generation(&fence.store, Duration::ZERO); Err(server_error()) }) .await; - assert!(res.is_ok()); + assert_eq!(res.unwrap(), WriteOutcome::Dropped); assert_eq!(attempts.load(Ordering::SeqCst), 1); } #[test] fn stores_fence_only_their_own_writes() { let fences = StoreFences::default(); - let other = ("https://vss.example".to_string(), "other".to_string()); + let other = ("https://vss.example".to_string(), "other".to_string(), [1; 32]); let other_generation = fences.start_generation(&other, Duration::ZERO).unwrap(); let _write = fences.begin_write(&other, other_generation).unwrap(); fences.start_generation(&store(), Duration::ZERO).unwrap(); assert!(fences.begin_write(&other, other_generation).is_some()); } + + #[test] + fn stores_of_other_wallets_are_not_fenced() { + let fences = StoreFences::default(); + let (url, store_id, _) = store(); + let other_wallet = (url, store_id, [2; 32]); + let other_generation = fences.start_generation(&other_wallet, Duration::ZERO).unwrap(); + assert!(fences.mark_live(&other_wallet, other_generation)); + fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.is_current(&other_wallet, other_generation)); + assert!(fences.begin_write(&other_wallet, other_generation).is_some()); + } + + #[test] + fn a_store_is_not_replaced_while_its_node_runs() { + let fences = StoreFences::default(); + let live = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.mark_live(&store(), live)); + let err = fences.start_generation(&store(), Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fences.is_current(&store(), live)); + assert!(fences.begin_write(&store(), live).is_some()); + } + + #[test] + fn a_new_store_waits_for_the_running_node_to_stop() { + let fences = Arc::new(StoreFences::default()); + let live = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(fences.mark_live(&store(), live)); + let builder = { + let fences = Arc::clone(&fences); + std::thread::spawn(move || fences.start_generation(&store(), Duration::from_secs(10))) + }; + std::thread::sleep(Duration::from_millis(50)); + assert!(!builder.is_finished(), "new store did not wait for the running node"); + assert!(fences.is_current(&store(), live)); + fences.clear_live(&store(), live); + builder.join().unwrap().unwrap(); + assert!(!fences.is_current(&store(), live)); + } + + #[test] + fn a_replaced_store_cannot_be_marked_live() { + let fences = StoreFences::default(); + let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); + let current = fences.start_generation(&store(), Duration::ZERO).unwrap(); + assert!(!fences.mark_live(&store(), replaced)); + assert!(fences.mark_live(&store(), current)); + // A stale clear leaves the current store's node marked as running. + fences.clear_live(&store(), replaced); + let err = fences.start_generation(&store(), Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fences.is_current(&store(), current)); + } + + #[tokio::test] + async fn fenced_retry_ends_an_attempt_that_does_not_finish() { + let fence = current_fence("stuck"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + let res = + fenced_retry(&fence, &write_retry_policy(), Duration::from_millis(10), || async { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + std::future::pending::<()>().await; + } + Ok(()) + }) + .await; + assert_eq!(res.unwrap(), WriteOutcome::Written); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + } } #[cfg(test)] @@ -1250,6 +1423,10 @@ mod tests { use super::*; use crate::io::test_utils::do_read_write_remove_list_persist; + fn logger() -> Arc { + Arc::new(Logger::new_log_facade()) + } + #[test] fn vss_read_write_remove_list_persist() { let vss_base_url = std::env::var("TEST_VSS_BASE_URL").unwrap(); @@ -1259,7 +1436,8 @@ mod tests { rng.fill_bytes(&mut vss_seed); let header_provider = Arc::new(FixedHeaders::new(HashMap::new())); let vss_store = - VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider).unwrap(); + VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider, logger()) + .unwrap(); do_read_write_remove_list_persist(&vss_store); } @@ -1272,7 +1450,8 @@ mod tests { rng.fill_bytes(&mut vss_seed); let header_provider = Arc::new(FixedHeaders::new(HashMap::new())); let vss_store = - VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider).unwrap(); + VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider, logger()) + .unwrap(); do_read_write_remove_list_persist(&vss_store); drop(vss_store) @@ -1291,10 +1470,12 @@ mod tests { rand_store_id.clone(), vss_seed, header_provider.clone(), + logger(), ) .unwrap(); let current = - VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider).unwrap(); + VssStore::new(vss_base_url, rand_store_id, vss_seed, header_provider, logger()) + .unwrap(); KVStoreSync::write(¤t, "ns", "", "key", vec![2]).unwrap(); KVStoreSync::write(&replaced, "ns", "", "key", vec![1]).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 4df8530106..6e4987dc86 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -138,6 +138,7 @@ use gossip::GossipSource; use graph::NetworkGraph; use io::utils::write_node_metrics; pub use io::utils::{derive_node_secret_from_mnemonic, generate_entropy_mnemonic}; +use io::vss_store::StoreFence; use lightning::chain::channelmonitor::Balance as LdkBalance; use lightning::chain::BestBlock; use lightning::events::bump_transaction::{Input, Wallet as LdkWallet}; @@ -207,6 +208,8 @@ pub struct Node { pathfinding_scores_sync_url: Option, liquidity_source: Option>>>, kv_store: Arc, + // Set for a VSS store, which the node marks as live while running. + vss_store_fence: Option, logger: Arc, _router: Arc, scorer: Arc>, @@ -342,6 +345,26 @@ impl Node { return Err(Error::AlreadyRunning); } + if let Some(fence) = &self.vss_store_fence { + if !fence.mark_live() { + log_error!( + self.logger, + "Refusing to start: another node was built on this node's VSS store since.", + ); + return Err(Error::PersistenceFailed); + } + } + let res = self.start_services(); + // After a failed background processor, `stop` is still required and clears the mark. + if res.is_err() && !self.background_processor_failed.load(Ordering::Acquire) { + if let Some(fence) = &self.vss_store_fence { + fence.clear_live(); + } + } + res + } + + fn start_services(&self) -> Result<(), Error> { // Start up any runtime-dependant chain sources (e.g. Electrum) // Electrum needs execution access without owning the runtime lifecycle. let runtime_handle = self.runtime.handle().clone(); @@ -884,6 +907,10 @@ impl Node { self.runtime.log_metrics(); log_info!(self.logger, "Shutdown complete."); + // Only now may a node be built on this node's VSS store: its writes have all been issued. + if let Some(fence) = &self.vss_store_fence { + fence.clear_live(); + } let background_processor_failed = self.background_processor_failed.swap(false, Ordering::AcqRel); match background_processor_result { diff --git a/tests/integration_tests_vss.rs b/tests/integration_tests_vss.rs index 3b384ec45d..aeabc7a7e5 100644 --- a/tests/integration_tests_vss.rs +++ b/tests/integration_tests_vss.rs @@ -196,3 +196,34 @@ async fn vss_node_restart() { node.stop().unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn vss_replaced_node_refuses_to_start() { + let (_bitcoind, electrsd) = common::setup_bitcoind_and_electrsd(); + let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap()); + let vss_base_url = std::env::var("TEST_VSS_BASE_URL").unwrap(); + + let rand_suffix: String = + (0..7).map(|_| rng().sample(rand::distr::Alphanumeric) as char).collect(); + let store_id = format!("replaced_test_{}", rand_suffix); + let mut builder = Builder::new(); + builder.set_network(bitcoin::Network::Regtest); + builder.set_storage_dir_path(common::random_storage_path().to_str().unwrap().to_owned()); + builder.set_entropy_seed_bytes([43u8; 64]); + builder.set_chain_source_esplora(esplora_url, None); + + let replaced = builder + .build_with_vss_store_and_fixed_headers( + vss_base_url.clone(), + store_id.clone(), + HashMap::new(), + ) + .unwrap(); + let current = builder + .build_with_vss_store_and_fixed_headers(vss_base_url, store_id, HashMap::new()) + .unwrap(); + + assert_eq!(replaced.start(), Err(ldk_node::NodeError::PersistenceFailed)); + current.start().unwrap(); + current.stop().unwrap(); +} From a3aa2c4ae46c0569f5c159db259119bfb57f1a45 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 15:49:30 +0100 Subject: [PATCH 3/9] fix: clear a node's live mark when its start panics Node::start marks its VSS store live through start_marked_live, whose drop guard clears the mark on a failed or panicking start unless the node still needs stop(). The helper is unit tested without a VSS server. Verified: cargo test --lib (149 passed), cargo clippy --lib (no new findings), nightly rustfmt on vss_store.rs. --- src/io/vss_store.rs | 111 +++++++++++++++++++++++++++++++++++++++++++- src/lib.rs | 24 +++------- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index 1641df803d..2f7707563c 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -20,7 +20,7 @@ use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; use lightning::io::{self, Error, ErrorKind}; use lightning::util::persist::{KVStore, KVStoreSync}; use lightning::util::ser::{Readable, Writeable}; -use lightning::{impl_writeable_tlv_based_enum, log_warn}; +use lightning::{impl_writeable_tlv_based_enum, log_error, log_warn}; use prost::Message; use rand::RngCore; use vss_client::client::VssClient; @@ -235,6 +235,43 @@ impl StoreFence { } } +/// Runs a node's `start` with the store of `fence` marked live (see [`StoreFence::mark_live`]), +/// refusing with [`crate::Error::PersistenceFailed`] if the store has been replaced. Clears the mark +/// again if `start` fails or panics, unless `stop_required` says the node still needs a stop, which +/// clears it. +pub(crate) fn start_marked_live( + fence: Option<&StoreFence>, logger: &Logger, start: impl FnOnce() -> Result<(), crate::Error>, + stop_required: impl FnOnce() -> bool, +) -> Result<(), crate::Error> { + let Some(fence) = fence else { + return start(); + }; + if !fence.mark_live() { + log_error!( + logger, + "Refusing to start: another node was built on this node's VSS store since." + ); + return Err(crate::Error::PersistenceFailed); + } + let mut mark = LiveMark(Some(fence)); + let res = start(); + if res.is_ok() || stop_required() { + mark.0 = None; + } + res +} + +/// Clears a live mark when dropped, also while unwinding from a panic. +struct LiveMark<'a>(Option<&'a StoreFence>); + +impl Drop for LiveMark<'_> { + fn drop(&mut self) { + if let Some(fence) = self.0 { + fence.clear_live(); + } + } +} + #[derive(Debug)] enum FencedWriteError { Replaced, @@ -1394,6 +1431,78 @@ mod store_fences_tests { assert!(fences.is_current(&store(), current)); } + fn is_live(fence: &StoreFence) -> bool { + STORE_FENCES.stores.lock().unwrap().get(&fence.store).is_some_and(|state| state.live) + } + + #[test] + fn a_started_node_keeps_its_store_live() { + let fence = current_fence("started"); + let logger = Logger::new_log_facade(); + assert!(start_marked_live(Some(&fence), &logger, || Ok(()), || false).is_ok()); + assert!(is_live(&fence)); + fence.clear_live(); + assert!(!is_live(&fence)); + } + + #[test] + fn a_failed_start_clears_the_live_mark() { + let fence = current_fence("failed-start"); + let logger = Logger::new_log_facade(); + let res = start_marked_live( + Some(&fence), + &logger, + || Err(crate::Error::ConnectionFailed), + || false, + ); + assert_eq!(res, Err(crate::Error::ConnectionFailed)); + assert!(!is_live(&fence)); + } + + #[test] + fn a_failed_start_that_needs_a_stop_stays_live() { + let fence = current_fence("failed-start-needs-stop"); + let logger = Logger::new_log_facade(); + let res = start_marked_live( + Some(&fence), + &logger, + || Err(crate::Error::PersistenceFailed), + || true, + ); + assert_eq!(res, Err(crate::Error::PersistenceFailed)); + assert!(is_live(&fence)); + } + + #[test] + fn a_panicking_start_clears_the_live_mark() { + let fence = current_fence("panicking-start"); + let logger = Logger::new_log_facade(); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + start_marked_live(Some(&fence), &logger, || panic!("start failed"), || false) + })); + assert!(res.is_err()); + assert!(!is_live(&fence)); + } + + #[test] + fn a_node_on_a_replaced_store_does_not_start() { + let fence = current_fence("replaced-node"); + current_fence("replaced-node"); + let logger = Logger::new_log_facade(); + let mut started = false; + let res = start_marked_live( + Some(&fence), + &logger, + || { + started = true; + Ok(()) + }, + || false, + ); + assert_eq!(res, Err(crate::Error::PersistenceFailed)); + assert!(!started); + } + #[tokio::test] async fn fenced_retry_ends_an_attempt_that_does_not_finish() { let fence = current_fence("stuck"); diff --git a/src/lib.rs b/src/lib.rs index 6e4987dc86..b19a31c90f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -138,7 +138,7 @@ use gossip::GossipSource; use graph::NetworkGraph; use io::utils::write_node_metrics; pub use io::utils::{derive_node_secret_from_mnemonic, generate_entropy_mnemonic}; -use io::vss_store::StoreFence; +use io::vss_store::{start_marked_live, StoreFence}; use lightning::chain::channelmonitor::Balance as LdkBalance; use lightning::chain::BestBlock; use lightning::events::bump_transaction::{Input, Wallet as LdkWallet}; @@ -345,23 +345,13 @@ impl Node { return Err(Error::AlreadyRunning); } - if let Some(fence) = &self.vss_store_fence { - if !fence.mark_live() { - log_error!( - self.logger, - "Refusing to start: another node was built on this node's VSS store since.", - ); - return Err(Error::PersistenceFailed); - } - } - let res = self.start_services(); // After a failed background processor, `stop` is still required and clears the mark. - if res.is_err() && !self.background_processor_failed.load(Ordering::Acquire) { - if let Some(fence) = &self.vss_store_fence { - fence.clear_live(); - } - } - res + start_marked_live( + self.vss_store_fence.as_ref(), + &self.logger, + || self.start_services(), + || self.background_processor_failed.load(Ordering::Acquire), + ) } fn start_services(&self) -> Result<(), Error> { From 61491b6fcf6c652c5a35da2e7ba88b25ee95ce63 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 16:25:00 +0100 Subject: [PATCH 4/9] fix: keep a vss store current until its writes return A write's retry backoff did not count as in flight, so a store built while a stopped node's write waited to retry replaced it at once and dropped the rest of that write. Each write call now counts until it returns, and building a store waits for the node to stop and its calls to return before it starts a new generation, so a build that times out replaces nothing. Documents on the VSS build methods and Node::start that building waits for a node on the same store, and that the earlier node then refuses to start with PersistenceFailed. Verified: cargo test --lib io::vss_store (store_fences_tests), cargo check with --cfg vss_test, cargo doc, cargo clippy --- CHANGELOG.md | 2 +- src/builder.rs | 30 +++++ src/io/vss_store.rs | 264 ++++++++++++++++++-------------------------- src/lib.rs | 3 + 4 files changed, 144 insertions(+), 155 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec8891a76b..10fb8c6957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Bug Fixes -- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for the earlier store's write requests to end, fails with `KVStoreSetupFailed` if they have not after 60 s, and drops the earlier store's writes from then on; a node whose store has been replaced fails to start with `PersistenceFailed`. +- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for its writes, retries included, to return, fails with `KVStoreSetupFailed` without replacing anything if they have not after 60 s, and otherwise drops the earlier store's writes from then on; a node whose store has been replaced fails to start with `PersistenceFailed`. - Prevent the native SIGABRT `A Tokio 1.x context was found, but it is being shutdown.` when a node is released while background work is still stuck, e.g. in a VSS write after a timed-out stop: the runtime is now kept alive until that work ends instead of being shut down under it. - Bump `lightning`, `lightning-liquidity`, `lightning-persister` and `lightning-transaction-sync` to 0.2.8 and `lightning-invoice` to 0.34.2. - `bump_fee_by_rbf` now only replaces transactions this wallet built and broadcast itself, and returns `TransactionNotBroadcastByWallet` for any other txid. diff --git a/src/builder.rs b/src/builder.rs index 762b118c5c..ef8490a862 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -724,6 +724,11 @@ impl NodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md pub fn build_with_vss_store( @@ -778,6 +783,11 @@ impl NodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( &self, vss_url: String, store_id: String, fixed_headers: HashMap, @@ -797,6 +807,11 @@ impl NodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( &self, vss_url: String, store_id: String, header_provider: Arc, @@ -1207,6 +1222,11 @@ impl ArcedNodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md pub fn build_with_vss_store( @@ -1231,6 +1251,11 @@ impl ArcedNodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( &self, vss_url: String, store_id: String, fixed_headers: HashMap, @@ -1252,6 +1277,11 @@ impl ArcedNodeBuilder { /// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are /// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted. /// + /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for + /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. + /// Once built, an earlier [`Node`] on that store drops its remaining writes and its + /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( &self, vss_url: String, store_id: String, header_provider: Arc, diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index 2f7707563c..c3ea89e20d 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -13,8 +13,7 @@ use std::panic::RefUnwindSafe; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex}; -use std::time::{Duration, Instant}; -use std::{error, fmt}; +use std::time::Duration; use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; use lightning::io::{self, Error, ErrorKind}; @@ -48,15 +47,6 @@ type CustomRetryPolicy = FilteredRetryPolicy< Box bool + 'static + Send + Sync>, >; -type WriteRetryPolicy = FilteredRetryPolicy< - JitteredRetryPolicy< - MaxTotalDelayRetryPolicy< - MaxAttemptsRetryPolicy>, - >, - >, - Box bool + 'static + Send + Sync>, ->; - #[derive(Debug, PartialEq)] enum VssSchemaVersion { // The initial schema version. @@ -75,9 +65,9 @@ impl_writeable_tlv_based_enum!(VssSchemaVersion, const VSS_SCHEMA_VERSION_KEY: &str = "vss_schema_version"; -// How long building a store waits for a node still running on the same VSS store to stop, and -// then for the write requests of that store to end. A replaced store starts no further attempt, -// so the second wait covers at most one attempt, which `WRITE_ATTEMPT_TIMEOUT` bounds. +// How long building a store waits for a node still running on the same VSS store to stop and for +// the store's write calls to return. A call retries for up to 180 s while VSS fails, so against a +// failing VSS the build can time out; it then replaces nothing. const REPLACED_WRITES_TIMEOUT: Duration = Duration::from_secs(60); // Bounds one write attempt, the header fetch included: the VSS client times a request out after @@ -96,13 +86,14 @@ type StoreKey = (String, String, [u8; 32]); /// VSS writes are unconditional puts, so a write of a stopped node that is still retrying, or one /// its detached work starts later, would overwrite what a node rebuilt on the same store wrote /// since, e.g. a newer channel monitor. Building a store therefore waits until no node runs on -/// the VSS store (see [`StoreFence::mark_live`]), starts a new generation for it and waits for the -/// write requests of earlier generations to end. From then on, an earlier generation's writes are -/// dropped before their next attempt (see `fenced_retry`), and its node refuses to start. +/// the VSS store (see [`StoreFence::mark_live`]) and no write call of the current store is in +/// flight, retries and their backoff included, then starts a new generation for it. From then on, +/// an earlier generation's write calls are dropped before they start (see `fenced_retry`), and +/// its node refuses to start. /// -/// A request stops counting once its attempt ends, also when it times out on the client or its -/// task is cancelled, e.g. by `VssStore`'s runtime shutting down. The server may still apply such -/// a request shortly after; ruling that out needs conditional writes. +/// A call stops counting once it returns, also when its last request timed out on the client, or +/// when its task is cancelled, e.g. by `VssStore`'s runtime shutting down. The server may still +/// apply such a request shortly after; ruling that out needs conditional writes. #[derive(Default)] struct StoreFences { stores: Mutex>, @@ -114,46 +105,31 @@ struct FenceState { generation: u64, // Whether a node runs on the current generation's store. live: bool, + // Write calls of the current generation's store that have not returned. writes_in_flight: usize, } impl StoreFences { + /// Waits up to `timeout` until no node runs on the store and none of its write calls is in + /// flight, then starts a new generation. On a timeout the store is left as it was. fn start_generation(&self, store: &StoreKey, timeout: Duration) -> io::Result { - let deadline = Instant::now() + timeout; let stores = self.stores.lock().unwrap(); let (mut stores, result) = self .changed .wait_timeout_while(stores, timeout, |stores| { - stores.get(store).is_some_and(|state| state.live) + stores.get(store).is_some_and(|state| state.live || state.writes_in_flight > 0) }) .unwrap(); if result.timed_out() { - let msg = "A node using this VSS store is still running"; + let msg = match stores.get(store) { + Some(state) if state.live => "A node using this VSS store is still running", + _ => "Writes of the current store to this VSS store are still in flight", + }; return Err(Error::new(ErrorKind::TimedOut, msg)); } let state = stores.entry(store.clone()).or_default(); state.generation += 1; - let generation = state.generation; - // Wakes an earlier store still waiting here, which has now been replaced itself. - self.changed.notify_all(); - let remaining = deadline.saturating_duration_since(Instant::now()); - let (stores, result) = self - .changed - .wait_timeout_while(stores, remaining, |stores| { - stores.get(store).is_some_and(|state| { - state.generation == generation && state.writes_in_flight > 0 - }) - }) - .unwrap(); - if stores.get(store).is_none_or(|state| state.generation != generation) { - let msg = "VSS store was replaced while being built"; - return Err(Error::new(ErrorKind::Other, msg)); - } - if result.timed_out() { - let msg = "Writes of a replaced store to this VSS store are still in flight"; - return Err(Error::new(ErrorKind::TimedOut, msg)); - } - Ok(generation) + Ok(state.generation) } fn is_current(&self, store: &StoreKey, generation: u64) -> bool { @@ -179,7 +155,8 @@ impl StoreFences { } } - /// Returns `None` if the store of `generation` has been replaced. + /// Returns `None` if the store of `generation` has been replaced. While the guard lives, the + /// store is not replaced. fn begin_write<'a>(&'a self, store: &'a StoreKey, generation: u64) -> Option> { let mut stores = self.stores.lock().unwrap(); let state = stores.get_mut(store).filter(|state| state.generation == generation)?; @@ -188,7 +165,7 @@ impl StoreFences { } } -/// Counts one write request as in flight until it ends or its future is dropped. +/// Counts one write call as in flight until it returns or its future is dropped. struct WriteGuard<'a> { fences: &'a StoreFences, store: &'a StoreKey, @@ -272,72 +249,41 @@ impl Drop for LiveMark<'_> { } } -#[derive(Debug)] -enum FencedWriteError { - Replaced, - Vss(VssError), -} - -impl fmt::Display for FencedWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Replaced => write!(f, "VSS store was replaced"), - Self::Vss(e) => e.fmt(f), - } - } -} - -impl error::Error for FencedWriteError {} - #[derive(Debug, PartialEq, Eq)] enum WriteOutcome { Written, - // The store was replaced, so the write was not sent or its failure ended the attempts. + // The store was replaced, so the write was not sent. Dropped, } -/// Runs `attempt` with `policy`'s retries while the store of `fence` is current, counting each -/// attempt as in flight and ending it after `attempt_timeout`. Once the store has been -/// replaced, returns [`WriteOutcome::Dropped`] without writing: its node has stopped and cannot -/// start again, and a failed write would make LDK treat a monitor update as unrecoverable and -/// panic in the node's detached work. +/// Runs `attempt` with `policy`'s retries, ending each attempt after `attempt_timeout`. The +/// whole call, backoff included, counts as in flight, so the store is not replaced before it +/// returns. If the store has been replaced already, returns [`WriteOutcome::Dropped`] without +/// writing: its node has stopped and cannot start again, and a failed write would make LDK treat +/// a monitor update as unrecoverable and panic in the node's detached work. async fn fenced_retry( - fence: &StoreFence, policy: &WriteRetryPolicy, attempt_timeout: Duration, mut attempt: F, + fence: &StoreFence, policy: &CustomRetryPolicy, attempt_timeout: Duration, mut attempt: F, ) -> Result where F: FnMut() -> Fut, Fut: Future>, { - let res = retry( + let Some(_write) = fence.begin_write() else { + return Ok(WriteOutcome::Dropped); + }; + retry( || { - let write = fence.begin_write(); - let request = write.as_ref().map(|_| tokio::time::timeout(attempt_timeout, attempt())); + let request = tokio::time::timeout(attempt_timeout, attempt()); async move { - let (Some(_write), Some(request)) = (write, request) else { - return Err(FencedWriteError::Replaced); - }; - let res = request.await.unwrap_or_else(|_| { + request.await.unwrap_or_else(|_| { Err(VssError::InternalError("VSS write attempt timed out".to_string())) - }); - // Once replaced, a failed attempt is not retried after a backoff either. - res.map_err(|e| { - if fence.is_current() { - FencedWriteError::Vss(e) - } else { - FencedWriteError::Replaced - } }) } }, policy, ) - .await; - match res { - Ok(()) => Ok(WriteOutcome::Written), - Err(FencedWriteError::Replaced) => Ok(WriteOutcome::Dropped), - Err(FencedWriteError::Vss(_)) if !fence.is_current() => Ok(WriteOutcome::Dropped), - Err(FencedWriteError::Vss(e)) => Err(e), - } + .await + .map(|()| WriteOutcome::Written) } // We set this to a small number of threads that would still allow to make some progress if one @@ -696,7 +642,7 @@ struct VssStoreInner { // Clients for writes and removes, which `fenced_retry` retries. blocking_write_client: VssClient, async_write_client: VssClient, - write_retry_policy: WriteRetryPolicy, + write_retry_policy: CustomRetryPolicy, store_id: String, fence: StoreFence, data_encryption_key: [u8; 32], @@ -723,7 +669,7 @@ impl VssStoreInner { async_client, blocking_write_client, async_write_client, - write_retry_policy: write_retry_policy(), + write_retry_policy: retry_policy(), store_id, fence, data_encryption_key, @@ -1072,18 +1018,6 @@ fn no_retry_policy() -> CustomRetryPolicy { .skip_retry_on_error(Box::new(|_: &VssError| true) as _) } -// The same retries as `retry_policy`, for `fenced_retry`. -fn write_retry_policy() -> WriteRetryPolicy { - ExponentialBackoffRetryPolicy::new(Duration::from_millis(10)) - .with_max_attempts(100) - .with_max_total_delay(Duration::from_secs(180)) - .with_max_jitter(Duration::from_millis(100)) - .skip_retry_on_error(Box::new(|e: &FencedWriteError| match e { - FencedWriteError::Replaced => true, - FencedWriteError::Vss(e) => is_permanent(e), - }) as _) -} - async fn determine_and_write_schema_version( client: &VssClient, store_id: &String, data_encryption_key: [u8; 32], key_obfuscator: &KeyObfuscator, @@ -1217,25 +1151,6 @@ mod store_fences_tests { assert!(second > first); } - #[test] - fn a_store_replaced_while_waiting_stops_waiting() { - let fences = Arc::new(StoreFences::default()); - let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); - let key = store(); - let write = fences.begin_write(&key, replaced).unwrap(); - let waiting = { - let fences = Arc::clone(&fences); - std::thread::spawn(move || fences.start_generation(&store(), Duration::from_secs(10))) - }; - while fences.is_current(&key, replaced) { - std::thread::yield_now(); - } - let err = fences.start_generation(&key, Duration::from_millis(20)).unwrap_err(); - assert_eq!(err.kind(), ErrorKind::TimedOut); - assert_eq!(waiting.join().unwrap().unwrap_err().kind(), ErrorKind::Other); - drop(write); - } - #[test] fn a_replaced_store_cannot_begin_writes() { let fences = StoreFences::default(); @@ -1248,7 +1163,7 @@ mod store_fences_tests { } #[test] - fn a_new_store_waits_for_writes_of_the_replaced_one() { + fn a_new_store_waits_for_writes_in_flight() { let fences = Arc::new(StoreFences::default()); let replaced = fences.start_generation(&store(), Duration::ZERO).unwrap(); let (started_tx, started_rx) = std::sync::mpsc::channel(); @@ -1275,14 +1190,31 @@ mod store_fences_tests { } #[test] - fn a_new_store_fails_but_still_fences_while_a_write_stays_in_flight() { + fn a_new_store_that_times_out_on_a_write_replaces_nothing() { + let fences = StoreFences::default(); + let store = store(); + let current = fences.start_generation(&store, Duration::ZERO).unwrap(); + let _write = fences.begin_write(&store, current).unwrap(); + let err = fences.start_generation(&store, Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fences.is_current(&store, current)); + assert!(fences.begin_write(&store, current).is_some()); + } + + #[test] + fn a_new_store_that_times_out_on_a_stopping_node_replaces_nothing() { let fences = StoreFences::default(); let store = store(); - let replaced = fences.start_generation(&store, Duration::ZERO).unwrap(); - let _write = fences.begin_write(&store, replaced).unwrap(); + let current = fences.start_generation(&store, Duration::ZERO).unwrap(); + let write = fences.begin_write(&store, current).unwrap(); + assert!(fences.mark_live(&store, current)); + fences.clear_live(&store, current); + // The node stopped, but a write it started is still in flight. let err = fences.start_generation(&store, Duration::from_millis(20)).unwrap_err(); assert_eq!(err.kind(), ErrorKind::TimedOut); - assert!(fences.begin_write(&store, replaced).is_none()); + assert!(fences.is_current(&store, current)); + drop(write); + assert!(fences.start_generation(&store, Duration::ZERO).unwrap() > current); } #[test] @@ -1313,7 +1245,7 @@ mod store_fences_tests { async fn fenced_retry_retries_until_a_write_succeeds() { let fence = current_fence("retries"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { + let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { if attempts.fetch_add(1, Ordering::SeqCst) < 2 { Err(server_error()) } else { @@ -1329,7 +1261,7 @@ mod store_fences_tests { async fn fenced_retry_returns_permanent_errors_without_retrying() { let fence = current_fence("permanent"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { + let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { attempts.fetch_add(1, Ordering::SeqCst); Err(VssError::ConflictError("conflict".to_string())) }) @@ -1343,7 +1275,7 @@ mod store_fences_tests { let fence = current_fence("replaced"); current_fence("replaced"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { + let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { attempts.fetch_add(1, Ordering::SeqCst); Ok(()) }) @@ -1352,19 +1284,44 @@ mod store_fences_tests { assert_eq!(attempts.load(Ordering::SeqCst), 0); } - #[tokio::test] - async fn fenced_retry_stops_retrying_once_the_store_is_replaced() { - let fence = current_fence("replaced-between-attempts"); - let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &write_retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { - attempts.fetch_add(1, Ordering::SeqCst); - // A new store starts its generation now; it times out waiting for this attempt. - let _ = STORE_FENCES.start_generation(&fence.store, Duration::ZERO); - Err(server_error()) - }) - .await; - assert_eq!(res.unwrap(), WriteOutcome::Dropped); - assert_eq!(attempts.load(Ordering::SeqCst), 1); + #[tokio::test(flavor = "multi_thread")] + async fn a_store_is_not_replaced_while_a_write_waits_to_retry() { + let fence = current_fence("retrying"); + let (failed_tx, failed_rx) = std::sync::mpsc::channel(); + let (retry_tx, retry_rx) = std::sync::mpsc::channel::<()>(); + let retry_rx = Arc::new(Mutex::new(retry_rx)); + let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let call = { + let (fence, attempts) = (fence.clone(), Arc::clone(&attempts)); + tokio::spawn(async move { + fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || { + let attempt = attempts.fetch_add(1, Ordering::SeqCst); + let (failed_tx, retry_rx) = (failed_tx.clone(), Arc::clone(&retry_rx)); + async move { + if attempt == 0 { + failed_tx.send(()).unwrap(); + return Err(server_error()); + } + // The second attempt starts once the test has tried to replace the store. + tokio::task::spawn_blocking(move || retry_rx.lock().unwrap().recv()) + .await + .unwrap() + .unwrap(); + Ok(()) + } + }) + .await + }) + }; + failed_rx.recv().unwrap(); + let err = + STORE_FENCES.start_generation(&fence.store, Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fence.is_current()); + retry_tx.send(()).unwrap(); + assert_eq!(call.await.unwrap().unwrap(), WriteOutcome::Written); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + STORE_FENCES.start_generation(&fence.store, Duration::ZERO).unwrap(); } #[test] @@ -1507,14 +1464,13 @@ mod store_fences_tests { async fn fenced_retry_ends_an_attempt_that_does_not_finish() { let fence = current_fence("stuck"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = - fenced_retry(&fence, &write_retry_policy(), Duration::from_millis(10), || async { - if attempts.fetch_add(1, Ordering::SeqCst) == 0 { - std::future::pending::<()>().await; - } - Ok(()) - }) - .await; + let res = fenced_retry(&fence, &retry_policy(), Duration::from_millis(10), || async { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + std::future::pending::<()>().await; + } + Ok(()) + }) + .await; assert_eq!(res.unwrap(), WriteOutcome::Written); assert_eq!(attempts.load(Ordering::SeqCst), 2); } diff --git a/src/lib.rs b/src/lib.rs index b19a31c90f..46592768cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -321,6 +321,9 @@ impl Node { /// /// After this returns, the [`Node`] instance can be controlled via the provided API methods in /// a thread-safe manner. + /// + /// With a VSS store, returns [`Error::PersistenceFailed`] if another [`Node`] has been built on + /// the same VSS store and wallet since this one: build a new [`Node`] to continue. pub fn start(&self) -> Result<(), Error> { let _lifecycle_lock = self.lifecycle_lock.lock().unwrap(); if *self.is_running.read().unwrap() { From 55735be9d569476c4bb4b31e47f7135359bc3516 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 16:34:13 +0100 Subject: [PATCH 5/9] docs: say when a vss build replaces an earlier node Verified: cargo doc --no-deps --- src/builder.rs | 30 ++++++++++++++++++------------ src/io/vss_store.rs | 2 +- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index ef8490a862..41a704486c 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -726,8 +726,9 @@ impl NodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md @@ -785,8 +786,9 @@ impl NodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( @@ -809,8 +811,9 @@ impl NodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( @@ -1224,8 +1227,9 @@ impl ArcedNodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md @@ -1253,8 +1257,9 @@ impl ArcedNodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( @@ -1279,8 +1284,9 @@ impl ArcedNodeBuilder { /// /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. - /// Once built, an earlier [`Node`] on that store drops its remaining writes and its - /// [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: + /// build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index c3ea89e20d..b1e81de998 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -350,7 +350,7 @@ impl VssStore { async_retry_policy, header_provider.clone(), ); - // Writes retry in `fenced_retry`, so that each attempt is fenced. + // Writes retry in `fenced_retry`, which counts each call in flight and bounds each attempt. let blocking_write_client = VssClient::new_with_headers( base_url.clone(), no_retry_policy(), From 3c715fc0017599f2873ceaf757603528339eab84 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 16:35:39 +0100 Subject: [PATCH 6/9] fix: fail writes of a replaced vss store outside channel monitors A replaced store's dropped write returned Ok, so a retained handle of the old node, e.g. one handing out a receive address, went on as if its state were saved. Only channel monitor writes, which LDK treats as unrecoverable on error, still succeed with a warning; other dropped writes and removals return an error. The fence key now uses the parsed VSS URL, so spellings of one URL, such as with the default port, share a fence. Verified: cargo test --lib io::vss_store, cargo check with --cfg vss_test, cargo doc --- CHANGELOG.md | 2 +- src/builder.rs | 24 ++++++------ src/io/vss_store.rs | 94 ++++++++++++++++++++++++++++++++++----------- 3 files changed, 85 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10fb8c6957..5342545258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Bug Fixes -- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for its writes, retries included, to return, fails with `KVStoreSetupFailed` without replacing anything if they have not after 60 s, and otherwise drops the earlier store's writes from then on; a node whose store has been replaced fails to start with `PersistenceFailed`. +- Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for its writes, retries included, to return, fails with `KVStoreSetupFailed` without replacing anything if they have not after 60 s, and otherwise drops the earlier store's writes from then on, failing all but channel monitor writes; a node whose store has been replaced fails to start with `PersistenceFailed`. - Prevent the native SIGABRT `A Tokio 1.x context was found, but it is being shutdown.` when a node is released while background work is still stuck, e.g. in a VSS write after a timed-out stop: the runtime is now kept alive until that work ends instead of being shut down under it. - Bump `lightning`, `lightning-liquidity`, `lightning-persister` and `lightning-transaction-sync` to 0.2.8 and `lightning-invoice` to 0.34.2. - `bump_fee_by_rbf` now only replaces transactions this wallet built and broadcast itself, and returns `TransactionNotBroadcastByWallet` for any other txid. diff --git a/src/builder.rs b/src/builder.rs index 41a704486c..002d5ddbcd 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -727,8 +727,8 @@ impl NodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md @@ -787,8 +787,8 @@ impl NodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( @@ -812,8 +812,8 @@ impl NodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( @@ -1228,8 +1228,8 @@ impl ArcedNodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md /// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md @@ -1258,8 +1258,8 @@ impl ArcedNodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_fixed_headers( @@ -1285,8 +1285,8 @@ impl ArcedNodeBuilder { /// Building waits for a [`Node`] still running on the same VSS store and wallet to stop and for /// its writes to return, and fails with [`BuildError::KVStoreSetupFailed`] after 60 seconds. /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its - /// remaining writes and its [`Node::start`] fails with [`crate::Error::PersistenceFailed`]: - /// build a new [`Node`] instead. + /// remaining writes, failing all but its channel monitor writes, and its [`Node::start`] fails + /// with [`crate::Error::PersistenceFailed`]: build a new [`Node`] instead. /// /// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md pub fn build_with_vss_store_and_header_provider( diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index b1e81de998..ecddd97a70 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -17,7 +17,10 @@ use std::time::Duration; use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; use lightning::io::{self, Error, ErrorKind}; -use lightning::util::persist::{KVStore, KVStoreSync}; +use lightning::util::persist::{ + KVStore, KVStoreSync, CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, +}; use lightning::util::ser::{Readable, Writeable}; use lightning::{impl_writeable_tlv_based_enum, log_error, log_warn}; use prost::Message; @@ -259,8 +262,7 @@ enum WriteOutcome { /// Runs `attempt` with `policy`'s retries, ending each attempt after `attempt_timeout`. The /// whole call, backoff included, counts as in flight, so the store is not replaced before it /// returns. If the store has been replaced already, returns [`WriteOutcome::Dropped`] without -/// writing: its node has stopped and cannot start again, and a failed write would make LDK treat -/// a monitor update as unrecoverable and panic in the node's detached work. +/// writing: its node has stopped and cannot start again. async fn fenced_retry( fence: &StoreFence, policy: &CustomRetryPolicy, attempt_timeout: Duration, mut attempt: F, ) -> Result @@ -310,7 +312,7 @@ impl VssStore { let wallet = sha256::Hash::hash(&obfuscation_master_key).to_byte_array(); let key_obfuscator = KeyObfuscator::new(obfuscation_master_key); - let store = (base_url.trim_end_matches('/').to_string(), store_id.clone(), wallet); + let store = (fence_url(&base_url), store_id.clone(), wallet); let generation = tokio::task::block_in_place(|| { STORE_FENCES.start_generation(&store, REPLACED_WRITES_TIMEOUT) })?; @@ -843,14 +845,7 @@ impl VssStoreInner { match res { Ok(WriteOutcome::Written) => Ok(()), Ok(WriteOutcome::Dropped) => { - log_warn!( - self.logger, - "Dropped write of key {}/{}/{}: another node was built on this VSS store", - primary_namespace, - secondary_namespace, - key - ); - Ok(()) + self.dropped(true, &primary_namespace, &secondary_namespace, &key) }, Err(e) => { let msg = format!( @@ -864,6 +859,26 @@ impl VssStoreInner { .await } + /// Reports a write or removal that `fenced_retry` dropped because the store was replaced: + /// channel monitor writes succeed with a warning (see `drops_quietly`), every other caller, + /// e.g. a wallet handing out an address, gets an error. + fn dropped( + &self, is_write: bool, primary_namespace: &str, secondary_namespace: &str, key: &str, + ) -> io::Result<()> { + let action = if is_write { "write" } else { "removal" }; + let msg = format!( + "Dropped {} of key {}/{}/{}: another node was built on this VSS store", + action, primary_namespace, secondary_namespace, key + ); + if drops_quietly(is_write, primary_namespace) { + log_warn!(self.logger, "{}", msg); + Ok(()) + } else { + log_error!(self.logger, "{}", msg); + Err(Error::new(ErrorKind::Other, msg)) + } + } + async fn remove_internal( &self, client: &VssClient, inner_lock_ref: Arc>, locking_key: String, version: u64, primary_namespace: String, secondary_namespace: String, @@ -894,14 +909,7 @@ impl VssStoreInner { match res { Ok(WriteOutcome::Written) => Ok(()), Ok(WriteOutcome::Dropped) => { - log_warn!( - self.logger, - "Dropped removal of key {}/{}/{}: another node was built on this VSS store", - primary_namespace, - secondary_namespace, - key - ); - Ok(()) + self.dropped(false, &primary_namespace, &secondary_namespace, &key) }, Err(e) => { let msg = format!( @@ -993,6 +1001,25 @@ fn derive_data_encryption_and_obfuscation_keys(vss_seed: &[u8; 32]) -> ([u8; 32] (k1, k2) } +/// Whether a dropped write or removal succeeds with a warning instead of an error: LDK treats a +/// failed channel monitor or monitor update write as unrecoverable and panics, while it only logs +/// failed removals and archive writes. +fn drops_quietly(is_write: bool, primary_namespace: &str) -> bool { + is_write + && [ + CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, + ] + .contains(&primary_namespace) +} + +/// The VSS URL as requests reach it, so that spellings of the same URL share a fence. +fn fence_url(base_url: &str) -> String { + let url = + reqwest::Url::parse(base_url).map(String::from).unwrap_or_else(|_| base_url.to_string()); + url.trim_end_matches('/').to_string() +} + fn retry_policy() -> CustomRetryPolicy { ExponentialBackoffRetryPolicy::new(Duration::from_millis(10)) .with_max_attempts(100) @@ -1324,6 +1351,23 @@ mod store_fences_tests { STORE_FENCES.start_generation(&fence.store, Duration::ZERO).unwrap(); } + #[test] + fn spellings_of_one_vss_url_share_a_fence() { + assert_eq!(fence_url("https://vss.example/vss"), fence_url("https://VSS.example:443/vss/")); + assert_ne!(fence_url("https://vss.example/vss"), fence_url("https://vss.example:8443/vss")); + } + + #[test] + fn only_channel_monitor_writes_are_dropped_quietly() { + assert!(drops_quietly(true, CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE)); + assert!(drops_quietly(true, CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE)); + assert!(!drops_quietly(false, CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE)); + assert!(!drops_quietly(false, CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE)); + assert!(!drops_quietly(true, "archived_monitors")); + assert!(!drops_quietly(true, "bdk_wallet")); + assert!(!drops_quietly(true, "")); + } + #[test] fn stores_fence_only_their_own_writes() { let fences = StoreFences::default(); @@ -1543,8 +1587,14 @@ mod tests { .unwrap(); KVStoreSync::write(¤t, "ns", "", "key", vec![2]).unwrap(); - KVStoreSync::write(&replaced, "ns", "", "key", vec![1]).unwrap(); - KVStoreSync::remove(&replaced, "ns", "", "key", false).unwrap(); + KVStoreSync::write(&replaced, "ns", "", "key", vec![1]).unwrap_err(); + KVStoreSync::remove(&replaced, "ns", "", "key", false).unwrap_err(); assert_eq!(KVStoreSync::read(¤t, "ns", "", "key").unwrap(), vec![2]); + + let monitors = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; + KVStoreSync::write(¤t, monitors, "", "monitor", vec![2]).unwrap(); + KVStoreSync::write(&replaced, monitors, "", "monitor", vec![1]).unwrap(); + KVStoreSync::remove(&replaced, monitors, "", "monitor", false).unwrap_err(); + assert_eq!(KVStoreSync::read(¤t, monitors, "", "monitor").unwrap(), vec![2]); } } From 602f5b24b8077e466751b0dce9200c4906bb5bb4 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 17:10:44 +0100 Subject: [PATCH 7/9] fix: count a vss write from when it is queued A write counted as in flight only once it held its key's lock, so a rebuild could replace the store while an event acknowledgement waited behind an earlier write of the same key, and the rebuilt node replayed the event. Each write and removal now counts from its call, where it takes its version. Node::start refuses a node whose store was replaced before it waits on detached work, so it returns PersistenceFailed instead of AlreadyRunning. Verified: cargo test --lib, cargo check with --cfg vss_test --- src/io/vss_store.rs | 205 +++++++++++++++++++++++--------------------- src/lib.rs | 8 ++ 2 files changed, 117 insertions(+), 96 deletions(-) diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index ecddd97a70..4d62de6146 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -160,24 +160,25 @@ impl StoreFences { /// Returns `None` if the store of `generation` has been replaced. While the guard lives, the /// store is not replaced. - fn begin_write<'a>(&'a self, store: &'a StoreKey, generation: u64) -> Option> { + fn begin_write(&self, store: &StoreKey, generation: u64) -> Option> { let mut stores = self.stores.lock().unwrap(); let state = stores.get_mut(store).filter(|state| state.generation == generation)?; state.writes_in_flight += 1; - Some(WriteGuard { fences: self, store }) + Some(WriteGuard { fences: self, store: store.clone() }) } } -/// Counts one write call as in flight until it returns or its future is dropped. -struct WriteGuard<'a> { +/// Counts one write call as in flight, from when it is queued until it returns or its future is +/// dropped. +pub(crate) struct WriteGuard<'a> { fences: &'a StoreFences, - store: &'a StoreKey, + store: StoreKey, } impl Drop for WriteGuard<'_> { fn drop(&mut self) { let mut stores = self.fences.stores.lock().unwrap(); - if let Some(state) = stores.get_mut(self.store) { + if let Some(state) = stores.get_mut(&self.store) { state.writes_in_flight -= 1; if state.writes_in_flight == 0 { self.fences.changed.notify_all(); @@ -206,11 +207,13 @@ impl StoreFence { STORE_FENCES.clear_live(&self.store, self.generation) } - fn is_current(&self) -> bool { + /// Whether no other store has been built for the same VSS store since this one. + pub(crate) fn is_current(&self) -> bool { STORE_FENCES.is_current(&self.store, self.generation) } - fn begin_write(&self) -> Option> { + /// Counts a write call as in flight. Returns `None` if the store has been replaced. + fn begin_write(&self) -> Option> { STORE_FENCES.begin_write(&self.store, self.generation) } } @@ -252,27 +255,15 @@ impl Drop for LiveMark<'_> { } } -#[derive(Debug, PartialEq, Eq)] -enum WriteOutcome { - Written, - // The store was replaced, so the write was not sent. - Dropped, -} - -/// Runs `attempt` with `policy`'s retries, ending each attempt after `attempt_timeout`. The -/// whole call, backoff included, counts as in flight, so the store is not replaced before it -/// returns. If the store has been replaced already, returns [`WriteOutcome::Dropped`] without -/// writing: its node has stopped and cannot start again. +/// Runs `attempt` with `policy`'s retries, ending each attempt after `attempt_timeout`. `_write` +/// counts the call as in flight, backoff included, so the store is not replaced before it returns. async fn fenced_retry( - fence: &StoreFence, policy: &CustomRetryPolicy, attempt_timeout: Duration, mut attempt: F, -) -> Result + _write: WriteGuard<'_>, policy: &CustomRetryPolicy, attempt_timeout: Duration, mut attempt: F, +) -> Result<(), VssError> where F: FnMut() -> Fut, Fut: Future>, { - let Some(_write) = fence.begin_write() else { - return Ok(WriteOutcome::Dropped); - }; retry( || { let request = tokio::time::timeout(attempt_timeout, attempt()); @@ -285,7 +276,6 @@ where policy, ) .await - .map(|()| WriteOutcome::Written) } // We set this to a small number of threads that would still allow to make some progress if one @@ -448,6 +438,8 @@ impl KVStoreSync for VssStore { let inner = Arc::clone(&self.inner); let locking_key = self.build_locking_key(&primary_namespace, &secondary_namespace, &key); let (inner_lock_ref, version) = self.get_new_version_and_lock_ref(locking_key.clone()); + // Counted from now, also while queued behind an earlier write of the same key. + let write = self.inner.fence.begin_write(); let fut = async move { inner .write_internal( @@ -455,6 +447,7 @@ impl KVStoreSync for VssStore { inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -479,6 +472,8 @@ impl KVStoreSync for VssStore { let inner = Arc::clone(&self.inner); let locking_key = self.build_locking_key(&primary_namespace, &secondary_namespace, &key); let (inner_lock_ref, version) = self.get_new_version_and_lock_ref(locking_key.clone()); + // Counted from now, also while queued behind an earlier write of the same key. + let write = self.inner.fence.begin_write(); let fut = async move { inner .remove_internal( @@ -486,6 +481,7 @@ impl KVStoreSync for VssStore { inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -543,6 +539,8 @@ impl KVStore for VssStore { ) -> Pin> + Send>> { let locking_key = self.build_locking_key(primary_namespace, secondary_namespace, key); let (inner_lock_ref, version) = self.get_new_version_and_lock_ref(locking_key.clone()); + // Counted from now, also while queued behind an earlier write of the same key. + let write = self.inner.fence.begin_write(); let primary_namespace = primary_namespace.to_string(); let secondary_namespace = secondary_namespace.to_string(); let key = key.to_string(); @@ -556,6 +554,7 @@ impl KVStore for VssStore { inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -573,6 +572,8 @@ impl KVStore for VssStore { ) -> Pin> + Send>> { let locking_key = self.build_locking_key(primary_namespace, secondary_namespace, key); let (inner_lock_ref, version) = self.get_new_version_and_lock_ref(locking_key.clone()); + // Counted from now, also while queued behind an earlier write of the same key. + let write = self.inner.fence.begin_write(); let primary_namespace = primary_namespace.to_string(); let secondary_namespace = secondary_namespace.to_string(); let key = key.to_string(); @@ -585,6 +586,7 @@ impl KVStore for VssStore { inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -806,8 +808,8 @@ impl VssStoreInner { async fn write_internal( &self, client: &VssClient, inner_lock_ref: Arc>, - locking_key: String, version: u64, primary_namespace: String, secondary_namespace: String, - key: String, buf: Vec, + locking_key: String, version: u64, write: Option>, + primary_namespace: String, secondary_namespace: String, key: String, buf: Vec, ) -> io::Result<()> { check_namespace_key_validity( &primary_namespace, @@ -835,18 +837,16 @@ impl VssStoreInner { }; self.execute_locked_write(inner_lock_ref, locking_key, version, async move || { - let res = fenced_retry( - &self.fence, - &self.write_retry_policy, - WRITE_ATTEMPT_TIMEOUT, - || async { client.put_object(&request).await.map(|_| ()) }, - ) - .await; + let Some(write) = write else { + return self.dropped(true, &primary_namespace, &secondary_namespace, &key); + }; + let res = + fenced_retry(write, &self.write_retry_policy, WRITE_ATTEMPT_TIMEOUT, || async { + client.put_object(&request).await.map(|_| ()) + }) + .await; match res { - Ok(WriteOutcome::Written) => Ok(()), - Ok(WriteOutcome::Dropped) => { - self.dropped(true, &primary_namespace, &secondary_namespace, &key) - }, + Ok(()) => Ok(()), Err(e) => { let msg = format!( "Failed to write to key {}/{}/{}: {}", @@ -881,8 +881,8 @@ impl VssStoreInner { async fn remove_internal( &self, client: &VssClient, inner_lock_ref: Arc>, - locking_key: String, version: u64, primary_namespace: String, secondary_namespace: String, - key: String, + locking_key: String, version: u64, write: Option>, + primary_namespace: String, secondary_namespace: String, key: String, ) -> io::Result<()> { check_namespace_key_validity( &primary_namespace, @@ -899,18 +899,16 @@ impl VssStoreInner { let request = DeleteObjectRequest { store_id: self.store_id.clone(), key_value: Some(key_value) }; - let res = fenced_retry( - &self.fence, - &self.write_retry_policy, - WRITE_ATTEMPT_TIMEOUT, - || async { client.delete_object(&request).await.map(|_| ()) }, - ) - .await; + let Some(write) = write else { + return self.dropped(false, &primary_namespace, &secondary_namespace, &key); + }; + let res = + fenced_retry(write, &self.write_retry_policy, WRITE_ATTEMPT_TIMEOUT, || async { + client.delete_object(&request).await.map(|_| ()) + }) + .await; match res { - Ok(WriteOutcome::Written) => Ok(()), - Ok(WriteOutcome::Dropped) => { - self.dropped(false, &primary_namespace, &secondary_namespace, &key) - }, + Ok(()) => Ok(()), Err(e) => { let msg = format!( "Failed to delete key {}/{}/{}: {}", @@ -1272,15 +1270,20 @@ mod store_fences_tests { async fn fenced_retry_retries_until_a_write_succeeds() { let fence = current_fence("retries"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { - if attempts.fetch_add(1, Ordering::SeqCst) < 2 { - Err(server_error()) - } else { - Ok(()) - } - }) + let res = fenced_retry( + fence.begin_write().unwrap(), + &retry_policy(), + WRITE_ATTEMPT_TIMEOUT, + || async { + if attempts.fetch_add(1, Ordering::SeqCst) < 2 { + Err(server_error()) + } else { + Ok(()) + } + }, + ) .await; - assert_eq!(res.unwrap(), WriteOutcome::Written); + res.unwrap(); assert_eq!(attempts.load(Ordering::SeqCst), 3); } @@ -1288,27 +1291,27 @@ mod store_fences_tests { async fn fenced_retry_returns_permanent_errors_without_retrying() { let fence = current_fence("permanent"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { - attempts.fetch_add(1, Ordering::SeqCst); - Err(VssError::ConflictError("conflict".to_string())) - }) + let res = fenced_retry( + fence.begin_write().unwrap(), + &retry_policy(), + WRITE_ATTEMPT_TIMEOUT, + || async { + attempts.fetch_add(1, Ordering::SeqCst); + Err(VssError::ConflictError("conflict".to_string())) + }, + ) .await; assert!(matches!(res, Err(VssError::ConflictError(..)))); assert_eq!(attempts.load(Ordering::SeqCst), 1); } - #[tokio::test] - async fn fenced_retry_drops_writes_of_a_replaced_store() { + #[test] + fn a_replaced_store_begins_no_write() { let fence = current_fence("replaced"); + assert!(fence.begin_write().is_some()); current_fence("replaced"); - let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || async { - attempts.fetch_add(1, Ordering::SeqCst); - Ok(()) - }) - .await; - assert_eq!(res.unwrap(), WriteOutcome::Dropped); - assert_eq!(attempts.load(Ordering::SeqCst), 0); + assert!(fence.begin_write().is_none()); + assert!(!fence.is_current()); } #[tokio::test(flavor = "multi_thread")] @@ -1321,22 +1324,27 @@ mod store_fences_tests { let call = { let (fence, attempts) = (fence.clone(), Arc::clone(&attempts)); tokio::spawn(async move { - fenced_retry(&fence, &retry_policy(), WRITE_ATTEMPT_TIMEOUT, || { - let attempt = attempts.fetch_add(1, Ordering::SeqCst); - let (failed_tx, retry_rx) = (failed_tx.clone(), Arc::clone(&retry_rx)); - async move { - if attempt == 0 { - failed_tx.send(()).unwrap(); - return Err(server_error()); + fenced_retry( + fence.begin_write().unwrap(), + &retry_policy(), + WRITE_ATTEMPT_TIMEOUT, + || { + let attempt = attempts.fetch_add(1, Ordering::SeqCst); + let (failed_tx, retry_rx) = (failed_tx.clone(), Arc::clone(&retry_rx)); + async move { + if attempt == 0 { + failed_tx.send(()).unwrap(); + return Err(server_error()); + } + // The second attempt starts once the test has tried to replace the store. + tokio::task::spawn_blocking(move || retry_rx.lock().unwrap().recv()) + .await + .unwrap() + .unwrap(); + Ok(()) } - // The second attempt starts once the test has tried to replace the store. - tokio::task::spawn_blocking(move || retry_rx.lock().unwrap().recv()) - .await - .unwrap() - .unwrap(); - Ok(()) - } - }) + }, + ) .await }) }; @@ -1346,7 +1354,7 @@ mod store_fences_tests { assert_eq!(err.kind(), ErrorKind::TimedOut); assert!(fence.is_current()); retry_tx.send(()).unwrap(); - assert_eq!(call.await.unwrap().unwrap(), WriteOutcome::Written); + call.await.unwrap().unwrap(); assert_eq!(attempts.load(Ordering::SeqCst), 2); STORE_FENCES.start_generation(&fence.store, Duration::ZERO).unwrap(); } @@ -1508,14 +1516,19 @@ mod store_fences_tests { async fn fenced_retry_ends_an_attempt_that_does_not_finish() { let fence = current_fence("stuck"); let attempts = std::sync::atomic::AtomicUsize::new(0); - let res = fenced_retry(&fence, &retry_policy(), Duration::from_millis(10), || async { - if attempts.fetch_add(1, Ordering::SeqCst) == 0 { - std::future::pending::<()>().await; - } - Ok(()) - }) + let res = fenced_retry( + fence.begin_write().unwrap(), + &retry_policy(), + Duration::from_millis(10), + || async { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + std::future::pending::<()>().await; + } + Ok(()) + }, + ) .await; - assert_eq!(res.unwrap(), WriteOutcome::Written); + res.unwrap(); assert_eq!(attempts.load(Ordering::SeqCst), 2); } } diff --git a/src/lib.rs b/src/lib.rs index 46592768cc..a0ed7979d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -332,6 +332,14 @@ impl Node { if self.background_processor_failed.load(Ordering::Acquire) { return Err(Error::PersistenceFailed); } + // Checked before waiting on detached work: a node whose store was replaced never starts. + if self.vss_store_fence.as_ref().is_some_and(|fence| !fence.is_current()) { + log_error!( + self.logger, + "Refusing to start: another node was built on this node's VSS store since." + ); + return Err(Error::PersistenceFailed); + } log_info!( self.logger, From d334b339c5b30666b00d5c85bb2df06625f43bf7 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 17:12:24 +0100 Subject: [PATCH 8/9] docs: say how long a vss write call can stay in flight Verified: none (comment only) --- src/io/vss_store.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index 4d62de6146..30ca9ecfe4 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -69,8 +69,9 @@ impl_writeable_tlv_based_enum!(VssSchemaVersion, const VSS_SCHEMA_VERSION_KEY: &str = "vss_schema_version"; // How long building a store waits for a node still running on the same VSS store to stop and for -// the store's write calls to return. A call retries for up to 180 s while VSS fails, so against a -// failing VSS the build can time out; it then replaces nothing. +// the store's write calls to return. Against a failing VSS one call can take minutes: its backoff +// sleeps add up to 180 s, on top of up to 30 s per attempt. The build then times out and replaces +// nothing. const REPLACED_WRITES_TIMEOUT: Duration = Duration::from_secs(60); // Bounds one write attempt, the header fetch included: the VSS client times a request out after From 337be92fd078c835092e81c7bfb631524e6138ec Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 21:50:19 +0100 Subject: [PATCH 9/9] test: cover a vss write queued behind another of its key A write queued behind an earlier write of the same key keeps the store current after the first returns. Comments now place the in-flight count at the call site instead of fenced_retry. Verified: cargo test --lib (152 passed); RUSTFLAGS="--cfg vss_test" cargo build --tests --- src/io/vss_store.rs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index 30ca9ecfe4..a2af084ef8 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -92,8 +92,8 @@ type StoreKey = (String, String, [u8; 32]); /// since, e.g. a newer channel monitor. Building a store therefore waits until no node runs on /// the VSS store (see [`StoreFence::mark_live`]) and no write call of the current store is in /// flight, retries and their backoff included, then starts a new generation for it. From then on, -/// an earlier generation's write calls are dropped before they start (see `fenced_retry`), and -/// its node refuses to start. +/// an earlier generation's write calls are dropped before their first attempt (see +/// `StoreFence::begin_write`), and its node refuses to start. /// /// A call stops counting once it returns, also when its last request timed out on the client, or /// when its task is cancelled, e.g. by `VssStore`'s runtime shutting down. The server may still @@ -171,7 +171,7 @@ impl StoreFences { /// Counts one write call as in flight, from when it is queued until it returns or its future is /// dropped. -pub(crate) struct WriteGuard<'a> { +struct WriteGuard<'a> { fences: &'a StoreFences, store: StoreKey, } @@ -343,7 +343,8 @@ impl VssStore { async_retry_policy, header_provider.clone(), ); - // Writes retry in `fenced_retry`, which counts each call in flight and bounds each attempt. + // Writes retry in `fenced_retry`, which bounds each attempt; each call counts in flight from + // `StoreFence::begin_write` at its call site. let blocking_write_client = VssClient::new_with_headers( base_url.clone(), no_retry_policy(), @@ -860,7 +861,7 @@ impl VssStoreInner { .await } - /// Reports a write or removal that `fenced_retry` dropped because the store was replaced: + /// Reports a write or removal dropped because the store was replaced before it began: /// channel monitor writes succeed with a warning (see `drops_quietly`), every other caller, /// e.g. a wallet handing out an address, gets an error. fn dropped( @@ -1215,6 +1216,22 @@ mod store_fences_tests { builder.join().unwrap().unwrap(); } + #[test] + fn a_write_queued_behind_another_keeps_the_store_current() { + let fences = StoreFences::default(); + let store = store(); + let current = fences.start_generation(&store, Duration::ZERO).unwrap(); + let first = fences.begin_write(&store, current).unwrap(); + // A second write of the same key, counted at its call while it waits for the key's lock. + let queued = fences.begin_write(&store, current).unwrap(); + drop(first); + let err = fences.start_generation(&store, Duration::from_millis(20)).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::TimedOut); + assert!(fences.is_current(&store, current)); + drop(queued); + assert!(fences.start_generation(&store, Duration::ZERO).unwrap() > current); + } + #[test] fn a_new_store_that_times_out_on_a_write_replaces_nothing() { let fences = StoreFences::default();