Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/panic-unwind.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down
85 changes: 85 additions & 0 deletions scripts/check_panic_unwind.py
Original file line number Diff line number Diff line change
@@ -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)
7 changes: 7 additions & 0 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1845,6 +1845,11 @@ fn build_with_store_internal(
channel_data_migration: Option<&ChannelDataMigration>,
) -> Result<Node, BuildError> {
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() {
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading