diff --git a/CHANGELOG.md b/CHANGELOG.md index 766076acac..5342545258 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 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 67cb9afec8..002d5ddbcd 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, @@ -724,6 +724,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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 pub fn build_with_vss_store( @@ -778,6 +784,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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( &self, vss_url: String, store_id: String, fixed_headers: HashMap, @@ -797,6 +809,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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( &self, vss_url: String, store_id: String, header_provider: Arc, @@ -830,10 +848,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 +866,7 @@ impl NodeBuilder { runtime, logger, Arc::new(vss_store), + Some(vss_store_fence), self.channel_data_migration.as_ref(), ) } @@ -881,6 +902,7 @@ impl NodeBuilder { runtime, logger, kv_store, + None, self.channel_data_migration.as_ref(), ) } @@ -1203,6 +1225,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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 pub fn build_with_vss_store( @@ -1227,6 +1255,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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( &self, vss_url: String, store_id: String, fixed_headers: HashMap, @@ -1248,6 +1282,12 @@ 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. + /// Past that wait, also if building fails later, an earlier [`Node`] on that store drops its + /// 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( &self, vss_url: String, store_id: String, header_provider: Arc, @@ -1726,7 +1766,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 +2640,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 bca3779455..a2af084ef8 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -12,14 +12,17 @@ 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 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::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; use rand::RngCore; use vss_client::client::VssClient; @@ -31,12 +34,13 @@ 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}; use crate::io::utils::check_namespace_key_validity; +use crate::logger::{LdkLogger, Logger}; use crate::runtime::StoreRuntime; type CustomRetryPolicy = FilteredRetryPolicy< @@ -64,6 +68,217 @@ 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. 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 +// 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 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 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 +/// apply such a request shortly after; ruling that out needs conditional writes. +#[derive(Default)] +struct StoreFences { + stores: Mutex>, + changed: Condvar, +} + +#[derive(Default)] +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 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 || state.writes_in_flight > 0) + }) + .unwrap(); + if result.timed_out() { + 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; + Ok(state.generation) + } + + 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. While the guard lives, the + /// store is not replaced. + 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: store.clone() }) + } +} + +/// Counts one write call as in flight, from when it is queued until it returns or its future is +/// dropped. +struct WriteGuard<'a> { + fences: &'a StoreFences, + 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) { + state.writes_in_flight -= 1; + if state.writes_in_flight == 0 { + self.fences.changed.notify_all(); + } + } + } +} + +/// A [`VssStore`]'s place in the process-wide fences of its VSS store. +#[derive(Clone)] +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) + } + + /// 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) + } + + /// 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) + } +} + +/// 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(); + } + } +} + +/// 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( + _write: WriteGuard<'_>, policy: &CustomRetryPolicy, attempt_timeout: Duration, mut attempt: F, +) -> Result<(), VssError> +where + F: FnMut() -> Fut, + Fut: Future>, +{ + retry( + || { + let request = tokio::time::timeout(attempt_timeout, attempt()); + async move { + request.await.unwrap_or_else(|_| { + Err(VssError::InternalError("VSS write attempt timed out".to_string())) + }) + } + }, + policy, + ) + .await +} + // 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; @@ -81,16 +296,23 @@ 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 next_version = AtomicU64::new(1); - 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 wallet = sha256::Hash::hash(&obfuscation_master_key).to_byte_array(); let key_obfuscator = KeyObfuscator::new(obfuscation_master_key); + 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) + })?; + 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")?); + let sync_retry_policy = retry_policy(); let blocking_client = VssClient::new_with_headers( base_url.clone(), @@ -100,6 +322,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,23 +333,47 @@ 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`, 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(), + 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, + 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")) } @@ -193,13 +440,16 @@ 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( - &inner.blocking_client, + &inner.blocking_write_client, inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -224,13 +474,16 @@ 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( - &inner.blocking_client, + &inner.blocking_write_client, inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -288,6 +541,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(); @@ -297,10 +552,11 @@ 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, + write, primary_namespace, secondary_namespace, key, @@ -318,6 +574,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(); @@ -326,10 +584,11 @@ impl KVStore for VssStore { let fut = async move { inner .remove_internal( - &inner.async_client, + &inner.async_write_client, inner_lock_ref, locking_key, version, + write, primary_namespace, secondary_namespace, key, @@ -386,28 +645,42 @@ 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: CustomRetryPolicy, store_id: String, + 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>>>, } impl VssStoreInner { + #[allow(clippy::too_many_arguments)] pub(crate) fn new( schema_version: VssSchemaVersion, blocking_client: VssClient, - async_client: VssClient, store_id: String, - data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, + async_client: VssClient, + blocking_write_client: VssClient, + async_write_client: VssClient, store_id: String, fence: StoreFence, + data_encryption_key: [u8; 32], key_obfuscator: KeyObfuscator, logger: Arc, ) -> Self { let locks = Mutex::new(HashMap::new()); Self { schema_version, blocking_client, async_client, + blocking_write_client, + async_write_client, + write_retry_policy: retry_policy(), store_id, + fence, data_encryption_key, key_obfuscator, + logger, locks, } } @@ -537,8 +810,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, @@ -566,23 +839,52 @@ 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 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(()) => Ok(()), + Err(e) => { + let msg = format!( + "Failed to write to key {}/{}/{}: {}", + primary_namespace, secondary_namespace, key, e + ); + Err(Error::new(ErrorKind::Other, msg)) + }, + } }) .await } + /// 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( + &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, - 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, @@ -599,15 +901,24 @@ 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 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(()) => Ok(()), + Err(e) => { + let msg = format!( + "Failed to delete key {}/{}/{}: {}", + primary_namespace, secondary_namespace, key, e + ); + Err(Error::new(ErrorKind::Other, msg)) + }, + } }) .await } @@ -690,19 +1001,48 @@ 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) .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(..) - ) - }) as _) + .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 _) } async fn determine_and_write_schema_version( @@ -822,6 +1162,395 @@ impl EntropySource for RandEntropySource { #[cfg(test)] impl RefUnwindSafe for VssStore {} +#[cfg(test)] +mod store_fences_tests { + use super::*; + + fn store() -> StoreKey { + ("https://vss.example".to_string(), "store".to_string(), [1; 32]) + } + + #[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_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_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(); + 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_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(); + 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 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.is_current(&store, current)); + drop(write); + assert!(fences.start_generation(&store, Duration::ZERO).unwrap() > current); + } + + #[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(), [1; 32]); + 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.begin_write().unwrap(), + &retry_policy(), + WRITE_ATTEMPT_TIMEOUT, + || async { + if attempts.fetch_add(1, Ordering::SeqCst) < 2 { + Err(server_error()) + } else { + Ok(()) + } + }, + ) + .await; + res.unwrap(); + 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.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); + } + + #[test] + fn a_replaced_store_begins_no_write() { + let fence = current_fence("replaced"); + assert!(fence.begin_write().is_some()); + current_fence("replaced"); + assert!(fence.begin_write().is_none()); + assert!(!fence.is_current()); + } + + #[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.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(()) + } + }, + ) + .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(); + call.await.unwrap().unwrap(); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + 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(); + 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)); + } + + 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"); + let attempts = std::sync::atomic::AtomicUsize::new(0); + 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; + res.unwrap(); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + } +} + #[cfg(test)] #[cfg(vss_test)] mod tests { @@ -834,6 +1563,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(); @@ -843,7 +1576,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); } @@ -856,9 +1590,42 @@ 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) } + + #[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(), + logger(), + ) + .unwrap(); + let current = + 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_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]); + } } diff --git a/src/lib.rs b/src/lib.rs index 4df8530106..a0ed7979d0 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::{start_marked_live, 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>, @@ -318,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() { @@ -326,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, @@ -342,6 +356,16 @@ impl Node { return Err(Error::AlreadyRunning); } + // After a failed background processor, `stop` is still required and clears the mark. + 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> { // 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 +908,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(); +}