diff --git a/.github/workflows/panic-unwind.yml b/.github/workflows/panic-unwind.yml new file mode 100644 index 0000000000..483cd7aabc --- /dev/null +++ b/.github/workflows/panic-unwind.yml @@ -0,0 +1,19 @@ +name: Panic strategy + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + mobile-builds-unwind: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: python3 scripts/check_panic_unwind.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ef82227dd4..ffc8c0184e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Bug Fixes +- A panic in the mobile bindings no longer aborts the app: exports return an error, every running node stops processing and persisting, and a node built before the panic fails to start with `PersistenceFailed`, so build a new one. - 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. diff --git a/Cargo.toml b/Cargo.toml index be81894b1c..087805052f 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ inherits = "release" opt-level = 'z' # Optimize for size. lto = true # Enable Link Time Optimization codegen-units = 1 # Reduce number of codegen units to increase optimizations. -panic = 'abort' # Abort on panic +panic = 'unwind' # UniFFI turns a panic into an error instead of aborting the app, see src/panic.rs [features] default = [] diff --git a/scripts/check_panic_unwind.py b/scripts/check_panic_unwind.py new file mode 100644 index 0000000000..6ce9b22e78 --- /dev/null +++ b/scripts/check_panic_unwind.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Fails if a mobile build of the bindings would abort on panic. + +UniFFI turns a Rust panic into a Kotlin or Swift error only when the library unwinds. +Needs Python 3.11+ for `tomllib`. +""" + +import re +import sys +import tomllib +from pathlib import Path + +MOBILE_BUILD_SCRIPTS = [ + "scripts/uniffi_bindgen_generate_kotlin_android.sh", + "scripts/uniffi_bindgen_generate_swift.sh", +] +# Other places a panic strategy can be set: the wrapper script, Cargo config, `RUSTFLAGS` and `CARGO_PROFILE_*`. +OTHER_SOURCES = ["bindgen.sh", ".cargo/config.toml", ".cargo/config"] +OTHER_SOURCES += [str(path) for path in Path("scripts").glob("*.sh")] +OTHER_SOURCES += [str(path) for path in Path(".github/workflows").glob("*.y*ml")] +ABORT = re.compile(r"panic[\\\"']*\s*=\s*[\\\"']*(immediate-)?abort|CARGO_PROFILE_\w+_PANIC|panic_immediate_abort") + + +# What Cargo's built-in profiles inherit from. +BUILT_IN = {"dev": None, "release": None, "test": "dev", "bench": "release"} +def panic_strategy(profiles, name): + seen = set() + while name: + if name in seen: + return "an `inherits` cycle" + seen.add(name) + if name not in profiles and name not in BUILT_IN: + return "a profile missing from `Cargo.toml`" + profile = profiles.get(name, {}) + if "panic" in profile: + return profile["panic"] + name = profile.get("inherits", BUILT_IN.get(name)) + return "unwind" + + +def built_profiles(script): + """The profile of each command in `script` that builds for a mobile target.""" + # A backslash at the end of a comment does not continue the line. + text = re.sub(r"(?m)^([ \t]*#.*|.*\s#[^\"'\n]*)\\$", r"\1", Path(script).read_text()) + commands = text.replace("\\\n", " ") + profiles = set() + for line in commands.splitlines(): + if line.lstrip().startswith("#") or not re.search(r"\bcargo\b(.*\sbuild\b|[^#;&|]*\s(b|rustc)(?![^\s;&|)<>]))", line): + continue + if not re.search(r"\s[\"']?--target[\"']?[ =]|\bcargo(\s+\+\S+)?\s+ndk\s", line): + continue # a host build, only used to generate bindings + # Flags are read only up to a `#`, so a comment cannot supply one. + flags = re.split(r"\s#", line)[0] + named = re.search(r"--profile(?:=|\s+)(\"[^\"]*\"|'[^']*'|[^\s;&|)]+)", flags) + release = re.search(r"\s([\"']?)(--release|-r)\1(?![\w-])", flags) + profiles.add(re.sub(r"^([\"'])(.*)\1$", r"\2", named[1]) if named else "release" if release else None) + return profiles + + +profiles = tomllib.loads(Path("Cargo.toml").read_text()).get("profile", {}) +errors = [] +for script in MOBILE_BUILD_SCRIPTS: + names = built_profiles(script) + if not names: + errors.append(f"{script}: no mobile build found, update this check") + for name in sorted(names, key=str): + if name is None: + errors.append(f"{script}: a mobile build without `--release` or `--profile`, update this check") + continue + if not re.fullmatch(r"[\w-]+", name): + errors.append(f"{script}: cannot resolve `--profile {name}`, update this check") + continue + strategy = panic_strategy(profiles, name) + print(f"{script}: profile {name}: panic = {strategy}") + if strategy != "unwind": + errors.append(f"Cargo.toml: profile {name} must unwind, not {strategy}") +for source in sorted(set(MOBILE_BUILD_SCRIPTS + OTHER_SOURCES)): + path = Path(source) + if path.is_file(): + if ".cargo/config" in source and "include" in tomllib.loads(path.read_text()): + errors.append(f"{source}: included config files are not checked") + for number, line in enumerate(path.read_text().splitlines(), 1): + if not line.lstrip().startswith("#") and ABORT.search(line): + errors.append(f"{source}:{number}: overrides the panic strategy: {line.strip()}") +sys.exit("\n".join(dict.fromkeys(errors)) or None) diff --git a/src/builder.rs b/src/builder.rs index 8972ccb4f0..cbb2f35bcb 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1845,6 +1845,11 @@ fn build_with_store_internal( channel_data_migration: Option<&ChannelDataMigration>, ) -> Result { optionally_install_rustls_cryptoprovider(); + #[cfg(feature = "uniffi")] + let panics_at_build = { + crate::panic::install_hook(); + crate::panic::count() + }; if let Err(err) = may_announce_channel(&config) { if config.announcement_addresses.is_some() { @@ -2726,6 +2731,8 @@ fn build_with_store_internal( is_running, background_processor_failed: Arc::new(AtomicBool::new(false)), background_processor_generation: Arc::new(AtomicU64::new(0)), + #[cfg(feature = "uniffi")] + panics_at_build, node_metrics, om_mailbox, async_payments_role, diff --git a/src/lib.rs b/src/lib.rs index a0ed7979d0..3a2da2c376 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -94,6 +94,8 @@ pub mod io; pub mod liquidity; pub mod logger; mod message_handler; +#[cfg(feature = "uniffi")] +mod panic; pub mod payment; mod peer_store; mod probe_handle; @@ -108,7 +110,7 @@ use std::default::Default; use std::net::ToSocketAddrs; use std::ops::Deref; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; pub use balance::{AddressTypeBalance, BalanceDetails, LightningBalance, PendingSweepBalance}; @@ -220,6 +222,9 @@ pub struct Node { is_running: Arc>, background_processor_failed: Arc, background_processor_generation: Arc, + /// Panics recorded when this node was built; any later one stops it for good. + #[cfg(feature = "uniffi")] + panics_at_build: u64, node_metrics: Arc>, om_mailbox: Option>, async_payments_role: Option, @@ -246,6 +251,16 @@ fn handle_background_processor_failure( runtime.cancel_tracked_tasks(); } +/// Disconnects all peers. This takes channel locks an earlier panic may have poisoned, and the +/// rest of a shutdown has to happen regardless. +fn disconnect_peers(peer_manager: &PeerManager, logger: &Arc) { + let disconnect = std::panic::AssertUnwindSafe(|| peer_manager.disconnect_all_peers()); + match std::panic::catch_unwind(disconnect) { + Ok(()) => log_debug!(logger, "Disconnected all network peers."), + Err(_) => log_error!(logger, "Failed to disconnect all network peers."), + } +} + #[derive(Default)] pub(crate) struct RgsPeerRecoveryExclusions { node_ids: tokio::sync::RwLock>, @@ -322,16 +337,27 @@ impl Node { /// After this returns, the [`Node`] instance can be controlled via the provided API methods in /// a thread-safe manner. /// + /// In bindings builds, a panic anywhere in the library stops every running node. A node built + /// before the panic then returns [`Error::PersistenceFailed`] here: build a new [`Node`]. + /// /// 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(); + let _lifecycle_lock = self.lock_lifecycle(); if *self.is_running.read().unwrap() { return Err(Error::AlreadyRunning); } if self.background_processor_failed.load(Ordering::Acquire) { return Err(Error::PersistenceFailed); } + #[cfg(feature = "uniffi")] + if panic::count() != self.panics_at_build { + log_error!( + self.logger, + "Refusing to start: a panic occurred since this node was built." + ); + 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!( @@ -366,6 +392,12 @@ impl Node { } fn start_services(&self) -> Result<(), Error> { + let background_processor_generation = + self.background_processor_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1); + // Before anything else, so that a panic during startup is caught too. + #[cfg(feature = "uniffi")] + self.spawn_panic_guard(background_processor_generation); + // 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(); @@ -721,8 +753,6 @@ impl Node { let background_scorer = Arc::clone(&self.scorer); let background_is_running = Arc::clone(&self.is_running); let background_processor_failed = Arc::clone(&self.background_processor_failed); - let background_processor_generation = - self.background_processor_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1); let current_background_processor_generation = Arc::clone(&self.background_processor_generation); let background_runtime = self.runtime.control(); @@ -748,9 +778,12 @@ impl Node { }) }; + #[cfg(feature = "uniffi")] + let panics_at_build = self.panics_at_build; + self.runtime.spawn_background_processor_task( async move { - process_events_async( + let processor = process_events_async( background_persister, |e| background_event_handler.handle_event(e), background_chain_mon, @@ -765,8 +798,10 @@ impl Node { sleeper, true, || Some(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()), - ) - .await + ); + #[cfg(feature = "uniffi")] + let processor = panic::end_on_panic(panics_at_build, processor); + processor.await }, move |e| { handle_background_processor_failure( @@ -811,6 +846,48 @@ impl Node { Ok(()) } + /// A panic inside `start` or `stop` poisons this lock, which guards no data: a later `stop`, + /// also the one `Drop` runs, still has to clean up. + fn lock_lifecycle(&self) -> MutexGuard<'_, ()> { + self.lifecycle_lock.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Fail-stops this node on the first panic since it was built: no background tasks and no peers. + /// The background processor ends itself, see [`panic::end_on_panic`]. + #[cfg(feature = "uniffi")] + fn spawn_panic_guard(&self, generation: u64) { + let mut panics = panic::subscribe(); + let panics_at_build = self.panics_at_build; + let logger = Arc::clone(&self.logger); + let is_running = Arc::clone(&self.is_running); + let failed = Arc::clone(&self.background_processor_failed); + let current_generation = Arc::clone(&self.background_processor_generation); + let runtime = self.runtime.control(); + let chain_source = Arc::clone(&self.chain_source); + let peer_manager = Arc::clone(&self.peer_manager); + self.runtime.spawn_cancellable_background_task(async move { + let message = match panics.wait_for(|p| p.count != panics_at_build).await { + Ok(panics) => panics.last.clone(), + Err(_) => return, + }; + // A stop in progress owns the shutdown. + if generation != current_generation.load(Ordering::Acquire) { + return; + } + handle_background_processor_failure( + &lightning::io::Error::new(lightning::io::ErrorKind::Other, message), + &logger, + &is_running, + &failed, + &runtime, + &chain_source, + generation, + ¤t_generation, + ); + disconnect_peers(&peer_manager, &logger); + }); + } + fn spawn_chain_sync_task(&self) { let stop_receiver = self.stop_sender.subscribe(); self.spawn_chain_sync_task_with_receiver(stop_receiver); @@ -841,7 +918,7 @@ impl Node { /// /// After this returns most API methods will return [`Error::NotRunning`]. pub fn stop(&self) -> Result<(), Error> { - let _lifecycle_lock = self.lifecycle_lock.lock().unwrap(); + let _lifecycle_lock = self.lock_lifecycle(); if !*self.is_running.read().unwrap() && !self.background_processor_failed.load(Ordering::Acquire) { @@ -877,8 +954,7 @@ impl Node { self.runtime.abort_cancellable_background_tasks(); // Disconnect all peers. - self.peer_manager.disconnect_all_peers(); - log_debug!(self.logger, "Disconnected all network peers."); + disconnect_peers(&self.peer_manager, &self.logger); // Wait until non-cancellable background tasks (mod LDK's background processor) are done. self.runtime.wait_on_background_tasks(); @@ -887,19 +963,20 @@ impl Node { self.chain_source.stop(); log_debug!(self.logger, "Stopped chain sources."); - // Stop the background processor. - self.background_processor_stop_sender - .send(()) - .map(|_| { - log_trace!(self.logger, "Sent shutdown signal to background processor."); - }) - .unwrap_or_else(|e| { - log_error!( - self.logger, - "Failed to send shutdown signal. This should never happen: {}", - e - ); - }); + // Stop the background processor. After a panic it has ended itself and nothing listens. + #[cfg(feature = "uniffi")] + let panicked = panic::count() != self.panics_at_build; + #[cfg(not(feature = "uniffi"))] + let panicked = false; + match self.background_processor_stop_sender.send(()) { + Ok(()) => log_trace!(self.logger, "Sent shutdown signal to background processor."), + Err(_) if panicked => {}, + Err(e) => log_error!( + self.logger, + "Failed to send shutdown signal. This should never happen: {}", + e + ), + } // Finally, wait until background processing stopped, at least until a timeout is reached. let background_processor_result = self.runtime.wait_on_background_processor_task(); @@ -907,6 +984,10 @@ impl Node { #[cfg(tokio_unstable)] self.runtime.log_metrics(); + // A panic during that wait ended the processor before its final persist. + #[cfg(feature = "uniffi")] + let panicked = panic::count() != self.panics_at_build; + 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 { @@ -919,7 +1000,7 @@ impl Node { log_error!(self.logger, "Failed to process events during shutdown: {}", e); Err(Error::PersistenceFailed) }, - Ok(()) if background_processor_failed => Err(Error::PersistenceFailed), + Ok(()) if background_processor_failed || panicked => Err(Error::PersistenceFailed), Ok(()) => Ok(()), } } @@ -1005,6 +1086,8 @@ impl Node { /// /// **Note:** This **MUST** be called after each event has been handled. pub fn event_handled(&self) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + panic::check(self.panics_at_build)?; // We use our runtime for the sync variant to ensure `tokio::task::block_in_place` is // always called if we'd ever hit this in an outer runtime context. let fut = self.event_queue.event_handled(); @@ -1076,6 +1159,7 @@ impl Node { Arc::clone(&self.is_running), Arc::clone(&self.logger), Arc::clone(&self._router), + self.panics_at_build, )) } @@ -1559,6 +1643,8 @@ impl Node { &self, user_channel_id: &UserChannelId, counterparty_node_id: PublicKey, splice_amount_sats: u64, ) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + panic::check(self.panics_at_build)?; let open_channels = self.channel_manager.list_channels_with_counterparty(&counterparty_node_id); if let Some(channel_details) = @@ -1674,6 +1760,8 @@ impl Node { &self, user_channel_id: &UserChannelId, counterparty_node_id: PublicKey, address: &Address, splice_amount_sats: u64, ) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + panic::check(self.panics_at_build)?; let open_channels = self.channel_manager.list_channels_with_counterparty(&counterparty_node_id); if let Some(channel_details) = @@ -1808,6 +1896,8 @@ impl Node { &self, user_channel_id: &UserChannelId, counterparty_node_id: PublicKey, force: bool, force_close_reason: Option, ) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + panic::check(self.panics_at_build)?; debug_assert!( force_close_reason.is_none() || force, "Reason can only be set for force closures" @@ -1855,6 +1945,8 @@ impl Node { &self, user_channel_id: &UserChannelId, counterparty_node_id: PublicKey, channel_config: ChannelConfig, ) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + panic::check(self.panics_at_build)?; let open_channels: Vec = self.channel_manager.list_channels_with_counterparty(&counterparty_node_id); if let Some(channel_details) = diff --git a/src/panic.rs b/src/panic.rs new file mode 100644 index 0000000000..bde51a2029 --- /dev/null +++ b/src/panic.rs @@ -0,0 +1,101 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +//! Stops nodes after a panic in bindings builds. +//! +//! The mobile bindings unwind, so a panic no longer aborts the process: UniFFI turns one inside an +//! export into an error and Tokio contains one inside a task. Whatever the panicking code was +//! changing may be half updated, so no node built before it may keep running or persisting. + +use std::future::Future; +use std::sync::{Once, OnceLock}; + +use lightning::io::Error as LdkIoError; +use tokio::sync::watch; + +use crate::Error; + +#[derive(Default)] +pub(crate) struct Panics { + pub count: u64, + pub last: String, +} + +fn sender() -> &'static watch::Sender { + static SENDER: OnceLock> = OnceLock::new(); + SENDER.get_or_init(|| watch::channel(Panics::default()).0) +} + +/// Records every panic from now on, on any thread, and then runs the previous hook. +/// +/// The hook only records: it runs on the panicking thread with that thread's locks still held. +pub(crate) fn install_hook() { + static INSTALL: Once = Once::new(); + INSTALL.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + sender().send_modify(|panics| { + panics.count += 1; + panics.last = info.to_string(); + }); + previous(info); + })); + }); +} + +pub(crate) fn count() -> u64 { + sender().borrow().count +} + +pub(crate) fn subscribe() -> watch::Receiver { + sender().subscribe() +} + +/// Refuses a call that changes channel state once a panic occurred since the node was built. +pub(crate) fn check(panics_at_build: u64) -> Result<(), Error> { + if count() != panics_at_build { + return Err(Error::PersistenceFailed); + } + Ok(()) +} + +/// Runs `processor` until a panic is recorded on top of `panics_at_build`, then drops it, which +/// skips everything it would still have persisted. The check sits inside the task so that it holds +/// until the processor has ended, also while [`Node::stop`] is waiting for it. +/// +/// Ending this way is not reported as a failure: the failure handler cancels the tracked tasks, the +/// panic guard among them, before that has disconnected the peers. +/// +/// [`Node::stop`]: crate::Node::stop +pub(crate) async fn end_on_panic(panics_at_build: u64, processor: F) -> Result<(), LdkIoError> +where + F: Future>, +{ + let mut panics = subscribe(); + tokio::select! { + biased; + _ = panics.wait_for(|p| p.count != panics_at_build) => Ok(()), + result = processor => result, + } +} + +#[cfg(test)] +mod tests { + use lightning::io::ErrorKind; + + use super::*; + + #[tokio::test] + async fn the_processor_runs_only_until_a_panic() { + let failing = async { Err(LdkIoError::new(ErrorKind::Other, "own result")) }; + assert!(end_on_panic(count(), failing).await.is_err()); + + // A count that differs from the current one stands for a panic since the build. + let endless = std::future::pending(); + assert!(end_on_panic(count().wrapping_add(1), endless).await.is_ok()); + } +} diff --git a/src/payment/bolt11.rs b/src/payment/bolt11.rs index 0e57449584..7eb9a24e33 100644 --- a/src/payment/bolt11.rs +++ b/src/payment/bolt11.rs @@ -66,6 +66,8 @@ pub struct Bolt11Payment { is_running: Arc>, logger: Arc, router: Arc, + #[cfg(feature = "uniffi")] + panics_at_build: u64, } impl Bolt11Payment { @@ -75,7 +77,7 @@ impl Bolt11Payment { liquidity_source: Option>>>, payment_store: Arc, peer_store: Arc>>, config: Arc, is_running: Arc>, logger: Arc, - router: Arc, + router: Arc, #[cfg(feature = "uniffi")] panics_at_build: u64, ) -> Self { Self { runtime, @@ -88,6 +90,8 @@ impl Bolt11Payment { is_running, logger, router, + #[cfg(feature = "uniffi")] + panics_at_build, } } @@ -360,6 +364,8 @@ impl Bolt11Payment { pub fn claim_for_hash( &self, payment_hash: PaymentHash, claimable_amount_msat: u64, preimage: PaymentPreimage, ) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + crate::panic::check(self.panics_at_build)?; let payment_id = PaymentId(payment_hash.0); let expected_payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array()); @@ -420,6 +426,8 @@ impl Bolt11Payment { /// [`receive_variable_amount_for_hash`]: Self::receive_variable_amount_for_hash /// [`PaymentClaimable`]: crate::Event::PaymentClaimable pub fn fail_for_hash(&self, payment_hash: PaymentHash) -> Result<(), Error> { + #[cfg(feature = "uniffi")] + crate::panic::check(self.panics_at_build)?; let payment_id = PaymentId(payment_hash.0); let update = PaymentDetailsUpdate { diff --git a/src/runtime.rs b/src/runtime.rs index 999635fcc1..5f5eefb9ef 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -94,9 +94,9 @@ impl Runtime { /// /// Work that is still running after `drain_timeout` (a task blocked inside `block_in_place`, /// e.g. a stuck VSS write) would poll timers on a shut-down runtime as soon as it resumes, and - /// Tokio's timer then panics, which aborts mobile builds. In that case a reaper thread takes - /// the runtime and shuts it down only once that work has finished, so this returns without - /// waiting for it. + /// Tokio's timer then panics, which stops every node in a mobile build. In that case a reaper + /// thread takes the runtime and shuts it down only once that work has finished, so this returns + /// without waiting for it. fn shutdown(&mut self, drain_timeout: Duration) { self.control.cancel_all_tasks(); self.control.detach_live_work(); diff --git a/tests/panic_test.rs b/tests/panic_test.rs new file mode 100644 index 0000000000..5349539c96 --- /dev/null +++ b/tests/panic_test.rs @@ -0,0 +1,92 @@ +#![cfg(feature = "uniffi")] + +mod common; + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::Hash; +use common::logging::TestLogWriter; +use common::{random_config, setup_node, TestChainSource, TestStoreType}; +use electrsd::corepc_node::{self, Node as BitcoinD}; +use ldk_node::config::ChannelConfig; +use ldk_node::logger::{LogRecord, LogWriter}; +use ldk_node::{NodeError, UserChannelId}; +use lightning_types::payment::{PaymentHash, PaymentPreimage}; + +fn setup_bitcoind() -> BitcoinD { + let bitcoind_exe = std::env::var("BITCOIND_EXE") + .ok() + .or_else(|| corepc_node::downloaded_exe_path().ok()) + .expect("set BITCOIND_EXE or specify a bitcoind version feature"); + let mut bitcoind_conf = corepc_node::Conf::default(); + bitcoind_conf.network = "regtest"; + BitcoinD::with_conf(bitcoind_exe, &bitcoind_conf).unwrap() +} + +/// Panics on another thread once `stop` has signalled the background processor and waits for it. +struct PanicDuringStop; + +impl LogWriter for PanicDuringStop { + fn log(&self, record: LogRecord) { + if record.args.contains("Sent shutdown signal to background processor") { + assert!(std::thread::spawn(|| panic!("panic during stop")).join().is_err()); + } + } +} + +// A test binary of its own: the panic it raises stops every node in the process. +#[test] +fn panic_stops_the_node_until_it_is_rebuilt() { + let bitcoind = setup_bitcoind(); + let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind); + let mut config = random_config(true); + config.store_type = TestStoreType::Sqlite; + let node = setup_node(&chain_source, config.clone(), None); + let peer = setup_node(&chain_source, random_config(true), None); + let peer_address = peer.listening_addresses().unwrap().first().unwrap().clone(); + node.connect(peer.node_id(), peer_address, false).unwrap(); + let connected = || node.list_peers().iter().any(|p| p.is_connected); + assert!(connected()); + + assert!(std::thread::spawn(|| panic!("panic outside the node's own tasks")).join().is_err()); + + let deadline = Instant::now() + Duration::from_secs(10); + while node.status().is_running || peer.status().is_running || connected() { + assert!(Instant::now() < deadline, "a node kept running or connected after a panic"); + std::thread::sleep(Duration::from_millis(10)); + } + + // Calls that change channel state are refused before they look at their arguments. + let channel = UserChannelId(0); + let refused = |result| matches!(result, Err(NodeError::PersistenceFailed)); + assert!(refused(node.close_channel(&channel, peer.node_id()))); + assert!(refused(node.force_close_channel(&channel, peer.node_id(), None))); + assert!(refused(node.update_channel_config( + &channel, + peer.node_id(), + ChannelConfig::default() + ))); + assert!(refused(node.event_handled())); + assert!(refused(node.splice_in(&channel, peer.node_id(), 1_000))); + let address = peer.onchain_payment().new_address().unwrap(); + assert!(refused(node.splice_out(&channel, peer.node_id(), &address, 1_000))); + let preimage = PaymentPreimage([1; 32]); + let hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array()); + assert!(refused(node.bolt11_payment().claim_for_hash(hash, 1_000, preimage))); + assert!(refused(node.bolt11_payment().fail_for_hash(hash))); + + assert!(matches!(node.start(), Err(NodeError::PersistenceFailed))); + assert!(matches!(node.stop(), Err(NodeError::PersistenceFailed))); + assert!(matches!(node.start(), Err(NodeError::PersistenceFailed))); + drop(node); + + // `setup_node` starts the node and asserts that it runs. + setup_node(&chain_source, config, None).stop().unwrap(); + + let mut config = random_config(true); + config.log_writer = TestLogWriter::Custom(Arc::new(PanicDuringStop)); + let node = setup_node(&chain_source, config, None); + assert!(matches!(node.stop(), Err(NodeError::PersistenceFailed))); +}