From fd86b67d1a085fbfe026b92257212a4e9d2f8c4b Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Tue, 17 Nov 2026 20:11:16 +0200 Subject: [PATCH 1/4] signer: Add device storage interface and file backend Expose DeviceStorage and an optional signer configuration hook for metadata kept on the device. Provide a file-backed implementation for glcli with atomic replacement and durable writes. Distinguish absent records from storage failures, and keep record encoding independent of the storage backend. --- Cargo.lock | 1 + libs/gl-cli/Cargo.toml | 5 +- libs/gl-cli/src/device_state.rs | 95 +++++++++++++++++++++++ libs/gl-cli/src/lib.rs | 1 + libs/gl-cli/src/signer.rs | 1 + libs/gl-client/CHANGELOG.md | 1 + libs/gl-client/src/signer/device_state.rs | 49 ++++++++++++ libs/gl-client/src/signer/mod.rs | 5 ++ 8 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 libs/gl-cli/src/device_state.rs create mode 100644 libs/gl-client/src/signer/device_state.rs diff --git a/Cargo.lock b/Cargo.lock index fbe009300..8ac429333 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1452,6 +1452,7 @@ checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" name = "gl-cli" version = "0.1.3" dependencies = [ + "anyhow", "bip39", "clap", "dirs", diff --git a/libs/gl-cli/Cargo.toml b/libs/gl-cli/Cargo.toml index 9b8f0449d..5e96be767 100644 --- a/libs/gl-cli/Cargo.toml +++ b/libs/gl-cli/Cargo.toml @@ -21,6 +21,7 @@ test = true doc = true [dependencies] +anyhow.workspace = true bip39 = { version = "2.2", features = ["rand"] } clap = { version = "4.5", features = ["derive"] } dirs = "6.0" @@ -32,10 +33,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2.0.11" tokio = "1.43.0" -vls-core.workspace = true - -[dev-dependencies] tempfile = "3.10.1" +vls-core.workspace = true [badges] maintenance = { status = "actively-developed" } diff --git a/libs/gl-cli/src/device_state.rs b/libs/gl-cli/src/device_state.rs new file mode 100644 index 000000000..28c1f356d --- /dev/null +++ b/libs/gl-cli/src/device_state.rs @@ -0,0 +1,95 @@ +use anyhow::{Context, Result}; +use gl_client::bitcoin::hashes::{sha256, Hash}; +use gl_client::signer::DeviceStorage; +use std::fs::{self, File}; +use std::io::{ErrorKind, Write}; +use std::path::{Path, PathBuf}; + +/// A file-backed device store using durable, atomic replacement. +#[derive(Debug)] +pub(crate) struct FileDeviceStorage { + dir: PathBuf, +} + +impl FileDeviceStorage { + pub(crate) fn new(dir: impl AsRef) -> Result { + let dir = dir.as_ref().to_owned(); + fs::create_dir_all(&dir) + .with_context(|| format!("creating device state directory {}", dir.display()))?; + Ok(Self { dir }) + } + + fn path(&self, key: &str) -> PathBuf { + // Keys are opaque logical identifiers and must never become paths. + self.dir + .join(sha256::Hash::hash(key.as_bytes()).to_string()) + } +} + +impl DeviceStorage for FileDeviceStorage { + fn load(&self, key: &str) -> Result>> { + match fs::read(self.path(key)) { + Ok(bytes) => Ok(Some(bytes)), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).context("reading signer device state"), + } + } + + fn save(&self, key: &str, value: &[u8]) -> Result<()> { + let mut tmp = tempfile::NamedTempFile::new_in(&self.dir) + .context("creating temporary device state file")?; + tmp.write_all(value) + .context("writing signer device state")?; + tmp.as_file() + .sync_all() + .context("syncing signer device state")?; + tmp.persist(self.path(key)) + .context("replacing signer device state")?; + #[cfg(unix)] + File::open(&self.dir) + .and_then(|dir| dir.sync_all()) + .context("syncing device state directory")?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_survive_reopening_and_replacement() { + let dir = tempfile::tempdir().unwrap(); + { + let store = FileDeviceStorage::new(dir.path()).unwrap(); + assert!(store.load("signer/regtest/node").unwrap().is_none()); + store.save("signer/regtest/node", b"old value").unwrap(); + store.save("signer/regtest/node", b"new").unwrap(); + store.save("signer/bitcoin/node", &[0, 255, 0]).unwrap(); + } + let store = FileDeviceStorage::new(dir.path()).unwrap(); + assert_eq!(store.load("signer/regtest/node").unwrap().unwrap(), b"new"); + assert_eq!( + store.load("signer/bitcoin/node").unwrap().unwrap(), + [0, 255, 0] + ); + } + + #[test] + fn logical_keys_cannot_escape_the_storage_directory() { + let dir = tempfile::tempdir().unwrap(); + let store = FileDeviceStorage::new(dir.path()).unwrap(); + let key = "../../outside"; + store.save(key, b"value").unwrap(); + assert_eq!(store.path(key).parent(), Some(dir.path())); + assert_eq!(store.load(key).unwrap().unwrap(), b"value"); + } + + #[test] + fn read_errors_are_not_treated_as_missing_state() { + let dir = tempfile::tempdir().unwrap(); + let store = FileDeviceStorage::new(dir.path()).unwrap(); + fs::create_dir(store.path("key")).unwrap(); + assert!(store.load("key").is_err()); + } +} diff --git a/libs/gl-cli/src/lib.rs b/libs/gl-cli/src/lib.rs index ddbe5b01b..34b476271 100644 --- a/libs/gl-cli/src/lib.rs +++ b/libs/gl-cli/src/lib.rs @@ -2,6 +2,7 @@ use crate::error::Result; use clap::{Parser, Subcommand}; use gl_client::bitcoin::Network; use std::{path::PathBuf, str::FromStr}; +mod device_state; mod error; mod json_hex; pub mod model; diff --git a/libs/gl-cli/src/signer.rs b/libs/gl-cli/src/signer.rs index e423c73c6..fb6fd4eb5 100644 --- a/libs/gl-cli/src/signer.rs +++ b/libs/gl-cli/src/signer.rs @@ -393,6 +393,7 @@ async fn run_handler>( SignerConfig { state_signature_mode: state_signature_mode.into(), state_signature_override, + device_storage: None, backup, fee_budget_limits, }, diff --git a/libs/gl-client/CHANGELOG.md b/libs/gl-client/CHANGELOG.md index 8cf8fbea1..660b6789c 100644 --- a/libs/gl-client/CHANGELOG.md +++ b/libs/gl-client/CHANGELOG.md @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Added - Configure routing and on-chain fee limits with `FeeBudgetLimits` through `SignerConfig::fee_budget_limits`. See [signer fee budgets](../../docs/src/reference/signer-fees.md) for configuration, defaults, and limitations. +- `DeviceStorage` and `SignerConfig::device_storage` for device-local signer metadata, scoped by node and network. ### Changed diff --git a/libs/gl-client/src/signer/device_state.rs b/libs/gl-client/src/signer/device_state.rs new file mode 100644 index 000000000..851189f1c --- /dev/null +++ b/libs/gl-client/src/signer/device_state.rs @@ -0,0 +1,49 @@ +//! Storage for signer metadata kept on the device, independently of the node. + +use anyhow::Result; +use std::fmt::Debug; + +/// Device-local storage for opaque signer metadata. +/// +/// Keys are logical identifiers, not filesystem paths. The signer namespaces +/// them by node ID, network and purpose. The store must preserve their bytes +/// unchanged; each caller owns its value encoding. +/// +/// A successful [`save`](Self::save) must atomically replace the value and +/// survive a crash. An interrupted save may leave either the old or the new +/// value, never a partial write. Missing values must be distinguished from read +/// failures. +/// +/// Device storage is trusted locally. Deleting it or restoring an older copy +/// can weaken the protections built on it. +pub trait DeviceStorage: Debug + Send + Sync { + /// Load a value, returning `None` only when the key is absent. + fn load(&self, key: &str) -> Result>>; + + /// Atomically replace a value and make it durable before returning success. + /// + /// An error may leave either the old or the new value stored. Callers must + /// not assume that a failed save left the value unchanged. + fn save(&self, key: &str, value: &[u8]) -> Result<()>; +} + +#[cfg(test)] +#[derive(Debug, Default)] +pub(super) struct MemoryDeviceStorage { + values: std::sync::Mutex>>, +} + +#[cfg(test)] +impl DeviceStorage for MemoryDeviceStorage { + fn load(&self, key: &str) -> Result>> { + Ok(self.values.lock().unwrap().get(key).cloned()) + } + + fn save(&self, key: &str, value: &[u8]) -> Result<()> { + self.values + .lock() + .unwrap() + .insert(key.to_owned(), value.to_vec()); + Ok(()) + } +} diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index c507e6277..9eb83ca32 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -50,6 +50,8 @@ use vls_protocol_signer::handler::Handler; mod approver; mod auth; +mod device_state; +pub use device_state::DeviceStorage; #[cfg(feature = "backup")] mod backup; #[cfg(feature = "backup")] @@ -113,6 +115,8 @@ pub struct SignerConfig { pub state_signature_mode: StateSignatureMode, pub state_signature_override: Option, pub fee_budget_limits: FeeBudgetLimits, + /// Storage for device-local signer metadata. + pub device_storage: Option>, #[cfg(feature = "backup")] pub backup: Option, } @@ -1876,6 +1880,7 @@ mod tests { path: "backup.json".into(), strategy: SignerBackupStrategy::Periodic { updates: 0 }, }), + ..SignerConfig::default() }, ); From 361186690b502c9ec08e0f003f89e45b6e845004 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Tue, 17 Nov 2026 20:12:11 +0200 Subject: [PATCH 2/4] signer: Make state migration one-time and transactional Default to Hard state signature checks and allow one successful Soft migration per device and node. Save the migration marker before publishing state or signatures. Processing failures leave migration available; marker-write failures close the allowance. Authorize and handle requests against scratch state, committing only after handling and state signing succeed. Rejected input and changes made during failed processing cannot be retained and signed later. --- docs/src/reference/signer-state.md | 95 +++- libs/gl-cli/CHANGELOG.md | 1 + libs/gl-cli/src/signer.rs | 23 +- libs/gl-client/CHANGELOG.md | 2 + libs/gl-client/src/persist.rs | 11 +- libs/gl-client/src/signer/mod.rs | 755 ++++++++++++++++++++++++++--- 6 files changed, 796 insertions(+), 91 deletions(-) diff --git a/docs/src/reference/signer-state.md b/docs/src/reference/signer-state.md index 4fa6c885a..565bdcb37 100644 --- a/docs/src/reference/signer-state.md +++ b/docs/src/reference/signer-state.md @@ -7,11 +7,12 @@ channel, which destinations the on-chain wallet may send to, and which invoices and preimages it has seen. This knowledge is the _signer state_. -Greenlight signers are stateless by design. They do not own durable -storage for the signer state, which is what allows a signer to run on -a phone, in a short-lived process, or on several devices at once. -Instead, the Greenlight node stores the signer state and attaches it to -every request it sends to the signer. +Greenlight signers do not keep a durable copy of the full signer state, +which is what allows a signer to run on a phone, in a short-lived process, +or on several devices at once. Instead, the Greenlight node stores the +signer state and attaches it to every request it sends to the signer. +A signer can keep a small amount of metadata in device-local storage, +independently of the node. This creates a tension with the [security model](security.md): the signer protects funds against an attacker with access to the node @@ -45,16 +46,22 @@ exchanging only what changed: carries a full snapshot of the state. 2. Every following request carries only the entries that changed since the node last sent state to that signer. - 3. The signer merges incoming entries into its in-memory copy. New - keys are added, higher versions replace lower ones, lower versions - are ignored. - 4. The signer processes the request and returns the entries it - changed, signed. + 3. The signer merges incoming entries into a scratch copy of its state. + New keys are added, higher versions replace lower ones, lower + versions are ignored. + 4. The signer authorizes and processes the request against that copy. + Only after processing and state signing succeed does it commit the + copy and return the signed changes. A rejected request leaves the + live state unchanged, including changes made while processing it. 5. The node merges and persists the returned entries _before_ it hands the signer's response on. If the entries cannot be stored, the response is dropped, so the node never acts on a signature whose state was lost. +Builds with the `permissive` feature report authorization failures but +continue processing them. Requests that return an error still leave the +live state unchanged. + The node pipelines requests, so several can be in flight at once, each carrying the state as it was when the request was sent. The signer handles them one after the other, and its in-memory state is always at @@ -96,18 +103,12 @@ _state signature mode_: | Mode | Missing signature | Invalid signature | Intended use | |------|-------------------|-------------------|--------------| | `off` | Accepted | Accepted | Development and tests only | -| `soft` | Accepted, and signed on the way out | Refused | Migrating nodes whose state predates state signatures | -| `hard` | Refused | Refused | Production, once all state is signed | - -`soft` is the current default. In `soft` mode a signer signs unsigned -entries it receives, which gradually migrates nodes created before -state signing existed. Only `hard` mode guarantees that every entry the -signer acts on was written by a signer of this node. +| `soft` | Accepted for one successfully processed snapshot, and signed on the way out | Refused | One-time migration of nodes whose state predates state signatures | +| `hard` | Refused | Refused | Production (default) | -!!! note "Planned default" - The default will move from `soft` to `hard` once the fleet's state - is fully signed. Applications embedding the signer should plan for - running in `hard` mode. +`hard` is the default. A signer never automatically falls back to +`soft` when it encounters unsigned state. Only `hard` mode guarantees +that every entry the signer acts on was written by a signer of this node. The mode is part of the signer configuration: @@ -133,6 +134,58 @@ The mode is part of the signer configuration: glcli signer run --state-signature-mode hard ``` +#### One-time migration + +An application can explicitly select `soft` to migrate a legacy node. +One successfully processed state snapshot can run in Soft mode. Missing +signatures in that snapshot are accepted and repaired; invalid signatures +are refused. After a successful migration, all subsequent requests use Hard, including after +reconnecting. Clones of the signer share this transition. + +Soft mode requires a persistent `DeviceStorage` supplied through +`SignerConfig::device_storage`. The signer saves a migration marker, +scoped by node ID and network, after processing and signing succeed but +**before** committing state or returning signatures. If that marker is +already present, requesting Soft starts the +signer in Hard with a warning. Applications can keep the same configuration +across restarts without reopening the migration. A successfully processed +empty snapshot also consumes the allowance. + +`DeviceStorage` provides fallible `load` and `save` operations over opaque +bytes; writes must replace values atomically and durably. Each purpose has +its own key and encoding. +Storage errors prevent the migration from publishing state or signatures. +If writing the marker fails, the current signer switches to Hard because +the failed write may still have persisted the marker. + +For explicit Soft mode, `glcli` supplies a file-backed store under +`/device-state`. To migrate a legacy node once: + +```bash +glcli signer run --state-signature-mode soft +``` + +Afterward, rerunning with `soft` logs a warning and uses Hard mode. +Running without the flag also uses Hard. The Rust, Python and SDK +constructors use Hard by default; Hard does not require a device store. + +The migration deliberately trusts the unsigned snapshot it migrates. If the +process crashes or the connection drops after saving the marker but +before the node persists the repaired state, the allowance stays +consumed. Restarting with Soft uses Hard; it does not retry the migration. +Contact Greenlight support for explicit recovery if the node still has +unsigned state. +Deleting device storage or restoring an older copy can reset this local +guard. That limitation is accepted for now. + +!!! note "Multi-device limitation" + The current solution does not coordinate migration across devices. + Each device has its own marker, so consuming the Soft allowance on one + device does not prevent another device from running Soft for the same + node. We plan to address this with an external watermarking service + that is not controlled by Blockstream. That service is outside the + scope of the current implementation. + #### Operator-assisted override For manual recovery, a signer can be started with an override that diff --git a/libs/gl-cli/CHANGELOG.md b/libs/gl-cli/CHANGELOG.md index f8bc931e1..1d56227e5 100644 --- a/libs/gl-cli/CHANGELOG.md +++ b/libs/gl-cli/CHANGELOG.md @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed +- `signer run` defaults to `hard` state signature mode. Explicit `soft` mode allows one successful migration per device and node, then uses Hard on subsequent requests and restarts. - `fundchannel` now creates private channels by default ## [0.1.2] - 2026-01-16 diff --git a/libs/gl-cli/src/signer.rs b/libs/gl-cli/src/signer.rs index fb6fd4eb5..d4df59923 100644 --- a/libs/gl-cli/src/signer.rs +++ b/libs/gl-cli/src/signer.rs @@ -3,13 +3,14 @@ use crate::util; use clap::{Subcommand, ValueEnum}; use core::fmt::Debug; use gl_client::signer::{ - CLNBackup, CLNBackupOptions, FeeBudgetLimits, RecoverableChannel, Signer, SignerBackupConfig, + CLNBackup, CLNBackupOptions, DeviceStorage, FeeBudgetLimits, RecoverableChannel, Signer, SignerBackupConfig, SignerBackupSnapshot, SignerBackupStrategy, SignerConfig, StateSignatureMode, StateSignatureOverrideConfig, }; use lightning_signer::bitcoin::Network; use serde::Serialize; use std::path::{Path, PathBuf}; +use std::sync::Arc; use tokio::{join, signal}; use util::{CREDENTIALS_FILE_NAME, SEED_FILE_NAME}; @@ -28,7 +29,7 @@ pub enum StateSignatureModeArg { impl Default for StateSignatureModeArg { fn default() -> Self { - Self::Soft + Self::Hard } } @@ -75,7 +76,8 @@ impl Default for BackupConvertFormat { pub enum Command { /// Starts a signer that connects to greenlight Run { - #[arg(long, value_enum, default_value_t = StateSignatureModeArg::Soft)] + /// Signature checks; soft migrates one state snapshot per device. + #[arg(long, value_enum, default_value_t = StateSignatureModeArg::Hard)] state_signature_mode: StateSignatureModeArg, #[arg(long = "state-override")] state_override: Option, @@ -385,6 +387,15 @@ async fn run_handler>( } }); let backup = backup_config_from_args(backup_path, backup_strategy, backup_periodic_updates)?; + let device_storage: Option> = match state_signature_mode { + StateSignatureModeArg::Soft => Some(Arc::new( + crate::device_state::FileDeviceStorage::new( + config.data_dir.as_ref().join("device-state"), + ) + .map_err(|e| Error::custom(format!("Failed to open device state storage: {e:#}")))?, + )), + _ => None, + }; let signer = Signer::new_with_config( seed, @@ -393,7 +404,7 @@ async fn run_handler>( SignerConfig { state_signature_mode: state_signature_mode.into(), state_signature_override, - device_storage: None, + device_storage, backup, fee_budget_limits, }, @@ -498,7 +509,7 @@ mod tests { } #[test] - fn run_mode_defaults_to_soft() { + fn run_mode_defaults_to_hard() { let cli = TestCli::parse_from(["test", "run"]); match cli.cmd { Command::Run { @@ -510,7 +521,7 @@ mod tests { backup_periodic_updates, .. } => { - assert_eq!(state_signature_mode, StateSignatureModeArg::Soft); + assert_eq!(state_signature_mode, StateSignatureModeArg::Hard); assert!(state_override.is_none()); assert!(state_override_note.is_none()); assert!(backup_path.is_none()); diff --git a/libs/gl-client/CHANGELOG.md b/libs/gl-client/CHANGELOG.md index 660b6789c..3e9aa0220 100644 --- a/libs/gl-client/CHANGELOG.md +++ b/libs/gl-client/CHANGELOG.md @@ -15,12 +15,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Enforce a routing-fee allowance per payment, shared across all parts and channels. The default is the larger of 1,000 sat and 0.5% of the payment amount. `pay`, direct-invoice `xpay`, and trampoline requests with fee limits above the allowance are rejected before HTLCs are offered. - Enforce on-chain fee limits of 100,000 sat per new commitment or signed local HTLC input, and 50,000 sat per mutual close by default. Previously accepted force-close commitments remain signable after limits are lowered. +- State signature checks default to Hard. Soft requires persistent device storage and is limited to one successful state snapshot migration before switching to Hard. Rejected requests leave migration available; marker-write failures close the allowance. Requesting Soft after migration starts in Hard with a warning. ### Fixed - Fix missing invoice approvals for invoice-backed `sendpay` and direct-invoice `xpay`, including amountless invoices. - Allow retrying an amountless invoice with a different amount once the previous attempt has no outstanding HTLCs. - Fix node hangs caused by signer errors during invoice and keysend preapproval. +- Rejected signer requests no longer retain incoming state or changes made during processing. Authorization and VLS handling use a scratch state that is committed only after success. ## [0.7.0] - 2026-10-12 diff --git a/libs/gl-client/src/persist.rs b/libs/gl-client/src/persist.rs index 55c5cef21..f9079b37a 100644 --- a/libs/gl-client/src/persist.rs +++ b/libs/gl-client/src/persist.rs @@ -694,10 +694,13 @@ pub(crate) struct MemoryPersister { impl MemoryPersister { pub fn new() -> Self { - let state = Arc::new(Mutex::new(State { - values: BTreeMap::new(), - })); - MemoryPersister { state } + Self::from_state(State::new()) + } + + pub fn from_state(state: State) -> Self { + MemoryPersister { + state: Arc::new(Mutex::new(state)), + } } pub fn state(&self) -> Arc> { diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 9eb83ca32..3613e9cf6 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -13,7 +13,7 @@ use crate::runes; use crate::signer::resolve::Resolver; use crate::tls::TlsConfig; use crate::{node, node::Client}; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use base64::engine::general_purpose; use base64::Engine; use bytes::BufMut; @@ -34,6 +34,7 @@ use runeauth::{Condition, Restriction, Rune, RuneError}; use std::convert::{TryFrom, TryInto}; use std::sync::Arc; use std::sync::Mutex; +use std::sync::PoisonError; use std::time::SystemTime; use tokio::sync::mpsc; use tokio::time::{sleep, Duration}; @@ -93,14 +94,18 @@ fn advertise_experimental_splicing(mut init: HsmdInitReplyV4) -> HsmdInitReplyV4 #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StateSignatureMode { + /// Disable signature verification (development and tests only). Off, + /// Migrate one successfully processed state snapshot, then switch to Hard. + /// Requires persistent device state storage in [`SignerConfig`]. Soft, + /// Reject incoming state with missing or invalid signatures (the default). Hard, } impl Default for StateSignatureMode { fn default() -> Self { - Self::Soft + Self::Hard } } @@ -115,7 +120,7 @@ pub struct SignerConfig { pub state_signature_mode: StateSignatureMode, pub state_signature_override: Option, pub fee_budget_limits: FeeBudgetLimits, - /// Storage for device-local signer metadata. + /// Device-local metadata storage, required for a one-time Soft migration. pub device_storage: Option>, #[cfg(feature = "backup")] pub backup: Option, @@ -133,12 +138,18 @@ impl OverrideSignatureUsage { } } +struct SoftMigration { + store: Arc, + key: String, +} + #[derive(Clone)] pub struct Signer { secret: [u8; 32], state_signing_secret: SecretKey, state_signing_pubkey: PublicKey, state_signature_mode: StateSignatureMode, + soft_migration: Arc>>, state_signature_override_enabled: bool, state_signature_override_note: Option, fee_budget_limits: FeeBudgetLimits, @@ -237,6 +248,7 @@ impl Signer { info!("Initializing signer for {VERSION} ({GITHASH}) (VLS)"); let state_signature_mode = config.state_signature_mode; + let device_storage = config.device_storage; #[cfg(feature = "backup")] let backup_config = { if let Some(backup) = &config.backup { @@ -360,12 +372,41 @@ impl Signer { let state_signing_pubkey = PublicKey::from_secret_key(&Secp256k1::signing_only(), &state_signing_secret); + let soft_migration = match (state_signature_mode, device_storage) { + (StateSignatureMode::Soft, Some(store)) => { + let key = format!("signer/{network}/{}/soft-migration", hex::encode(&id)); + if store + .load(&key) + .context("loading Soft migration marker")? + .is_some() + { + warn!("Soft state migration has already been used on this device for this node; using Hard mode"); + None + } else { + Some(SoftMigration { store, key }) + } + } + (StateSignatureMode::Soft, None) => { + return Err(anyhow!( + "Soft state signature mode requires persistent device state storage" + )); + } + _ => None, + }; + // Soft remains available until processing succeeds. After migration + // or a failed marker write, requests use the stored mode. + let state_signature_mode = match state_signature_mode { + StateSignatureMode::Soft => StateSignatureMode::Hard, + mode => mode, + }; + trace!("Initialized signer for node_id={}", hex::encode(&id)); Ok(Signer { secret: sec, state_signing_secret, state_signing_pubkey, state_signature_mode, + soft_migration: Arc::new(Mutex::new(soft_migration)), state_signature_override_enabled, state_signature_override_note, fee_budget_limits: config.fee_budget_limits, @@ -408,16 +449,14 @@ impl Signer { fn handler_with_approver( &self, approver: Arc, + services: NodeServices, ) -> Result { - let mut h = handler::HandlerBuilder::new( - self.network, - 0 as u64, - self.services.clone(), - self.secret, - ) - .approver(approver) - .build() - .map_err(|e| crate::signer::Error::Other(anyhow!("Could not create handler: {:?}", e)))?; + let mut h = handler::HandlerBuilder::new(self.network, 0 as u64, services, self.secret) + .approver(approver) + .build() + .map_err(|e| { + crate::signer::Error::Other(anyhow!("Could not create handler: {:?}", e)) + })?; h.handle(Signer::initreq()) .map_err(|e| Error::Other(anyhow!("Failed to handle hsmd_init message: {:?}", e)))?; Ok(h.into()) @@ -505,8 +544,19 @@ impl Signer { Ok(()) } - fn state_signature_mode_label(&self) -> &'static str { - match self.state_signature_mode { + fn current_mode(&self) -> StateSignatureMode { + match *self + .soft_migration + .lock() + .unwrap_or_else(PoisonError::into_inner) + { + Some(_) => StateSignatureMode::Soft, + None => self.state_signature_mode, + } + } + + fn state_signature_mode_label(mode: StateSignatureMode) -> &'static str { + match mode { StateSignatureMode::Off => "off", StateSignatureMode::Soft => "soft", StateSignatureMode::Hard => "hard", @@ -515,9 +565,10 @@ impl Signer { fn inspect_incoming_state_signatures( &self, + mode: StateSignatureMode, entries: &[SignerStateEntry], ) -> Result { - if self.state_signature_mode == StateSignatureMode::Off { + if mode == StateSignatureMode::Off { return Ok(OverrideSignatureUsage::default()); } @@ -526,7 +577,7 @@ impl Signer { for entry in entries.iter() { if entry.signature.is_empty() { - if self.state_signature_mode == StateSignatureMode::Hard { + if mode == StateSignatureMode::Hard { usage.missing_keys.push(entry.key.clone()); if first_error.is_none() { first_error = Some(anyhow!("missing state signature for key {}", entry.key)); @@ -559,7 +610,7 @@ impl Signer { } let message = report::build_state_signature_override_enabled_message( - self.state_signature_mode_label(), + Self::state_signature_mode_label(self.current_mode()), &self.id, self.state_signature_override_note.as_deref(), ); @@ -575,6 +626,7 @@ impl Signer { async fn report_state_signature_override_usage( &self, + mode: StateSignatureMode, req: &HsmRequest, usage: &OverrideSignatureUsage, ) { @@ -583,7 +635,7 @@ impl Signer { } let message = report::build_state_signature_override_used_message( - self.state_signature_mode_label(), + Self::state_signature_mode_label(mode), req.request_id as u64, &usage.missing_keys, &usage.invalid_keys, @@ -795,17 +847,14 @@ impl Signer { msg: &vls_protocol::msgs::Message, reqs: &[model::Request], hsm_context: Option<&HsmRequestContext>, + state: &crate::persist::State, ) -> Result<(), Error> { log::trace!( "Resolving signature request against pending grpc commands: {:?}", reqs ); - let state = self - .state - .lock() - .map_err(|e| Error::Other(anyhow!("Failed to acquire state lock: {:?}", e)))?; - Resolver::try_resolve(msg, reqs, &state, &self.id, hsm_context)?; + Resolver::try_resolve(msg, reqs, state, &self.id, hsm_context)?; Ok(()) } @@ -823,7 +872,7 @@ impl Signer { _ => None, }; let result = self - .process_request_inner(req, msg, decline.is_some()) + .process_request_with_message(req, msg, decline.is_some()) .await; match (result, decline) { (Err(cause), Some(reply)) => Err(Error::PreapprovalDeclined { @@ -834,7 +883,7 @@ impl Signer { } } - async fn process_request_inner( + async fn process_request_with_message( &self, req: HsmRequest, msg: vls_protocol::msgs::Message, @@ -843,15 +892,47 @@ impl Signer { debug!("Processing request {:?}", req); let req = req; - let signature_usage = self.inspect_incoming_state_signatures(&req.signer_state)?; + let mode = self.current_mode(); + let signature_usage = self.inspect_incoming_state_signatures(mode, &req.signer_state)?; if signature_usage.is_used() { - self.report_state_signature_override_usage(&req, &signature_usage) + self.report_state_signature_override_usage(mode, &req, &signature_usage) .await; } let incoming_state = crate::persist::State::try_from(req.signer_state.as_slice()) .map_err(|e| Error::Other(anyhow!("Failed to decode signer state: {e}")))?; + let mut rejections = Vec::new(); + let result = self.process_request_inner( + &req, + msg, + preapproval, + incoming_state, + mode, + &mut rejections, + ); + // No live-state lock is held while reporting to the server. + for msg in rejections { + report::Reporter::report(crate::pb::scheduler::SignerRejection { + msg, + request: Some(req.clone()), + git_version: GITHASH.to_string(), + node_id: self.node_id(), + }) + .await; + } + result + } + + fn process_request_inner( + &self, + req: &HsmRequest, + msg: vls_protocol::msgs::Message, + preapproval: bool, + incoming_state: crate::persist::State, + mode: StateSignatureMode, + rejections: &mut Vec, + ) -> Result { // Create sketch from incoming state (nodelet's view) so we can // send back any entries the nodelet doesn't know about yet, // including the initial VLS state created during Signer::new(). @@ -860,14 +941,19 @@ impl Signer { #[cfg(feature = "backup")] let pre_backup_state; + // Keep snapshot and commit atomic with respect to other signer clones. + // All processing below is synchronous; reporting happens after return. + let mut live_state = self + .state + .lock() + .map_err(|e| Error::Other(anyhow!("Failed to acquire state lock: {:?}", e)))?; + let mut candidate = live_state.clone(); let prestate_log = { - debug!("Updating local signer state with state from node"); - let mut state = self.state.lock().map_err(|e| { - Error::Other(anyhow!("Failed to acquire state lock: {:?}", e)) - })?; - let merge_res = state.merge(&incoming_state).map_err(|e| { - Error::Other(anyhow!("Failed to merge signer state: {:?}", e)) - })?; + debug!("Merging incoming signer state into a scratch copy"); + let state = &mut candidate; + let merge_res = state + .merge(&incoming_state) + .map_err(|e| Error::Other(anyhow!("Failed to merge signer state: {:?}", e)))?; if merge_res.has_conflicts() { debug!( "State merge ignored stale versions (count={})", @@ -885,6 +971,11 @@ impl Signer { prestate_log }; + let persister = Arc::new(crate::persist::MemoryPersister::from_state(candidate)); + let state = persister.state(); + let mut services = self.services.clone(); + services.persister = persister.clone(); + // The first two bytes represent the message type. Check that // it is not a `sign-message` request (type 23). if let &[h, l, ..] = req.raw.as_slice() { @@ -914,17 +1005,17 @@ impl Signer { log::debug!("Handling message {:?}", msg); log::trace!("Signer state {}", prestate_log); - if let Err(e) = self.authenticate_request(&msg, &ctxrequests, req.context.as_ref()) { + let authentication = { + let state = state + .lock() + .map_err(|e| Error::Other(anyhow!("Failed to acquire scratch state lock: {e}")))?; + self.authenticate_request(&msg, &ctxrequests, req.context.as_ref(), &state) + }; + if let Err(e) = authentication { if preapproval { warn!("Preapproval context did not resolve: {e}"); } else { - report::Reporter::report(crate::pb::scheduler::SignerRejection { - msg: e.to_string(), - request: Some(req.clone()), - git_version: GITHASH.to_string(), - node_id: self.node_id(), - }) - .await; + rejections.push(e.to_string()); } #[cfg(not(feature = "permissive"))] return Err(e); @@ -937,8 +1028,7 @@ impl Signer { let pubkey = PublicKey::from_slice(&self.id); match pubkey { Ok(p) => { - let _ = self - .services + let _ = services .persister .update_node_allowlist(&p, vec![gl_config.close_to_addr.clone()]); } @@ -961,7 +1051,7 @@ impl Signer { vls_protocol_signer::approver::NegativeApprover(), ))); approver.approve(approvals); - let root_handler = self.handler_with_approver(approver)?; + let root_handler = self.handler_with_approver(approver, services)?; fee_budget::check_payment_preapproval(&msg, &ctxrequests, self.fee_budget_limits) .map_err(Error::FeeBudget)?; @@ -971,7 +1061,7 @@ impl Signer { if let Err(e) = record_invoice( request, &root_handler.node(), - self.services.persister.as_ref(), + persister.as_ref(), self.services.clock.now().as_secs(), ) { warn!("Skipping payment context: {e:#}"); @@ -1016,13 +1106,7 @@ impl Signer { return Err(Error::Other(anyhow!("preapproving payment: {e:?}"))); } Err(e) => { - report::Reporter::report(crate::pb::scheduler::SignerRejection { - msg: format!("{:?}", e), - request: Some(req.clone()), - git_version: GITHASH.to_string(), - node_id: self.node_id(), - }) - .await; + rejections.push(format!("{:?}", e)); return Err(Error::Other(anyhow!("processing request: {e:?}"))); } }; @@ -1032,7 +1116,7 @@ impl Signer { let signer_state = { debug!("Serializing state changes to report to node"); - let mut state = self.state.lock().map_err(|e| { + let mut state = state.lock().map_err(|e| { Error::Other(anyhow!( "Failed to acquire state lock for serialization: {:?}", e @@ -1064,6 +1148,45 @@ impl Signer { } diff_entries }; + let response = HsmResponse { + raw: response.as_vec(), + request_id: req.request_id, + signer_state, + error: "".to_owned(), + }; + let committed_state = state + .lock() + .map_err(|e| { + Error::Other(anyhow!( + "Failed to acquire scratch state lock for commit: {e}" + )) + })? + .clone(); + if mode == StateSignatureMode::Soft { + // Claim only after all processing and signing succeed. A request + // checked in Soft must claim its own allowance, even if another + // clone completed the migration while it was waiting. + let migration = self + .soft_migration + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .ok_or_else(|| { + Error::Other(anyhow!("Soft state migration has already been claimed")) + })?; + // A failed write may still have persisted the marker. Keep the + // allowance consumed and publish neither state nor signatures. + migration + .store + .save(&migration.key, b"used") + .context("persisting one-time Soft migration marker") + .map_err(Error::Other)?; + } + // The marker is durable before any migrated state or signatures can + // leave this transaction. Rejected requests never publish their state. + *live_state = committed_state; + drop(live_state); + #[cfg(feature = "backup")] { match self.backup_runtime.lock() { @@ -1077,12 +1200,7 @@ impl Signer { } } } - Ok(HsmResponse { - raw: response.as_vec(), - request_id: req.request_id, - signer_state, - error: "".to_owned(), - }) + Ok(response) } pub fn node_id(&self) -> Vec { @@ -1784,6 +1902,7 @@ impl From for crate::pb::scheduler::StartupMessage { #[cfg(test)] mod tests { + use super::device_state::MemoryDeviceStorage; use super::*; use crate::credentials; use crate::pb; @@ -1805,6 +1924,7 @@ mod tests { SignerConfig { state_signature_mode: mode, state_signature_override: None, + device_storage: Some(Arc::new(MemoryDeviceStorage::default())), ..SignerConfig::default() }, ) @@ -1819,6 +1939,7 @@ mod tests { SignerConfig { state_signature_mode: mode, state_signature_override: Some(test_override_config(note)), + device_storage: Some(Arc::new(MemoryDeviceStorage::default())), ..SignerConfig::default() }, ) @@ -1863,6 +1984,520 @@ mod tests { } } + fn heartbeat_request(entries: Vec) -> HsmRequest { + HsmRequest { + request_id: 0, + context: None, + raw: heartbeat_raw(), + signer_state: entries, + requests: vec![], + } + } + + fn signed_config_request(signer: &Signer, address: &str) -> pb::PendingRequest { + use prost::Message; + use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_FIXED_SIGNING}; + + let rng = ring::rand::SystemRandom::new(); + let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng).unwrap(); + let key = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8.as_ref(), &rng) + .unwrap(); + let pubkey = key.public_key().as_ref().to_vec(); + let payload = pb::GlConfig { + close_to_addr: address.to_string(), + } + .encode_to_vec(); + let mut request = vec![0]; + request.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + request.extend_from_slice(&payload); + let signature = key.sign(&rng, &request).unwrap().as_ref().to_vec(); + let restriction = format!("pubkey={}", hex::encode(&pubkey)); + let rune = signer.create_rune(None, vec![vec![&restriction]]).unwrap(); + pb::PendingRequest { + request, + uri: "/greenlight.Node/Configure".to_string(), + pubkey, + signature, + rune: general_purpose::URL_SAFE.decode(rune).unwrap(), + ..Default::default() + } + } + + #[tokio::test] + async fn rejected_messages_discard_unsigned_state_and_do_not_launder_it_later() { + for raw in [ + hex::decode("0017000B48656c6c6f20776f726c64").unwrap(), + vec![], + ] { + let signer = mk_signer(StateSignatureMode::Soft); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let mut req = heartbeat_request(vec![mk_state_entry("state/injected", 1, json!(1))]); + req.raw = raw; + assert!(signer.process_request(req).await.is_err()); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + assert_eq!(signer.current_mode(), StateSignatureMode::Soft); + let response = signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + assert!(response + .signer_state + .iter() + .all(|entry| entry.key != "state/injected")); + assert_eq!(signer.current_mode(), StateSignatureMode::Hard); + } + } + + #[tokio::test] + async fn failed_soft_request_can_retry_the_same_legacy_state_after_restart() { + let store: Arc = Arc::new(MemoryDeviceStorage::default()); + let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + let key = signer + .soft_migration + .lock() + .unwrap() + .as_ref() + .unwrap() + .key + .clone(); + let legacy = mk_state_entry("state/legacy", 1, json!(1)); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let mut req = heartbeat_request(vec![legacy.clone()]); + req.raw = hex::decode("0017000B48656c6c6f20776f726c64").unwrap(); + assert!(signer.process_request(req).await.is_err()); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + assert!(store.load(&key).unwrap().is_none()); + assert_eq!(signer.current_mode(), StateSignatureMode::Soft); + drop(signer); + + let restarted = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + assert_eq!(restarted.current_mode(), StateSignatureMode::Soft); + let response = restarted + .process_request(heartbeat_request(vec![legacy])) + .await + .unwrap(); + let repaired = response + .signer_state + .iter() + .find(|entry| entry.key == "state/legacy") + .unwrap(); + restarted.verify_state_entry_signature(repaired).unwrap(); + assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); + assert_eq!(store.load(&key).unwrap().unwrap(), b"used"); + let next = signer_with_device_storage(store, 0, Network::Bitcoin).unwrap(); + assert_eq!(next.current_mode(), StateSignatureMode::Hard); + } + + #[cfg(not(feature = "permissive"))] + #[tokio::test] + async fn failed_authorization_does_not_commit_incoming_state() { + for mode in [StateSignatureMode::Soft, StateSignatureMode::Hard] { + let signer = mk_signer(mode); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let mut entry = mk_state_entry("state/incoming", 1, json!(1)); + if mode == StateSignatureMode::Hard { + entry.signature = signer + .sign_state_payload(&entry.key, entry.version, &entry.value) + .unwrap(); + } + let mut req = heartbeat_request(vec![entry]); + // HsmdInit has no matching authenticated user command and is not + // among the messages that the resolver accepts without context. + req.raw = Signer::initreq().inner().as_vec(); + assert!(matches!( + signer.process_request(req).await, + Err(Error::Resolver(..)) + )); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + assert_eq!(signer.current_mode(), mode); + } + } + + #[tokio::test] + async fn failed_vls_handler_discards_incoming_state_and_context_updates() { + for mode in [StateSignatureMode::Soft, StateSignatureMode::Hard] { + let signer = mk_signer(mode); + let address = "1BoatSLRHtKNngkdXEeobR76b53LETtpyT"; + let config = signed_config_request(&signer, address); + assert!(signer.check_request_auth(vec![config.clone()])[0].is_ok()); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let mut entry = mk_state_entry("state/incoming", 1, json!(1)); + if mode == StateSignatureMode::Hard { + entry.signature = signer + .sign_state_payload(&entry.key, entry.version, &entry.value) + .unwrap(); + } + let mut req = heartbeat_request(vec![entry]); + req.requests = vec![config.clone()]; + req.raw = vls_protocol::msgs::GetPerCommitmentPoint { + commitment_number: 0, + } + .as_vec(); + req.context = Some(HsmRequestContext { + node_id: signer.node_id(), + dbid: 7, + ..Default::default() + }); + // Authorization allows this message, but VLS cannot load the missing + // channel. The authenticated allowlist update precedes that failure. + let err = signer.process_request(req).await.unwrap_err(); + assert!(err.to_string().contains("processing request:"), "{err}"); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + + assert_eq!(signer.current_mode(), mode); + + let mut valid = heartbeat_request(vec![]); + valid.requests = vec![config]; + let response = signer.process_request(valid).await.unwrap(); + let allowlist = response + .signer_state + .iter() + .find(|entry| entry.key == format!("allowlists/{}", hex::encode(signer.node_id()))) + .unwrap(); + assert_eq!( + serde_json::from_slice::(&allowlist.value).unwrap(), + json!([address]) + ); + signer.verify_state_entry_signature(allowlist).unwrap(); + let committed: Vec = signer.state.lock().unwrap().clone().into(); + assert!(committed.iter().any(|entry| entry.key == allowlist.key)); + assert!(committed.iter().all(|entry| entry.key != "state/incoming")); + assert_eq!(signer.current_mode(), StateSignatureMode::Hard); + } + } + + #[tokio::test] + async fn successful_vls_changes_are_signed_and_committed() { + let signer = mk_signer(StateSignatureMode::Hard); + let mut req = heartbeat_request(vec![]); + req.raw = vls_protocol::msgs::NewChannel { + peer_id: vls_protocol::model::PubKey(signer.node_id().try_into().unwrap()), + dbid: 1, + } + .as_vec(); + let response = signer.process_request(req).await.unwrap(); + let channel = response + .signer_state + .iter() + .find(|entry| entry.key.starts_with("channels/")) + .unwrap(); + signer.verify_state_entry_signature(channel).unwrap(); + let committed: Vec = signer.state.lock().unwrap().clone().into(); + let persisted = committed + .iter() + .find(|entry| entry.key == channel.key) + .unwrap(); + assert_eq!(persisted.value, channel.value); + assert_eq!(persisted.signature, channel.signature); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn successful_requests_on_clones_do_not_lose_each_others_updates() { + let signer = mk_signer(StateSignatureMode::Hard); + let barrier = Arc::new(tokio::sync::Barrier::new(2)); + let spawn = |key: &'static str| { + let signer = signer.clone(); + let barrier = barrier.clone(); + tokio::spawn(async move { + let mut entry = mk_state_entry(key, 1, json!(1)); + entry.signature = signer + .sign_state_payload(&entry.key, entry.version, &entry.value) + .unwrap(); + barrier.wait().await; + signer.process_request(heartbeat_request(vec![entry])).await + }) + }; + let first = spawn("state/a"); + let second = spawn("state/b"); + let (a, b) = tokio::join!(first, second); + a.unwrap().unwrap(); + b.unwrap().unwrap(); + let committed: Vec = signer.state.lock().unwrap().clone().into(); + for key in ["state/a", "state/b"] { + assert!(committed.iter().any(|entry| entry.key == key)); + } + } + + fn signer_with_device_storage( + store: Arc, + secret: u8, + network: Network, + ) -> anyhow::Result { + Signer::new_with_config( + vec![secret; 32], + network, + credentials::Nobody::default(), + SignerConfig { + state_signature_mode: StateSignatureMode::Soft, + device_storage: Some(store), + ..SignerConfig::default() + }, + ) + } + + #[test] + fn hard_is_the_default_and_soft_requires_storage() { + assert_eq!( + SignerConfig::default().state_signature_mode, + StateSignatureMode::Hard + ); + let err = Signer::new_with_config( + vec![0; 32], + Network::Bitcoin, + credentials::Nobody::default(), + SignerConfig { + state_signature_mode: StateSignatureMode::Soft, + ..SignerConfig::default() + }, + ) + .err() + .unwrap(); + assert!(err + .to_string() + .contains("requires persistent device state storage")); + } + + #[tokio::test] + async fn soft_migration_rejects_subsequent_unsigned_additions_updates_and_tombstones() { + let signer = mk_signer(StateSignatureMode::Soft); + let migrated = signer + .process_request(heartbeat_request(vec![mk_state_entry( + "state/test", + 1, + json!(1), + )])) + .await + .unwrap(); + assert_eq!(signer.current_mode(), StateSignatureMode::Hard); + let repaired = migrated + .signer_state + .iter() + .find(|e| e.key == "state/test") + .unwrap(); + signer.verify_state_entry_signature(repaired).unwrap(); + + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + for entry in [ + mk_state_entry("allowlists/injected", 0, json!([])), + mk_state_entry("state/test", 2, json!(2)), + mk_state_entry("state/test", u64::MAX, serde_json::Value::Null), + ] { + let err = signer + .process_request(heartbeat_request(vec![entry])) + .await + .unwrap_err(); + assert!(err.to_string().contains("missing state signature")); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + } + // Signed echoes of the migration result are accepted after the switch. + signer + .process_request(heartbeat_request(migrated.signer_state)) + .await + .unwrap(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn soft_migration_is_shared_across_clones() { + let signer = mk_signer(StateSignatureMode::Soft); + let barrier = Arc::new(tokio::sync::Barrier::new(2)); + let spawn = |key: &'static str| { + let signer = signer.clone(); + let barrier = barrier.clone(); + tokio::spawn(async move { + barrier.wait().await; + signer + .process_request(heartbeat_request(vec![mk_state_entry(key, 1, json!(1))])) + .await + }) + }; + let first = spawn("state/a"); + let second = spawn("state/b"); + let (a, b) = tokio::join!(first, second); + assert_eq!( + usize::from(a.unwrap().is_ok()) + usize::from(b.unwrap().is_ok()), + 1 + ); + } + + #[tokio::test] + async fn soft_migration_is_persisted_and_scoped_by_node_and_network() { + let store: Arc = Arc::new(MemoryDeviceStorage::default()); + let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + drop(signer); + let restarted = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); + assert_eq!(restarted.state_signature_mode, StateSignatureMode::Hard); + assert_eq!( + signer_with_device_storage(store.clone(), 1, Network::Bitcoin) + .unwrap() + .current_mode(), + StateSignatureMode::Soft + ); + assert_eq!( + signer_with_device_storage(store, 0, Network::Regtest) + .unwrap() + .current_mode(), + StateSignatureMode::Soft + ); + } + + #[tokio::test] + async fn malformed_or_invalid_snapshots_do_not_consume_soft_migration() { + let signer = mk_signer(StateSignatureMode::Soft); + let mut malformed = mk_state_entry("state/test", 1, json!(1)); + malformed.value = b"{".to_vec(); + let mut invalid = mk_state_entry("state/test", 1, json!(1)); + invalid.signature = vec![1; COMPACT_SIGNATURE_LEN]; + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + for entry in [malformed, invalid] { + assert!(signer + .process_request(heartbeat_request(vec![entry])) + .await + .is_err()); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + assert_eq!(signer.current_mode(), StateSignatureMode::Soft); + } + signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + } + + #[tokio::test] + async fn default_hard_signer_signs_its_own_initial_state_without_device_storage() { + let signer = Signer::new( + vec![0; 32], + Network::Bitcoin, + credentials::Nobody::default(), + ) + .unwrap(); + let response = signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + assert!(!response.signer_state.is_empty()); + for entry in response.signer_state { + signer.verify_state_entry_signature(&entry).unwrap(); + } + } + + #[tokio::test] + async fn any_soft_migration_marker_value_starts_in_hard() { + for bytes in [b"".as_slice(), b"{".as_slice(), b"used".as_slice()] { + let store: Arc = Arc::new(MemoryDeviceStorage::default()); + let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + let key = signer + .soft_migration + .lock() + .unwrap() + .as_ref() + .unwrap() + .key + .clone(); + store.save(&key, bytes).unwrap(); + drop(signer); + let restarted = signer_with_device_storage(store, 0, Network::Bitcoin).unwrap(); + let err = restarted + .process_request(heartbeat_request(vec![mk_state_entry( + "state/injected", + 0, + json!(1), + )])) + .await + .unwrap_err(); + assert!(err.to_string().contains("missing state signature")); + } + } + + #[derive(Debug)] + struct FailingDeviceStorage { + fail_load: bool, + // Some filesystems can report an error after the new bytes are written. + saved: Mutex>>, + } + + impl DeviceStorage for FailingDeviceStorage { + fn load(&self, _: &str) -> anyhow::Result>> { + if self.fail_load { + return Err(anyhow!("device storage unavailable")); + } + Ok(self.saved.lock().unwrap().clone()) + } + + fn save(&self, _: &str, value: &[u8]) -> anyhow::Result<()> { + *self.saved.lock().unwrap() = Some(value.to_vec()); + Err(anyhow!("device storage sync failed")) + } + } + + #[tokio::test] + async fn storage_failures_never_merge_unsigned_state_or_reopen_a_spent_migration() { + let unavailable: Arc = Arc::new(FailingDeviceStorage { + fail_load: true, + saved: Mutex::new(None), + }); + assert!(signer_with_device_storage(unavailable, 0, Network::Bitcoin).is_err()); + + let store: Arc = Arc::new(FailingDeviceStorage { + fail_load: false, + saved: Mutex::new(None), + }); + let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let mut req = heartbeat_request(vec![mk_state_entry("state/legacy", 1, json!(1))]); + req.raw = vls_protocol::msgs::NewChannel { + peer_id: vls_protocol::model::PubKey(signer.node_id().try_into().unwrap()), + dbid: 1, + } + .as_vec(); + let err = signer.process_request(req).await.unwrap_err(); + assert_eq!(signer.current_mode(), StateSignatureMode::Hard); + assert!(err + .to_string() + .contains("persisting one-time Soft migration marker")); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + let err = signer + .process_request(heartbeat_request(vec![mk_state_entry( + "state/injected", + 0, + json!(1), + )])) + .await + .unwrap_err(); + assert!(err.to_string().contains("missing state signature")); + let restarted = signer_with_device_storage(store, 0, Network::Bitcoin).unwrap(); + assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); + } + #[cfg(feature = "backup")] #[test] fn periodic_backup_rejects_zero_updates() { From 340fab9c7ae084f09a1aab6c81ecd6b1d055f035 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Tue, 17 Nov 2026 20:43:59 +0200 Subject: [PATCH 3/4] signer: Expose migration configuration in Python and SDK Allow Python and UniFFI SDK callers to opt into Soft mode with a persistent device storage directory. Keep Hard as the default and preserve signer configuration through authentication and NodeBuilder creation paths. Share FileDeviceStorage through the optional gl-client file-storage feature. Update generated Python and Swift bindings and document the migration APIs. --- Cargo.lock | 2 +- docs/src/reference/signer-state.md | 54 ++++- libs/gl-cli/Cargo.toml | 7 +- libs/gl-cli/src/lib.rs | 1 - libs/gl-cli/src/signer.rs | 8 +- libs/gl-client-py/CHANGELOG.md | 4 + libs/gl-client-py/Cargo.toml | 1 + libs/gl-client-py/glclient/__init__.py | 24 +- libs/gl-client-py/glclient/glclient.pyi | 10 +- libs/gl-client-py/src/signer.rs | 49 +++- libs/gl-client-py/tests/test_signer_config.py | 68 ++++++ libs/gl-client/CHANGELOG.md | 1 + libs/gl-client/Cargo.toml | 1 + libs/gl-client/src/signer/device_state.rs | 5 + .../src/signer/device_state/file.rs} | 9 +- libs/gl-client/src/signer/mod.rs | 2 + libs/gl-sdk/CHANGELOG.md | 5 + libs/gl-sdk/Cargo.toml | 5 +- libs/gl-sdk/bindings/glsdk.swift | 225 +++++++++++++++++- libs/gl-sdk/bindings/glsdkFFI.h | 33 +++ libs/gl-sdk/glsdk/glsdk.py | 198 ++++++++++++++- libs/gl-sdk/src/config.rs | 50 +++- libs/gl-sdk/src/lib.rs | 15 +- libs/gl-sdk/src/signer.rs | 27 ++- libs/gl-sdk/src/signer_config.rs | 124 ++++++++++ libs/gl-sdk/tests/test_signer_config.py | 64 +++++ 26 files changed, 931 insertions(+), 61 deletions(-) create mode 100644 libs/gl-client-py/tests/test_signer_config.py rename libs/{gl-cli/src/device_state.rs => gl-client/src/signer/device_state/file.rs} (93%) create mode 100644 libs/gl-sdk/src/signer_config.rs create mode 100644 libs/gl-sdk/tests/test_signer_config.py diff --git a/Cargo.lock b/Cargo.lock index 8ac429333..4d5a5f25e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1452,7 +1452,6 @@ checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" name = "gl-cli" version = "0.1.3" dependencies = [ - "anyhow", "bip39", "clap", "dirs", @@ -1607,6 +1606,7 @@ dependencies = [ "once_cell", "serde", "serde_json", + "tempfile", "thiserror 2.0.18", "tokio", "tonic", diff --git a/docs/src/reference/signer-state.md b/docs/src/reference/signer-state.md index 565bdcb37..e20c1e509 100644 --- a/docs/src/reference/signer-state.md +++ b/docs/src/reference/signer-state.md @@ -158,16 +158,44 @@ Storage errors prevent the migration from publishing state or signatures. If writing the marker fails, the current signer switches to Hard because the failed write may still have persisted the marker. -For explicit Soft mode, `glcli` supplies a file-backed store under -`/device-state`. To migrate a legacy node once: +The optional `file-storage` feature provides `FileDeviceStorage` for Rust. +Python and gl-sdk accept a persistent directory in the application's data +directory; `glcli` uses `/device-state`. -```bash -glcli signer run --state-signature-mode soft -``` +=== "glcli" + + ```bash + glcli signer run --state-signature-mode soft + ``` + +=== "Python" + + ```python + signer = glclient.Signer( + seed, network, creds, + state_signature_mode="soft", + device_storage_path="/path/to/app/device-state", + ) + ``` + +=== "gl-sdk (Python)" + + ```python + migration = glsdk.SignerConfig( + state_signature_mode=glsdk.StateSignatureMode.SOFT, + device_storage_path="/path/to/app/device-state", + ) + config = glsdk.Config().with_signer_config(migration) + node = glsdk.NodeBuilder(config).connect(credentials, mnemonic) + ``` + + Standalone signers use `Signer.new_with_config(mnemonic, migration)` + or `Signer.new_from_seed_with_config(seed, migration)`. Authenticating + a signer preserves its migration configuration and storage. -Afterward, rerunning with `soft` logs a warning and uses Hard mode. -Running without the flag also uses Hard. The Rust, Python and SDK -constructors use Hard by default; Hard does not require a device store. +After a successful migration, reusing the Soft configuration logs a +warning and uses Hard mode. The Rust, Python and SDK constructors use +Hard by default; Hard does not require a device store. The migration deliberately trusts the unsigned snapshot it migrates. If the process crashes or the connection drops after saving the marker but @@ -251,14 +279,14 @@ persistent storage, not secret storage. #### Storing the anchor -`gl-client` itself does not access the filesystem, so that the signer -can also run in environments without one, such as a hardware security -module. It defines a storage interface for the anchor instead, and the -higher-level libraries provide implementations: +The core signer operates through a storage interface, so it can also run +in environments without a filesystem, such as a hardware security module. +The optional `file-storage` feature supplies a file backend shared by the +higher-level libraries: | Library | Anchor storage | |---------|----------------| -| `gl-client` (Rust) | Storage interface only; bring your own implementation | +| `gl-client` (Rust) | Storage interface, with an optional file backend | | `gl-sdk` | File-backed, configured with a path in the application's data directory | | `gl-client-py`, `glcli` | File-backed, configured with a path | | `gl-testing` | In memory | diff --git a/libs/gl-cli/Cargo.toml b/libs/gl-cli/Cargo.toml index 5e96be767..0a25fa888 100644 --- a/libs/gl-cli/Cargo.toml +++ b/libs/gl-cli/Cargo.toml @@ -21,20 +21,21 @@ test = true doc = true [dependencies] -anyhow.workspace = true bip39 = { version = "2.2", features = ["rand"] } clap = { version = "4.5", features = ["derive"] } dirs = "6.0" env_logger = "0.11" futures = "0.3" -gl-client = { version = "0.7", path = "../gl-client", features = ["backup"] } +gl-client = { version = "0.7", path = "../gl-client", features = ["backup", "file-storage"] } hex = "0.4" serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2.0.11" tokio = "1.43.0" -tempfile = "3.10.1" vls-core.workspace = true +[dev-dependencies] +tempfile = "3.10.1" + [badges] maintenance = { status = "actively-developed" } diff --git a/libs/gl-cli/src/lib.rs b/libs/gl-cli/src/lib.rs index 34b476271..ddbe5b01b 100644 --- a/libs/gl-cli/src/lib.rs +++ b/libs/gl-cli/src/lib.rs @@ -2,7 +2,6 @@ use crate::error::Result; use clap::{Parser, Subcommand}; use gl_client::bitcoin::Network; use std::{path::PathBuf, str::FromStr}; -mod device_state; mod error; mod json_hex; pub mod model; diff --git a/libs/gl-cli/src/signer.rs b/libs/gl-cli/src/signer.rs index d4df59923..5118368b5 100644 --- a/libs/gl-cli/src/signer.rs +++ b/libs/gl-cli/src/signer.rs @@ -3,9 +3,9 @@ use crate::util; use clap::{Subcommand, ValueEnum}; use core::fmt::Debug; use gl_client::signer::{ - CLNBackup, CLNBackupOptions, DeviceStorage, FeeBudgetLimits, RecoverableChannel, Signer, SignerBackupConfig, - SignerBackupSnapshot, SignerBackupStrategy, SignerConfig, StateSignatureMode, - StateSignatureOverrideConfig, + CLNBackup, CLNBackupOptions, DeviceStorage, FeeBudgetLimits, FileDeviceStorage, RecoverableChannel, + Signer, SignerBackupConfig, SignerBackupSnapshot, SignerBackupStrategy, SignerConfig, + StateSignatureMode, StateSignatureOverrideConfig, }; use lightning_signer::bitcoin::Network; use serde::Serialize; @@ -389,7 +389,7 @@ async fn run_handler>( let backup = backup_config_from_args(backup_path, backup_strategy, backup_periodic_updates)?; let device_storage: Option> = match state_signature_mode { StateSignatureModeArg::Soft => Some(Arc::new( - crate::device_state::FileDeviceStorage::new( + FileDeviceStorage::new( config.data_dir.as_ref().join("device-state"), ) .map_err(|e| Error::custom(format!("Failed to open device state storage: {e:#}")))?, diff --git a/libs/gl-client-py/CHANGELOG.md b/libs/gl-client-py/CHANGELOG.md index d6514b644..2a1022db9 100644 --- a/libs/gl-client-py/CHANGELOG.md +++ b/libs/gl-client-py/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## Unreleased +### Added + +- Optional `state_signature_mode` and `device_storage_path` keyword arguments for `Signer`, allowing explicit one-time Soft migration with persistent storage. Existing constructors continue to use Hard by default. + ## [0.4.0] - 2026-10-12 ### Changed diff --git a/libs/gl-client-py/Cargo.toml b/libs/gl-client-py/Cargo.toml index 11776bb44..0b5ebadb4 100644 --- a/libs/gl-client-py/Cargo.toml +++ b/libs/gl-client-py/Cargo.toml @@ -17,6 +17,7 @@ bytes = "1.6" env_logger = { workspace = true } gl-client = { path = "../gl-client", default-features = false, features = [ "export", + "file-storage", ] } hex = "*" log = "*" diff --git a/libs/gl-client-py/glclient/__init__.py b/libs/gl-client-py/glclient/__init__.py index a3b72eefc..578603223 100644 --- a/libs/gl-client-py/glclient/__init__.py +++ b/libs/gl-client-py/glclient/__init__.py @@ -27,8 +27,28 @@ def _convert(cls: Type[E], res: Iterable[Any]) -> E: class Signer(object): - def __init__(self, secret: bytes, network: str, creds: Credentials): - self.inner = native.Signer(secret, network, creds) + """Signer using Hard state verification by default. + + Explicit Soft mode migrates legacy state once using the persistent + directory supplied by ``device_storage_path``. + """ + + def __init__( + self, + secret: bytes, + network: str, + creds: Credentials, + *, + state_signature_mode: str = "hard", + device_storage_path: Optional[str] = None, + ): + self.inner = native.Signer( + secret, + network, + creds, + state_signature_mode=state_signature_mode, + device_storage_path=device_storage_path, + ) self.creds = creds self.handle: Optional[native.SignerHandle] = None diff --git a/libs/gl-client-py/glclient/glclient.pyi b/libs/gl-client-py/glclient/glclient.pyi index c4b1ab5eb..ec9f5db5b 100644 --- a/libs/gl-client-py/glclient/glclient.pyi +++ b/libs/gl-client-py/glclient/glclient.pyi @@ -35,7 +35,15 @@ class SignerHandle: def shutdown(self) -> None: ... class Signer: - def __init__(self, secret: bytes, network: str, creds: Credentials): ... + def __init__( + self, + secret: bytes, + network: str, + creds: Credentials, + *, + state_signature_mode: str = "hard", + device_storage_path: Optional[str] = None, + ): ... def sign_challenge(self, challenge: bytes) -> bytes: ... def run_in_thread(self) -> SignerHandle: ... def run_in_foreground(self) -> None: ... diff --git a/libs/gl-client-py/src/signer.rs b/libs/gl-client-py/src/signer.rs index 9aa7920ed..8d5ebd41e 100644 --- a/libs/gl-client-py/src/signer.rs +++ b/libs/gl-client-py/src/signer.rs @@ -1,7 +1,9 @@ use crate::credentials::Credentials; use gl_client::bitcoin::Network; +use gl_client::signer::{DeviceStorage, FileDeviceStorage, SignerConfig, StateSignatureMode}; use log::warn; use pyo3::{exceptions::PyValueError, prelude::*}; +use std::sync::Arc; use tokio::sync::mpsc; #[pyclass] @@ -13,7 +15,14 @@ pub struct Signer { #[pymethods] impl Signer { #[new] - fn new(secret: Vec, network: String, creds: Credentials) -> PyResult { + #[pyo3(signature = (secret, network, creds, *, state_signature_mode="hard", device_storage_path=None))] + fn new( + secret: Vec, + network: String, + creds: Credentials, + state_signature_mode: &str, + device_storage_path: Option, + ) -> PyResult { let network: Network = match network.parse() { Ok(network) => network, Err(_) => { @@ -24,11 +33,45 @@ impl Signer { } }; - let inner = match gl_client::signer::Signer::new(secret, network, creds.inner) { + let state_signature_mode = match state_signature_mode { + "hard" => StateSignatureMode::Hard, + "soft" => StateSignatureMode::Soft, + "off" => StateSignatureMode::Off, + other => { + return Err(PyValueError::new_err(format!( + "Unknown state signature mode {other}: expected hard, soft or off" + ))) + } + }; + let device_storage: Option> = match state_signature_mode { + StateSignatureMode::Soft => { + let path = device_storage_path + .as_deref() + .filter(|path| !path.is_empty()) + .ok_or_else(|| { + PyValueError::new_err("Soft mode requires device_storage_path") + })?; + Some(Arc::new(FileDeviceStorage::new(path).map_err(|e| { + PyValueError::new_err(format!("opening device storage: {e:#}")) + })?)) + } + _ => None, + }; + let config = SignerConfig { + state_signature_mode, + device_storage, + ..Default::default() + }; + let inner = match gl_client::signer::Signer::new_with_config( + secret, + network, + creds.inner, + config, + ) { Ok(v) => v, Err(e) => { return Err(pyo3::exceptions::PyValueError::new_err(format!( - "Error initializing Signer: {}", + "Error initializing Signer: {:#}", e ))) } diff --git a/libs/gl-client-py/tests/test_signer_config.py b/libs/gl-client-py/tests/test_signer_config.py new file mode 100644 index 000000000..64b69eff3 --- /dev/null +++ b/libs/gl-client-py/tests/test_signer_config.py @@ -0,0 +1,68 @@ +import pytest + +import glclient +from glclient import native + + +@pytest.mark.parametrize("constructor", [glclient.Signer, native.Signer]) +def test_hard_default_does_not_open_device_storage(constructor, tmp_path): + path = tmp_path / "not-a-directory" + path.write_text("unused") + signer = constructor( + b"\x00" * 32, + "regtest", + glclient.Credentials(), + device_storage_path=str(path), + ) + assert len(bytes(signer.node_id())) == 33 + + +@pytest.mark.parametrize("constructor", [glclient.Signer, native.Signer]) +@pytest.mark.parametrize("path", [None, ""]) +def test_soft_requires_device_storage(constructor, path): + with pytest.raises(ValueError, match="requires device_storage_path"): + constructor( + b"\x00" * 32, + "regtest", + glclient.Credentials(), + state_signature_mode="soft", + device_storage_path=path, + ) + + +@pytest.mark.parametrize("constructor", [glclient.Signer, native.Signer]) +def test_soft_opens_persistent_storage(constructor, tmp_path): + path = tmp_path / "device-state" + for _ in range(2): + signer = constructor( + b"\x00" * 32, + "regtest", + glclient.Credentials(), + state_signature_mode="soft", + device_storage_path=str(path), + ) + assert len(bytes(signer.node_id())) == 33 + assert path.is_dir() + + +def test_unknown_state_signature_mode_is_rejected(): + with pytest.raises(ValueError, match="Unknown state signature mode"): + glclient.Signer( + b"\x00" * 32, + "regtest", + glclient.Credentials(), + state_signature_mode="typo", + ) + + +def test_storage_errors_reach_python(tmp_path): + path = tmp_path / "not-a-directory" + path.write_text("unavailable") + with pytest.raises(ValueError, match="opening device storage"): + glclient.Signer( + b"\x00" * 32, + "regtest", + glclient.Credentials(), + state_signature_mode="soft", + device_storage_path=str(path), + ) diff --git a/libs/gl-client/CHANGELOG.md b/libs/gl-client/CHANGELOG.md index 3e9aa0220..79e3850d0 100644 --- a/libs/gl-client/CHANGELOG.md +++ b/libs/gl-client/CHANGELOG.md @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Configure routing and on-chain fee limits with `FeeBudgetLimits` through `SignerConfig::fee_budget_limits`. See [signer fee budgets](../../docs/src/reference/signer-fees.md) for configuration, defaults, and limitations. - `DeviceStorage` and `SignerConfig::device_storage` for device-local signer metadata, scoped by node and network. +- Reusable `FileDeviceStorage`, available through the optional `file-storage` feature and shared by the CLI and language bindings. ### Changed diff --git a/libs/gl-client/Cargo.toml b/libs/gl-client/Cargo.toml index b7f51a964..f02ab8ee6 100644 --- a/libs/gl-client/Cargo.toml +++ b/libs/gl-client/Cargo.toml @@ -15,6 +15,7 @@ default = ["permissive", "export"] permissive = [] export = ["chacha20poly1305", "secp256k1"] backup = [] +file-storage = [] experimental-splicing = [] [dependencies] diff --git a/libs/gl-client/src/signer/device_state.rs b/libs/gl-client/src/signer/device_state.rs index 851189f1c..6443883a3 100644 --- a/libs/gl-client/src/signer/device_state.rs +++ b/libs/gl-client/src/signer/device_state.rs @@ -3,6 +3,11 @@ use anyhow::Result; use std::fmt::Debug; +#[cfg(feature = "file-storage")] +mod file; +#[cfg(feature = "file-storage")] +pub use file::FileDeviceStorage; + /// Device-local storage for opaque signer metadata. /// /// Keys are logical identifiers, not filesystem paths. The signer namespaces diff --git a/libs/gl-cli/src/device_state.rs b/libs/gl-client/src/signer/device_state/file.rs similarity index 93% rename from libs/gl-cli/src/device_state.rs rename to libs/gl-client/src/signer/device_state/file.rs index 28c1f356d..61678c416 100644 --- a/libs/gl-cli/src/device_state.rs +++ b/libs/gl-client/src/signer/device_state/file.rs @@ -1,18 +1,19 @@ +use super::DeviceStorage; +use crate::bitcoin::hashes::{sha256, Hash}; use anyhow::{Context, Result}; -use gl_client::bitcoin::hashes::{sha256, Hash}; -use gl_client::signer::DeviceStorage; use std::fs::{self, File}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; /// A file-backed device store using durable, atomic replacement. #[derive(Debug)] -pub(crate) struct FileDeviceStorage { +pub struct FileDeviceStorage { dir: PathBuf, } impl FileDeviceStorage { - pub(crate) fn new(dir: impl AsRef) -> Result { + /// Open directory-backed storage, creating the directory when needed. + pub fn new(dir: impl AsRef) -> Result { let dir = dir.as_ref().to_owned(); fs::create_dir_all(&dir) .with_context(|| format!("creating device state directory {}", dir.display()))?; diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 3613e9cf6..74bf6d63f 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -53,6 +53,8 @@ mod approver; mod auth; mod device_state; pub use device_state::DeviceStorage; +#[cfg(feature = "file-storage")] +pub use device_state::FileDeviceStorage; #[cfg(feature = "backup")] mod backup; #[cfg(feature = "backup")] diff --git a/libs/gl-sdk/CHANGELOG.md b/libs/gl-sdk/CHANGELOG.md index 911cb7554..d387c7f9d 100644 --- a/libs/gl-sdk/CHANGELOG.md +++ b/libs/gl-sdk/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## Unreleased +### Added + +- `SignerConfig`, `StateSignatureMode`, and `Config.with_signer_config()` to configure state verification and persistent migration storage for all signers started by `NodeBuilder`. +- `Signer.new_with_config()` and `Signer.new_from_seed_with_config()` for standalone signers. Authentication preserves the configuration; existing constructors continue to use Hard by default. + ### Changed - `Node.send` and `Node.lnurl_pay` set CLN's `maxfee` to the larger of 1,000 sat and 0.5% of the payment principal, matching the signer's default routing policy for fixed and amountless invoices. diff --git a/libs/gl-sdk/Cargo.toml b/libs/gl-sdk/Cargo.toml index b2456db3c..0cb8f998a 100644 --- a/libs/gl-sdk/Cargo.toml +++ b/libs/gl-sdk/Cargo.toml @@ -17,7 +17,7 @@ name = "glsdk" anyhow = "1" bip39 = "2.2.0" bitcoin = { version = "0.32", features = ["base64"] } -gl-client = { version = "0.7.0", path = "../gl-client" } +gl-client = { version = "0.7.0", path = "../gl-client", features = ["file-storage"] } hex = "0.4" log = "0.4" lightning-invoice = "0.34" @@ -33,3 +33,6 @@ url = "2" [build-dependencies] uniffi = { version = "0.29.4", features = [ "build" ] } + +[dev-dependencies] +tempfile = "3.10.1" diff --git a/libs/gl-sdk/bindings/glsdk.swift b/libs/gl-sdk/bindings/glsdk.swift index b10a33f9c..b73cc5352 100644 --- a/libs/gl-sdk/bindings/glsdk.swift +++ b/libs/gl-sdk/bindings/glsdk.swift @@ -550,6 +550,11 @@ public protocol ConfigProtocol: AnyObject, Sendable { */ func withNetwork(network: Network) -> Config + /** + * Configure all signers started by NodeBuilder with this Config. + */ + func withSignerConfig(signerConfig: SignerConfig) -> Config + } open class Config: ConfigProtocol, @unchecked Sendable { fileprivate let pointer: UnsafeMutableRawPointer! @@ -636,6 +641,17 @@ open func withNetwork(network: Network) -> Config { }) } + /** + * Configure all signers started by NodeBuilder with this Config. + */ +open func withSignerConfig(signerConfig: SignerConfig) -> Config { + return try! FfiConverterTypeConfig_lift(try! rustCall() { + uniffi_glsdk_fn_method_config_with_signer_config(self.uniffiClonePointer(), + FfiConverterTypeSignerConfig_lower(signerConfig),$0 + ) +}) +} + } @@ -2335,8 +2351,12 @@ public protocol SchedulerProtocol: AnyObject, Sendable { * before it creates a node. It needs no credentials, and the * `node_id` is passed explicitly. * - * The answer is advisory and may change over time. Treat an - * error as "unknown" rather than as a negative answer. + * The answer is monotonic: once the node has been registered + * it is reported as available, and stays available regardless + * of the node's status or the provider's current capacity. + * Before registration the answer is advisory and may change + * over time. Treat an error as "unknown" rather than as a + * negative answer. */ func lightningAvailable(nodeId: Data) throws -> Bool @@ -2434,8 +2454,12 @@ public convenience init(network: Network)throws { * before it creates a node. It needs no credentials, and the * `node_id` is passed explicitly. * - * The answer is advisory and may change over time. Treat an - * error as "unknown" rather than as a negative answer. + * The answer is monotonic: once the node has been registered + * it is reported as available, and stays available regardless + * of the node's status or the provider's current capacity. + * Before registration the answer is advisory and may change + * over time. Treat an error as "unknown" rather than as a + * negative answer. */ open func lightningAvailable(nodeId: Data)throws -> Bool { return try FfiConverterBool.lift(try rustCallWithError(FfiConverterTypeError_lift) { @@ -2611,6 +2635,24 @@ public static func newFromSeed(seed: Data)throws -> Signer { }) } +public static func newFromSeedWithConfig(seed: Data, config: SignerConfig)throws -> Signer { + return try FfiConverterTypeSigner_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_signer_new_from_seed_with_config( + FfiConverterData.lower(seed), + FfiConverterTypeSignerConfig_lower(config),$0 + ) +}) +} + +public static func newWithConfig(phrase: String, config: SignerConfig)throws -> Signer { + return try FfiConverterTypeSigner_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_signer_new_with_config( + FfiConverterString.lower(phrase), + FfiConverterTypeSignerConfig_lower(config),$0 + ) +}) +} + open func authenticate(creds: Credentials)throws -> Signer { @@ -6881,6 +6923,87 @@ public func FfiConverterTypeSendResponse_lower(_ value: SendResponse) -> RustBuf return FfiConverterTypeSendResponse.lower(value) } + +/** + * State verification and storage settings for SDK signers. + */ +public struct SignerConfig { + public var stateSignatureMode: StateSignatureMode + /** + * Persistent directory for the migration marker; required in Soft mode. + * Hard and Off modes do not open this directory. + */ + public var deviceStoragePath: String? + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(stateSignatureMode: StateSignatureMode, + /** + * Persistent directory for the migration marker; required in Soft mode. + * Hard and Off modes do not open this directory. + */deviceStoragePath: String?) { + self.stateSignatureMode = stateSignatureMode + self.deviceStoragePath = deviceStoragePath + } +} + +#if compiler(>=6) +extension SignerConfig: Sendable {} +#endif + + +extension SignerConfig: Equatable, Hashable { + public static func ==(lhs: SignerConfig, rhs: SignerConfig) -> Bool { + if lhs.stateSignatureMode != rhs.stateSignatureMode { + return false + } + if lhs.deviceStoragePath != rhs.deviceStoragePath { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(stateSignatureMode) + hasher.combine(deviceStoragePath) + } +} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeSignerConfig: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SignerConfig { + return + try SignerConfig( + stateSignatureMode: FfiConverterTypeStateSignatureMode.read(from: &buf), + deviceStoragePath: FfiConverterOptionString.read(from: &buf) + ) + } + + public static func write(_ value: SignerConfig, into buf: inout [UInt8]) { + FfiConverterTypeStateSignatureMode.write(value.stateSignatureMode, into: &buf) + FfiConverterOptionString.write(value.deviceStoragePath, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSignerConfig_lift(_ buf: RustBuffer) throws -> SignerConfig { + return try FfiConverterTypeSignerConfig.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSignerConfig_lower(_ value: SignerConfig) -> RustBuffer { + return FfiConverterTypeSignerConfig.lower(value) +} + // Note that we don't yet support `indirect` for enums. // See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. /** @@ -8602,6 +8725,89 @@ extension ResolvedInput: Equatable, Hashable {} +// Note that we don't yet support `indirect` for enums. +// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. + +public enum StateSignatureMode { + + /** + * Disable signature checks for development and testing only. + */ + case off + /** + * Allow one successful migration, then use Hard mode. + */ + case soft + case hard +} + + +#if compiler(>=6) +extension StateSignatureMode: Sendable {} +#endif + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeStateSignatureMode: FfiConverterRustBuffer { + typealias SwiftType = StateSignatureMode + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> StateSignatureMode { + let variant: Int32 = try readInt(&buf) + switch variant { + + case 1: return .off + + case 2: return .soft + + case 3: return .hard + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: StateSignatureMode, into buf: inout [UInt8]) { + switch value { + + + case .off: + writeInt(&buf, Int32(1)) + + + case .soft: + writeInt(&buf, Int32(2)) + + + case .hard: + writeInt(&buf, Int32(3)) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeStateSignatureMode_lift(_ buf: RustBuffer) throws -> StateSignatureMode { + return try FfiConverterTypeStateSignatureMode.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeStateSignatureMode_lower(_ value: StateSignatureMode) -> RustBuffer { + return FfiConverterTypeStateSignatureMode.lower(value) +} + + +extension StateSignatureMode: Equatable, Hashable {} + + + + + + // Note that we don't yet support `indirect` for enums. // See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. /** @@ -9627,6 +9833,9 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_method_config_with_network() != 35643) { return InitializationResult.apiChecksumMismatch } + if (uniffi_glsdk_checksum_method_config_with_signer_config() != 6578) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_glsdk_checksum_method_credentials_node_id() != 16312) { return InitializationResult.apiChecksumMismatch } @@ -9720,7 +9929,7 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_method_nodeeventstream_next() != 12635) { return InitializationResult.apiChecksumMismatch } - if (uniffi_glsdk_checksum_method_scheduler_lightning_available() != 7327) { + if (uniffi_glsdk_checksum_method_scheduler_lightning_available() != 8721) { return InitializationResult.apiChecksumMismatch } if (uniffi_glsdk_checksum_method_scheduler_recover() != 55514) { @@ -9762,6 +9971,12 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 6776) { return InitializationResult.apiChecksumMismatch } + if (uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config() != 11623) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_glsdk_checksum_constructor_signer_new_with_config() != 4613) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_glsdk_checksum_method_loglistener_on_log() != 34844) { return InitializationResult.apiChecksumMismatch } diff --git a/libs/gl-sdk/bindings/glsdkFFI.h b/libs/gl-sdk/bindings/glsdkFFI.h index 327e93234..5f1d98764 100644 --- a/libs/gl-sdk/bindings/glsdkFFI.h +++ b/libs/gl-sdk/bindings/glsdkFFI.h @@ -307,6 +307,11 @@ void*_Nonnull uniffi_glsdk_fn_method_config_with_developer_cert(void*_Nonnull pt void*_Nonnull uniffi_glsdk_fn_method_config_with_network(void*_Nonnull ptr, RustBuffer network, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_CONFIG_WITH_SIGNER_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_CONFIG_WITH_SIGNER_CONFIG +void*_Nonnull uniffi_glsdk_fn_method_config_with_signer_config(void*_Nonnull ptr, RustBuffer signer_config, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_CREDENTIALS #define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_CREDENTIALS void*_Nonnull uniffi_glsdk_fn_clone_credentials(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status @@ -592,6 +597,16 @@ void*_Nonnull uniffi_glsdk_fn_constructor_signer_new(RustBuffer phrase, RustCall void*_Nonnull uniffi_glsdk_fn_constructor_signer_new_from_seed(RustBuffer seed, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_FROM_SEED_WITH_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_FROM_SEED_WITH_CONFIG +void*_Nonnull uniffi_glsdk_fn_constructor_signer_new_from_seed_with_config(RustBuffer seed, RustBuffer config, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_WITH_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_WITH_CONFIG +void*_Nonnull uniffi_glsdk_fn_constructor_signer_new_with_config(RustBuffer phrase, RustBuffer config, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_AUTHENTICATE #define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_AUTHENTICATE void*_Nonnull uniffi_glsdk_fn_method_signer_authenticate(void*_Nonnull ptr, void*_Nonnull creds, RustCallStatus *_Nonnull out_status @@ -951,6 +966,12 @@ uint16_t uniffi_glsdk_checksum_method_config_with_developer_cert(void #define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CONFIG_WITH_NETWORK uint16_t uniffi_glsdk_checksum_method_config_with_network(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CONFIG_WITH_SIGNER_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CONFIG_WITH_SIGNER_CONFIG +uint16_t uniffi_glsdk_checksum_method_config_with_signer_config(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CREDENTIALS_NODE_ID @@ -1221,6 +1242,18 @@ uint16_t uniffi_glsdk_checksum_constructor_signer_new(void #define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW_FROM_SEED uint16_t uniffi_glsdk_checksum_constructor_signer_new_from_seed(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW_FROM_SEED_WITH_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW_FROM_SEED_WITH_CONFIG +uint16_t uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW_WITH_CONFIG +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW_WITH_CONFIG +uint16_t uniffi_glsdk_checksum_constructor_signer_new_with_config(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_LOGLISTENER_ON_LOG diff --git a/libs/gl-sdk/glsdk/glsdk.py b/libs/gl-sdk/glsdk/glsdk.py index 86b90b14e..014bbc6f1 100644 --- a/libs/gl-sdk/glsdk/glsdk.py +++ b/libs/gl-sdk/glsdk/glsdk.py @@ -472,6 +472,8 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_config_with_network() != 35643: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_config_with_signer_config() != 6578: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_credentials_node_id() != 16312: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_credentials_save() != 26677: @@ -534,7 +536,7 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_nodeeventstream_next() != 12635: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_scheduler_lightning_available() != 7327: + if lib.uniffi_glsdk_checksum_method_scheduler_lightning_available() != 8721: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_scheduler_recover() != 55514: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -562,6 +564,10 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 6776: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config() != 11623: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_signer_new_with_config() != 4613: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_loglistener_on_log() != 34844: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_nodeeventlistener_on_event() != 17790: @@ -714,6 +720,12 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_method_config_with_network.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_config_with_signer_config.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_config_with_signer_config.restype = ctypes.c_void_p _UniffiLib.uniffi_glsdk_fn_clone_credentials.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -1041,6 +1053,18 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_constructor_signer_new_from_seed.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_from_seed_with_config.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_from_seed_with_config.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_with_config.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_with_config.restype = ctypes.c_void_p _UniffiLib.uniffi_glsdk_fn_method_signer_authenticate.argtypes = ( ctypes.c_void_p, ctypes.c_void_p, @@ -1372,6 +1396,9 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): _UniffiLib.uniffi_glsdk_checksum_method_config_with_network.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_config_with_network.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_config_with_signer_config.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_config_with_signer_config.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_method_credentials_node_id.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_credentials_node_id.restype = ctypes.c_uint16 @@ -1507,6 +1534,12 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): _UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_from_seed.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_from_seed.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_with_config.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new_with_config.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_method_loglistener_on_log.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_loglistener_on_log.restype = ctypes.c_uint16 @@ -4344,6 +4377,51 @@ def write(value, buf): _UniffiConverterUInt32.write(value.parts, buf) +class SignerConfig: + """ + State verification and storage settings for SDK signers. + """ + + state_signature_mode: "StateSignatureMode" + device_storage_path: "typing.Optional[str]" + """ + Persistent directory for the migration marker; required in Soft mode. + Hard and Off modes do not open this directory. + """ + + def __init__(self, *, state_signature_mode: "StateSignatureMode", device_storage_path: "typing.Optional[str]"): + self.state_signature_mode = state_signature_mode + self.device_storage_path = device_storage_path + + def __str__(self): + return "SignerConfig(state_signature_mode={}, device_storage_path={})".format(self.state_signature_mode, self.device_storage_path) + + def __eq__(self, other): + if self.state_signature_mode != other.state_signature_mode: + return False + if self.device_storage_path != other.device_storage_path: + return False + return True + +class _UniffiConverterTypeSignerConfig(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return SignerConfig( + state_signature_mode=_UniffiConverterTypeStateSignatureMode.read(buf), + device_storage_path=_UniffiConverterOptionalString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterTypeStateSignatureMode.check_lower(value.state_signature_mode) + _UniffiConverterOptionalString.check_lower(value.device_storage_path) + + @staticmethod + def write(value, buf): + _UniffiConverterTypeStateSignatureMode.write(value.state_signature_mode, buf) + _UniffiConverterOptionalString.write(value.device_storage_path, buf) + + @@ -6138,6 +6216,60 @@ def write(value, buf): +class StateSignatureMode(enum.Enum): + OFF = 0 + """ + Disable signature checks for development and testing only. + """ + + + SOFT = 1 + """ + Allow one successful migration, then use Hard mode. + """ + + + HARD = 2 + + + +class _UniffiConverterTypeStateSignatureMode(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return StateSignatureMode.OFF + if variant == 2: + return StateSignatureMode.SOFT + if variant == 3: + return StateSignatureMode.HARD + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value == StateSignatureMode.OFF: + return + if value == StateSignatureMode.SOFT: + return + if value == StateSignatureMode.HARD: + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value == StateSignatureMode.OFF: + buf.write_i32(1) + if value == StateSignatureMode.SOFT: + buf.write_i32(2) + if value == StateSignatureMode.HARD: + buf.write_i32(3) + + + + + + + class SuccessActionProcessed: """ A processed success action from an LNURL-pay callback. @@ -7038,6 +7170,12 @@ def with_network(self, network: "Network"): Return a new Config with the given network. """ + raise NotImplementedError + def with_signer_config(self, signer_config: "SignerConfig"): + """ + Configure all signers started by NodeBuilder with this Config. + """ + raise NotImplementedError # Config is a Rust-only trait - it's a wrapper around a Rust implementation. class Config(): @@ -7101,6 +7239,22 @@ def with_network(self, network: "Network") -> "Config": + def with_signer_config(self, signer_config: "SignerConfig") -> "Config": + """ + Configure all signers started by NodeBuilder with this Config. + """ + + _UniffiConverterTypeSignerConfig.check_lower(signer_config) + + return _UniffiConverterTypeConfig.lift( + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_method_config_with_signer_config,self._uniffi_clone_pointer(), + _UniffiConverterTypeSignerConfig.lower(signer_config)) + ) + + + + + class _UniffiConverterTypeConfig: @@ -8616,8 +8770,12 @@ def lightning_available(self, node_id: "bytes"): before it creates a node. It needs no credentials, and the `node_id` is passed explicitly. - The answer is advisory and may change over time. Treat an - error as "unknown" rather than as a negative answer. + The answer is monotonic: once the node has been registered + it is reported as available, and stays available regardless + of the node's status or the provider's current capacity. + Before registration the answer is advisory and may change + over time. Treat an error as "unknown" rather than as a + negative answer. """ raise NotImplementedError @@ -8685,8 +8843,12 @@ def lightning_available(self, node_id: "bytes") -> "bool": before it creates a node. It needs no credentials, and the `node_id` is passed explicitly. - The answer is advisory and may change over time. Treat an - error as "unknown" rather than as a negative answer. + The answer is monotonic: once the node has been registered + it is reported as available, and stays available regardless + of the node's status or the provider's current capacity. + Before registration the answer is advisory and may change + over time. Treat an error as "unknown" rather than as a + negative answer. """ _UniffiConverterBytes.check_lower(node_id) @@ -8818,6 +8980,30 @@ def new_from_seed(cls, seed: "bytes"): _UniffiConverterBytes.lower(seed)) return cls._make_instance_(pointer) + @classmethod + def new_from_seed_with_config(cls, seed: "bytes",config: "SignerConfig"): + _UniffiConverterBytes.check_lower(seed) + + _UniffiConverterTypeSignerConfig.check_lower(config) + + # Call the (fallible) function before creating any half-baked object instances. + pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_from_seed_with_config, + _UniffiConverterBytes.lower(seed), + _UniffiConverterTypeSignerConfig.lower(config)) + return cls._make_instance_(pointer) + + @classmethod + def new_with_config(cls, phrase: "str",config: "SignerConfig"): + _UniffiConverterString.check_lower(phrase) + + _UniffiConverterTypeSignerConfig.check_lower(config) + + # Call the (fallible) function before creating any half-baked object instances. + pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_signer_new_with_config, + _UniffiConverterString.lower(phrase), + _UniffiConverterTypeSignerConfig.lower(config)) + return cls._make_instance_(pointer) + def authenticate(self, creds: "Credentials") -> "Signer": @@ -8982,6 +9168,7 @@ def set_logger(level: "LogLevel",listener: "LogListener") -> None: "PaymentType", "PaymentTypeFilter", "ResolvedInput", + "StateSignatureMode", "SuccessActionProcessed", "FundChannel", "FundOutput", @@ -9016,6 +9203,7 @@ def set_logger(level: "LogLevel",listener: "LogListener") -> None: "PreparedOnchainSend", "ReceiveResponse", "SendResponse", + "SignerConfig", "parse_input", "resolve_input", "set_log_level", diff --git a/libs/gl-sdk/src/config.rs b/libs/gl-sdk/src/config.rs index 94d3a371d..34dcbdc61 100644 --- a/libs/gl-sdk/src/config.rs +++ b/libs/gl-sdk/src/config.rs @@ -1,17 +1,32 @@ // SDK configuration for Greenlight node operations. -// Holds network selection and optional developer certificate. +// Holds network selection, signer settings and optional developer certificate. -use std::sync::Arc; use crate::credentials::DeveloperCert; -use crate::Network; +use crate::{Error, Network, SignerConfig}; +use std::sync::Arc; #[derive(uniffi::Object, Clone)] pub struct Config { pub(crate) network: gl_client::bitcoin::Network, pub(crate) developer_cert: Option, + pub(crate) signer_config: SignerConfig, } impl Config { + pub(crate) fn create_signer( + &self, + seed: Vec, + credentials: T, + ) -> Result { + gl_client::signer::Signer::new_with_config( + seed, + self.network, + credentials, + self.signer_config.to_client()?, + ) + .map_err(|e| Error::other(format!("{e:#}"))) + } + /// Resolve the credentials to use for unauthenticated scheduler /// calls (register, recover). Uses the developer certificate if /// one was provided, otherwise falls back to the compiled-in default. @@ -30,6 +45,7 @@ impl Config { Self { network: gl_client::bitcoin::Network::Bitcoin, developer_cert: None, + signer_config: SignerConfig::default(), } } @@ -49,4 +65,32 @@ impl Config { ..self.clone() }) } + + /// Configure all signers started by NodeBuilder with this Config. + pub fn with_signer_config(&self, signer_config: SignerConfig) -> Arc { + Arc::new(Config { + signer_config, + ..self.clone() + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::StateSignatureMode; + + #[test] + fn configured_signers_use_migration_settings_without_changing_the_original_config() { + let base = Config::new().with_network(Network::REGTEST); + let migration = base.with_signer_config(SignerConfig { + state_signature_mode: StateSignatureMode::Soft, + device_storage_path: None, + }); + assert_eq!(migration.network, base.network); + let creds = gl_client::credentials::Nobody::new(); + let result = migration.create_signer(vec![0; 32], creds.clone()); + assert!(matches!(result, Err(Error::Argument { .. }))); + assert!(base.create_signer(vec![0; 32], creds).is_ok()); + } } diff --git a/libs/gl-sdk/src/lib.rs b/libs/gl-sdk/src/lib.rs index cf1e89435..74ca218f0 100644 --- a/libs/gl-sdk/src/lib.rs +++ b/libs/gl-sdk/src/lib.rs @@ -134,6 +134,7 @@ mod node; mod node_builder; mod scheduler; mod signer; +mod signer_config; mod util; pub use crate::{ @@ -158,6 +159,7 @@ pub use crate::{ node_builder::NodeBuilder, scheduler::Scheduler, signer::{Handle, Signer}, + signer_config::{SignerConfig, StateSignatureMode}, }; /// Which scheduler operation to perform. @@ -178,10 +180,9 @@ fn schedule_node( let nobody = config.nobody(); let seed_for_async = seed.clone(); + let config_for_async = config.clone(); let credentials = util::exec(async move { - let signer = - gl_client::signer::Signer::new(seed_for_async, network, nobody.clone()) - .map_err(|e| Error::other(e.to_string()))?; + let signer = config_for_async.create_signer(seed_for_async, nobody.clone())?; let scheduler = gl_client::scheduler::Scheduler::new(network, nobody) .await @@ -209,9 +210,7 @@ fn schedule_node( credentials::Credentials::load(creds_bytes) })?; - let authenticated_signer = - gl_client::signer::Signer::new(seed, network, credentials.inner.clone()) - .map_err(|e| Error::other(e.to_string()))?; + let authenticated_signer = config.create_signer(seed, credentials.inner.clone())?; let handle = signer::Handle::spawn(authenticated_signer); let node = node::Node::with_signer(credentials, handle, network)?; @@ -272,9 +271,7 @@ pub(crate) fn connect_internal( let network = config.network; let creds = credentials::Credentials::load(credentials)?; - let authenticated_signer = - gl_client::signer::Signer::new(seed, network, creds.inner.clone()) - .map_err(|e| Error::other(e.to_string()))?; + let authenticated_signer = config.create_signer(seed, creds.inner.clone())?; let handle = signer::Handle::spawn(authenticated_signer); let node = node::Node::with_signer(creds, handle, network)?; diff --git a/libs/gl-sdk/src/signer.rs b/libs/gl-sdk/src/signer.rs index f36f0868f..853a50a25 100644 --- a/libs/gl-sdk/src/signer.rs +++ b/libs/gl-sdk/src/signer.rs @@ -1,4 +1,4 @@ -use crate::{Credentials, Error}; +use crate::{Credentials, Error, SignerConfig}; use bip39::Mnemonic; use std::str::FromStr; use tracing; @@ -8,44 +8,59 @@ pub struct Signer { seed: Vec, pub(crate) inner: gl_client::signer::Signer, credentials: Option, + config: gl_client::signer::SignerConfig, } #[uniffi::export] impl Signer { #[uniffi::constructor()] pub fn new(phrase: String) -> Result { + Self::new_with_config(phrase, SignerConfig::default()) + } + + #[uniffi::constructor()] + pub fn new_with_config(phrase: String, config: SignerConfig) -> Result { let phrase = Mnemonic::from_str(phrase.as_str()).map_err(|_e| Error::phrase_corrupted())?; let seed = phrase.to_seed_normalized(&"").to_vec(); - Self::new_from_seed(seed) + Self::new_from_seed_with_config(seed, config) } #[uniffi::constructor()] pub fn new_from_seed(seed: Vec) -> Result { + Self::new_from_seed_with_config(seed, SignerConfig::default()) + } + + #[uniffi::constructor()] + pub fn new_from_seed_with_config(seed: Vec, config: SignerConfig) -> Result { let credentials = gl_client::credentials::Nobody::new(); + let config = config.to_client()?; - let inner = gl_client::signer::Signer::new( + let inner = gl_client::signer::Signer::new_with_config( seed.clone(), gl_client::bitcoin::Network::Bitcoin, credentials, + config.clone(), ) - .map_err(|e| Error::other(e.to_string()))?; + .map_err(|e| Error::other(format!("{e:#}")))?; let credentials = None; Ok(Signer { seed, inner, credentials, + config, }) } pub fn authenticate(&self, creds: &Credentials) -> Result { let credentials = Some(creds.clone()); - let inner = gl_client::signer::Signer::new( + let inner = gl_client::signer::Signer::new_with_config( self.seed.clone(), gl_client::bitcoin::Network::Bitcoin, creds.inner.clone(), + self.config.clone(), ) - .map_err(|e| Error::other(e.to_string()))?; + .map_err(|e| Error::other(format!("{e:#}")))?; Ok(Signer { inner, diff --git a/libs/gl-sdk/src/signer_config.rs b/libs/gl-sdk/src/signer_config.rs new file mode 100644 index 000000000..1e1702956 --- /dev/null +++ b/libs/gl-sdk/src/signer_config.rs @@ -0,0 +1,124 @@ +use crate::Error; +use gl_client::signer::{DeviceStorage, FileDeviceStorage}; +use std::sync::Arc; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, uniffi::Enum)] +pub enum StateSignatureMode { + /// Disable signature checks for development and testing only. + Off, + /// Allow one successful migration, then use Hard mode. + Soft, + #[default] + Hard, +} + +impl From for gl_client::signer::StateSignatureMode { + fn from(mode: StateSignatureMode) -> Self { + match mode { + StateSignatureMode::Off => Self::Off, + StateSignatureMode::Soft => Self::Soft, + StateSignatureMode::Hard => Self::Hard, + } + } +} + +/// State verification and storage settings for SDK signers. +#[derive(Clone, Debug, Default, uniffi::Record)] +pub struct SignerConfig { + pub state_signature_mode: StateSignatureMode, + /// Persistent directory for the migration marker; required in Soft mode. + /// Hard and Off modes do not open this directory. + pub device_storage_path: Option, +} + +impl SignerConfig { + pub(crate) fn to_client(&self) -> Result { + let device_storage: Option> = match self.state_signature_mode { + StateSignatureMode::Soft => { + let path = self + .device_storage_path + .as_deref() + .filter(|path| !path.is_empty()) + .ok_or_else(|| { + Error::argument("device_storage_path", "required for Soft mode") + })?; + Some(Arc::new(FileDeviceStorage::new(path).map_err(|e| { + Error::other(format!("opening device storage: {e:#}")) + })?)) + } + _ => None, + }; + Ok(gl_client::signer::SignerConfig { + state_signature_mode: self.state_signature_mode.into(), + device_storage, + ..Default::default() + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_config_uses_hard_without_opening_storage() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("unused"); + let config = SignerConfig { + device_storage_path: Some(path.to_str().unwrap().to_string()), + ..Default::default() + } + .to_client() + .unwrap(); + assert_eq!( + config.state_signature_mode, + gl_client::signer::StateSignatureMode::Hard + ); + assert!(config.device_storage.is_none()); + assert!(!path.exists()); + } + + #[test] + fn soft_requires_a_nonempty_storage_path() { + for path in [None, Some(String::new())] { + let err = SignerConfig { + state_signature_mode: StateSignatureMode::Soft, + device_storage_path: path, + } + .to_client() + .unwrap_err(); + assert!(matches!(err, Error::Argument { .. })); + } + } + + #[test] + fn separate_configs_reopen_the_same_persistent_storage() { + let dir = tempfile::tempdir().unwrap(); + let config = SignerConfig { + state_signature_mode: StateSignatureMode::Soft, + device_storage_path: Some(dir.path().to_str().unwrap().to_string()), + }; + { + let first = config.to_client().unwrap(); + assert_eq!( + first.state_signature_mode, + gl_client::signer::StateSignatureMode::Soft + ); + first + .device_storage + .unwrap() + .save("marker", b"used") + .unwrap(); + } + let reopened = config.to_client().unwrap(); + assert_eq!( + reopened + .device_storage + .unwrap() + .load("marker") + .unwrap() + .unwrap(), + b"used" + ); + } +} diff --git a/libs/gl-sdk/tests/test_signer_config.py b/libs/gl-sdk/tests/test_signer_config.py new file mode 100644 index 000000000..d13f99634 --- /dev/null +++ b/libs/gl-sdk/tests/test_signer_config.py @@ -0,0 +1,64 @@ +import pytest + +import glsdk + + +MNEMONIC = ( + "abandon abandon abandon abandon abandon abandon " + "abandon abandon abandon abandon abandon about" +) + + +def migration_config(path=None): + return glsdk.SignerConfig( + state_signature_mode=glsdk.StateSignatureMode.SOFT, + device_storage_path=str(path) if path is not None else None, + ) + + +def test_existing_signer_constructors_keep_working(): + assert len(glsdk.Signer(MNEMONIC).node_id()) == 33 + assert len(glsdk.Signer.new_from_seed(b"\x00" * 32).node_id()) == 33 + + +@pytest.mark.parametrize("from_seed", [False, True]) +def test_configured_signer_constructors(from_seed, tmp_path): + path = tmp_path / "device-state" + config = migration_config(path) + if from_seed: + signer = glsdk.Signer.new_from_seed_with_config(b"\x00" * 32, config) + else: + signer = glsdk.Signer.new_with_config(MNEMONIC, config) + assert len(signer.node_id()) == 33 + assert path.is_dir() + + +def test_authentication_preserves_migration_storage(tmp_path): + path = tmp_path / "device-state" + signer = glsdk.Signer.new_with_config(MNEMONIC, migration_config(path)) + creds = glsdk.Credentials.load(b"") + authenticated = signer.authenticate(creds) + assert authenticated.node_id() == signer.node_id() + # If authentication lost the configuration and reverted to Hard, this + # storage failure would go unnoticed by the newly constructed signer. + path.rmdir() + path.write_text("unavailable") + with pytest.raises(glsdk.Error, match="loading Soft migration marker"): + authenticated.authenticate(creds) + + +@pytest.mark.parametrize( + "action", ["register", "recover", "connect", "register_or_recover"] +) +def test_node_builder_forwards_signer_configuration(action, monkeypatch): + # A regression must never send these tests to a production scheduler. + monkeypatch.setenv("GL_SCHEDULER_GRPC_URI", "https://localhost:0") + config = glsdk.Config().with_signer_config(migration_config()) + builder = glsdk.NodeBuilder(config) + with pytest.raises(glsdk.Error, match="device_storage_path"): + if action in ("register", "register_or_recover"): + getattr(builder, action)(MNEMONIC, None) + elif action == "connect": + builder.connect(b"", MNEMONIC) + else: + builder.recover(MNEMONIC) From 1c7cd5cd29e6629738a55ebe7960d84b7fb7e593 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Wed, 18 Nov 2026 01:31:56 +0200 Subject: [PATCH 4/4] signer: Accept backend peer addresses as backup hints The node updates peers/ entries without a signer signature. Keep valid addresses for channel backup recovery and skip malformed hints so a peer update cannot block Hard mode. Keep peer hints out of signed responses. --- docs/src/reference/signer-state.md | 6 ++- libs/gl-client/src/persist.rs | 79 +++++++++++++++++++++--------- libs/gl-client/src/signer/mod.rs | 63 ++++++++++++++++++++++-- 3 files changed, 120 insertions(+), 28 deletions(-) diff --git a/docs/src/reference/signer-state.md b/docs/src/reference/signer-state.md index e20c1e509..24c1720f0 100644 --- a/docs/src/reference/signer-state.md +++ b/docs/src/reference/signer-state.md @@ -28,11 +28,15 @@ The signer state is a key-value map. Every entry consists of: | Field | Description | |-------|-------------| -| `key` | The entry name, prefixed by its class: `nodes/`, `nodestates/`, `channels/`, `allowlists/`, `trackers/`, `peers/` | +| `key` | The entry name, prefixed by its class: `nodes/`, `nodestates/`, `channels/`, `allowlists/`, `trackers/` | | `version` | A counter that increases with every change to this key | | `value` | The serialized VLS object | | `signature` | The signer's signature over the key, version and value | +The node also sends `peers/` entries as address hints for channel backup +recovery. These are untrusted metadata. The signer keeps valid hints for +backups and excludes them from state signatures. + Deleting a key leaves a _tombstone_ behind: the entry is kept with the highest possible version and an empty value, so that an older value of the key cannot be merged back in. diff --git a/libs/gl-client/src/persist.rs b/libs/gl-client/src/persist.rs index f9079b37a..b6514c0a1 100644 --- a/libs/gl-client/src/persist.rs +++ b/libs/gl-client/src/persist.rs @@ -11,7 +11,7 @@ pub use splice::{ pub(crate) use splice::{CandidateFundingFacts, WalletInput}; pub(crate) use splice::{SpliceOrigin, SplicePhase, SpliceSessionV1}; -use anyhow::anyhow; +use anyhow::{anyhow, bail}; use lightning_signer::bitcoin::secp256k1::PublicKey; use lightning_signer::chain::tracker::ChainTracker; use lightning_signer::channel::ChannelId; @@ -39,7 +39,7 @@ const NODE_STATE_PREFIX: &str = "nodestates"; const CHANNEL_PREFIX: &str = "channels"; const ALLOWLIST_PREFIX: &str = "allowlists"; const TRACKER_PREFIX: &str = "trackers"; -const PEER_PREFIX: &str = "peers"; +pub(crate) const PEER_PREFIX: &str = "peers/"; const TOMBSTONE_VERSION: u64 = u64::MAX; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -246,7 +246,7 @@ impl State { } pub fn insert_or_update_peer(&mut self, peer: PeerEntry) -> Result<(), Error> { - let key = format!("{PEER_PREFIX}/{}", peer.peer_id); + let key = format!("{PEER_PREFIX}{}", peer.peer_id); self.ensure_not_tombstone(&key)?; let value = serde_json::to_value(peer).unwrap(); match self.values.get_mut(&key) { @@ -412,6 +412,11 @@ impl State { self.values.len() } + pub(crate) fn without_peer_hints(mut self) -> Self { + self.values.retain(|key, _| !key.starts_with(PEER_PREFIX)); + self + } + /// Merge incoming state and track potential version conflicts. /// /// A conflict means the incoming state is stale or incompatible with local @@ -535,14 +540,14 @@ impl State { State { values } } - /// Sign entries missing signatures and return how many signatures were added. + /// Sign signer-owned entries missing signatures. Peer address hints are written by the node. pub fn resign_signatures(&mut self, mut signer: F) -> anyhow::Result where F: FnMut(&str, u64, &[u8]) -> anyhow::Result>, { let mut changed = 0usize; for (key, entry) in self.values.iter_mut() { - if !entry.signature.is_empty() { + if key.starts_with(PEER_PREFIX) || !entry.signature.is_empty() { continue; } let value = entry.canonical_value_bytes()?; @@ -651,30 +656,56 @@ impl Into> for State { } } +fn decode_entry(entry: &crate::pb::SignerStateEntry) -> anyhow::Result { + let value = serde_json::from_slice(&entry.value).map_err(|e| { + anyhow!( + "failed to decode signer state value for key {}: {}", + entry.key, + e + ) + })?; + Ok(StateEntry { + version: entry.version, + value, + signature: entry.signature.clone(), + }) +} + +impl State { + pub(crate) fn from_signer_request( + entries: &[crate::pb::SignerStateEntry], + ) -> anyhow::Result { + let mut state = Self::new(); + for entry in entries { + if let Some(peer_id) = entry.key.strip_prefix(PEER_PREFIX) { + // These hints are for backup recovery. Invalid hints cannot block signing. + if let Ok(value) = serde_json::from_slice::(&entry.value) { + if entry.version != TOMBSTONE_VERSION && value.peer_id == peer_id { + state.values.insert( + entry.key.clone(), + StateEntry::new(entry.version, serde_json::to_value(value)?), + ); + } + } + } else if state + .values + .insert(entry.key.clone(), decode_entry(entry)?) + .is_some() + { + bail!("duplicate signer state entry {}", entry.key); + } + } + Ok(state) + } +} + impl TryFrom<&[crate::pb::SignerStateEntry]> for State { type Error = anyhow::Error; fn try_from(v: &[crate::pb::SignerStateEntry]) -> Result { let values = v .iter() - .map(|entry| -> anyhow::Result<(String, StateEntry)> { - let value = serde_json::from_slice(&entry.value).map_err(|e| { - anyhow!( - "failed to decode signer state value for key {}: {}", - entry.key, - e - ) - })?; - - Ok(( - entry.key.to_owned(), - StateEntry { - version: entry.version, - value, - signature: entry.signature.clone(), - }, - )) - }) + .map(|entry| Ok((entry.key.clone(), decode_entry(entry)?))) .collect::>>()?; Ok(State { values }) @@ -1529,7 +1560,7 @@ mod tests { #[test] fn insert_or_update_peer_keeps_last_known_address() { let mut state = State::new(); - let key = format!("{PEER_PREFIX}/02aa"); + let key = format!("{PEER_PREFIX}02aa"); state .insert_or_update_peer(PeerEntry { diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 74bf6d63f..8bac630bf 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -9,6 +9,7 @@ use crate::pb::scheduler::{ /// signing if ok, and then shipping the response to the node. use crate::pb::{node_client::NodeClient, Empty, HsmRequest, HsmRequestContext, HsmResponse}; use crate::pb::{PendingRequest, SignerStateEntry}; +use crate::persist::PEER_PREFIX; use crate::runes; use crate::signer::resolve::Resolver; use crate::tls::TlsConfig; @@ -578,6 +579,9 @@ impl Signer { let mut first_error: Option = None; for entry in entries.iter() { + if entry.key.starts_with(PEER_PREFIX) { + continue; + } if entry.signature.is_empty() { if mode == StateSignatureMode::Hard { usage.missing_keys.push(entry.key.clone()); @@ -901,7 +905,7 @@ impl Signer { .await; } - let incoming_state = crate::persist::State::try_from(req.signer_state.as_slice()) + let incoming_state = crate::persist::State::from_signer_request(&req.signer_state) .map_err(|e| Error::Other(anyhow!("Failed to decode signer state: {e}")))?; let mut rejections = Vec::new(); @@ -1130,10 +1134,11 @@ impl Signer { }) .map_err(|e| Error::Other(anyhow!("Failed to sign signer state entries: {e}")))?; let full_wire_bytes = { - let full_entries: Vec = state.clone().into(); + let full_entries: Vec = + state.clone().without_peer_hints().into(); signer_state_response_wire_bytes(&full_entries) }; - let diff_state = prestate_sketch.diff_state(&state); + let diff_state = prestate_sketch.diff_state(&state).without_peer_hints(); let diff_entries: Vec = diff_state.into(); let diff_wire_bytes = signer_state_response_wire_bytes(&diff_entries); let saved_percent = savings_percent(full_wire_bytes, diff_wire_bytes); @@ -2500,6 +2505,58 @@ mod tests { assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); } + #[tokio::test] + async fn backend_peer_hints_are_accepted_without_being_signed() { + use crate::persist::{PeerEntry, State}; + + let signer = mk_signer(StateSignatureMode::Hard); + let mut backend = State::new(); + let mut hint = PeerEntry { + peer_id: "02aa".into(), + addr: "127.0.0.1:9735".into(), + direction: "out".into(), + features: "".into(), + }; + backend.insert_or_update_peer(hint.clone()).unwrap(); + let response = signer + .process_request(heartbeat_request(backend.clone().into())) + .await + .unwrap() + .signer_state; + assert!(response + .iter() + .all(|entry| !entry.key.starts_with(PEER_PREFIX))); + let cached: Vec = signer.state.lock().unwrap().clone().into(); + assert!(cached + .iter() + .any(|entry| entry.key == "peers/02aa" && entry.signature.is_empty())); + hint.addr = "127.0.0.2:9735".into(); + backend.insert_or_update_peer(hint.clone()).unwrap(); + let mut entries: Vec = backend.into(); + let mut malformed = mk_state_entry("peers/02bb", 0, json!(null)); + malformed.value = b"{".to_vec(); + entries.push(malformed); + let response = signer + .process_request(heartbeat_request(entries)) + .await + .unwrap(); + assert!(response + .signer_state + .iter() + .all(|entry| !entry.key.starts_with(PEER_PREFIX))); + let cached: Vec = signer.state.lock().unwrap().clone().into(); + let peers = cached + .iter() + .filter(|entry| entry.key.starts_with(PEER_PREFIX)) + .collect::>(); + assert_eq!(peers.len(), 1); + assert_eq!( + serde_json::from_slice::(&peers[0].value).unwrap(), + hint + ); + assert!(peers[0].signature.is_empty()); + } + #[cfg(feature = "backup")] #[test] fn periodic_backup_rejects_zero_updates() {