feat: asset refactor, phoenixd/sparkl2 included, add dmg (#4167)
What changed, and why it matters
This commit is a feature release for the LNbits desktop packaging system. It adds the ability to bundle external Bitcoin/Lightning 'funding' programs (Spark L2 and Phoenixd) directly into the desktop app, adds macOS DMG packaging, and makes a small fix so failed payments report their actual error message. Most of the changes are build scripts, packaging workflows, and tests. There is no obvious remote attack introduced, but the new code does download and execute external binaries, manage wallet seeds, and run local daemons, which increases the app's security surface area.
Treat this as a routine feature commit, not an emergency security patch. Reviewers should verify that pinned checksums in pins.json match the published upstream releases, that the seed file permissions and backup warnings are adequate, and that the Phoenixd terms acceptance and readonly settings behave as intended. Run the new smoke_sidecars.py and packaging unit tests in CI.
Security signals we found
New bundled funding daemons (Spark L2, Phoenixd) run as child processes and bind to loopback ports.
Wallet seed is generated and stored in funding/<provider>/seed.dat with 0o600 permissions; seed replacement is refused if existing/invalid.
prepare_sidecars.py downloads external runtimes from GitHub/Node.js over HTTPS and enforces pinned SHA-256 checksums.
macOS build rejects shared OpenSSL in cryptography to avoid PyInstaller merging incompatible dynamic libraries.
Settings related to bundled funding are marked readonly so saved settings cannot override the launcher's configuration.
Phoenixd terms-of-service acceptance is required before first launch.
SparkL2Wallet now surfaces explicit failure reasons from the sidecar instead of treating all non-success statuses as pending.
No vendor-authored security disclosure, CVE, or researcher attribution is present in the commit or supplied references.
Evidence from the diff
The commit refactors LNbits desktop packaging: introduces prepare_sidecars.py to download pinned Node.js, Spark sidecar, and Phoenixd binaries with SHA-256 verification; adds funding.py to own and supervise bundled Spark/Phoenixd daemons, generate/lock BIP39 seeds, and protect launcher-managed settings; extends desktop.py GUI/CLI to select and start a bundled funding source; adds macOS app/DMG build scripts and a GitHub Actions workflow; and fixes SparkL2Wallet.pay_invoice to include error_message from the sidecar response when ok=False. Tests and smoke checks are added for the new components.
Changed components
.github/packaging/build.py.github/packaging/desktop.py.github/packaging/funding.py.github/packaging/prepare_sidecars.py.github/packaging/sidecars/supervisor.mjs.github/packaging/sidecars/pins.json.github/packaging/macos/dmg.py.github/workflows/macos.yml.github/workflows/appimage.yml.github/workflows/windows.yml.github/workflows/release.yml.github/workflows/release-rc.ymllnbits/wallets/sparkl2.pyInspect captured patch +1805 / −21
diff --git a/.github/packaging/build.py b/.github/packaging/build.py
index f991ad1..9b1d722 100644
--- a/.github/packaging/build.py
+++ b/.github/packaging/build.py
@@ -7,8 +7,23 @@ import sys
from pathlib import Path
import wasmtime
+from prepare_sidecars import main as prepare_sidecars
+from PyInstaller.depend.bindepend import get_imports
os.environ["DEBUG"] = "false"
+if sys.platform == "darwin":
+ # PyInstaller can merge different OpenSSL builds into one libssl.3.dylib.
+ # cryptography must carry its own statically linked OpenSSL instead.
+ rust = importlib.util.find_spec("cryptography.hazmat.bindings._rust")
+ if rust is None or rust.origin is None:
+ raise RuntimeError("cryptography's native bindings are missing")
+ for name, _ in get_imports(rust.origin):
+ if Path(name).name.startswith(("libssl.", "libcrypto.")):
+ raise RuntimeError(
+ "macOS packaging requires cryptography with static OpenSSL. "
+ "Clear its uv cache and reinstall with OPENSSL_STATIC=1."
+ )
+prepare_sidecars()
packages = [
"embit",
@@ -26,9 +41,9 @@ args = [
"PyInstaller",
"--clean",
"--noconfirm",
- "--onefile",
+ "--onedir" if sys.platform == "darwin" else "--onefile",
"--name",
- "lnbits",
+ "LNbits" if sys.platform == "darwin" else "lnbits",
"--specpath",
"build",
"--hidden-import=embit",
@@ -36,6 +51,30 @@ args = [
"--collect-data=pyinstrument",
"--collect-data=random_username",
]
+# Keep external executables as binaries so macOS signs them with the app.
+sidecars = Path("build/sidecars").resolve()
+for resource in sidecars.iterdir():
+ kind = (
+ "--add-binary"
+ if resource.name in ("node", "node.exe", "phoenixd")
+ else "--add-data"
+ )
+ destination = "sidecars/spark" if resource.is_dir() else "sidecars"
+ args += [kind, f"{resource}:{destination}"]
+ if sys.platform == "linux" and resource.name in ("node", "phoenixd"):
+ # Phoenixd still needs libcrypt.so.1; newer distros need it bundled.
+ for name, path in get_imports(str(resource)):
+ if name in (
+ "libcrypt.so.1",
+ "libz.so.1",
+ "libgcc_s.so.1",
+ "libstdc++.so.6",
+ ):
+ if path is None:
+ raise RuntimeError(
+ f"Install {name} before building bundled funding"
+ )
+ args += ["--add-binary", f"{path}:sidecars/lib"]
# Wasmtime opens its native library by package-relative path via ctypes.
for library in Path(wasmtime.__file__).parent.glob("*/*"):
if library.suffix in (".so", ".dll", ".dylib"):
@@ -47,6 +86,16 @@ if sys.platform == "win32":
"hide-early",
f"--icon={icon}",
]
+if sys.platform == "darwin":
+ args += [
+ "--windowed",
+ "--osx-bundle-identifier=com.lnbits.desktop",
+ f"--icon={Path(__file__).resolve().parent / 'linux/AppDir/lnbits.png'}",
+ ]
+ if identity := os.environ.get("MACOS_CODESIGN_IDENTITY"):
+ args += ["--codesign-identity", identity]
+ if entitlements := os.environ.get("MACOS_ENTITLEMENTS_FILE"):
+ args += ["--osx-entitlements-file", entitlements]
for package in packages:
args += ["--collect-all", package]
for package in ("breez_sdk", "breez_sdk_liquid"):
diff --git a/.github/packaging/desktop.py b/.github/packaging/desktop.py
index 43aaf57..f7e2175 100644
--- a/.github/packaging/desktop.py
+++ b/.github/packaging/desktop.py
@@ -14,17 +14,30 @@ import traceback
import webbrowser
from pathlib import Path
+from funding import PROVIDERS, Funding, load_profile, protect_settings
+
def default_folder():
if sys.platform == "win32":
return Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "LNbits"
+ if sys.platform == "darwin":
+ return Path.home() / "Library" / "Application Support" / "LNbits"
return (
Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share")
/ "lnbits-desktop"
)
-def configuration(host, port, folder, https_only, admin_ui):
+def configuration(
+ host,
+ port,
+ folder,
+ https_only,
+ admin_ui,
+ funding_source=None,
+ funding_port=None,
+ phoenix_terms=False,
+):
host = host.strip()
if not host or "://" in host or "/" in host:
raise ValueError("Enter a host name or IP address, without http:// or a path.")
@@ -38,6 +51,19 @@ def configuration(host, port, folder, https_only, admin_ui):
raise ValueError("Choose a data folder.")
root = Path(folder).expanduser().resolve()
root.mkdir(parents=True, exist_ok=True)
+ profile = load_profile(root)
+ funding_source = funding_source or profile.get("provider", "none")
+ if funding_source not in ("none", *PROVIDERS):
+ raise ValueError("Unknown funding source.")
+ funding_port = int(
+ funding_port
+ or profile.get("port")
+ or (9740 if funding_source == "phoenixd" else 8765)
+ )
+ if funding_source != "none" and (
+ not 1 <= funding_port <= 65535 or funding_port == port
+ ):
+ raise ValueError("Choose a different, valid port for the funding source.")
return {
"HOST": host,
"PORT": str(port),
@@ -45,6 +71,9 @@ def configuration(host, port, folder, https_only, admin_ui):
"LNBITS_EXTENSIONS_PATH": os.environ.get("LNBITS_EXTENSIONS_PATH", str(root)),
"AUTH_HTTPS_ONLY": str(https_only).lower(),
"LNBITS_ADMIN_UI": str(admin_ui).lower(),
+ "LNBITS_DESKTOP_FUNDING": funding_source,
+ "LNBITS_DESKTOP_FUNDING_PORT": str(funding_port),
+ "LNBITS_DESKTOP_PHOENIX_TERMS": str(phoenix_terms).lower(),
}
@@ -75,6 +104,7 @@ def worker(environment, stop, ready):
contextlib.redirect_stderr(log),
):
try:
+ protect_settings(environment)
run_server(environment, stop, ready)
except KeyboardInterrupt:
# Uvicorn re-raises Ctrl+C after completing its shutdown handlers.
@@ -108,6 +138,15 @@ def run_server(environment, stop, ready):
async def monitor():
while not server.should_exit:
if server.started:
+ if environment.get("LNBITS_DESKTOP_FUNDING", "none") in PROVIDERS:
+ from lnbits.wallets import get_funding_source
+
+ if (
+ type(get_funding_source()).__name__
+ != environment["LNBITS_BACKEND_WALLET_CLASS"]
+ ):
+ server.should_exit = True
+ return
ready.set()
if stop.is_set() or server_restart.is_set():
server.should_exit = True
@@ -136,6 +175,8 @@ class Server:
self.process = None
self.stopping_at = None
self.started_at = None
+ self.funding = None
+ self.error = None
def start(self):
# Fail before launching if another service is using the requested address.
@@ -147,6 +188,16 @@ class Server:
):
pass
self.ready.clear()
+ self.started_at = time.monotonic()
+ if self.environment.get("LNBITS_DESKTOP_FUNDING", "none") in PROVIDERS:
+ if self.funding is None:
+ self.funding = Funding(self.environment)
+ self.funding.start()
+ if not self.funding.ready.is_set():
+ return
+ self._start_worker()
+
+ def _start_worker(self):
self.process = self.context.Process(
target=worker, args=(self.environment, self.stop_event, self.ready)
)
@@ -159,8 +210,19 @@ class Server:
self.stop_event.set()
def poll(self):
+ if self.funding and self.stopping_at is None:
+ if self.funding.error or self.funding.poll() is not None:
+ self.error = (
+ self.funding.error
+ or "The funding daemon stopped. See its log in the data folder."
+ )
+ self.stop()
+ elif self.process is None and self.funding.ready.is_set():
+ self._start_worker()
if self.process is None:
- return 0
+ if self.funding and self.stopping_at is None:
+ return None
+ return self._finish(1 if self.error else 0)
if self.process.is_alive():
if (
not self.ready.is_set()
@@ -179,6 +241,14 @@ class Server:
if code == 75 and self.stopping_at is None:
self.start()
return None
+ return self._finish(1 if self.error else code)
+
+ def _finish(self, code):
+ if self.funding:
+ self.funding.stop()
+ if self.funding.poll() is None:
+ return None
+ self.funding.close()
return code
@@ -252,9 +322,59 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
ttk.Label(
frame, text="Allow the administrator to configure LNbits in the browser."
).grid(row=10, columnspan=3, sticky="w", pady=(4, 16))
+ funding_frame = ttk.LabelFrame(frame, text="Bundled funding source", padding=8)
+ funding_frame.grid(row=11, columnspan=3, sticky="ew")
+ funding_choices = {"Neither (use LNbits settings)": "none", "Spark L2": "spark"}
+ if sys.platform != "win32":
+ funding_choices["Phoenixd"] = "phoenixd"
+ funding_choice = tk.StringVar(value=next(iter(funding_choices)))
+ funding_port = tk.StringVar(value="8765")
+ funding_select = ttk.Combobox(
+ funding_frame,
+ textvariable=funding_choice,
+ values=list(funding_choices),
+ state="readonly",
+ )
+ funding_select.grid(row=0, column=0, sticky="w")
+ ttk.Label(funding_frame, text="Port").grid(row=0, column=1, padx=8)
+ funding_entry = ttk.Entry(funding_frame, textvariable=funding_port, width=8)
+ funding_entry.grid(row=0, column=2)
+ ttk.Label(
+ funding_frame,
+ text=(
+ "Runs locally with LNbits. Back up your data folder, including "
+ "funding/<provider>/seed.dat."
+ ),
+ wraplength=560,
+ ).grid(row=1, columnspan=3, sticky="w", pady=(6, 0))
+
+ def load_funding(*_):
+ try:
+ profile = load_profile(fields["LNBITS_DATA_FOLDER"].get())
+ label = next(
+ (
+ label
+ for label, name in funding_choices.items()
+ if name == profile.get("provider")
+ ),
+ next(iter(funding_choices)),
+ )
+ funding_choice.set(label)
+ funding_port.set(str(profile.get("port", 8765)))
+ except (OSError, ValueError):
+ pass # The launch validation reports an unreadable profile.
+
+ def select_funding(*_):
+ funding_port.set(
+ "9740" if funding_choices[funding_choice.get()] == "phoenixd" else "8765"
+ )
+
+ funding_select.bind("<<ComboboxSelected>>", select_funding)
+ fields["LNBITS_DATA_FOLDER"].trace_add("write", load_funding)
+ load_funding()
status = tk.StringVar(value="Choose your settings, then launch.")
ttk.Label(frame, textvariable=status, wraplength=560).grid(
- row=11, columnspan=3, sticky="w", pady=8
+ row=12, columnspan=3, sticky="w", pady=8
)
server = None
closing = False
@@ -282,7 +402,8 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
root.destroy()
return
status.set(
- f"LNbits stopped (exit {code}). "
+ server.error
+ or f"LNbits stopped (exit {code}). "
"See logs/desktop.log in your data folder."
)
launch.configure(text="Close", command=close)
@@ -294,7 +415,11 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
elif not closing:
open_browser.configure(state="disabled")
status.set(
- "Starting LNbits…"
+ (
+ "Starting funding source…"
+ if server.funding and not server.funding.ready.is_set()
+ else "Starting LNbits…"
+ )
if server.stopping_at is None
else "Startup timed out; stopping LNbits…"
)
@@ -303,25 +428,54 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
def start():
nonlocal server
try:
+ provider = funding_choices[funding_choice.get()]
+ accepted = False
+ if provider == "phoenixd" and not load_profile(
+ fields["LNBITS_DATA_FOLDER"].get()
+ ).get("phoenix_terms"):
+ accepted = messagebox.askokcancel(
+ "Phoenixd first setup",
+ "Back up your funding seed and never run another Phoenix instance "
+ "with the same seed.\n\n"
+ "Phoenixd purchases incoming liquidity automatically. Mining and "
+ "service fees apply; small incoming payments may become "
+ "non-refundable fee credit.\n\n"
+ "Details: https://phoenix.acinq.co/server/auto-liquidity\n\n"
+ "Continue with these terms?",
+ parent=root,
+ )
+ if not accepted:
+ return
env = configuration(
*(fields[key].get() for key in ("HOST", "PORT", "LNBITS_DATA_FOLDER")),
https.get(),
admin.get(),
+ provider,
+ funding_port.get(),
+ accepted,
)
server = Server(env)
server.start()
- except (ValueError, OSError):
+ except (ValueError, OSError) as exc:
+ if server and server.funding:
+ server.funding.close()
server = None
messagebox.showerror(
"Cannot launch LNbits",
- "Check the host, port and folder. The address may already be in use "
- "or the folder may not be writable.",
+ (
+ str(exc)
+ if isinstance(exc, ValueError)
+ else "Check the ports and data folder. "
+ "Another instance may already be running."
+ ),
parent=root,
)
return
for child in frame.winfo_children():
if isinstance(child, (ttk.Entry, ttk.Checkbutton, ttk.Button)):
child.configure(state="disabled")
+ funding_select.configure(state="disabled")
+ funding_entry.configure(state="disabled")
launch.configure(text="Stop LNbits", command=close, state="normal")
status.set("Starting LNbits…")
poll()
@@ -334,16 +488,18 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
webbrowser.open(f"http://{host}:{server.environment['PORT']}")
launch = ttk.Button(frame, text="Launch LNbits", command=start)
- launch.grid(row=12, column=0, columnspan=2, sticky="w", pady=(12, 0))
+ launch.grid(row=13, column=0, columnspan=2, sticky="w", pady=(12, 0))
open_browser = ttk.Button(
frame, text="Open in browser", command=open_url, state="disabled"
)
- open_browser.grid(row=12, column=2, pady=(12, 0))
+ open_browser.grid(row=13, column=2, pady=(12, 0))
root.protocol("WM_DELETE_WINDOW", close)
+ if sys.platform == "darwin":
+ root.createcommand("tk::mac::Quit", close)
try:
root.mainloop()
finally:
- if server and server.process:
+ if server and (server.process or server.funding):
server.stop()
while server.poll() is None:
time.sleep(0.1)
@@ -393,7 +549,7 @@ def launched_from_terminal():
def should_show_gui():
if len(sys.argv) != 1 or launched_from_terminal():
return False
- return sys.platform == "win32" or bool(
+ return sys.platform in ("win32", "darwin") or bool(
os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")
)
@@ -409,6 +565,19 @@ def main():
parser.add_argument("--stop-file", help="Headless mode: stop when this file exists")
parser.add_argument("--host", default=os.environ.get("HOST", "127.0.0.1"))
parser.add_argument("--port", default=os.environ.get("PORT", "5000"))
+ parser.add_argument(
+ "--funding-source",
+ choices=("none", *PROVIDERS),
+ help="Start a bundled funding daemon (defaults to the saved selection)",
+ )
+ parser.add_argument(
+ "--funding-port", type=int, help="Local port for the bundled daemon"
+ )
+ parser.add_argument(
+ "--accept-phoenixd-terms",
+ action="store_true",
+ help="Acknowledge Phoenixd backup and automatic liquidity terms on first setup",
+ )
args = parser.parse_args()
if args.gui or (not args.headless and should_show_gui()):
gui()
@@ -419,15 +588,25 @@ def main():
os.environ.get("LNBITS_DATA_FOLDER", str(default_folder())),
os.environ.get("AUTH_HTTPS_ONLY", "false").lower() == "true",
os.environ.get("LNBITS_ADMIN_UI", "true").lower() == "true",
+ args.funding_source,
+ args.funding_port,
+ args.accept_phoenixd_terms,
)
server = Server(env)
signal.signal(signal.SIGTERM, lambda *_: server.stop())
signal.signal(signal.SIGINT, lambda *_: server.stop())
- server.start()
- while (code := server.poll()) is None:
- if args.stop_file and Path(args.stop_file).exists():
- server.stop()
- time.sleep(0.1)
+ try:
+ server.start()
+ while (code := server.poll()) is None:
+ if args.stop_file and Path(args.stop_file).exists():
+ server.stop()
+ time.sleep(0.1)
+ finally:
+ server.stop()
+ while server.poll() is None:
+ time.sleep(0.1)
+ if server.error:
+ print(server.error, file=sys.stderr)
sys.exit(code)
diff --git a/.github/packaging/funding.py b/.github/packaging/funding.py
new file mode 100644
index 0000000..87e3a74
--- /dev/null
+++ b/.github/packaging/funding.py
@@ -0,0 +1,309 @@
+"""Own one bundled funding daemon and its persistent wallet, outside LNbits core."""
+
+import base64
+import json
+import os
+import secrets
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+from embit.bip39 import mnemonic_from_bytes, mnemonic_is_valid
+
+PROVIDERS = {"spark": "SparkL2Wallet", "phoenixd": "PhoenixdWallet"}
+
+
+def bundled_path():
+ if getattr(sys, "frozen", False):
+ return Path(sys._MEIPASS) / "sidecars"
+ return Path(__file__).resolve().parents[2] / "build/sidecars"
+
+
+def load_profile(folder):
+ path = Path(folder).expanduser() / "funding/profile.json"
+ if not path.exists():
+ return {}
+ profile = json.loads(path.read_text())
+ if not isinstance(profile, dict) or profile.get("provider") not in PROVIDERS:
+ raise ValueError(
+ "The funding profile is invalid. Restore your data folder backup."
+ )
+ return profile
+
+
+def save_private(path, contents):
+ """Replace a complete private file; never leave a partially written seed."""
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream:
+ temporary = Path(stream.name)
+ try:
+ os.chmod(temporary, 0o600)
+ stream.write(contents)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ temporary.unlink(missing_ok=True)
+ raise
+ try:
+ os.replace(temporary, path)
+ if os.name != "nt":
+ descriptor = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def check_port(port):
+ with socket.create_server(("127.0.0.1", port)):
+ pass
+
+
+def protect_settings(environment):
+ """Keep this launcher's connection settings authoritative over saved settings."""
+ from lnbits.settings import readonly_variables, settings
+
+ provider = environment.get("LNBITS_DESKTOP_FUNDING", "none")
+ if provider not in PROVIDERS:
+ return
+ if settings.lnbits_database_url:
+ raise ValueError("Use a local SQLite data folder for bundled funding.")
+ prefix = "SPARK_L2_" if provider == "spark" else "PHOENIXD_"
+ for key, value in environment.items():
+ if key.startswith(prefix) or key == "LNBITS_BACKEND_WALLET_CLASS":
+ name = key.lower()
+ setattr(settings, name, value)
+ if name not in readonly_variables:
+ readonly_variables.append(name)
+
+
+class Funding:
+ def __init__(self, environment):
+ self.environment = environment
+ self.provider = environment["LNBITS_DESKTOP_FUNDING"]
+ self.port = int(environment["LNBITS_DESKTOP_FUNDING_PORT"])
+ self.folder = Path(environment["LNBITS_DATA_FOLDER"]) / "funding"
+ self.process = None
+ self.log = None
+ self.lock = None
+ self.ready = threading.Event()
+ self.stopping = threading.Event()
+ self.error = None
+ self.stopping_at = None
+
+ def start(self):
+ if self.provider == "phoenixd" and sys.platform == "win32":
+ raise ValueError("Bundled Phoenixd is available on Linux and macOS.")
+ resources = bundled_path()
+ node = resources / ("node.exe" if sys.platform == "win32" else "node")
+ runtime = resources / (
+ "spark/server.mjs" if self.provider == "spark" else "phoenixd"
+ )
+ if not all(
+ path.is_file() for path in (node, resources / "supervisor.mjs", runtime)
+ ):
+ raise ValueError("Bundled funding sources are missing from this build.")
+ if os.environ.get("LNBITS_DATABASE_URL"):
+ raise ValueError("Use a local SQLite data folder for bundled funding.")
+ check_port(self.port)
+ self.folder.mkdir(mode=0o700, parents=True, exist_ok=True)
+ self.lock = (self.folder / "owner.lock").open("a+b")
+ try:
+ if os.name == "nt":
+ import msvcrt
+
+ self.lock.seek(0)
+ self.lock.write(b"\0")
+ self.lock.flush()
+ self.lock.seek(0)
+ msvcrt.locking(self.lock.fileno(), msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(self.lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ profile = load_profile(self.folder.parent)
+ if not profile and (self.folder.parent / "database.sqlite3").exists():
+ raise ValueError(
+ "Choose a new data folder for bundled funding. Existing balances "
+ "cannot be moved to a new funding wallet."
+ )
+ if profile and profile.get("provider") != self.provider:
+ raise ValueError(
+ "Choose a separate data folder to use a different funding wallet."
+ )
+ if self.provider == "phoenixd" and not (
+ profile.get("phoenix_terms")
+ or self.environment.get("LNBITS_DESKTOP_PHOENIX_TERMS") == "true"
+ ):
+ raise ValueError(
+ "Please acknowledge Phoenixd's backup and liquidity terms."
+ )
+ self._start(resources, node, profile)
+ except BaseException:
+ self.close()
+ raise
+
+ def _start(self, resources, node, profile):
+ data = self.folder / self.provider
+ data.mkdir(mode=0o700, exist_ok=True)
+ seed_file = data / "seed.dat"
+ if seed_file.exists():
+ mnemonic = seed_file.read_text().strip()
+ if not mnemonic_is_valid(mnemonic):
+ raise ValueError(
+ "The saved funding seed is invalid. Restore your backup; "
+ "it will not be replaced."
+ )
+ elif profile:
+ raise ValueError(
+ "The funding seed is missing. Restore your backup; "
+ "a replacement wallet will not be created."
+ )
+ else:
+ mnemonic = mnemonic_from_bytes(
+ secrets.token_bytes(32 if self.provider == "spark" else 16)
+ )
+ save_private(seed_file, mnemonic + "\n")
+ profile.update(provider=self.provider, port=self.port)
+ if self.provider == "phoenixd":
+ profile["phoenix_terms"] = True
+ save_private(self.folder / "profile.json", json.dumps(profile))
+ # A new secret per launch also prevents stale saved API keys being reused.
+ key = secrets.token_hex(32)
+ endpoint = f"http://127.0.0.1:{self.port}"
+ self.environment["LNBITS_BACKEND_WALLET_CLASS"] = PROVIDERS[self.provider]
+ child_environment = dict(os.environ)
+ # Do not inject frozen Python's libraries into the external runtimes.
+ for name in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"):
+ child_environment.pop(name, None)
+ if original := os.environ.get(name + "_ORIG"):
+ child_environment[name] = original
+ if sys.platform == "linux":
+ child_environment["LD_LIBRARY_PATH"] = os.pathsep.join(
+ filter(
+ None,
+ (str(resources / "lib"), child_environment.get("LD_LIBRARY_PATH")),
+ )
+ )
+ if self.provider == "spark":
+ self.environment.update(
+ SPARK_L2_EXTERNAL_ENDPOINT=endpoint,
+ SPARK_L2_EXTERNAL_API_KEY=key,
+ SPARK_L2_MNEMONIC=mnemonic,
+ SPARK_L2_NETWORK="MAINNET",
+ )
+ child_environment.update(
+ SPARK_SIDECAR_HOST="127.0.0.1",
+ SPARK_SIDECAR_PORT=str(self.port),
+ SPARK_SIDECAR_API_KEY=key,
+ SPARK_MNEMONIC=mnemonic,
+ SPARK_NETWORK="MAINNET",
+ SPARK_ONCHAIN_ENABLED="false",
+ SPARK_SIDECAR_STATE_PATH=str(data / "state.json"),
+ )
+ request = urllib.request.Request( # noqa: S310 - fixed loopback URL
+ endpoint + "/v1/balance", data=b"", headers={"X-Api-Key": key}
+ )
+ else:
+ config = data / "phoenix.conf"
+ lines = config.read_text().splitlines() if config.exists() else []
+ lines = [
+ line
+ for line in lines
+ if line.split("=", 1)[0].strip() != "http-password"
+ ]
+ save_private(config, "\n".join([*lines, f"http-password={key}", ""]))
+ self.environment.update(
+ PHOENIXD_API_ENDPOINT=endpoint,
+ PHOENIXD_API_PASSWORD=key,
+ PHOENIXD_DATA_DIR=str(data),
+ PHOENIXD_MNEMONIC=mnemonic,
+ )
+ child_environment.pop("PHOENIX_SEED", None)
+ child_environment.update(
+ PHOENIX_DATADIR=str(data), LNBITS_DAEMON_PORT=str(self.port)
+ )
+ token = base64.b64encode(f":{key}".encode()).decode()
+ request = urllib.request.Request( # noqa: S310 - fixed loopback URL
+ endpoint + "/getinfo", headers={"Authorization": f"Basic {token}"}
+ )
+ logs = self.folder.parent / "logs"
+ logs.mkdir(exist_ok=True)
+ self.log = (logs / f"{self.provider}.log").open("ab")
+ self.process = subprocess.Popen( # noqa: S603
+ [str(node), str(resources / "supervisor.mjs"), self.provider],
+ env=child_environment,
+ cwd=data,
+ stdin=subprocess.PIPE,
+ stdout=self.log,
+ stderr=subprocess.STDOUT,
+ creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
+ start_new_session=sys.platform != "win32",
+ )
+ threading.Thread(target=self._wait_ready, args=(request,), daemon=True).start()
+
+ def _wait_ready(self, request):
+ # Local credentials must never be forwarded through a configured proxy.
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *_args, **_kwargs):
+ return None
+
+ client = urllib.request.build_opener(
+ urllib.request.ProxyHandler({}), NoRedirect()
+ )
+ deadline = time.monotonic() + 120
+ while not self.stopping.is_set() and self.process.poll() is None:
+ try:
+ with client.open(request, timeout=2) as response:
+ result = json.load(response)
+ if (self.provider == "spark" and "balance_sats" in result) or (
+ self.provider == "phoenixd" and "channels" in result
+ ):
+ self.ready.set()
+ return
+ except (OSError, ValueError, urllib.error.URLError):
+ pass
+ if time.monotonic() >= deadline:
+ self.error = (
+ "Funding source startup timed out. See its log in the data folder."
+ )
+ return
+ self.stopping.wait(0.25)
+
+ def stop(self):
+ if not self.stopping.is_set():
+ self.stopping.set()
+ self.stopping_at = time.monotonic()
+ if self.process and self.process.stdin:
+ try:
+ self.process.stdin.close()
+ except OSError:
+ pass # The daemon may already have exited.
+
+ def poll(self):
+ if self.process is None:
+ return 0
+ if self.stopping_at is not None and time.monotonic() - self.stopping_at > 20:
+ if self.process.poll() is None:
+ self.process.kill()
+ return self.process.poll()
+
+ def close(self):
+ self.stop()
+ if self.process and self.process.poll() is None:
+ try:
+ self.process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait()
+ if self.log:
+ self.log.close()
+ if self.lock:
+ self.lock.close()
diff --git a/.github/packaging/macos/dmg.py b/.github/packaging/macos/dmg.py
new file mode 100644
index 0000000..76e44fd
--- /dev/null
+++ b/.github/packaging/macos/dmg.py
@@ -0,0 +1,82 @@
+"""Create a versioned, verified DMG from the PyInstaller app on macOS."""
+
+import hashlib
+import os
+import platform
+import plistlib
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import tomllib
+from packaging.version import Version
+
+
+def run(*args):
+ subprocess.run(args, check=True) # noqa: S603
+
+
+def main():
+ if sys.platform != "darwin":
+ raise SystemExit("Build the DMG on macOS.")
+ version = Version(
+ tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
+ )
+ output = Path("dist", f"LNbits-v{version}-macOS-{platform.machine()}.dmg").resolve()
+ identity = os.environ.get("MACOS_CODESIGN_IDENTITY") or "-"
+ with tempfile.TemporaryDirectory(prefix="lnbits-dmg-") as directory:
+ staging = Path(directory)
+ app = staging / "LNbits.app"
+ shutil.copytree("dist/LNbits.app", app, symlinks=True)
+ plist = app / "Contents/Info.plist"
+ with plist.open("rb") as stream:
+ info = plistlib.load(stream)
+ info.update(
+ CFBundleDisplayName="LNbits",
+ CFBundleShortVersionString=version.base_version,
+ CFBundleVersion=version.base_version,
+ LSMinimumSystemVersion="15.0",
+ LSApplicationCategoryType="public.app-category.finance",
+ NSHighResolutionCapable=True,
+ )
+ with plist.open("wb") as stream:
+ plistlib.dump(info, stream)
+ # Updating Info.plist invalidates the outer bundle signature. Nested
+ # binaries retain the signatures applied by PyInstaller during the build.
+ signing = ["/usr/bin/codesign", "--force", "--sign", identity]
+ if identity != "-":
+ signing += ["--options", "runtime", "--timestamp"]
+ if entitlements := os.environ.get("MACOS_ENTITLEMENTS_FILE"):
+ signing += ["--entitlements", entitlements]
+ run(*signing, str(app))
+ run("/usr/bin/codesign", "--verify", "--deep", "--strict", str(app))
+ (staging / "Applications").symlink_to("/Applications")
+ run(
+ "/usr/bin/hdiutil",
+ "create",
+ "-volname",
+ "LNbits",
+ "-srcfolder",
+ str(staging),
+ "-fs",
+ "HFS+",
+ "-format",
+ "UDZO",
+ "-ov",
+ str(output),
+ )
+ run("/usr/bin/hdiutil", "verify", str(output))
+ digest = hashlib.sha256()
+ with output.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(block)
+ output.with_suffix(".dmg.sha256").write_text(
+ f"{digest.hexdigest()} {output.name}\n", encoding="utf-8"
+ )
+ print(output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/packaging/prepare_sidecars.py b/.github/packaging/prepare_sidecars.py
new file mode 100644
index 0000000..20e7014
--- /dev/null
+++ b/.github/packaging/prepare_sidecars.py
@@ -0,0 +1,142 @@
+"""Prepare bundled runtimes at build time; never download at application startup."""
+
+import hashlib
+import json
+import platform
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import urllib.request
+import zipfile
+from pathlib import Path
+
+
+def download(url, digest, destination):
+ request = urllib.request.Request( # noqa: S310 - HTTPS runtime downloads
+ url, headers={"User-Agent": "LNbits-packaging"}
+ )
+ checksum = hashlib.sha256()
+ with (
+ urllib.request.urlopen(request, timeout=60) as response, # noqa: S310
+ destination.open("wb") as stream,
+ ):
+ while block := response.read(1024 * 1024):
+ checksum.update(block)
+ stream.write(block)
+ if checksum.hexdigest() != digest:
+ raise RuntimeError(f"Checksum mismatch for {destination.name}")
+ return checksum.hexdigest()
+
+
+def download_spark(staging, pin):
+ tag = pin["release"]
+ revision = pin["revision"]
+ print(f"Spark sidecar release: {tag} ({revision})", flush=True)
+ archive = staging / "spark.tar.gz"
+ download(
+ f"https://api.github.com/repos/lnbits/spark_sidecar/tarball/{revision}",
+ pin["sha256"],
+ archive,
+ )
+ extracted = staging / "spark"
+ extracted.mkdir()
+ return unpack(archive, extracted)
+
+
+def unpack(archive, destination):
+ if archive.suffix == ".zip":
+ with zipfile.ZipFile(archive) as contents:
+ contents.extractall(destination) # noqa: S202 - verified runtime archive
+ else:
+ with tarfile.open(archive) as contents:
+ contents.extractall(destination, filter="data")
+ return next(destination.iterdir())
+
+
+def main():
+ here = Path(__file__).resolve().parent
+ pins = json.loads((here / "sidecars/pins.json").read_text())
+ system = {"linux": "linux", "darwin": "darwin", "win32": "win"}[sys.platform]
+ arch = {"x86_64": "x64", "AMD64": "x64", "arm64": "arm64", "aarch64": "arm64"}[
+ platform.machine()
+ ]
+ target = f"{system}-{arch}"
+ output = Path("build/sidecars").resolve()
+ if output.exists():
+ shutil.rmtree(output)
+ output.mkdir(parents=True)
+ with tempfile.TemporaryDirectory(prefix="lnbits-sidecars-") as folder:
+ staging = Path(folder)
+ version = pins["node"]["version"]
+ suffix = (
+ "zip" if system == "win" else "tar.gz" if system == "darwin" else "tar.xz"
+ )
+ filename = f"node-v{version}-{target}.{suffix}"
+ archive = staging / filename
+ download(
+ f"https://nodejs.org/dist/v{version}/{filename}",
+ pins["node"]["sha256"][target],
+ archive,
+ )
+ extracted = staging / "node"
+ extracted.mkdir()
+ node = unpack(archive, extracted)
+ executable = "node.exe" if system == "win" else "node"
+ shutil.copy2(
+ node / ("node.exe" if system == "win" else "bin/node"), output / executable
+ )
+ shutil.copy2(node / "LICENSE", output / "NODE-LICENSE.txt")
+
+ source = download_spark(staging, pins["spark"])
+ spark = output / "spark"
+ spark.mkdir()
+ for filename in (
+ "package.json",
+ "package-lock.json",
+ "README.md",
+ ):
+ shutil.copy2(source / filename, spark / filename)
+ for module in source.glob("*.mjs"):
+ shutil.copy2(module, spark / module.name)
+ npm = shutil.which("npm.cmd" if system == "win" else "npm")
+ if not npm:
+ raise RuntimeError("npm is required to prepare the Spark sidecar")
+ subprocess.run( # noqa: S603
+ [npm, "ci", "--omit=dev", "--ignore-scripts"], cwd=spark, check=True
+ )
+ subprocess.run( # noqa: S603
+ [npm, "audit", "--omit=dev", "--audit-level=high"], cwd=spark, check=True
+ )
+ # The SDK also publishes mobile native libraries; Node never loads them.
+ sdk = spark / "node_modules/@buildonspark/spark-sdk"
+ for directory in ("android", "ios"):
+ shutil.rmtree(sdk / directory, ignore_errors=True)
+ shutil.rmtree(spark / "node_modules/.bin", ignore_errors=True)
+
+ if system != "win":
+ version = pins["phoenixd"]["version"]
+ target = f"{'macos' if system == 'darwin' else system}-{arch}"
+ filename = f"phoenixd-{version}-{target}.zip"
+ archive = staging / filename
+ download(
+ f"https://github.com/ACINQ/phoenixd/releases/download/v{version}/{filename}",
+ pins["phoenixd"]["sha256"][target],
+ archive,
+ )
+ extracted = staging / "phoenixd"
+ extracted.mkdir()
+ source = unpack(archive, extracted)
+ shutil.copy2(source / "phoenixd", output / "phoenixd")
+ (output / "phoenixd").chmod(0o755)
+ shutil.copy2(
+ here / "sidecars/PHOENIXD-LICENSE.txt", output / "PHOENIXD-LICENSE.txt"
+ )
+ shutil.copy2(here / "sidecars/supervisor.mjs", output / "supervisor.mjs")
+ (output / "pins.json").write_text(json.dumps(pins, indent=2) + "\n")
+ print(f"Prepared bundled funding sources in {output}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/packaging/sidecars/PHOENIXD-LICENSE.txt b/.github/packaging/sidecars/PHOENIXD-LICENSE.txt
new file mode 100644
index 0000000..d565dcd
--- /dev/null
+++ b/.github/packaging/sidecars/PHOENIXD-LICENSE.txt
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018 ACINQ SAS
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/.github/packaging/sidecars/pins.json b/.github/packaging/sidecars/pins.json
new file mode 100644
index 0000000..9e32d68
--- /dev/null
+++ b/.github/packaging/sidecars/pins.json
@@ -0,0 +1,26 @@
+{
+ "spark": {
+ "release": "v0.1.5",
+ "revision": "dbfed1fd9cb72f0a589d7479022f2cbb209b5924",
+ "sha256": "e6720e4a5ad2ee7746403ab766ccbb6d97ae5dd3d0f9f364f7c56064b9583730"
+ },
+ "phoenixd": {
+ "version": "0.9.0",
+ "sha256": {
+ "linux-x64": "d9e54b93813f1771b072c96c5ae968ffb5b052f2ca1c42762b66e2cb80362a0f",
+ "linux-arm64": "c806f0d8058a487284173536accba9041176f8217f8c84ce59b6e97d04a88b31",
+ "macos-x64": "c6699426e7d29f6f9e8f96a3d7f9d3aab68b3142e08346532dae45a17412824e",
+ "macos-arm64": "350c87c90cdf91d2cfa509ee48fd3d71267021303d4359a5eeada1694dea9b9a"
+ }
+ },
+ "node": {
+ "version": "24.21.0",
+ "sha256": {
+ "linux-x64": "fd8e59d5a511510f6a298afb548f18c7d2b1be404d8b4a27d94fbe49f56cb2d6",
+ "linux-arm64": "6ad1325edbdb5649c379b75a237147a666c95d4f9ae8d340fef2d1575d289ad2",
+ "darwin-x64": "1462cb3b3046b815cf8ea436d3da450ec1a9f11dac7e5a46b0ada5305d7e8097",
+ "darwin-arm64": "bed7eea5325e1108f32ce5228ddd6a5f0f08a499ee42aa7442aea583702f6057",
+ "win-x64": "158f7685b44de51f6c0df1d153526cbcd3e1bc739a8dfc607721cef75de9e541"
+ }
+ }
+}
diff --git a/.github/packaging/sidecars/supervisor.mjs b/.github/packaging/sidecars/supervisor.mjs
new file mode 100644
index 0000000..aae57ef
--- /dev/null
+++ b/.github/packaging/sidecars/supervisor.mjs
@@ -0,0 +1,34 @@
+// The launcher owns stdin. EOF also stops the daemon if the launcher crashes.
+import {spawn} from 'node:child_process'
+import {fileURLToPath} from 'node:url'
+
+if (process.argv[2] === 'phoenixd') {
+ const daemon = spawn(
+ fileURLToPath(new URL('./phoenixd', import.meta.url)),
+ [
+ '--http-bind-ip=127.0.0.1',
+ `--http-bind-port=${process.env.LNBITS_DAEMON_PORT}`,
+ '--agree-to-terms-of-service'
+ ],
+ {stdio: ['ignore', 'inherit', 'inherit']}
+ )
+ let stopping = false
+ const stop = () => {
+ if (stopping) return
+ stopping = true
+ daemon.kill('SIGTERM')
+ setTimeout(() => daemon.kill('SIGKILL'), 15000).unref()
+ }
+ process.stdin.on('end', stop)
+ process.on('SIGINT', stop)
+ process.on('SIGTERM', stop)
+ daemon.on('error', () => process.exit(1))
+ daemon.on('exit', code => process.exit(code ?? 1))
+} else if (process.argv[2] === 'spark') {
+ await import('./spark/server.mjs')
+ // Emitting the event runs the existing cleanup handler on Windows too.
+ process.stdin.on('end', () => process.emit('SIGTERM'))
+} else {
+ process.exit(2)
+}
+process.stdin.resume()
diff --git a/.github/packaging/smoke_sidecars.py b/.github/packaging/smoke_sidecars.py
new file mode 100644
index 0000000..f7acab8
--- /dev/null
+++ b/.github/packaging/smoke_sidecars.py
@@ -0,0 +1,116 @@
+"""Offline native runtime checks: versions, Spark authentication and owned shutdown."""
+
+# ruff: noqa: S101, S603
+import json
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+
+def check(resources):
+ pins = json.loads((resources / "pins.json").read_text())
+ node = resources / ("node.exe" if sys.platform == "win32" else "node")
+ env = dict(os.environ)
+ if sys.platform == "linux":
+ env["LD_LIBRARY_PATH"] = os.pathsep.join(
+ filter(None, (str(resources / "lib"), env.get("LD_LIBRARY_PATH")))
+ )
+ version = subprocess.check_output([str(node), "--version"], env=env, text=True)
+ assert version.strip() == f"v{pins['node']['version']}"
+ if sys.platform != "win32":
+ version = subprocess.check_output(
+ [str(resources / "phoenixd"), "--version"], env=env, text=True
+ )
+ assert f"phoenixd version {pins['phoenixd']['version']}-" in version
+ with tempfile.TemporaryDirectory(prefix="lnbits-funding-smoke-") as folder:
+ with socket.create_server(("127.0.0.1", 0)) as sock:
+ port = sock.getsockname()[1]
+ # No mnemonic means no wallet initialization or Lightning/Spark traffic.
+ env.update(
+ SPARK_MNEMONIC="",
+ SPARK_SIDECAR_HOST="127.0.0.1",
+ SPARK_SIDECAR_PORT=str(port),
+ SPARK_SIDECAR_API_KEY="smoke-test",
+ SPARK_ONCHAIN_ENABLED="false",
+ SPARK_SIDECAR_STATE_PATH=str(Path(folder) / "state.json"),
+ )
+ with tempfile.TemporaryFile() as log:
+ process = subprocess.Popen(
+ [str(node), str(resources / "supervisor.mjs"), "spark"],
+ cwd=folder,
+ env=env,
+ stdin=subprocess.PIPE,
+ stdout=log,
+ stderr=log,
+ )
+ try:
+ client = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ request = urllib.request.Request(
+ f"http://127.0.0.1:{port}/health",
+ headers={"X-Api-Key": "smoke-test"},
+ )
+ deadline = time.monotonic() + 30
+ while True:
+ assert process.poll() is None, "Spark runtime exited during startup"
+ try:
+ with client.open(request, timeout=1) as response:
+ assert json.load(response)["status"] == "ok"
+ break
+ except urllib.error.URLError:
+ assert time.monotonic() < deadline, "Spark startup timed out"
+ time.sleep(0.1)
+ try:
+ client.open(f"http://127.0.0.1:{port}/health", timeout=1)
+ except urllib.error.HTTPError as exc:
+ assert exc.code == 401
+ else:
+ raise AssertionError("Spark accepted a request without credentials")
+ process.stdin.close()
+ assert process.wait(timeout=20) == 0
+ with socket.socket() as probe:
+ assert probe.connect_ex(("127.0.0.1", port)) != 0
+ except BaseException:
+ log.seek(0)
+ print(log.read().decode(errors="replace"), file=sys.stderr)
+ raise
+ finally:
+ if process.poll() is None:
+ process.stdin.close()
+ try:
+ process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ print("Bundled funding runtimes passed offline smoke checks")
+
+
+if __name__ == "__main__":
+ source = Path(sys.argv[1]).resolve()
+ if source.is_dir():
+ check(source)
+ else:
+ # Exercise the files actually shipped inside Linux/Windows onefile builds.
+ from PyInstaller.archive.readers import CArchiveReader
+
+ archive = CArchiveReader(str(source))
+ with tempfile.TemporaryDirectory(prefix="lnbits-bundled-runtimes-") as folder:
+ for name, entry in archive.toc.items():
+ path = Path(name.replace("\\", "/"))
+ if path.parts[0] != "sidecars" or ".." in path.parts:
+ continue
+ destination = Path(folder) / path
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ content = archive.extract(name)
+ if entry[-1] == "n":
+ destination.symlink_to(content.rstrip(b"\0").decode())
+ else:
+ destination.write_bytes(content)
+ if entry[-1] == "b":
+ destination.chmod(0o755)
+ check(Path(folder) / "sidecars")
diff --git a/.github/packaging/test_build.py b/.github/packaging/test_build.py
new file mode 100644
index 0000000..8a80424
--- /dev/null
+++ b/.github/packaging/test_build.py
@@ -0,0 +1,58 @@
+"""Check the macOS dependency guard without building an application."""
+
+import runpy
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+BUILD = Path(__file__).with_name("build.py")
+
+
+class BuildReadyError(Exception):
+ """Stop once dependency validation allows the build to proceed."""
+
+
+class BuildTests(unittest.TestCase):
+ def check_bindings(self, imports, error):
+ bindepend = Mock()
+ bindepend.get_imports.return_value = imports
+ with (
+ patch("prepare_sidecars.main", side_effect=BuildReadyError) as prepare,
+ patch.dict(
+ "sys.modules",
+ {
+ "wasmtime": Mock(),
+ "PyInstaller": Mock(),
+ "PyInstaller.depend": Mock(),
+ "PyInstaller.depend.bindepend": bindepend,
+ },
+ ),
+ patch("sys.platform", "darwin"),
+ patch.dict("os.environ"),
+ patch(
+ "importlib.util.find_spec",
+ return_value=SimpleNamespace(origin="/env/_rust.abi3.so"),
+ ),
+ ):
+ with self.assertRaises(error):
+ runpy.run_path(str(BUILD))
+ bindepend.get_imports.assert_called_once_with("/env/_rust.abi3.so")
+ if error is BuildReadyError:
+ prepare.assert_called_once_with()
+ else:
+ prepare.assert_not_called()
+
+ def test_shared_openssl_is_rejected_before_preparing_sidecars(self):
+ for library in (
+ "@rpath/libssl.3.dylib",
+ "/opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib",
+ ):
+ with self.subTest(library=library):
+ self.check_bindings({(library, None)}, RuntimeError)
+
+ def test_static_openssl_allows_build(self):
+ self.check_bindings(
+ {("/usr/lib/libSystem.B.dylib", "/usr/lib/libSystem.B.dylib")},
+ BuildReadyError,
+ )
diff --git a/.github/packaging/test_desktop.py b/.github/packaging/test_desktop.py
index e9412dc..e1fccad 100644
--- a/.github/packaging/test_desktop.py
+++ b/.github/packaging/test_desktop.py
@@ -3,6 +3,7 @@
import os
import socket
import ssl
+import sys
import tempfile
import time
import unittest
@@ -13,6 +14,24 @@ import desktop
class DesktopTests(unittest.TestCase):
+ def test_macos_finder_launch_and_data_folder(self):
+ with (
+ patch("desktop.sys.platform", "darwin"),
+ patch("desktop.sys.argv", ["LNbits"]),
+ patch.dict(os.environ, {}, clear=True),
+ patch("desktop.launched_from_terminal", return_value=False),
+ patch("desktop.Path.home", return_value=Path("/Users/test")),
+ ):
+ self.assertTrue(desktop.should_show_gui())
+ self.assertEqual(
+ desktop.default_folder(),
+ Path("/Users/test/Library/Application Support/LNbits"),
+ )
+ with patch("desktop.launched_from_terminal", return_value=True):
+ self.assertFalse(desktop.should_show_gui())
+ with patch("desktop.sys.argv", ["LNbits", "--headless"]):
+ self.assertFalse(desktop.should_show_gui())
+
def test_gui_flag_bypasses_terminal_detection(self):
with (
patch("desktop.sys.argv", ["lnbits", "--gui"]),
@@ -272,7 +291,11 @@ class DesktopTests(unittest.TestCase):
launched = True
elif str(browser.cget("state")) == "normal":
ready = True
- root.tk.call(root.protocol("WM_DELETE_WINDOW"))
+ root.tk.call(
+ "tk::mac::Quit"
+ if sys.platform == "darwin"
+ else root.protocol("WM_DELETE_WINDOW")
+ )
return
elif time.monotonic() > deadline:
timed_out = True
diff --git a/.github/packaging/test_dmg.py b/.github/packaging/test_dmg.py
new file mode 100644
index 0000000..5821181
--- /dev/null
+++ b/.github/packaging/test_dmg.py
@@ -0,0 +1,66 @@
+"""Check DMG staging without requiring macOS command-line tools."""
+
+import contextlib
+import hashlib
+import plistlib
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from macos import dmg
+
+
+class DmgTests(unittest.TestCase):
+ def test_staging_preserves_app_and_verifies_before_publishing_checksum(self):
+ for fail_verification in (False, True):
+ with (
+ self.subTest(fail_verification=fail_verification),
+ tempfile.TemporaryDirectory() as folder,
+ contextlib.chdir(folder),
+ patch("macos.dmg.sys.platform", "darwin"),
+ patch("macos.dmg.platform.machine", return_value="arm64"),
+ patch.dict("os.environ", {}, clear=True),
+ ):
+ Path("pyproject.toml").write_text('[project]\nversion="1.6.2-rc1"\n')
+ original = Path("dist/LNbits.app/Contents")
+ original.mkdir(parents=True)
+ metadata = {"CFBundleIdentifier": "com.lnbits.desktop"}
+ (original / "Info.plist").write_bytes(plistlib.dumps(metadata))
+ (original / "Resources").mkdir()
+ (original / "Frameworks").symlink_to("Resources")
+ output = Path("dist/LNbits-v1.6.2rc1-macOS-arm64.dmg").resolve()
+
+ def run(*args, output=output, fail_verification=fail_verification):
+ if args[:2] == ("/usr/bin/hdiutil", "create"):
+ staging = Path(args[args.index("-srcfolder") + 1])
+ app = staging / "LNbits.app/Contents"
+ info = plistlib.loads((app / "Info.plist").read_bytes())
+ self.assertEqual(info["CFBundleShortVersionString"], "1.6.2")
+ self.assertEqual(info["LSMinimumSystemVersion"], "15.0")
+ self.assertTrue((app / "Frameworks").is_symlink())
+ self.assertEqual(
+ (staging / "Applications").readlink(), Path("/Applications")
+ )
+ output.write_bytes(b"disk image")
+ if fail_verification and args[:2] == ("/usr/bin/hdiutil", "verify"):
+ raise subprocess.CalledProcessError(1, args)
+
+ with patch("macos.dmg.run", side_effect=run) as commands:
+ if fail_verification:
+ with self.assertRaises(subprocess.CalledProcessError):
+ dmg.main()
+ self.assertFalse(output.with_suffix(".dmg.sha256").exists())
+ else:
+ dmg.main()
+ checksum = output.with_suffix(".dmg.sha256").read_text()
+ digest = hashlib.sha256(b"disk image").hexdigest()
+ self.assertEqual(
+ checksum,
+ f"{digest} {output.name}\n",
+ )
+ commands.assert_any_call("/usr/bin/hdiutil", "verify", str(output))
+ self.assertEqual(
+ plistlib.loads((original / "Info.plist").read_bytes()), metadata
+ )
diff --git a/.github/packaging/test_funding.py b/.github/packaging/test_funding.py
new file mode 100644
index 0000000..a67626d
--- /dev/null
+++ b/.github/packaging/test_funding.py
@@ -0,0 +1,240 @@
+"""Funding lifecycle tests use isolated data and never create real payments."""
+
+import json
+import os
+import sys
+import tempfile
+import threading
+import unittest
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+import desktop
+import funding
+from embit.bip39 import mnemonic_is_valid
+
+
+class FundingTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.folder = Path(self.temporary.name)
+ resources = self.folder / "bundled"
+ (resources / "spark").mkdir(parents=True)
+ for filename in (
+ "node",
+ "node.exe",
+ "phoenixd",
+ "supervisor.mjs",
+ "spark/server.mjs",
+ ):
+ (resources / filename).touch()
+ self.enterContext(patch("funding.bundled_path", return_value=resources))
+ self.enterContext(patch("funding.check_port"))
+ self.enterContext(patch.dict(os.environ, {}, clear=True))
+ self.process = Mock()
+ self.process.poll.return_value = None
+ self.process.stdin.close.side_effect = lambda: setattr(
+ self.process.poll, "return_value", 0
+ )
+ self.popen = self.enterContext(
+ patch("funding.subprocess.Popen", return_value=self.process)
+ )
+ self.enterContext(patch("funding.threading.Thread"))
+
+ def start(self, provider="spark", port=8765):
+ environment = desktop.configuration(
+ "127.0.0.1",
+ 5000,
+ str(self.folder / "data"),
+ False,
+ True,
+ provider,
+ port,
+ True,
+ )
+ daemon = funding.Funding(environment)
+ self.addCleanup(daemon.close)
+ daemon.start()
+ return daemon
+
+ def test_identity_survives_restart_and_port_change(self):
+ for provider, words in (("spark", 24), ("phoenixd", 12)):
+ if provider == "phoenixd" and sys.platform == "win32":
+ continue
+ with self.subTest(provider=provider):
+ # Each backing wallet owns a separate LNbits data folder.
+ self.folder = self.folder / provider
+ self.folder.mkdir()
+ self.process.poll.return_value = None
+ daemon = self.start(provider)
+ seed = daemon.folder / provider / "seed.dat"
+ mnemonic = seed.read_text().strip()
+ self.assertTrue(mnemonic_is_valid(mnemonic))
+ self.assertEqual(len(mnemonic.split()), words)
+ old_key = (
+ daemon.environment.get("SPARK_L2_EXTERNAL_API_KEY")
+ or daemon.environment["PHOENIXD_API_PASSWORD"]
+ )
+ daemon.close()
+ self.process.poll.return_value = None
+ restarted = self.start(provider, 9876)
+ self.assertEqual(seed.read_text().strip(), mnemonic)
+ self.assertEqual(funding.load_profile(seed.parents[2])["port"], 9876)
+ key = (
+ restarted.environment.get("SPARK_L2_EXTERNAL_API_KEY")
+ or restarted.environment["PHOENIXD_API_PASSWORD"]
+ )
+ self.assertNotEqual(key, old_key)
+ self.assertNotIn(mnemonic, " ".join(self.popen.call_args.args[0]))
+ if os.name != "nt":
+ self.assertEqual(seed.stat().st_mode & 0o777, 0o600)
+ restarted.close()
+
+ def test_missing_or_invalid_seed_is_never_replaced(self):
+ daemon = self.start()
+ seed = daemon.folder / "spark/seed.dat"
+ daemon.close()
+ seed.unlink()
+ with self.assertRaisesRegex(ValueError, "seed is missing"):
+ self.start()
+ self.assertFalse(seed.exists())
+ seed.write_text("damaged")
+ with self.assertRaisesRegex(ValueError, "seed is invalid"):
+ self.start()
+ self.assertEqual(seed.read_text(), "damaged")
+
+ def test_existing_balance_cannot_be_assigned_a_new_backing_wallet(self):
+ data = self.folder / "data"
+ data.mkdir()
+ (data / "database.sqlite3").touch()
+ with self.assertRaisesRegex(ValueError, "new data folder"):
+ self.start()
+ self.popen.assert_not_called()
+
+ def test_one_owner_per_wallet(self):
+ daemon = self.start()
+ with self.assertRaises(OSError):
+ self.start()
+ daemon.close()
+ self.start().close()
+
+ def test_provider_change_and_corrupt_profile_are_rejected(self):
+ daemon = self.start()
+ daemon.close()
+ profile = daemon.folder / "profile.json"
+ data = json.loads(profile.read_text())
+ data["provider"] = "phoenixd"
+ profile.write_text(json.dumps(data))
+ with self.assertRaisesRegex(ValueError, "separate data folder"):
+ self.start()
+ profile.write_text("[]")
+ with self.assertRaisesRegex(ValueError, "profile is invalid"):
+ self.start()
+
+ def test_local_only_authenticated_configuration(self):
+ daemon = self.start()
+ env = self.popen.call_args.kwargs["env"]
+ self.assertEqual(env["SPARK_SIDECAR_HOST"], "127.0.0.1")
+ self.assertEqual(
+ env["SPARK_SIDECAR_API_KEY"],
+ daemon.environment["SPARK_L2_EXTERNAL_API_KEY"],
+ )
+ self.assertEqual(env["SPARK_MNEMONIC"], daemon.environment["SPARK_L2_MNEMONIC"])
+ self.assertEqual(env["SPARK_ONCHAIN_ENABLED"], "false")
+
+ def test_ports_cannot_conflict(self):
+ with self.assertRaisesRegex(ValueError, "different, valid port"):
+ desktop.configuration(
+ "127.0.0.1", 5000, str(self.folder), False, True, "spark", 5000
+ )
+
+ def test_saved_settings_cannot_override_managed_connection(self):
+ from lnbits.core.services.settings import update_cached_settings
+ from lnbits.settings import readonly_variables, settings
+
+ original = readonly_variables.copy()
+ self.addCleanup(lambda: readonly_variables.__setitem__(slice(None), original))
+ env = {
+ "LNBITS_DESKTOP_FUNDING": "spark",
+ "LNBITS_BACKEND_WALLET_CLASS": "SparkL2Wallet",
+ "SPARK_L2_EXTERNAL_ENDPOINT": "http://127.0.0.1:8765",
+ }
+ with (
+ patch.object(settings, "lnbits_backend_wallet_class", "VoidWallet"),
+ patch.object(settings, "spark_l2_external_endpoint", ""),
+ patch.object(settings, "lnbits_database_url", None),
+ ):
+ funding.protect_settings(env)
+ update_cached_settings(
+ {
+ "lnbits_backend_wallet_class": "VoidWallet",
+ "spark_l2_external_endpoint": "http://old.invalid",
+ }
+ )
+ self.assertEqual(settings.lnbits_backend_wallet_class, "SparkL2Wallet")
+ self.assertEqual(
+ settings.spark_l2_external_endpoint, env["SPARK_L2_EXTERNAL_ENDPOINT"]
+ )
+
+ def test_readiness_requires_wallet_balance(self):
+ daemon = self.start()
+ response = Mock()
+ response.__enter__ = Mock(return_value=response)
+ response.__exit__ = Mock(return_value=False)
+ response.read.side_effect = [
+ '{"status":"missing_mnemonic"}',
+ '{"balance_sats":"0"}',
+ ]
+ client = Mock()
+ client.open.return_value = response
+ # _wait_ready normally runs in its background thread.
+ with patch("funding.urllib.request.build_opener", return_value=client):
+ daemon._wait_ready(Mock())
+ self.assertTrue(daemon.ready.is_set())
+ self.assertEqual(client.open.call_count, 2)
+
+ def test_server_waits_for_daemon_and_stops_if_it_dies(self):
+ env = desktop.configuration(
+ "127.0.0.1", 5000, str(self.folder), False, True, "spark"
+ )
+ server = desktop.Server(env)
+ self.addCleanup(server.stop)
+ daemon = Mock(error=None)
+ daemon.ready = threading.Event()
+ daemon.poll.return_value = None
+ with (
+ patch("desktop.Funding", return_value=daemon),
+ patch("desktop.socket.create_server"),
+ patch.object(server, "_start_worker") as start_worker,
+ ):
+ server.start()
+ self.assertIsNone(server.poll())
+ start_worker.assert_not_called()
+ daemon.ready.set()
+ server.poll()
+ start_worker.assert_called_once()
+ daemon.poll.return_value = 1
+ self.assertEqual(server.poll(), 1)
+ self.assertTrue(server.stop_event.is_set())
+ daemon.stop.assert_called_once()
+ daemon.close.assert_called_once()
+
+ def test_daemon_survives_lnbits_restart(self):
+ server = desktop.Server(
+ {"HOST": "127.0.0.1", "PORT": "5000", "LNBITS_DESKTOP_FUNDING": "spark"}
+ )
+ daemon = Mock(error=None)
+ daemon.poll.return_value = None
+ daemon.ready.is_set.return_value = True
+ server.funding = daemon
+ server.process = Mock(exitcode=75)
+ server.process.is_alive.return_value = False
+ with (
+ patch("desktop.socket.create_server"),
+ patch.object(server, "_start_worker") as start_worker,
+ ):
+ self.assertIsNone(server.poll())
+ start_worker.assert_called_once()
+ daemon.stop.assert_not_called()
+ daemon.start.assert_not_called()
diff --git a/.github/packaging/test_prepare_sidecars.py b/.github/packaging/test_prepare_sidecars.py
new file mode 100644
index 0000000..2bde24b
--- /dev/null
+++ b/.github/packaging/test_prepare_sidecars.py
@@ -0,0 +1,73 @@
+"""Pinned release and integrity checks do not depend on live GitHub state."""
+
+import hashlib
+import io
+import tempfile
+import unittest
+import urllib.error
+from pathlib import Path
+from unittest.mock import patch
+
+import prepare_sidecars
+
+
+class PrepareSidecarsTests(unittest.TestCase):
+ def test_pinned_revision_and_checksum_are_used(self):
+ pin = {"release": "v0.1.4", "revision": "a" * 40, "sha256": "archive-digest"}
+ with (
+ tempfile.TemporaryDirectory() as folder,
+ patch("prepare_sidecars.download") as download,
+ patch("prepare_sidecars.unpack", return_value=Path(folder) / "source"),
+ patch("builtins.print"),
+ ):
+ source = prepare_sidecars.download_spark(Path(folder), pin)
+ self.assertEqual(source, Path(folder) / "source")
+ download.assert_called_once_with(
+ "https://api.github.com/repos/lnbits/spark_sidecar/tarball/"
+ + pin["revision"],
+ pin["sha256"],
+ Path(folder) / "spark.tar.gz",
+ )
+
+ def test_missing_archive_fails_without_falling_back(self):
+ pin = {"release": "v0.1.4", "revision": "a" * 40, "sha256": "archive-digest"}
+ with (
+ patch(
+ "prepare_sidecars.download",
+ side_effect=urllib.error.HTTPError(
+ "https://api.github.com", 404, "Not Found", {}, None
+ ),
+ ) as download,
+ patch("prepare_sidecars.unpack") as unpack,
+ patch("builtins.print"),
+ ):
+ with self.assertRaises(urllib.error.HTTPError):
+ prepare_sidecars.download_spark(Path("unused"), pin)
+ download.assert_called_once()
+ unpack.assert_not_called()
+
+ def test_download_records_digest_and_still_enforces_pinned_checksums(self):
+ content = b"runtime archive"
+ expected = hashlib.sha256(content).hexdigest()
+ with tempfile.TemporaryDirectory() as folder:
+ for digest in (None, expected, "incorrect"):
+ with patch(
+ "prepare_sidecars.urllib.request.urlopen",
+ return_value=io.BytesIO(content),
+ ):
+ if digest != expected:
+ with self.assertRaisesRegex(RuntimeError, "Checksum mismatch"):
+ prepare_sidecars.download(
+ "https://example.com/runtime",
+ digest,
+ Path(folder) / "archive",
+ )
+ else:
+ self.assertEqual(
+ prepare_sidecars.download(
+ "https://example.com/runtime",
+ digest,
+ Path(folder) / "archive",
+ ),
+ expected,
+ )
diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml
index 3ed7e74..a764760 100644
--- a/.github/workflows/appimage.yml
+++ b/.github/workflows/appimage.yml
@@ -43,7 +43,7 @@ jobs:
- name: Install system dependencies
run: |
sudo apt-get update
- sudo apt-get install -y libfuse2 python3-tk xvfb
+ sudo apt-get install -y libfuse2 libcrypt1 python3-tk xvfb
shell: bash
- uses: astral-sh/setup-uv@v6
@@ -66,6 +66,9 @@ jobs:
- name: Test launcher window and shutdown
run: xvfb-run -a uv run --no-sync python -m unittest discover -s .github/packaging -v
+ - name: Test bundled funding runtimes
+ run: uv run --no-sync python .github/packaging/smoke_sidecars.py dist/lnbits
+
- name: Verify packaged dependency data
run: |
ARCHIVE_LIST="$(mktemp)"
diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
new file mode 100644
index 0000000..520d125
--- /dev/null
+++ b/.github/workflows/macos.yml
@@ -0,0 +1,130 @@
+name: Build LNbits macOS DMG
+
+on:
+ push:
+ branches:
+ - "**"
+ paths:
+ - ".github/packaging/**"
+ - ".github/workflows/macos.yml"
+ - "pyproject.toml"
+ - "uv.lock"
+ workflow_call:
+ inputs:
+ tag_name:
+ required: true
+ type: string
+ workflow_dispatch:
+ inputs:
+ tag_name:
+ description: Release tag (leave empty to build this branch as an artifact)
+ required: false
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: macos-15
+ arch: arm64
+ - runner: macos-15-intel
+ arch: x86_64
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 40
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.tag_name || github.ref }}
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - uses: astral-sh/setup-uv@v6
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "24.x"
+ cache: npm
+ - name: Verify frontend assets
+ run: |
+ npm ci
+ npm run bundle
+ ./node_modules/.bin/prettier -w ./lnbits/static/vendor.json
+ git diff --exit-code -- lnbits/static
+ - name: Build application
+ run: |
+ # Intel builds cryptography from source; avoid sharing Python's libssl.
+ uv cache clean cryptography
+ OPENSSL_STATIC=1 OPENSSL_DIR="$(brew --prefix openssl@3)" \
+ uv sync --locked --no-dev --no-editable --reinstall-package cryptography
+ uv pip install pyinstaller==6.22.2
+ uv run --no-sync python .github/packaging/build.py
+ - name: Test launcher window and shutdown
+ run: uv run --no-sync python -m unittest discover -s .github/packaging -v
+ - name: Verify native architecture and packaged data
+ env:
+ EXPECTED_ARCH: ${{ matrix.arch }}
+ run: |
+ test "$(lipo -archs dist/LNbits.app/Contents/MacOS/LNbits)" = "$EXPECTED_ARCH"
+ test -f dist/LNbits.app/Contents/Resources/certifi/cacert.pem
+ test -f dist/LNbits.app/Contents/Resources/random_username/data/nouns.txt
+ test -f dist/LNbits.app/Contents/Resources/pyinstrument/renderers/html_resources/app.js
+ codesign --verify --deep --strict dist/LNbits.app
+ - name: Build and verify DMG
+ run: uv run --no-sync python .github/packaging/macos/dmg.py
+ - name: Test application from read-only disk image
+ run: |
+ MOUNT_DIR="$(mktemp -d)"
+ hdiutil attach dist/*.dmg -mountpoint "$MOUNT_DIR" -nobrowse -readonly
+ cleanup() {
+ status=$?
+ # macOS can briefly keep the volume busy after the tests exit.
+ for attempt in 1 2 3 4 5; do
+ if hdiutil detach "$MOUNT_DIR"; then
+ rmdir "$MOUNT_DIR"
+ return "$status"
+ fi
+ echo "Disk image detach attempt $attempt/5 failed; waiting before retry."
+ sleep 2
+ done
+ # This is a read-only test image and the smoke tests have finished.
+ hdiutil detach -force "$MOUNT_DIR"
+ rmdir "$MOUNT_DIR"
+ return "$status"
+ }
+ trap cleanup EXIT
+ test -L "$MOUNT_DIR/Applications"
+ codesign --verify --deep --strict "$MOUNT_DIR/LNbits.app"
+ uv run --no-sync python .github/packaging/smoke_sidecars.py "$MOUNT_DIR/LNbits.app/Contents/Frameworks/sidecars"
+ uv run --no-sync python .github/packaging/smoke.py "$MOUNT_DIR/LNbits.app/Contents/MacOS/LNbits"
+ - name: Record signing status
+ run: echo 'DMGs are ad-hoc signed, without Apple Developer ID or notarization.' >> "$GITHUB_STEP_SUMMARY"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: LNbits-macOS-${{ matrix.arch }}
+ path: |
+ dist/*.dmg
+ dist/*.dmg.sha256
+ if-no-files-found: error
+
+ upload:
+ if: inputs.tag_name != ''
+ needs: build
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: LNbits-macOS-*
+ merge-multiple: true
+ path: dist
+ - name: Attach DMGs and checksums to release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ TAG_NAME: ${{ inputs.tag_name }}
+ run: gh release upload "$TAG_NAME" dist/*.dmg dist/*.dmg.sha256 --clobber
diff --git a/.github/workflows/release-rc.yml b/.github/workflows/release-rc.yml
index e259e8c..5fa1c8c 100644
--- a/.github/workflows/release-rc.yml
+++ b/.github/workflows/release-rc.yml
@@ -87,3 +87,9 @@ jobs:
uses: ./.github/workflows/windows.yml
with:
tag_name: ${{ github.ref_name }}
+
+ macos:
+ needs: [ release ]
+ uses: ./.github/workflows/macos.yml
+ with:
+ tag_name: ${{ github.ref_name }}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8bc3dcc..db6c88d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -98,3 +98,9 @@ jobs:
uses: ./.github/workflows/windows.yml
with:
tag_name: ${{ github.ref_name }}
+
+ macos:
+ needs: [ release ]
+ uses: ./.github/workflows/macos.yml
+ with:
+ tag_name: ${{ github.ref_name }}
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 38e3a17..620ce76 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -54,6 +54,8 @@ jobs:
uv run --no-sync python .github/packaging/build.py
- name: Test launcher window and shutdown
run: uv run --no-sync python -m unittest discover -s .github/packaging -v
+ - name: Test bundled funding runtimes
+ run: uv run --no-sync python .github/packaging/smoke_sidecars.py dist/lnbits.exe
- name: Test executable startup, assets and shutdown
run: uv run --no-sync python .github/packaging/smoke.py dist/lnbits.exe
- uses: actions/upload-artifact@v4
diff --git a/.gitignore b/.gitignore
index 2b2c7c8..a13beb6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -58,6 +58,7 @@ lnbits-backup.zip
# builded python package
dist
+/build/
# jetbrains
.idea
diff --git a/lnbits/wallets/sparkl2.py b/lnbits/wallets/sparkl2.py
index ea1370b..562e49d 100644
--- a/lnbits/wallets/sparkl2.py
+++ b/lnbits/wallets/sparkl2.py
@@ -174,6 +174,7 @@ class SparkL2Wallet(Wallet):
checking_id=checking_id,
fee_msat=int(fee_msat) if fee_msat is not None else None,
preimage=res.get("preimage"),
+ error_message=res.get("error_message") if ok is False else None,
)
except Exception as e:
diff --git a/tests/unit/test_wallet_payment_ambiguity.py b/tests/unit/test_wallet_payment_ambiguity.py
index 3c8724a..9c23d32 100644
--- a/tests/unit/test_wallet_payment_ambiguity.py
+++ b/tests/unit/test_wallet_payment_ambiguity.py
@@ -475,6 +475,43 @@ async def test_phoenix_request_error_is_pending(mocker: MockerFixture):
assert response.ok is None
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ ("status", "expected_ok", "expected_error"),
+ [
+ ("LIGHTNING_PAYMENT_FAILED", False, "Lightning fee exceeds the limit"),
+ ("UNKNOWN", None, None),
+ ("LIGHTNING_PAYMENT_SUCCEEDED", True, None),
+ ],
+)
+async def test_spark_sidecar_preserves_explicit_failure_reason(
+ mocker: MockerFixture,
+ status: str,
+ expected_ok: bool | None,
+ expected_error: str | None,
+):
+ wallet = object.__new__(SparkL2Wallet)
+ mocker.patch(
+ "lnbits.wallets.sparkl2.bolt11_decode",
+ return_value=SimpleNamespace(payment_hash="payment-hash"),
+ )
+ mocker.patch.object(
+ wallet,
+ "_request",
+ return_value={
+ "checking_id": "payment-hash",
+ "status": status,
+ "error_message": "Lightning fee exceeds the limit",
+ },
+ )
+
+ response = await wallet.pay_invoice("bolt11", 2_000)
+
+ assert response.ok is expected_ok
+ assert response.error_message == expected_error
+ assert response.checking_id == "payment-hash"
+
+
@pytest.mark.anyio
async def test_spark_sidecar_missing_checking_id_is_pending(mocker: MockerFixture):
wallet = object.__new__(SparkL2Wallet)
Why this scored 24/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.