From 8e21b5e0c575970c93303dd0fe280e895726120a Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Wed, 18 Nov 2026 01:54:27 +0200 Subject: [PATCH 1/4] signer: Resync state after rejecting an incoming delta The node advances its delta baseline when it sends a request. A signer that discards a rejected request must reconnect to receive a full snapshot. Back off before reconnecting to a node that keeps failing. --- libs/gl-client/src/signer/mod.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 8bac630bf..919a59a02 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -842,7 +842,12 @@ impl Signer { warn!( "Rejected request {} with error: {}. State: {:?}", hex_req, e, signer_state, - ) + ); + if !signer_state.is_empty() { + // The node advances its delta baseline on send. Request a full + // snapshot on reconnect when we discarded incoming state. + return Err(e); + } } }; } @@ -1456,6 +1461,7 @@ impl Signer { .await { warn!("Error running against node: {e}"); + sleep(Duration::from_secs(1)).await; } } } From a188499f0dbb9bcdb10e4bfd6e1eff4ae1251228 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Wed, 18 Nov 2026 01:54:27 +0200 Subject: [PATCH 2/4] signer: Sync new device storage directories A synced file can still be lost if the directory that contains it was just created. Sync the parent when creating a storage directory on Unix. --- .../gl-client/src/signer/device_state/file.rs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/libs/gl-client/src/signer/device_state/file.rs b/libs/gl-client/src/signer/device_state/file.rs index 61678c416..bd99897bc 100644 --- a/libs/gl-client/src/signer/device_state/file.rs +++ b/libs/gl-client/src/signer/device_state/file.rs @@ -15,7 +15,7 @@ impl FileDeviceStorage { /// 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) + create_storage_directory(&dir) .with_context(|| format!("creating device state directory {}", dir.display()))?; Ok(Self { dir }) } @@ -27,6 +27,26 @@ impl FileDeviceStorage { } } +fn create_storage_directory(path: &Path) -> std::io::Result<()> { + if path.is_dir() { + return Ok(()); + } + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + create_storage_directory(parent)?; + match fs::create_dir(path) { + Ok(()) => (), + Err(error) if error.kind() == ErrorKind::AlreadyExists && path.is_dir() => (), + Err(error) => return Err(error), + } + // A file sync alone cannot make the newly created directory durable. + #[cfg(unix)] + File::open(parent)?.sync_all()?; + Ok(()) +} + impl DeviceStorage for FileDeviceStorage { fn load(&self, key: &str) -> Result>> { match fs::read(self.path(key)) { From dee0fc615d67d29d52be588befd10f0f5617a7f9 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Wed, 18 Nov 2026 01:57:04 +0200 Subject: [PATCH 3/4] signer: Enforce a durable watermark across restarts Check the startup snapshot against the last committed versions and value hashes before restoring VLS state. Save the watermark before returning signatures and stop the signer when a snapshot violates it. Require complete node records, preserve signed tombstones, and restore the VLS channel ID high-water mark while allowing retries for existing channels. --- docs/src/reference/security.md | 28 +- docs/src/reference/signer-state.md | 230 ++++++---------- libs/gl-client/CHANGELOG.md | 1 + libs/gl-client/src/persist.rs | 135 ++++++++-- libs/gl-client/src/signer/mod.rs | 350 ++++++++++++++++++++++--- libs/gl-client/src/signer/watermark.rs | 142 ++++++++++ libs/gl-plugin/src/node/mod.rs | 4 +- 7 files changed, 668 insertions(+), 222 deletions(-) create mode 100644 libs/gl-client/src/signer/watermark.rs diff --git a/docs/src/reference/security.md b/docs/src/reference/security.md index 6c3b863ba..bde27c4e1 100644 --- a/docs/src/reference/security.md +++ b/docs/src/reference/security.md @@ -104,7 +104,7 @@ operational limitations. ## Signer State Integrity -The signer does not store its own state. The node stores the +The node stores the full [signer state](signer-state.md) (channel states, allowed on-chain destinations, known invoices) and attaches it to every request. An attacker with access to the node infrastructure can therefore read, @@ -115,25 +115,23 @@ must not trust it blindly. |-------|--------------|------------------| | Node infrastructure | Storing and returning the state | The content, age or completeness of the state | | Signer | Writing and signing state entries | | -| Application embedding the signer | Keeping the state anchor, choosing enforcement options | | +| Application embedding the signer | Persisting the device watermark and choosing a signature mode | | - **Authenticity:** every state entry is signed with a key derived from the node secret. In `hard` state signature mode the signer refuses entries with missing or invalid signatures, so the node cannot inject or alter state. - - **Freshness and completeness** (planned): a small _state anchor_ - kept on the device records the latest version of every key the - signer has seen. On start, the signer refuses state that is older - than its anchor, is missing keys, or brings back deleted keys. - - **Enforcement options belong to the application.** The state - signature mode and anchor enforcement are set where the signer is - embedded; the node cannot change them, and there is no way for the - node to reset an anchor. - -A signer without an anchor, for example right after pairing or -recovery, trusts the first state it receives. See -[Signer State](signer-state.md) for the details and the configuration -options. + - **Freshness and completeness:** Signers with device storage persist + a device-local watermark before releasing signatures. A fresh process + refuses state that is older than its watermark, is missing keys, or + brings back deleted keys. + - **Configuration belongs to the application.** The application chooses + the signature mode and controls the local storage. The node cannot + reset the watermark. + +On first use, the signer establishes its watermark from the first +accepted snapshot. See [Signer State](signer-state.md) for configuration, +recovery implications, and limits. ## Client ⇄ Signer Authorization diff --git a/docs/src/reference/signer-state.md b/docs/src/reference/signer-state.md index 24c1720f0..dad1f94bf 100644 --- a/docs/src/reference/signer-state.md +++ b/docs/src/reference/signer-state.md @@ -11,7 +11,7 @@ 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, +With persistent device storage, the signer keeps a watermark independently of the node. This creates a tension with the [security model](security.md): the @@ -35,7 +35,7 @@ The signer state is a key-value map. Every entry consists of: 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. +backups and excludes them from state signatures and the watermark. 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 @@ -47,7 +47,8 @@ The node and the signer keep their copies of the state in sync by exchanging only what changed: 1. When a signer connects, the node sends it a heartbeat request that - carries a full snapshot of the state. + carries a full snapshot of the state, including tombstones. The signer + checks the first snapshot after startup against the saved watermark. 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 a scratch copy of its state. @@ -55,8 +56,9 @@ exchanging only what changed: 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. + copy and return the signed changes. It saves the watermark before + committing the copy or returning signatures. A request rejected + before the save leaves both live state and the watermark unchanged. 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 @@ -91,8 +93,8 @@ There are three properties the signer needs from the state it receives: | Property | Question | Mechanism | Status | |----------|----------|-----------|--------| | Authenticity | Was every entry written by a signer of this node? | State signatures | Available | -| Freshness | Is any entry older than one this signer has already seen? | State anchor | Planned | -| Completeness | Is any entry this signer has seen missing? | State anchor | Planned | +| Freshness | Is any entry older than one this signer has already seen? | Device watermark | With persistent device storage | +| Completeness | Is any entry this signer has seen missing? | Device watermark | With persistent device storage | ### Authenticity: state signatures @@ -112,24 +114,22 @@ _state signature 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. +that every entry the signer acts on was written by a signer of this node, +provided the operator override is disabled. The mode is part of the signer configuration: === "Rust" ```rust - use gl_client::signer::{Signer, SignerConfig, StateSignatureMode}; - - let signer = Signer::new_with_config( - seed, - network, - creds, - SignerConfig { - state_signature_mode: StateSignatureMode::Hard, - ..Default::default() - }, - )?; + use gl_client::signer::{FileDeviceStorage, Signer, SignerConfig}; + use std::sync::Arc; + + let storage = Arc::new(FileDeviceStorage::new("/path/to/app/device-state")?); + let signer = Signer::new_with_config(seed, network, creds, SignerConfig { + device_storage: Some(storage), + ..Default::default() + })?; ``` === "glcli" @@ -146,14 +146,12 @@ 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. +The signer saves a migration marker in device storage after processing +and signing succeed, then saves the watermark before returning signatures. +The marker and watermark are scoped by node ID and network. If either is +already present, requesting Soft starts the signer in Hard with a warning. +Applications can keep the same configuration across restarts. 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 @@ -162,10 +160,6 @@ 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. -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`. - === "glcli" ```bash @@ -197,26 +191,12 @@ directory; `glcli` uses `/device-state`. or `Signer.new_from_seed_with_config(seed, migration)`. Authenticating a signer preserves its migration configuration and storage. -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 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 @@ -224,8 +204,8 @@ For manual recovery, a signer can be started with an override that accepts missing and invalid state signatures for the lifetime of the process. The override has to be acknowledged explicitly (`I_ACCEPT_OPERATOR_ASSISTED_STATE_OVERRIDE`), and its use is reported -to Greenlight. It disables the authenticity guarantee and should only -be used together with the Greenlight team. +to Greenlight. It disables the authenticity guarantee while watermark +checks continue to apply. Use it only together with the Greenlight team. ```bash glcli signer run \ @@ -233,105 +213,61 @@ glcli signer run \ --state-override-note "support case reference" ``` -### Freshness and completeness: the state anchor - -!!! example "Planned" - The state anchor is not available yet. Option and function names on - this page may change before it ships. - -Signatures show that an entry was written by a signer of the node, but -not that it is the _latest_ version, or that nothing was left out. A -signer starting from scratch, which on mobile happens at every app -launch, cannot tell an old, validly signed snapshot from a current one. - -The _state anchor_ closes that gap. It is a small record, kept on the -device, of the highest version and a short hash of every key the signer -has seen, including tombstones. It is not a copy of the state, and it -contains no keys or secrets. - -When a signer process starts and receives its first snapshot, it -compares the snapshot against its anchor: - -| Check | Condition | Outcome | -|-------|-----------|---------| -| Rollback | An entry is older than the anchored version | Refused | -| Omission | A key in the anchor is missing from the snapshot | Refused | -| Resurrection | A key the anchor knows as deleted comes back | Refused | -| Discrepancy | An entry has the anchored version but a different value | Accepted, reported | - -A validly signed entry at the same or a higher version is always -accepted: only another signer of the node can have produced it. Keys -the anchor has never seen are accepted and are protected by their -signatures. - -The anchor only advances to versions the node has sent back to the -signer, never to versions the signer merely wrote. This way a response -that the node failed to store cannot leave the anchor ahead of the -node's state and lock the signer out. - -#### Signers without an anchor - -A signer without an anchor trusts the first snapshot it receives and -anchors it. This is the case on first start, after [pairing](pairing.md) -a new device, after [recovery](../getting-started/recover.md), after -reinstalling the application, and after the anchor has been cleared. - -Losing the anchor, or restoring an older copy of it from a device -backup, is safe: the anchor only ever records versions the node once -had, so an older anchor is merely less protective. The anchor needs -persistent storage, not secret storage. - -#### Storing the anchor - -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, 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 | - -#### Enforcement - -Anchor enforcement is a signer option with two values: - - - `report`: the checks run and their results are reported to - Greenlight, but nothing is refused. - - `enforce`: rollback, omission and resurrection are refused. - -The anchor is only meaningful together with `hard` state signature -mode, because `soft` mode accepts unsigned entries at any version. It -will start out as `report` and move to `enforce` after `hard` mode is -the default. - -Like the state signature mode, the enforcement option is chosen by the -application embedding the signer. The Greenlight node cannot change it. - -#### Clearing the anchor - -If a signer refuses to start because of an anchor check, either the -state was tampered with, or the node's stored state went back in time -for an operational reason, for example a restore from backup. The -signer cannot tell these apart, and there is deliberately no way for -the node to tell it. - -Clearing the anchor on the device (`reset_anchor()` in `gl-sdk`, -`--reset-anchor` in `glcli`) makes the signer trust the next snapshot -again, like a signer without an anchor. Applications should only -offer this as an explicit user action, ideally after contacting -Greenlight support. - -## Limits - - - A signer without an anchor trusts the first state it receives. - - The anchor protects what that particular device has seen. A key - written by another signer, and never seen by this one, is protected - by its signature only. - - A device that has been offline for a long time only refuses state - older than what it saw when it was last online. +### Freshness and completeness with the watermark + +The watermark records the version and hash of each value in the last +committed state. It includes tombstones and covers only state committed +by this signer. At startup, the signer rejects a snapshot that omits an +anchored key, lowers its version, changes its value at the same version, +or brings a deleted key back. Once initialized, it can merge incremental +updates with newer state already in memory. + +The signer saves the watermark before releasing any response that +depends on a state change. If the storage write fails, the signer stops +processing requests until it is reconstructed and reloads storage. A +watermark violation also stops the signer loop and surfaces an error. + +A response lost before the node saves it can leave the watermark ahead +of the node. Two devices can also produce different values at the same +version. After restart, the saved watermark requires the node to supply +a snapshot that satisfies it. The signer has no automatic recovery for +missing or conflicting state. + +#### Manual recovery in Hard mode + +First try to restore a node snapshot that satisfies the saved watermark. +If that snapshot is unavailable, an operator of a Hard-only app can +explicitly accept a new baseline after independently verifying the state +the node will supply. Stop the signer, back up the device storage, and +remove only the `signer/{network}/{node_id}/watermark` record. For +`FileDeviceStorage`, the filename is the hex SHA-256 hash of that key, +using the hex node ID. Keep the Soft migration marker intact. + +Restart in Hard mode. The first accepted signed snapshot establishes the +new baseline. Resetting the watermark discards the ability to reject a +previously signed snapshot based on the old baseline. + +#### Configuring device storage + +Soft mode requires persistent storage. In Hard mode, set +`SignerConfig::device_storage` in Rust to enable the watermark. Reuse the +same storage across restarts. Unreadable storage and invalid watermark +data prevent signer initialization. + +Upgrade the node plugin first so it includes tombstones in initial +snapshots. Off mode is intended for development and bypasses both +signature verification and the watermark. + +#### Limits + +A device without a watermark uses the first accepted snapshot as its +baseline, including after pairing or reinstalling. Deleting or rolling back +device storage can weaken both rollback protection and the Soft migration +limit. + +Run one active signer instance per device storage namespace. Clones +share the watermark, but separate signer instances and devices cannot +coordinate their local records. We plan to address coordination with an +external watermarking service outside Blockstream’s control. [vls]: https://vls.tech diff --git a/libs/gl-client/CHANGELOG.md b/libs/gl-client/CHANGELOG.md index 79e3850d0..713b2a6d5 100644 --- a/libs/gl-client/CHANGELOG.md +++ b/libs/gl-client/CHANGELOG.md @@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed +- The signer uses a durable watermark to reject rollback and omissions across restarts. - 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. diff --git a/libs/gl-client/src/persist.rs b/libs/gl-client/src/persist.rs index b6514c0a1..fdf4cee6a 100644 --- a/libs/gl-client/src/persist.rs +++ b/libs/gl-client/src/persist.rs @@ -12,6 +12,7 @@ pub(crate) use splice::{CandidateFundingFacts, WalletInput}; pub(crate) use splice::{SpliceOrigin, SplicePhase, SpliceSessionV1}; use anyhow::{anyhow, bail}; +use lightning_signer::bitcoin::hashes::{sha256, Hash}; use lightning_signer::bitcoin::secp256k1::PublicKey; use lightning_signer::chain::tracker::ChainTracker; use lightning_signer::channel::ChannelId; @@ -148,21 +149,19 @@ impl State { ) -> Result<(), Error> { let node_key = format!("{NODE_PREFIX}/{key}"); let state_key = format!("{NODE_STATE_PREFIX}/{key}"); - self.ensure_not_tombstone(&node_key)?; - self.ensure_not_tombstone(&state_key)?; - let node_version = self.next_version(&node_key); - let state_version = self.next_version(&state_key); + if self.values.contains_key(&node_key) || self.values.contains_key(&state_key) { + return Err(Error::Internal(format!( + "node {key} already exists in signer state" + ))); + } self.values.insert( node_key, - StateEntry::new(node_version, serde_json::to_value(node_entry).unwrap()), + StateEntry::new(0, serde_json::to_value(node_entry).unwrap()), ); self.values.insert( state_key, - StateEntry::new( - state_version, - serde_json::to_value(node_state_entry).unwrap(), - ), + StateEntry::new(0, serde_json::to_value(node_state_entry).unwrap()), ); Ok(()) } @@ -215,11 +214,14 @@ impl State { channel_entry: lightning_signer::persist::model::ChannelEntry, ) -> Result<(), Error> { let key = format!("{CHANNEL_PREFIX}/{key}"); - self.ensure_not_tombstone(&key)?; - let version = self.next_version(&key); + if self.values.contains_key(&key) { + return Err(Error::Internal(format!( + "channel {key} already exists in signer state" + ))); + } self.values.insert( key, - StateEntry::new(version, serde_json::to_value(channel_entry).unwrap()), + StateEntry::new(0, serde_json::to_value(channel_entry).unwrap()), ); Ok(()) } @@ -412,11 +414,84 @@ impl State { self.values.len() } + pub(crate) fn entry_fingerprints( + &self, + ) -> impl Iterator> { + self.values + .iter() + .filter(|(key, _)| !key.starts_with(PEER_PREFIX)) + .map(|(key, entry)| { + let hash = sha256::Hash::hash(&entry.canonical_value_bytes()?).to_byte_array(); + Ok((key.as_str(), entry.version, hash)) + }) + } + pub(crate) fn without_peer_hints(mut self) -> Self { self.values.retain(|key, _| !key.starts_with(PEER_PREFIX)); self } + // A full snapshot is authoritative for every entry it supplies, including version zero. + pub(crate) fn restore_snapshot(&self, mut snapshot: Self, node_id: &[u8]) -> Self { + let id = hex::encode(node_id); + let node_key = format!("{NODE_PREFIX}/{id}"); + let state_key = format!("{NODE_STATE_PREFIX}/{id}"); + let channel_prefix = format!("{CHANNEL_PREFIX}/{id}"); + let tracker_key = format!("{TRACKER_PREFIX}/{id}"); + let allowlist_key = format!("{ALLOWLIST_PREFIX}/{id}"); + // Only use the seed defaults for a new node. The caller validates the complete candidate. + let has_node_records = snapshot.values.keys().any(|key| { + *key == node_key + || *key == state_key + || *key == tracker_key + || *key == allowlist_key + || key.starts_with(&channel_prefix) + }); + if !has_node_records { + for (key, entry) in &self.values { + snapshot + .values + .entry(key.clone()) + .or_insert_with(|| entry.clone()); + } + } + snapshot + } + + pub(crate) fn validate_signer_state(&self, node_id: &[u8]) -> anyhow::Result<()> { + let id = hex::encode(node_id); + let node_key = format!("{NODE_PREFIX}/{id}"); + let state_key = format!("{NODE_STATE_PREFIX}/{id}"); + let tracker_key = format!("{TRACKER_PREFIX}/{id}"); + let is_live = |key: &str| { + self.values + .get(key) + .is_some_and(|entry| entry.version != TOMBSTONE_VERSION) + }; + if !is_live(&node_key) || !is_live(&state_key) { + bail!("incomplete signer node records for {id}"); + } + if self.values.keys().any(|key| { + (key.starts_with("nodes/") && *key != node_key) + || (key.starts_with("nodestates/") && *key != state_key) + }) { + bail!("signer state contains an unexpected node"); + } + if !is_live(&tracker_key) { + bail!("signer state is missing required entry {tracker_key}"); + } + Ok(()) + } + + pub(crate) fn channel_is_tombstoned( + &self, + node_id: &PublicKey, + channel_id: &ChannelId, + ) -> bool { + let id = vls_persist::model::NodeChannelId::new(node_id, channel_id); + self.is_tombstone(&format!("{CHANNEL_PREFIX}/{}", hex::encode(id.0))) + } + /// Merge incoming state and track potential version conflicts. /// /// A conflict means the incoming state is stale or incompatible with local @@ -430,11 +505,7 @@ impl State { None => { trace!("Insert new key {}: version={}", key, newver); res.changes.push((key.to_owned(), None, newver)); - let mut inserted = incoming.clone(); - if incoming_is_tombstone { - inserted.value = serde_json::Value::Null; - } - self.values.insert(key.clone(), inserted); + self.values.insert(key.clone(), incoming.clone()); } Some(v) => { if incoming_is_tombstone { @@ -448,11 +519,8 @@ impl State { newver ); res.changes.push((key.to_owned(), Some(v.version), newver)); - *v = StateEntry { - version: newver, - value: serde_json::Value::Null, - signature: incoming.signature.clone(), - }; + // The version marks deletion. Preserve the signed payload for the watermark. + *v = incoming.clone(); continue; } @@ -1005,9 +1073,7 @@ impl Persist for MemoryPersister { 0, state_e.velocity_control.into(), state_e.fee_velocity_control.into(), - 0u64, - /* dbid_high_water_mark: prevents reuse of - * channel dbid, 0 disables enforcement. */ + state_e.dbid_high_water_mark, allowlist, ); @@ -1461,6 +1527,25 @@ mod tests { assert_eq!(res.conflict_count, 0); } + #[test] + fn merge_preserves_tombstone_payload_and_signature() { + let key = "channels/abc"; + let entry = SignerStateEntry { + key: key.to_owned(), + version: TOMBSTONE_VERSION, + value: br#"{"reason":"closed"}"#.to_vec(), + signature: vec![1, 2, 3], + }; + let incoming = State::try_from(std::slice::from_ref(&entry)).unwrap(); + + for mut state in [State::new(), mk_state(vec![(key, 2, json!({"v": 1}))])] { + state.merge(&incoming).unwrap(); + assert!(state.is_tombstone(key)); + let merged: Vec = state.into(); + assert_eq!(merged, vec![entry.clone()]); + } + } + #[test] fn merge_ignores_live_entry_if_key_is_tombstone() { let live_key = format!("{CHANNEL_PREFIX}/abc"); diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 919a59a02..136f364bf 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -72,6 +72,8 @@ pub mod model; mod report; mod resolve; mod splice_policy; +mod watermark; +use watermark::WatermarkRuntime; const VERSION: &str = "v26.06"; const GITHASH: &str = env!("GIT_HASH"); @@ -123,7 +125,7 @@ pub struct SignerConfig { pub state_signature_mode: StateSignatureMode, pub state_signature_override: Option, pub fee_budget_limits: FeeBudgetLimits, - /// Device-local metadata storage, required for a one-time Soft migration. + /// Persistent device-local watermark storage, required in Soft mode. pub device_storage: Option>, #[cfg(feature = "backup")] pub backup: Option, @@ -153,6 +155,7 @@ pub struct Signer { state_signing_pubkey: PublicKey, state_signature_mode: StateSignatureMode, soft_migration: Arc>>, + watermark: Arc>>, state_signature_override_enabled: bool, state_signature_override_note: Option, fee_budget_limits: FeeBudgetLimits, @@ -208,6 +211,12 @@ pub enum Error { #[error("hard fee budget rejected request: {0}")] FeeBudget(#[source] anyhow::Error), + #[error("{0:#}")] + WatermarkStorage(#[source] anyhow::Error), + + #[error("{0:#}")] + WatermarkViolation(#[source] anyhow::Error), + #[error("preapproval declined: {cause}")] PreapprovalDeclined { #[source] @@ -228,6 +237,15 @@ pub enum Error { ApprovePairingRequestError(String), } +impl Error { + fn is_fatal_watermark_error(&self) -> bool { + matches!( + self, + Self::WatermarkStorage(_) | Self::WatermarkViolation(_) + ) + } +} + impl Signer { pub fn new(secret: Vec, network: Network, creds: T) -> Result where @@ -251,7 +269,10 @@ impl Signer { info!("Initializing signer for {VERSION} ({GITHASH}) (VLS)"); let state_signature_mode = config.state_signature_mode; - let device_storage = config.device_storage; + let device_storage = match state_signature_mode { + StateSignatureMode::Off => None, + _ => config.device_storage, + }; #[cfg(feature = "backup")] let backup_config = { if let Some(backup) = &config.backup { @@ -375,15 +396,23 @@ impl Signer { let state_signing_pubkey = PublicKey::from_secret_key(&Secp256k1::signing_only(), &state_signing_secret); + let device_key = format!("signer/{network}/{}", hex::encode(&id)); + let watermark = device_storage + .as_ref() + .map(|store| WatermarkRuntime::load(store.clone(), format!("{device_key}/watermark"))) + .transpose()?; let soft_migration = match (state_signature_mode, device_storage) { (StateSignatureMode::Soft, Some(store)) => { - let key = format!("signer/{network}/{}/soft-migration", hex::encode(&id)); + let key = format!("{device_key}/soft-migration"); if store .load(&key) .context("loading Soft migration marker")? .is_some() + || watermark + .as_ref() + .is_some_and(WatermarkRuntime::has_checkpoint) { - warn!("Soft state migration has already been used on this device for this node; using Hard mode"); + warn!("Device storage already has a Soft migration marker or watermark for this node; using Hard mode"); None } else { Some(SoftMigration { store, key }) @@ -410,6 +439,7 @@ impl Signer { state_signing_pubkey, state_signature_mode, soft_migration: Arc::new(Mutex::new(soft_migration)), + watermark: Arc::new(Mutex::new(watermark)), state_signature_override_enabled, state_signature_override_note, fee_budget_limits: config.fee_budget_limits, @@ -808,6 +838,7 @@ impl Signer { .await .map_err(|e| Error::NodeDisconnect(e))?; } + Err(e) if e.is_fatal_watermark_error() => return Err(e), Err(e) => { let rejection = crate::pb::scheduler::SignerRejection { msg: format!("Error in run_once loop: {:?}", e), @@ -886,6 +917,7 @@ impl Signer { .process_request_with_message(req, msg, decline.is_some()) .await; match (result, decline) { + (Err(e), _) if e.is_fatal_watermark_error() => Err(e), (Err(cause), Some(reply)) => Err(Error::PreapprovalDeclined { cause: Box::new(cause), reply, @@ -958,29 +990,37 @@ impl Signer { .state .lock() .map_err(|e| Error::Other(anyhow!("Failed to acquire state lock: {:?}", e)))?; - let mut candidate = live_state.clone(); - let prestate_log = { - 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)))?; + let mut watermark = self + .watermark + .lock() + .map_err(|_| Error::WatermarkStorage(anyhow!("watermark runtime lock poisoned")))?; + let first_snapshot = watermark + .as_ref() + .map_or(Ok(false), |runtime| runtime.admit(&incoming_state))?; + let candidate = if first_snapshot { + live_state.restore_snapshot(incoming_state, &self.id) + } else { + let mut candidate = live_state.clone(); + let merge_res = candidate.merge(&incoming_state).map_err(Error::Other)?; if merge_res.has_conflicts() { debug!( "State merge ignored stale versions (count={})", merge_res.conflict_count ); } - trace!("Processing request {}", hex::encode(&req.raw)); - #[cfg(feature = "backup")] - { - pre_backup_state = state.clone(); - } - let prestate_log = serde_json::to_string(&*state).map_err(|e| { - Error::Other(anyhow!("Failed to serialize signer state for logging: {:?}", e)) - })?; - prestate_log + candidate }; + candidate + .validate_signer_state(&self.id) + .map_err(Error::Other)?; + trace!("Processing request {}", hex::encode(&req.raw)); + #[cfg(feature = "backup")] + { + pre_backup_state = candidate.clone(); + } + let prestate_log = serde_json::to_string(&candidate) + .context("serializing signer state for logging") + .map_err(Error::Other)?; let persister = Arc::new(crate::persist::MemoryPersister::from_state(candidate)); let state = persister.state(); @@ -1094,7 +1134,31 @@ impl Signer { let response = match req.context.clone() { Some(HsmRequestContext { dbid: 0, .. }) | None => { // This is the main daemon talking to us. - root_handler.handle(msg) + if let vls_protocol::msgs::Message::NewChannel(message) = &msg { + let node = root_handler.node(); + let id = lightning_signer::channel::ChannelId::new_from_peer_id_and_oid( + &message.peer_id.0, + message.dbid, + ); + if state + .lock() + .map_err(|_| Error::Other(anyhow!("scratch state lock poisoned")))? + .channel_is_tombstoned(&node.get_id(), &id) + { + return Err(Error::Other(anyhow!( + "cannot recreate a deleted signer channel" + ))); + } + if node.get_channels().contains_key(&id) { + // An existing channel is a retry, even if forgetting a different + // channel raised the dbid high-water mark above this id. + Ok(Box::new(vls_protocol::msgs::NewChannelReply {}) as Box) + } else { + root_handler.handle(msg) + } + } else { + root_handler.handle(msg) + } } Some(c) => { let node_id_len = c.node_id.len(); @@ -1194,9 +1258,12 @@ impl Signer { .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. + if let Some(runtime) = watermark.as_mut() { + runtime.advance(&committed_state)?; + } + // Device metadata is durable before any state or signature leaves the transaction. *live_state = committed_state; + drop(watermark); drop(live_state); #[cfg(feature = "backup")] @@ -1460,6 +1527,9 @@ impl Signer { .run_once(Uri::from_maybe_shared(node_info.grpc_uri)?) .await { + if e.is_fatal_watermark_error() { + return Err(e.into()); + } warn!("Error running against node: {e}"); sleep(Duration::from_secs(1)).await; } @@ -1474,7 +1544,7 @@ impl Signer { let scheduler = self.init_scheduler(scheduler_uri).await?; tokio::select! { run_forever_inner_res = self.run_forever_inner(scheduler.clone()) => { - error!("Inner signer loop exited unexpectedly: {run_forever_inner_res:?}"); + run_forever_inner_res?; }, run_forever_scheduler_res = self.run_forever_scheduler(scheduler) => { error!("Scheduler signer loop exited unexpectedly: {run_forever_scheduler_res:?}") @@ -2447,21 +2517,25 @@ mod tests { #[derive(Debug)] struct FailingDeviceStorage { fail_load: bool, - // Some filesystems can report an error after the new bytes are written. - saved: Mutex>>, + fail_suffix: &'static str, + saved: MemoryDeviceStorage, } impl DeviceStorage for FailingDeviceStorage { - fn load(&self, _: &str) -> anyhow::Result>> { + fn load(&self, key: &str) -> anyhow::Result>> { if self.fail_load { return Err(anyhow!("device storage unavailable")); } - Ok(self.saved.lock().unwrap().clone()) + self.saved.load(key) } - fn save(&self, _: &str, value: &[u8]) -> anyhow::Result<()> { - *self.saved.lock().unwrap() = Some(value.to_vec()); - Err(anyhow!("device storage sync failed")) + fn save(&self, key: &str, value: &[u8]) -> anyhow::Result<()> { + self.saved.save(key, value)?; + // A filesystem can report an error after replacing the old bytes. + if key.ends_with(self.fail_suffix) { + return Err(anyhow!("device storage sync failed")); + } + Ok(()) } } @@ -2469,13 +2543,15 @@ mod tests { 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), + fail_suffix: "/soft-migration", + saved: MemoryDeviceStorage::default(), }); assert!(signer_with_device_storage(unavailable, 0, Network::Bitcoin).is_err()); let store: Arc = Arc::new(FailingDeviceStorage { fail_load: false, - saved: Mutex::new(None), + fail_suffix: "/soft-migration", + saved: MemoryDeviceStorage::default(), }); let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); @@ -2511,6 +2587,214 @@ mod tests { assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); } + fn hard_signer_with_storage(device_storage: Arc) -> Signer { + Signer::new_with_config( + vec![0; 32], + Network::Bitcoin, + credentials::Nobody::default(), + SignerConfig { + device_storage: Some(device_storage), + ..Default::default() + }, + ) + .unwrap() + } + + fn signed_state_entry( + signer: &Signer, + key: &str, + version: u64, + value: serde_json::Value, + ) -> SignerStateEntry { + let mut entry = mk_state_entry(key, version, value); + entry.signature = signer + .sign_state_payload(key, version, &entry.value) + .unwrap(); + entry + } + + #[cfg(feature = "file-storage")] + #[tokio::test] + async fn watermark_survives_restart_and_checks_full_snapshots_before_merge() { + let dir = tempfile::tempdir().unwrap(); + let open = + || hard_signer_with_storage(Arc::new(FileDeviceStorage::new(dir.path()).unwrap())); + let signer = open(); + let live = signed_state_entry(&signer, "state/live", 2, json!(2)); + let deleted = signed_state_entry(&signer, "state/deleted", u64::MAX, json!(null)); + let hint = mk_state_entry( + "peers/02aa", + 0, + json!({"peer_id": "02aa", "addr": "127.0.0.1:9735", "direction": "out"}), + ); + let mut full = signer + .process_request(heartbeat_request(vec![live.clone(), deleted.clone(), hint])) + .await + .unwrap() + .signer_state; + assert!(full.iter().all(|entry| !entry.key.starts_with(PEER_PREFIX))); + full.extend([live, deleted]); + let stale = signed_state_entry(&signer, "state/live", 1, json!(1)); + // Stale entries and omitted keys in an incremental update are safe in a warm runtime. + signer + .process_request(heartbeat_request(vec![stale.clone()])) + .await + .unwrap(); + drop(signer); + + let restarted = open(); + for (key, replacement, message) in [ + ("state/live", Some(stale), "fell from version"), + ("state/live", None, "missing state entry"), + ( + "state/live", + Some(signed_state_entry(&restarted, "state/live", 2, json!(9))), + "differs at version", + ), + ( + "state/deleted", + Some(signed_state_entry(&restarted, "state/deleted", 3, json!(1))), + "fell from version", + ), + ] { + let mut candidate: Vec<_> = full + .iter() + .filter(|entry| entry.key != key) + .cloned() + .collect(); + candidate.extend(replacement); + let error = restarted + .process_request(heartbeat_request(candidate)) + .await + .unwrap_err(); + assert!(matches!(error, Error::WatermarkViolation(_))); + assert!(error.to_string().contains(message), "{error}"); + } + let newer = signed_state_entry(&restarted, "state/live", 3, json!(3)); + *full + .iter_mut() + .find(|entry| entry.key == "state/live") + .unwrap() = newer; + restarted + .process_request(heartbeat_request(full)) + .await + .unwrap(); + } + + #[tokio::test] + async fn partial_node_snapshot_is_not_repaired_with_seed_defaults() { + let signer = mk_signer(StateSignatureMode::Hard); + let state: Vec = signer.state.lock().unwrap().clone().into(); + let entry = state + .into_iter() + .find(|entry| entry.key.starts_with("nodestates/")) + .unwrap(); + let signed = signed_state_entry( + &signer, + &entry.key, + entry.version, + serde_json::from_slice(&entry.value).unwrap(), + ); + let error = signer + .process_request(heartbeat_request(vec![signed])) + .await + .unwrap_err(); + assert!(error.to_string().contains("incomplete signer node records")); + } + + #[tokio::test] + async fn restored_channel_ids_distinguish_retries_from_new_channels() { + use vls_protocol::{ + model::PubKey, + msgs::{ForgetChannel, NewChannel}, + }; + + let store = Arc::new(MemoryDeviceStorage::default()); + let open = || hard_signer_with_storage(store.clone()); + let signer = open(); + let peer = PubKey(signer.node_id().try_into().unwrap()); + let create = |dbid| HsmRequest { + raw: NewChannel { + peer_id: peer.clone(), + dbid, + } + .as_vec(), + ..Default::default() + }; + signer + .process_request(heartbeat_request(vec![])) + .await + .unwrap(); + signer.process_request(create(1)).await.unwrap(); + signer.process_request(create(3)).await.unwrap(); + signer + .process_request(HsmRequest { + raw: ForgetChannel { + node_id: peer.clone(), + dbid: 3, + } + .as_vec(), + ..Default::default() + }) + .await + .unwrap(); + + let snapshot: Vec = signer.state.lock().unwrap().clone().into(); + drop(signer); + let restarted = open(); + restarted + .process_request(heartbeat_request(snapshot)) + .await + .unwrap(); + assert!(restarted.process_request(create(1)).await.is_ok()); + assert!(restarted.process_request(create(2)).await.is_err()); + assert!(restarted.process_request(create(3)).await.is_err()); + assert!(restarted.process_request(create(4)).await.is_ok()); + } + + #[tokio::test] + async fn ambiguous_watermark_write_blocks_clones_and_keeps_soft_spent() { + let store = Arc::new(FailingDeviceStorage { + fail_load: false, + fail_suffix: "/watermark", + saved: MemoryDeviceStorage::default(), + }); + let signer = signer_with_device_storage(store.clone(), 0, Network::Bitcoin).unwrap(); + let before = serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(); + let request = heartbeat_request(vec![mk_state_entry("state/legacy", 1, json!(1))]); + let error = signer.process_request(request).await.unwrap_err(); + assert!(matches!(error, Error::WatermarkStorage(_))); + assert_eq!( + serde_json::to_value(&*signer.state.lock().unwrap()).unwrap(), + before + ); + let error = signer + .clone() + .process_request(heartbeat_request(vec![])) + .await + .unwrap_err(); + assert!(matches!(error, Error::WatermarkStorage(_))); + let restarted = signer_with_device_storage(store, 0, Network::Bitcoin).unwrap(); + assert_eq!(restarted.current_mode(), StateSignatureMode::Hard); + let error = restarted + .process_request(heartbeat_request(vec![])) + .await + .unwrap_err(); + assert!(error.to_string().contains("watermark: missing state entry")); + } + + #[tokio::test] + async fn existing_watermark_prevents_switching_from_hard_to_soft() { + let store = Arc::new(MemoryDeviceStorage::default()); + let hard = hard_signer_with_storage(store.clone()); + hard.process_request(heartbeat_request(vec![])) + .await + .unwrap(); + drop(hard); + let signer = signer_with_device_storage(store, 0, Network::Bitcoin).unwrap(); + assert_eq!(signer.current_mode(), StateSignatureMode::Hard); + } + #[tokio::test] async fn backend_peer_hints_are_accepted_without_being_signed() { use crate::persist::{PeerEntry, State}; diff --git a/libs/gl-client/src/signer/watermark.rs b/libs/gl-client/src/signer/watermark.rs new file mode 100644 index 000000000..ae1c7ddbc --- /dev/null +++ b/libs/gl-client/src/signer/watermark.rs @@ -0,0 +1,142 @@ +use super::{DeviceStorage, Error}; +use crate::persist::State; +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, sync::Arc}; + +const FORMAT_VERSION: u32 = 1; + +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Entry { + version: u64, + value_hash: [u8; 32], +} + +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Watermark { + format_version: u32, + entries: BTreeMap, +} + +impl Watermark { + fn from_state(state: &State) -> Result { + let entries = state + .entry_fingerprints() + .map(|entry| { + let (key, version, value_hash) = entry?; + Ok(( + key.to_owned(), + Entry { + version, + value_hash, + }, + )) + }) + .collect::>()?; + Ok(Self { + format_version: FORMAT_VERSION, + entries, + }) + } + + fn check(&self, candidate: &Self) -> Result<()> { + for (key, previous) in &self.entries { + let entry = candidate + .entries + .get(key) + .with_context(|| format!("watermark: missing state entry {key}"))?; + if entry.version < previous.version { + bail!( + "watermark: state entry {key} fell from version {} to {}", + previous.version, + entry.version + ); + } + if entry.version == previous.version && entry.value_hash != previous.value_hash { + bail!( + "watermark: state entry {key} differs at version {}", + entry.version + ); + } + } + Ok(()) + } +} + +pub(super) struct WatermarkRuntime { + store: Arc, + key: String, + committed: Option, + initialized: bool, + blocked: bool, +} + +impl WatermarkRuntime { + pub(super) fn load(store: Arc, key: String) -> Result { + let committed = store + .load(&key) + .context("loading watermark")? + .map(|bytes| -> Result { + let watermark: Watermark = + serde_json::from_slice(&bytes).context("decoding watermark")?; + if watermark.format_version != FORMAT_VERSION || watermark.entries.is_empty() { + bail!("invalid watermark format version or empty entries"); + } + Ok(watermark) + }) + .transpose()?; + Ok(Self { + store, + key, + committed, + initialized: false, + blocked: false, + }) + } + + pub(super) fn has_checkpoint(&self) -> bool { + self.committed.is_some() + } + + /// Check the first full snapshot before the signer merges its seed defaults. + pub(super) fn admit(&self, incoming: &State) -> Result { + if self.blocked { + return Err(Error::WatermarkStorage(anyhow::anyhow!( + "watermark storage failed; reconstruct the signer to reload it" + ))); + } + if self.initialized { + return Ok(false); + } + if let Some(committed) = &self.committed { + let snapshot = Watermark::from_state(incoming).map_err(Error::Other)?; + committed + .check(&snapshot) + .map_err(Error::WatermarkViolation)?; + } + Ok(true) + } + + /// Save the signed candidate before the signer commits it or releases signatures. + pub(super) fn advance(&mut self, state: &State) -> Result<(), Error> { + let watermark = Watermark::from_state(state).map_err(Error::Other)?; + if let Some(committed) = &self.committed { + committed + .check(&watermark) + .map_err(Error::WatermarkViolation)?; + } + if !self.initialized || self.committed.as_ref() != Some(&watermark) { + let bytes = serde_json::to_vec(&watermark) + .context("encoding watermark") + .map_err(Error::WatermarkStorage)?; + if let Err(error) = self.store.save(&self.key, &bytes) { + // The write can fail after replacing the old bytes. + self.blocked = true; + return Err(Error::WatermarkStorage(error.context("saving watermark"))); + } + self.committed = Some(watermark); + } + self.initialized = true; + Ok(()) + } +} diff --git a/libs/gl-plugin/src/node/mod.rs b/libs/gl-plugin/src/node/mod.rs index fea0b4848..0785e6205 100644 --- a/libs/gl-plugin/src/node/mod.rs +++ b/libs/gl-plugin/src/node/mod.rs @@ -472,7 +472,7 @@ impl Node for PluginNodeServer { let state_snapshot = signer_state.lock().await.clone(); let state_entries: Vec = - state_snapshot.omit_tombstones().into(); + state_snapshot.clone().into(); let state_wire_bytes = signer_state_request_wire_bytes(&state_entries); let state_entries: Vec = state_entries .into_iter() @@ -528,7 +528,7 @@ impl Node for PluginNodeServer { let state_snapshot = signer_state.lock().await.clone(); // Estimate the size of the full state to calculate the bandwidth savings of sending diffs let full_entries: Vec = - state_snapshot.omit_tombstones().into(); + state_snapshot.clone().into(); let full_wire_bytes = signer_state_request_wire_bytes(&full_entries); // Send only the changes since the last time we sent state to this signer. From 694d77acc56ee2ce879832b24b9c550199535735 Mon Sep 17 00:00:00 2001 From: Ihor Diachenko Date: Wed, 18 Nov 2026 01:57:04 +0200 Subject: [PATCH 4/4] signer: Require device storage in Hard mode Make callers supply durable storage for production signers. Thread the storage path through the bindings, CLIs, examples and test fixtures. Reuse the signer and its loaded device state when applying credentials after registration, recovery or standalone authentication. --- .github/workflows/python.yml | 6 +- docs/src/reference/certs.md | 8 +- docs/src/reference/security.md | 56 +++-- docs/src/reference/signer-state.md | 233 +++++++++++------- examples/python/app_test.py | 8 +- examples/python/snippets/getting_started.py | 6 +- examples/rust/Cargo.toml | 2 +- examples/rust/snippets/getting_started.rs | 21 +- libs/gl-cli/src/scheduler.rs | 9 +- libs/gl-cli/src/signer.rs | 38 ++- libs/gl-cli/src/util.rs | 8 + libs/gl-client-py/CHANGELOG.md | 6 +- libs/gl-client-py/glclient/__init__.py | 4 +- libs/gl-client-py/src/signer.rs | 6 +- libs/gl-client-py/tests/fixtures.py | 9 +- libs/gl-client-py/tests/test_scheduler.py | 8 +- libs/gl-client-py/tests/test_signer_config.py | 19 +- libs/gl-client/CHANGELOG.md | 3 +- libs/gl-client/src/scheduler.rs | 27 +- libs/gl-client/src/signer/fee_budget.rs | 1 + libs/gl-client/src/signer/mod.rs | 103 +++++--- .../com/blockstream/glsdk/AuthApiTest.kt | 14 +- .../com/blockstream/glsdk/ListPaymentTest.kt | 6 +- .../com/blockstream/glsdk/LoggingTest.kt | 2 +- .../blockstream/glsdk/NodeOperationsTest.kt | 4 +- .../blockstream/glsdk/SignerTestStorage.kt | 14 ++ .../com/blockstream/glsdk/CommonTest.kt | 5 +- .../com/blockstream/glsdk/NativeTest.kt | 5 +- libs/gl-sdk-cli/src/scheduler.rs | 6 +- libs/gl-sdk-cli/src/util.rs | 14 +- libs/gl-sdk-napi/README.md | 8 +- libs/gl-sdk-napi/src/lib.rs | 6 +- libs/gl-sdk-napi/tests/basic.spec.ts | 3 +- libs/gl-sdk-napi/tests/eventstream.spec.ts | 4 +- libs/gl-sdk-napi/tests/misc.spec.ts | 13 +- libs/gl-sdk-napi/tests/test.helper.ts | 6 +- libs/gl-sdk/CHANGELOG.md | 1 + libs/gl-sdk/bindings/glsdk.rb | 9 +- libs/gl-sdk/bindings/glsdk.swift | 26 +- libs/gl-sdk/bindings/glsdkFFI.h | 4 +- libs/gl-sdk/glsdk/glsdk.py | 29 ++- libs/gl-sdk/src/config.rs | 8 +- libs/gl-sdk/src/lib.rs | 13 +- libs/gl-sdk/src/signer.rs | 49 ++-- libs/gl-sdk/src/signer_config.rs | 33 +-- libs/gl-sdk/tests/conftest.py | 11 + libs/gl-sdk/tests/test_auth_api.py | 106 +++----- libs/gl-sdk/tests/test_basic.py | 10 +- libs/gl-sdk/tests/test_list_payments.py | 36 +-- libs/gl-sdk/tests/test_lnurl.py | 14 +- libs/gl-sdk/tests/test_node_methods.py | 12 +- libs/gl-sdk/tests/test_scheduler.py | 4 +- libs/gl-sdk/tests/test_signer_config.py | 16 +- libs/gl-testing/gltesting/clients.py | 5 +- 54 files changed, 610 insertions(+), 467 deletions(-) create mode 100644 libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/SignerTestStorage.kt create mode 100644 libs/gl-sdk/tests/conftest.py diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index c1a9ce535..f425abe85 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -85,14 +85,14 @@ jobs: uv sync run: | uv pip install libs/gl-client-py/dist/gl_client*.whl --force-reinstall - python3 -c "import glclient;creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds);print(repr(creds));print(signer.version())" + python3 -c "import glclient,tempfile;store=tempfile.TemporaryDirectory();creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds,device_storage_path=store.name);print(repr(creds));print(signer.version())" - name: Install built wheel (native) if: matrix.target == 'x86_64' run: | uv sync uv pip install libs/gl-client-py/dist/gl_client*.whl --force-reinstall - uv run python3 -c "import glclient;creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds);print(repr(creds));print(signer.version())" + uv run python3 -c "import glclient,tempfile;store=tempfile.TemporaryDirectory();creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds,device_storage_path=store.name);print(repr(creds));print(signer.version())" - name: Upload wheels uses: actions/upload-artifact@v4 @@ -143,7 +143,7 @@ jobs: run: | uv sync uv pip install libs/gl-client-py/dist/gl_client*.whl --force-reinstall - uv run python3 -c "import glclient;creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds);print(repr(creds));print(signer.version())" + uv run python3 -c "import glclient,tempfile;store=tempfile.TemporaryDirectory();creds=glclient.Credentials();signer=glclient.Signer(b'\x00'*32,'bitcoin', creds,device_storage_path=store.name);print(repr(creds));print(signer.version())" - name: Upload wheels uses: actions/upload-artifact@v4 diff --git a/docs/src/reference/certs.md b/docs/src/reference/certs.md index 3a6ff456a..e02fa2727 100644 --- a/docs/src/reference/certs.md +++ b/docs/src/reference/certs.md @@ -124,13 +124,15 @@ For the lower-level `gl-client` library, you can construct a ```rust use gl_client::credentials::Nobody; use gl_client::scheduler::Scheduler; - use gl_client::signer::Signer; + use gl_client::signer::{FileDeviceStorage, Signer}; + use std::sync::Arc; let cert = std::fs::read("client.crt")?; let key = std::fs::read("client-key.pem")?; let developer_creds = Nobody::with(cert, key); - let signer = Signer::new(seed, Network::Bitcoin, developer_creds.clone())?; + let storage = Arc::new(FileDeviceStorage::new("/path/to/app/device-state")?); + let signer = Signer::new(seed, Network::Bitcoin, developer_creds.clone(), storage)?; let scheduler = Scheduler::new(Network::Bitcoin, developer_creds).await?; let res = scheduler.register(&signer, None).await?; ``` @@ -143,7 +145,7 @@ For the lower-level `gl-client` library, you can construct a key = open("client-key.pem", "rb").read() creds = Credentials.nobody_with(cert, key) - signer = Signer(seed, network="bitcoin", creds=creds) + signer = Signer(seed, network="bitcoin", creds=creds, device_storage_path="/path/to/app/device-state") scheduler = Scheduler(network="bitcoin", creds=creds) res = scheduler.register(signer) ``` diff --git a/docs/src/reference/security.md b/docs/src/reference/security.md index bde27c4e1..060bf7bb5 100644 --- a/docs/src/reference/security.md +++ b/docs/src/reference/security.md @@ -52,17 +52,17 @@ section. ## Client ⇄ Signer Authentication The signer cannot rely on the mTLS CA structure, since that is under -control of the Greenlight team. Instead, Greenlight employs an -attestation scheme in which the signer identity attests to itself and -other signers that a particular client is authorized to perform +control of the Greenlight team. Instead, Greenlight employs an +attestation scheme in which the signer identity attests to itself and +other signers that a particular client is authorized to perform certain operations. When registering a new client, the signer will submit a [`rune`][rune] -as an access token. The rune serves mainly as an authentication while the -client's identity in form of a mTLS key-pair provides authorization. -The run is bound to the client's identity; it is presented to the signer -on each request. This will allow multiple signers to recognize which -clients are authorized, even if the signer who carved the rune is not the +as an access token. The rune serves mainly as an authentication while the +client's identity in form of a mTLS key-pair provides authorization. +The run is bound to the client's identity; it is presented to the signer +on each request. This will allow multiple signers to recognize which +clients are authorized, even if the signer who carved the rune is not the signer verifying the authorization. Before signing a request the signer independently verifies that: @@ -82,11 +82,11 @@ preventing read-access that doesn't involve the signer, while the latter ensures funds are not moved without a client authorizing it. The client-identity pubkey, its signature of the command payload, and -the rune are all passed to the node via grpc headers. The node -extracts them, alongside the call itself, and adds it to a request +the rune are all passed to the node via grpc headers. The node +extracts them, alongside the call itself, and adds it to a request context which will itself be attached to requests that are sent to the -signer, so it can verify the validity and authenticity of the -operations. An attacker that gains access to the node is unable to +signer, so it can verify the validity and authenticity of the +operations. An attacker that gains access to the node is unable to provide either these signatures and will therefore fail to convince the signer of its injected commands. @@ -115,36 +115,38 @@ must not trust it blindly. |-------|--------------|------------------| | Node infrastructure | Storing and returning the state | The content, age or completeness of the state | | Signer | Writing and signing state entries | | -| Application embedding the signer | Persisting the device watermark and choosing a signature mode | | +| Application embedding the signer | Persisting signer metadata, choosing enforcement options | | - **Authenticity:** every state entry is signed with a key derived from the node secret. In `hard` state signature mode the signer refuses entries with missing or invalid signatures, so the node cannot inject or alter state. - - **Freshness and completeness:** Signers with device storage persist - a device-local watermark before releasing signatures. A fresh process - refuses state that is older than its watermark, is missing keys, or - brings back deleted keys. + - **Freshness and completeness:** the signer keeps a _watermark_ in + device storage with a version and value hash for each signer-owned + entry it has committed. It saves the watermark before releasing + signatures. A newly started signer refuses older or missing entries, + resurrected entries, and values that differ at the same version. - **Configuration belongs to the application.** The application chooses the signature mode and controls the local storage. The node cannot reset the watermark. -On first use, the signer establishes its watermark from the first -accepted snapshot. See [Signer State](signer-state.md) for configuration, -recovery implications, and limits. +A signer without a watermark, for example on first use, trusts the first +snapshot it accepts. See +[Signer State](signer-state.md#freshness-and-completeness-the-watermark) +for configuration, recovery and limits. ## Client ⇄ Signer Authorization -The [`rune`][rune]-based signer authentication verifies a client's -identity and their authorization to execute commands. To achieve more -granular control over command authorization for individual clients, a -rune can be created with specific restrictions. When verifying client -identity, the signer additionally ensures that specific conditions, +The [`rune`][rune]-based signer authentication verifies a client's +identity and their authorization to execute commands. To achieve more +granular control over command authorization for individual clients, a +rune can be created with specific restrictions. When verifying client +identity, the signer additionally ensures that specific conditions, such as the requested command, align with the limitations of the given rune. -This enables a user to share access to the signer across multiple -clients that are restricted to a subset of commands, for example +This enables a user to share access to the signer across multiple +clients that are restricted to a subset of commands, for example read-only clients, or invoice-only clients, or clients that can only create on-chain addresses and so on. diff --git a/docs/src/reference/signer-state.md b/docs/src/reference/signer-state.md index dad1f94bf..5c87ea780 100644 --- a/docs/src/reference/signer-state.md +++ b/docs/src/reference/signer-state.md @@ -11,13 +11,15 @@ 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. -With persistent device storage, the signer keeps a watermark -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 -infrastructure, yet that same infrastructure stores the state the -signer relies on. This page describes how the signer can use state it +On the device, the signer keeps a small record called the +[watermark](#freshness-and-completeness-the-watermark). It records the +version and value hash of each signer-owned entry in the last committed +state so the signer can detect stale or incomplete state after restart. + +Storing the state on the node creates a tension with the +[security model](security.md). The signer protects funds against an +attacker with access to the infrastructure that stores the state it +relies on. This page describes how the signer can use state it receives from an untrusted store, what is protected today, what is planned, and which options an application embedding the signer controls. @@ -47,18 +49,18 @@ The node and the signer keep their copies of the state in sync by exchanging only what changed: 1. When a signer connects, the node sends it a heartbeat request that - carries a full snapshot of the state, including tombstones. The signer - checks the first snapshot after startup against the saved watermark. + carries a full snapshot of the state, including tombstones. A newly + started signer checks this first snapshot against its watermark. 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 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. It saves the watermark before - committing the copy or returning signatures. A request rejected - before the save leaves both live state and the watermark unchanged. + Only after processing and state signing succeed does it save the + watermark, commit the copy and return the signed changes, in that + order. If anything fails before the watermark is saved, both the live + state and the watermark stay unchanged. 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 @@ -75,16 +77,16 @@ least as new as the state attached to a request, so this is safe. ### Multiple signers -A node can have several signers connected at the same time, for example -the same wallet on a phone and a desktop. Every connected signer -receives every request, the first response wins, and the node merges -the state returned by all of them key by key. Because concurrent -requests touch different keys, all signers make progress, and the node -never needs to create or modify a signature itself. +Run one active signing device per node when using a watermark. If a phone +and desktop sign concurrently, both receive each request. The node uses +the first response and merges state from both signers by key. -Some cryptographic operations are not fully determined by their inputs. -Two signers handling the same request may therefore return different -but equally valid entries. The signer accepts either. +Two signers can produce different values at the same version. The node +keeps the first value it stored, and a running signer keeps the value it +already holds at that version. Different signatures over the same value +do not cause a conflict. After restart, the device whose value the node +did not keep can refuse the snapshot. See +[When legitimate state is refused](#when-legitimate-state-is-refused). ## Protecting the state @@ -93,8 +95,8 @@ There are three properties the signer needs from the state it receives: | Property | Question | Mechanism | Status | |----------|----------|-----------|--------| | Authenticity | Was every entry written by a signer of this node? | State signatures | Available | -| Freshness | Is any entry older than one this signer has already seen? | Device watermark | With persistent device storage | -| Completeness | Is any entry this signer has seen missing? | Device watermark | With persistent device storage | +| Freshness | Is any entry older than one this signer has already seen? | Device watermark | Hard and Soft modes | +| Completeness | Is any entry this signer has seen missing? | Device watermark | Hard and Soft modes | ### Authenticity: state signatures @@ -122,11 +124,12 @@ The mode is part of the signer configuration: === "Rust" ```rust - use gl_client::signer::{FileDeviceStorage, Signer, SignerConfig}; + use gl_client::signer::{FileDeviceStorage, Signer, SignerConfig, StateSignatureMode}; use std::sync::Arc; let storage = Arc::new(FileDeviceStorage::new("/path/to/app/device-state")?); let signer = Signer::new_with_config(seed, network, creds, SignerConfig { + state_signature_mode: StateSignatureMode::Hard, device_storage: Some(storage), ..Default::default() })?; @@ -143,19 +146,18 @@ The mode is part of the signer configuration: 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. +are refused. After a successful migration, all subsequent requests use +Hard, including after reconnecting. Clones of the signer share this +transition. The signer saves a migration marker in device storage after processing -and signing succeed, then saves the watermark before returning signatures. -The marker and watermark are scoped by node ID and network. If either is -already present, requesting Soft starts the signer in Hard with a warning. -Applications can keep the same configuration across restarts. 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. +and signing succeed, before it returns state or signatures. If the marker +or a watermark already exists for the node, requesting Soft starts the +signer in Hard with a warning. A watermark means that this device has +already accepted state, so there is nothing left to migrate. Applications +can therefore keep the same configuration across restarts. A successfully +processed empty snapshot also consumes the allowance. + 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. @@ -204,8 +206,8 @@ For manual recovery, a signer can be started with an override that accepts missing and invalid state signatures for the lifetime of the process. The override has to be acknowledged explicitly (`I_ACCEPT_OPERATOR_ASSISTED_STATE_OVERRIDE`), and its use is reported -to Greenlight. It disables the authenticity guarantee while watermark -checks continue to apply. Use it only together with the Greenlight team. +to Greenlight. It disables the authenticity guarantee, but the watermark +checks still apply. Use it only together with the Greenlight team. ```bash glcli signer run \ @@ -213,61 +215,120 @@ glcli signer run \ --state-override-note "support case reference" ``` -### Freshness and completeness with the watermark - -The watermark records the version and hash of each value in the last -committed state. It includes tombstones and covers only state committed -by this signer. At startup, the signer rejects a snapshot that omits an -anchored key, lowers its version, changes its value at the same version, -or brings a deleted key back. Once initialized, it can merge incremental -updates with newer state already in memory. - -The signer saves the watermark before releasing any response that -depends on a state change. If the storage write fails, the signer stops -processing requests until it is reconstructed and reloads storage. A -watermark violation also stops the signer loop and surfaces an error. - -A response lost before the node saves it can leave the watermark ahead -of the node. Two devices can also produce different values at the same -version. After restart, the saved watermark requires the node to supply -a snapshot that satisfies it. The signer has no automatic recovery for -missing or conflicting state. +### Freshness and completeness: the watermark + +A valid signature proves that a signer of this node wrote an entry. It +does not prove that the entry is the latest version, or that the node +sent every entry. A signer that starts from scratch, which on a phone +happens at every app launch, cannot tell an old, validly signed snapshot +from the current one. + +The _watermark_ closes this gap. Like a high-water mark, it records the +highest point the state has reached on this device, and the signer +refuses state that falls below it. It is a small record in device +storage with one line per state entry: the key, its latest version, and +a hash of its value. It includes tombstones. It contains no secrets and +no copy of the state itself. + +The signer saves a new watermark with every state change it commits +(step 4 of [Synchronization](#synchronization)). When a newly started +signer receives its first snapshot, it compares the snapshot with the +saved watermark and refuses it on any of these: + +| Check | The snapshot... | +|-------|-----------------| +| Rollback | has an entry at a lower version than the watermark, including a deleted key that comes back | +| Omission | is missing a key that the watermark records | +| Conflict | has an entry at the watermark's version, but with a different value | + +Entries at higher versions, and keys the watermark has never seen, are +accepted and protected by their signatures. After the first snapshot, +requests carry only changes, and the signer merges them into its +in-memory state, which already satisfies the watermark. + +A refused snapshot stops the signer with an error. So does a failed +watermark write, because the write may have partly succeeded. After a +failed write, create a new signer instance so that it reloads the +watermark from storage. + +#### When legitimate state is refused + +The watermark can also refuse state that nobody tampered with: + + - The signer saves the watermark and sends its response, but the + response is lost before the node stores the new state. If the signer + process then restarts, its watermark is ahead of the node. + - Two devices change the same entry starting from the same version. + The device whose change the node did not keep now has a watermark + that conflicts with the node. + +The signer cannot distinguish these cases from an attack. Restart can +succeed once the node supplies state that satisfies the watermark. For +a conflict, a higher version of each conflicting entry also satisfies +the check. + +#### Resetting the watermark + +The preferred fix is to restore node state that satisfies the watermark. +If that is not possible, and you have confirmed that the node's current +state is legitimate, reset the watermark so that the signer accepts that +state as a new baseline: + + 1. Stop the signer and back up its device storage. + 2. Remove only the record with the key + `signer/{network}/{node_id}/watermark`, for example + `signer/bitcoin/02ab…/watermark`, with the node ID in hex. + `FileDeviceStorage` names each file after the hex SHA-256 hash of + its key: + + ```bash + printf '%s' 'signer/bitcoin//watermark' | shasum -a 256 + ``` + + Leave the Soft migration marker in place. + + 3. Restart the signer in Hard mode, so that the reset cannot reopen the + Soft migration. The first signed snapshot it accepts becomes the new + baseline, even if it is older than the state the old watermark + recorded. -#### Manual recovery in Hard mode - -First try to restore a node snapshot that satisfies the saved watermark. -If that snapshot is unavailable, an operator of a Hard-only app can -explicitly accept a new baseline after independently verifying the state -the node will supply. Stop the signer, back up the device storage, and -remove only the `signer/{network}/{node_id}/watermark` record. For -`FileDeviceStorage`, the filename is the hex SHA-256 hash of that key, -using the hex node ID. Keep the Soft migration marker intact. +#### Configuring device storage -Restart in Hard mode. The first accepted signed snapshot establishes the -new baseline. Resetting the watermark discards the ability to reject a -previously signed snapshot based on the old baseline. +Hard and Soft require persistent device storage, which holds the +watermark and the Soft migration marker for each node and network. Reuse +the same storage across restarts. The signer does not start if storage is +not configured or cannot be read, or if the watermark is invalid. Off mode +skips both signature verification and the watermark, and needs no +storage. -#### Configuring device storage +| Entry point | Where to supply storage | +|-------------|-------------------------| +| Rust | Pass an `Arc` to `Signer::new` or set `SignerConfig::device_storage`. The optional `file-storage` feature provides `FileDeviceStorage`. | +| gl-client Python | Set the `device_storage_path` keyword on `Signer`. | +| gl-sdk | Pass the path to the standalone constructors, or set `SignerConfig.device_storage_path` through `Config.with_signer_config` before using `NodeBuilder` with a signer. | +| Node.js SDK | Pass the path as the second argument to `Signer`. | +| glcli and gl-sdk-cli | Both use `/device-state`. | -Soft mode requires persistent storage. In Hard mode, set -`SignerConfig::device_storage` in Rust to enable the watermark. Reuse the -same storage across restarts. Unreadable storage and invalid watermark -data prevent signer initialization. +A custom `DeviceStorage` provides fallible `load` and `save` operations +over opaque bytes. Writes must replace values atomically and durably. -Upgrade the node plugin first so it includes tombstones in initial -snapshots. Off mode is intended for development and bypasses both -signature verification and the watermark. +The node plugin must include tombstones in the first snapshot. Older +plugins left them out, which the signer refuses as an omission once its +watermark records a deleted key. #### Limits -A device without a watermark uses the first accepted snapshot as its -baseline, including after pairing or reinstalling. Deleting or rolling back -device storage can weaken both rollback protection and the Soft migration -limit. - -Run one active signer instance per device storage namespace. Clones -share the watermark, but separate signer instances and devices cannot -coordinate their local records. We plan to address coordination with an -external watermarking service outside Blockstream’s control. + - A device without a watermark trusts the first snapshot it accepts and + makes it the baseline. This happens on first start, after pairing, + reinstalling or a reset, and whenever device storage is deleted. + Restoring an older copy of device storage weakens protection in the + same way. Either can also reopen the Soft migration. + - The watermark only covers what this device has seen. An entry written + by another signer that never reached this device is protected by its + signature alone. + - Run one signer instance per device storage. Clones of a signer share + its watermark, but separate instances and separate devices keep + independent watermarks. We plan to coordinate them through an external + watermarking service outside Blockstream's control. [vls]: https://vls.tech diff --git a/examples/python/app_test.py b/examples/python/app_test.py index d7ba3307d..afd95029b 100644 --- a/examples/python/app_test.py +++ b/examples/python/app_test.py @@ -16,11 +16,11 @@ class GetInfoApp: (run it from the host). `pytest -s -v app_test.py::test_getinfoapp`. """ - def __init__(self, secret: bytes, network: str, tls: TlsConfig): + def __init__(self, secret: bytes, network: str, tls: TlsConfig, device_storage_path: str): self.secret: bytes = secret self.network = network self.tls: TlsConfig = tls - self.signer: Signer = Signer(secret, network, tls) # signer needs to keep running + self.signer: Signer = Signer(secret, network, tls, device_storage_path=device_storage_path) # signer needs to keep running self.node_id: bytes = self.signer.node_id() def scheduler(self) -> Scheduler: @@ -51,7 +51,7 @@ def get_info(self) -> nodepb.GetInfoResponse: return node.get_info() -def test_getinfoapp(): +def test_getinfoapp(tmp_path): # These are normally persisted on disk and need to be loaded and # passed to the glclient library by the application. In this # example we store them directly in the "app". @@ -60,7 +60,7 @@ def test_getinfoapp(): tls = TlsConfig() # Register a node - giap = GetInfoApp(secret, network, tls) + giap = GetInfoApp(secret, network, tls, str(tmp_path / "device-state")) giap.register_or_recover() # GetInfo diff --git a/examples/python/snippets/getting_started.py b/examples/python/snippets/getting_started.py index 61033bdda..ba013fa85 100644 --- a/examples/python/snippets/getting_started.py +++ b/examples/python/snippets/getting_started.py @@ -65,7 +65,7 @@ def load_developer_creds(): def register_node(seed: bytes, developer_creds: Credentials): # ---8<--- [start: init_signer] - signer = Signer(seed, NETWORK, developer_creds) + signer = Signer(seed, NETWORK, developer_creds, device_storage_path=str(Path(TEST_NODE_DATA_DIR_1) / "device-state")) # ---8<--- [end: init_signer] # ---8<--- [start: register_node] @@ -106,7 +106,7 @@ def start_node(device_creds_file_path: str) -> None: # ---8<--- [start: start_signer] seed = read_file("hsm_secret") - signer = Signer(seed, NETWORK, device_creds) + signer = Signer(seed, NETWORK, device_creds, device_storage_path=str(Path(TEST_NODE_DATA_DIR_1) / "device-state")) signer.run_in_thread() # ---8<--- [end: start_signer] @@ -125,7 +125,7 @@ def recover_node(developer_cert: bytes, developer_key: bytes) -> None: # ---8<--- [start: recover_node] seed = read_file("hsm_secret") signer_creds = Credentials.nobody_with(developer_cert, developer_key) - signer = Signer(seed, NETWORK, signer_creds) + signer = Signer(seed, NETWORK, signer_creds, device_storage_path=str(Path(TEST_NODE_DATA_DIR_1) / "device-state")) scheduler = Scheduler(NETWORK, signer_creds) recover_response = scheduler.recover(signer) # ---8<--- [end: recover_node] diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 88a9128f4..3eaa453cb 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -gl-client = { path = "../../libs/gl-client" } +gl-client = { path = "../../libs/gl-client", features = ["file-storage"] } rand = "0.8" bip39 = { version = "2", features = ["rand_core"] } tokio = { version = "1.29.1", features = ["rt", "macros"] } diff --git a/examples/rust/snippets/getting_started.rs b/examples/rust/snippets/getting_started.rs index f07bb4016..3452d06d6 100644 --- a/examples/rust/snippets/getting_started.rs +++ b/examples/rust/snippets/getting_started.rs @@ -6,15 +6,21 @@ use gl_client::{ node::ClnClient, pb::{cln, cln::{amount_or_any, Amount, AmountOrAny}}, scheduler::Scheduler, - signer::Signer, + signer::{FileDeviceStorage, Signer}, }; use rand::RngCore; -use std::{env, fs, path::PathBuf}; +use std::{env, fs, path::PathBuf, sync::Arc}; use tokio; const NETWORK: Network = Network::Regtest; const TEST_NODE_DATA_DIR: &str = "/tmp/gltests/node2"; +fn device_storage() -> Result> { + Ok(Arc::new(FileDeviceStorage::new( + PathBuf::from(TEST_NODE_DATA_DIR).join("device-state"), + )?)) +} + fn save_to_file(file_name: &str, data: &[u8]) -> Result<()> { let path = PathBuf::from(TEST_NODE_DATA_DIR).join(file_name); if let Some(parent) = path.parent() { @@ -78,7 +84,12 @@ fn load_developer_creds() -> Result { async fn register_node(seed: Vec, developer_creds: Nobody) -> Result<(Scheduler, Device, Signer)> { // ---8<--- [start: init_signer] - let signer = Signer::new(seed.clone(), NETWORK, developer_creds.clone())?; + let signer = Signer::new( + seed.clone(), + NETWORK, + developer_creds.clone(), + device_storage()?, + )?; // ---8<--- [end: init_signer] // ---8<--- [start: register_node] @@ -118,7 +129,7 @@ async fn start_node(device_creds_file_path: &str) -> Result<(cln::GetinfoRespons // ---8<--- [start: start_signer] let seed = read_file("hsm_secret")?; - let signer = Signer::new(seed, NETWORK, creds.clone())?; + let signer = Signer::new(seed, NETWORK, creds.clone(), device_storage()?)?; let (_tx, rx) = tokio::sync::mpsc::channel(1); tokio::spawn(async move { signer.run_forever(rx).await.unwrap(); @@ -145,7 +156,7 @@ async fn start_node(device_creds_file_path: &str) -> Result<(cln::GetinfoRespons async fn recover_node(dev_creds: Nobody) -> Result<(Scheduler, Device, Signer)> { // ---8<--- [start: recover_node] let seed = read_file("hsm_secret")?; - let signer = Signer::new(seed.clone(), NETWORK, dev_creds.clone())?; + let signer = Signer::new(seed.clone(), NETWORK, dev_creds.clone(), device_storage()?)?; let scheduler = Scheduler::new(NETWORK, dev_creds).await?; let recover_response = scheduler.recover(&signer).await?; // ---8<--- [end: recover_node] diff --git a/libs/gl-cli/src/scheduler.rs b/libs/gl-cli/src/scheduler.rs index 775d7eb40..82fea5190 100644 --- a/libs/gl-cli/src/scheduler.rs +++ b/libs/gl-cli/src/scheduler.rs @@ -106,7 +106,8 @@ async fn register_handler>( // Initialize a signer and scheduler with default credentials. let creds = credentials::Nobody::new(); - let signer = Signer::new(seed, config.network, creds.clone()) + let storage = util::device_storage(config.data_dir.as_ref())?; + let signer = Signer::new(seed, config.network, creds.clone(), storage) .map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?; let scheduler = Scheduler::new(config.network, creds) .await @@ -147,7 +148,8 @@ async fn recover_handler>(config: Config

) -> Result<()> { // Initialize a signer and scheduler with default credentials. let creds = credentials::Nobody::new(); - let signer = Signer::new(seed, config.network, creds.clone()) + let storage = util::device_storage(config.data_dir.as_ref())?; + let signer = Signer::new(seed, config.network, creds.clone(), storage) .map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?; let scheduler = Scheduler::new(config.network, creds) .await @@ -226,7 +228,8 @@ async fn upgrade_credentials_handler>(config: Config

) -> Resul // Initialize a signer and scheduler with default credentials. let nobody = credentials::Nobody::new(); - let signer = Signer::new(seed, config.network, nobody.clone()) + let storage = util::device_storage(config.data_dir.as_ref())?; + let signer = Signer::new(seed, config.network, nobody.clone(), storage) .map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?; let scheduler = Scheduler::new(config.network, nobody) .await diff --git a/libs/gl-cli/src/signer.rs b/libs/gl-cli/src/signer.rs index 5118368b5..f66f46b02 100644 --- a/libs/gl-cli/src/signer.rs +++ b/libs/gl-cli/src/signer.rs @@ -3,15 +3,15 @@ use crate::util; use clap::{Subcommand, ValueEnum}; use core::fmt::Debug; use gl_client::signer::{ - CLNBackup, CLNBackupOptions, DeviceStorage, FeeBudgetLimits, FileDeviceStorage, RecoverableChannel, - Signer, SignerBackupConfig, SignerBackupSnapshot, SignerBackupStrategy, SignerConfig, + 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 tokio::signal; use util::{CREDENTIALS_FILE_NAME, SEED_FILE_NAME}; pub struct Config> { @@ -388,12 +388,9 @@ 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( - FileDeviceStorage::new( - config.data_dir.as_ref().join("device-state"), - ) - .map_err(|e| Error::custom(format!("Failed to open device state storage: {e:#}")))?, - )), + StateSignatureModeArg::Hard | StateSignatureModeArg::Soft => { + Some(util::device_storage(config.data_dir.as_ref())?) + } _ => None, }; @@ -412,16 +409,16 @@ async fn run_handler>( .map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?; let (tx, rx) = tokio::sync::mpsc::channel(1); - let handle = tokio::spawn(async move { - let _ = signer.run_forever(rx).await; - }); - - _ = signal::ctrl_c().await.map_err(|e| Error::custom(e))?; - - _ = tx.send(()).await; - _ = join!(handle); - - Ok(()) + let mut handle = tokio::spawn(async move { signer.run_forever(rx).await }); + let result = tokio::select! { + result = &mut handle => result, + signal = signal::ctrl_c() => { + signal.map_err(Error::custom)?; + let _ = tx.send(()).await; + handle.await + } + }; + result.map_err(Error::custom)?.map_err(Error::custom) } fn backup_config_from_args( @@ -1208,7 +1205,8 @@ async fn version>(config: Config

) -> Result<()> { // Initialize a signer and scheduler with default credentials. let creds = gl_client::credentials::Nobody::new(); - let signer = gl_client::signer::Signer::new(seed, config.network, creds.clone()) + let storage = util::device_storage(config.data_dir.as_ref())?; + let signer = Signer::new(seed, config.network, creds, storage) .map_err(|e| Error::custom(format!("Failed to create signer: {}", e)))?; println!("{}", signer.version()); Ok(()) diff --git a/libs/gl-cli/src/util.rs b/libs/gl-cli/src/util.rs index 1dc044841..6f0ed8120 100644 --- a/libs/gl-cli/src/util.rs +++ b/libs/gl-cli/src/util.rs @@ -1,6 +1,8 @@ use dirs; use gl_client::credentials; +use gl_client::signer::FileDeviceStorage; use std::path::PathBuf; +use std::sync::Arc; use std::{ fs::{self, File}, io::Write, @@ -12,6 +14,12 @@ pub const SEED_FILE_NAME: &str = "hsm_secret"; pub const CREDENTIALS_FILE_NAME: &str = "credentials.gfs"; pub const DEFAULT_GREENLIGHT_DIR: &str = "greenlight"; +pub fn device_storage(data_dir: &Path) -> crate::error::Result> { + FileDeviceStorage::new(data_dir.join("device-state")) + .map(Arc::new) + .map_err(crate::error::Error::custom) +} + // -- Seed section pub fn generate_seed(words: Option) -> Result<([u8; 32], bip39::Mnemonic)> { diff --git a/libs/gl-client-py/CHANGELOG.md b/libs/gl-client-py/CHANGELOG.md index 2a1022db9..ee918f20a 100644 --- a/libs/gl-client-py/CHANGELOG.md +++ b/libs/gl-client-py/CHANGELOG.md @@ -8,7 +8,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### 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. +- `state_signature_mode` and `device_storage_path` keyword arguments for `Signer`, allowing explicit one-time Soft migration. + +### Changed + +- **Breaking:** `Signer` defaults to Hard and requires a persistent `device_storage_path` in Hard and Soft modes. ## [0.4.0] - 2026-10-12 diff --git a/libs/gl-client-py/glclient/__init__.py b/libs/gl-client-py/glclient/__init__.py index 578603223..2db5f04c5 100644 --- a/libs/gl-client-py/glclient/__init__.py +++ b/libs/gl-client-py/glclient/__init__.py @@ -29,8 +29,8 @@ def _convert(cls: Type[E], res: Iterable[Any]) -> E: class Signer(object): """Signer using Hard state verification by default. - Explicit Soft mode migrates legacy state once using the persistent - directory supplied by ``device_storage_path``. + Hard and Soft require a persistent ``device_storage_path``. Reuse this + directory across restarts. Explicit Soft mode migrates legacy state once. """ def __init__( diff --git a/libs/gl-client-py/src/signer.rs b/libs/gl-client-py/src/signer.rs index 8d5ebd41e..56add8c21 100644 --- a/libs/gl-client-py/src/signer.rs +++ b/libs/gl-client-py/src/signer.rs @@ -44,12 +44,14 @@ impl Signer { } }; let device_storage: Option> = match state_signature_mode { - StateSignatureMode::Soft => { + StateSignatureMode::Hard | 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") + PyValueError::new_err( + "Hard and Soft modes require a nonempty device_storage_path", + ) })?; Some(Arc::new(FileDeviceStorage::new(path).map_err(|e| { PyValueError::new_err(format!("opening device storage: {e:#}")) diff --git a/libs/gl-client-py/tests/fixtures.py b/libs/gl-client-py/tests/fixtures.py index b228a8c9f..dd7f34742 100644 --- a/libs/gl-client-py/tests/fixtures.py +++ b/libs/gl-client-py/tests/fixtures.py @@ -13,10 +13,15 @@ def creds(nobody_id): @pytest.fixture -def signer(scheduler, creds): +def signer(scheduler, creds, tmp_path): secret = b"\x00" * 32 network = "regtest" - return Signer(secret, network=network, creds=creds) + return Signer( + secret, + network=network, + creds=creds, + device_storage_path=str(tmp_path / "device-state"), + ) @pytest.fixture diff --git a/libs/gl-client-py/tests/test_scheduler.py b/libs/gl-client-py/tests/test_scheduler.py index 06ebe0505..bd74b235c 100644 --- a/libs/gl-client-py/tests/test_scheduler.py +++ b/libs/gl-client-py/tests/test_scheduler.py @@ -1,16 +1,14 @@ from fixtures import * -from glclient import Signer, Scheduler, Node, Credentials +from glclient import Scheduler, Node, Credentials from binascii import hexlify import unittest -def test_connect(scheduler, creds): +def test_connect(signer, creds): """Test that we can connect to the scheduler.""" - sig = Signer(b"\x00" * 32, network="regtest", creds=creds) - node_id = sig.node_id() s = Scheduler(network="regtest", creds=creds) with pytest.raises(ValueError): - s.recover(sig) + s.recover(signer) def test_register(sclient, signer): diff --git a/libs/gl-client-py/tests/test_signer_config.py b/libs/gl-client-py/tests/test_signer_config.py index 64b69eff3..43a0e4117 100644 --- a/libs/gl-client-py/tests/test_signer_config.py +++ b/libs/gl-client-py/tests/test_signer_config.py @@ -4,10 +4,15 @@ from glclient import native +@pytest.fixture(autouse=True) +def use_embedded_credentials(monkeypatch): + for name in ("GL_CA_CRT", "GL_NOBODY_CRT", "GL_NOBODY_KEY"): + monkeypatch.delenv(name, raising=False) + + @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") +def test_hard_default_opens_device_storage(constructor, tmp_path): + path = tmp_path / "device-state" signer = constructor( b"\x00" * 32, "regtest", @@ -15,17 +20,19 @@ def test_hard_default_does_not_open_device_storage(constructor, tmp_path): device_storage_path=str(path), ) assert len(bytes(signer.node_id())) == 33 + assert path.is_dir() @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"): +@pytest.mark.parametrize("mode", ["hard", "soft"]) +def test_production_modes_require_device_storage(constructor, path, mode): + with pytest.raises(ValueError, match="device_storage_path"): constructor( b"\x00" * 32, "regtest", glclient.Credentials(), - state_signature_mode="soft", + state_signature_mode=mode, device_storage_path=path, ) diff --git a/libs/gl-client/CHANGELOG.md b/libs/gl-client/CHANGELOG.md index 713b2a6d5..f6e02a051 100644 --- a/libs/gl-client/CHANGELOG.md +++ b/libs/gl-client/CHANGELOG.md @@ -14,7 +14,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed -- The signer uses a durable watermark to reject rollback and omissions across restarts. +- **Breaking:** `Signer::new` takes a `DeviceStorage` argument, configuring a persistent metadata storage. `Signer::new_with_config` requires storage in Hard and Soft modes. +- The signer uses a durable watermark to reject rollback, omissions, and same-version conflicts across restarts on the same device. - 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. diff --git a/libs/gl-client/src/scheduler.rs b/libs/gl-client/src/scheduler.rs index 19375f8d1..52f1c4e7a 100644 --- a/libs/gl-client/src/scheduler.rs +++ b/libs/gl-client/src/scheduler.rs @@ -144,15 +144,16 @@ impl Scheduler { /// /// ```rust /// # use gl_client::credentials::Nobody; - /// # use gl_client::{scheduler::Scheduler, signer::Signer}; + /// # use gl_client::{scheduler::Scheduler, signer::{DeviceStorage, Signer}}; + /// # use std::sync::Arc; /// # use lightning_signer::bitcoin::Network; - /// # async fn example() { + /// # async fn example(device_storage: Arc) { /// let node_id = vec![0, 1, 2, 3]; /// let network = Network::Regtest; /// let creds = Nobody::new(); /// let scheduler = Scheduler::new(network, creds.clone()).await.unwrap(); - /// let secret = vec![0, 0, 0, 0]; - /// let signer = Signer::new(secret, network, creds).unwrap(); // Create or obtain a signer instance + /// let secret = vec![0; 32]; + /// let signer = Signer::new(secret, network, creds, device_storage).unwrap(); // Create or obtain a signer instance /// let registration_response = scheduler.register(&signer, None).await.unwrap(); /// # } /// ``` @@ -272,15 +273,16 @@ impl Scheduler { /// /// ```rust /// # use gl_client::credentials::Nobody; - /// # use gl_client::{scheduler::Scheduler, signer::Signer}; + /// # use gl_client::{scheduler::Scheduler, signer::{DeviceStorage, Signer}}; + /// # use std::sync::Arc; /// # use lightning_signer::bitcoin::Network; - /// # async fn example() { + /// # async fn example(device_storage: Arc) { /// let node_id = vec![0, 1, 2, 3]; /// let network = Network::Regtest; /// let creds = Nobody::new(); /// let scheduler = Scheduler::new(network, creds.clone()).await.unwrap(); - /// let secret = vec![0, 0, 0, 0]; - /// let signer = Signer::new(secret, network, creds).unwrap(); // Create or obtain a signer instance + /// let secret = vec![0; 32]; + /// let signer = Signer::new(secret, network, creds, device_storage).unwrap(); // Create or obtain a signer instance /// let recovery_response = scheduler.recover(&signer).await.unwrap(); /// # } /// ``` @@ -371,15 +373,16 @@ impl Scheduler { /// /// ```rust /// # use gl_client::credentials::{Device, Nobody}; - /// # use gl_client::{scheduler::Scheduler, signer::Signer}; + /// # use gl_client::{scheduler::Scheduler, signer::{DeviceStorage, Signer}}; + /// # use std::sync::Arc; /// # use lightning_signer::bitcoin::Network; - /// # async fn example() { + /// # async fn example(device_storage: Arc) { /// let node_id = vec![0, 1, 2, 3]; /// let network = Network::Regtest; /// let creds = Nobody::new(); /// let scheduler_unauthed = Scheduler::new(network, creds.clone()).await.unwrap(); - /// let secret = vec![0, 0, 0, 0]; - /// let signer = Signer::new(secret, network, creds).unwrap(); // Create or obtain a signer instance + /// let secret = vec![0; 32]; + /// let signer = Signer::new(secret, network, creds, device_storage).unwrap(); // Create or obtain a signer instance /// let registration_response = scheduler_unauthed.register(&signer, None).await.unwrap(); /// let creds = Device::from_bytes(registration_response.creds); /// let scheduler_authed = scheduler_unauthed.authenticate(creds); diff --git a/libs/gl-client/src/signer/fee_budget.rs b/libs/gl-client/src/signer/fee_budget.rs index b139fb11f..8c133bb4e 100644 --- a/libs/gl-client/src/signer/fee_budget.rs +++ b/libs/gl-client/src/signer/fee_budget.rs @@ -400,6 +400,7 @@ mod tests { vec![1; 32], Network::Bitcoin, crate::credentials::Nobody::default(), + Arc::new(super::super::device_state::MemoryDeviceStorage::default()), ) .unwrap(); let node = signer.handler().unwrap().node().clone(); diff --git a/libs/gl-client/src/signer/mod.rs b/libs/gl-client/src/signer/mod.rs index 136f364bf..49a3dd903 100644 --- a/libs/gl-client/src/signer/mod.rs +++ b/libs/gl-client/src/signer/mod.rs @@ -125,7 +125,7 @@ pub struct SignerConfig { pub state_signature_mode: StateSignatureMode, pub state_signature_override: Option, pub fee_budget_limits: FeeBudgetLimits, - /// Persistent device-local watermark storage, required in Soft mode. + /// Persistent device-local metadata storage, required in Hard and Soft modes. pub device_storage: Option>, #[cfg(feature = "backup")] pub backup: Option, @@ -247,11 +247,24 @@ impl Error { } impl Signer { - pub fn new(secret: Vec, network: Network, creds: T) -> Result + pub fn new( + secret: Vec, + network: Network, + creds: T, + device_storage: Arc, + ) -> Result where T: TlsConfigProvider, { - Self::new_with_config(secret, network, creds, SignerConfig::default()) + Self::new_with_config( + secret, + network, + creds, + SignerConfig { + device_storage: Some(device_storage), + ..Default::default() + }, + ) } pub fn new_with_config( @@ -269,9 +282,14 @@ impl Signer { info!("Initializing signer for {VERSION} ({GITHASH}) (VLS)"); let state_signature_mode = config.state_signature_mode; - let device_storage = match state_signature_mode { - StateSignatureMode::Off => None, - _ => config.device_storage, + let device_storage = match (state_signature_mode, config.device_storage) { + (StateSignatureMode::Off, _) => None, + (_, Some(store)) => Some(store), + (_, None) => { + return Err(anyhow!( + "{state_signature_mode:?} mode requires persistent device storage" + )) + } }; #[cfg(feature = "backup")] let backup_config = { @@ -418,11 +436,6 @@ impl Signer { 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 @@ -459,6 +472,14 @@ impl Signer { }) } + /// Use different TLS credentials while keeping the shared signer state. + pub fn with_credentials(&self, creds: impl TlsConfigProvider) -> Self { + Self { + tls: creds.tls_config(), + ..self.clone() + } + } + fn init_handler(&self) -> Result { let h = handler::HandlerBuilder::new( self.network, @@ -2331,25 +2352,27 @@ mod tests { } #[test] - fn hard_is_the_default_and_soft_requires_storage() { + fn hard_is_the_default_and_both_production_modes_require_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")); + for mode in [StateSignatureMode::Hard, StateSignatureMode::Soft] { + let err = Signer::new_with_config( + vec![0; 32], + Network::Bitcoin, + credentials::Nobody::default(), + SignerConfig { + state_signature_mode: mode, + ..SignerConfig::default() + }, + ) + .err() + .unwrap(); + assert!(err + .to_string() + .contains("requires persistent device storage")); + } } #[tokio::test] @@ -2469,11 +2492,12 @@ mod tests { } #[tokio::test] - async fn default_hard_signer_signs_its_own_initial_state_without_device_storage() { + async fn default_hard_signer_signs_its_own_initial_state() { let signer = Signer::new( vec![0; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); let response = signer @@ -2860,6 +2884,7 @@ mod tests { state_signature_mode: StateSignatureMode::Soft, state_signature_override: None, fee_budget_limits: FeeBudgetLimits::default(), + device_storage: Some(Arc::new(MemoryDeviceStorage::default())), backup: Some(SignerBackupConfig { path: "backup.json".into(), strategy: SignerBackupStrategy::Periodic { updates: 0 }, @@ -2886,6 +2911,7 @@ mod tests { vec![0 as u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -2909,6 +2935,7 @@ mod tests { vec![0 as u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -3212,6 +3239,7 @@ mod tests { ack: "WRONG".to_string(), note: None, }), + device_storage: Some(Arc::new(MemoryDeviceStorage::default())), ..SignerConfig::default() }, ); @@ -3248,6 +3276,7 @@ mod tests { vec![0u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -3269,6 +3298,7 @@ mod tests { vec![0u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -3293,6 +3323,7 @@ mod tests { vec![0u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -3320,6 +3351,7 @@ mod tests { vec![0u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); let rune = "wjEjvKoFJToMLBv4QVbJpSbMoGFlnYVxs8yy40PIBgs9MC1nbDAmcHVia2V5PTAwMDAwMA=="; @@ -3337,6 +3369,7 @@ mod tests { vec![0u8; 32], Network::Bitcoin, credentials::Nobody::default(), + Arc::new(MemoryDeviceStorage::default()), ) .unwrap(); @@ -3403,7 +3436,13 @@ mod tests { #[test] fn test_empty_rune_is_valid() { let creds = credentials::Nobody::default(); - let signer = Signer::new(vec![0u8; 32], Network::Bitcoin, creds).unwrap(); + let signer = Signer::new( + vec![0u8; 32], + Network::Bitcoin, + creds, + Arc::new(MemoryDeviceStorage::default()), + ) + .unwrap(); // This is just a placeholder public key, could also be a different one; let pubkey = signer.node_id(); @@ -3426,7 +3465,13 @@ mod tests { #[test] fn test_empty_rune_checks_pubkey() { let creds = credentials::Nobody::default(); - let signer = Signer::new(vec![0u8; 32], Network::Bitcoin, creds).unwrap(); + let signer = Signer::new( + vec![0u8; 32], + Network::Bitcoin, + creds, + Arc::new(MemoryDeviceStorage::default()), + ) + .unwrap(); // This is just a placeholder public key, could also be a different one; let pubkey = signer.node_id(); diff --git a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/AuthApiTest.kt b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/AuthApiTest.kt index 418f3486e..ff5451bc5 100644 --- a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/AuthApiTest.kt +++ b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/AuthApiTest.kt @@ -64,19 +64,19 @@ class AuthApiTest { @Test(expected = Exception.PhraseCorrupted::class) fun register_bad_mnemonic() { - val config = Config() + val config = signerConfig() NodeBuilder(config).register("not a valid mnemonic", null) } @Test(expected = Exception.PhraseCorrupted::class) fun recover_bad_mnemonic() { - val config = Config() + val config = signerConfig() NodeBuilder(config).recover("not a valid mnemonic") } @Test(expected = Exception.PhraseCorrupted::class) fun connect_bad_mnemonic() { - val config = Config() + val config = signerConfig() NodeBuilder(config).connect("fake-creds".toByteArray(), "not a valid mnemonic") } @@ -87,7 +87,7 @@ class AuthApiTest { @OptIn(ExperimentalUuidApi::class) @Test fun register_or_recover_returns_node() { - val config = Config() + val config = signerConfig() val node = NodeBuilder(config).registerOrRecover(testMnemonic, null) assertNotNull(node) node.use { n -> @@ -100,7 +100,7 @@ class AuthApiTest { @OptIn(ExperimentalUuidApi::class) @Test fun credentials_roundtrip_via_connect() { - val config = Config() + val config = signerConfig() // Register or recover to get credentials val savedCreds: ByteArray @@ -138,7 +138,7 @@ class AuthApiTest { @OptIn(ExperimentalUuidApi::class) @Test fun register_or_recover_and_create_invoice() { - val config = Config() + val config = signerConfig() NodeBuilder(config).registerOrRecover(testMnemonic, null).use { node -> val addrResponse = node.onchainReceive() assertNotNull(addrResponse) @@ -161,7 +161,7 @@ class AuthApiTest { @Test fun low_level_signer_still_available() { - val signer = Signer(testMnemonic) + val signer = Signer(testMnemonic, signerStoragePath()) assertNotNull(signer) val nodeId = signer.nodeId() assertTrue("Node ID should not be empty", nodeId.isNotEmpty()) diff --git a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/ListPaymentTest.kt b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/ListPaymentTest.kt index d12c2661e..8ab3227f9 100644 --- a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/ListPaymentTest.kt +++ b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/ListPaymentTest.kt @@ -62,7 +62,7 @@ class ListPaymentTest { @OptIn(ExperimentalUuidApi::class) @Test fun created_invoice_appears_in_list_invoices() { - val config = Config() + val config = signerConfig() NodeBuilder(config).registerOrRecover(testMnemonic, null).use { node -> val label = Uuid.random().toString() node.receive(label = label, description = "Coffee", amountMsat = 10_000_000uL) @@ -83,7 +83,7 @@ class ListPaymentTest { @OptIn(ExperimentalUuidApi::class) @Test fun unpaid_invoices_excluded() { - val config = Config() + val config = signerConfig() NodeBuilder(config).registerOrRecover(testMnemonic, null).use { node -> val label = Uuid.random().toString() node.receive(label = label, description = "Tea", amountMsat = 5_000_000uL) @@ -106,7 +106,7 @@ class ListPaymentTest { @OptIn(ExperimentalUuidApi::class) @Test fun type_filter_received_only() { - val config = Config() + val config = signerConfig() NodeBuilder(config).registerOrRecover(testMnemonic, null).use { node -> val label = Uuid.random().toString() node.receive(label = label, description = "Tea", amountMsat = 5_000_000uL) diff --git a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/LoggingTest.kt b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/LoggingTest.kt index d54f268db..6c726e5e8 100644 --- a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/LoggingTest.kt +++ b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/LoggingTest.kt @@ -50,7 +50,7 @@ class LoggingTest { captured.clear() setLogLevel(LogLevel.TRACE) - val config = Config() + val config = signerConfig() val mnemonic = "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong" try { NodeBuilder(config).registerOrRecover(mnemonic, null) diff --git a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/NodeOperationsTest.kt b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/NodeOperationsTest.kt index 2c4061bb3..33779134a 100644 --- a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/NodeOperationsTest.kt +++ b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/NodeOperationsTest.kt @@ -25,7 +25,7 @@ class NodeOperationsTest { @OptIn(ExperimentalUuidApi::class) @Test fun test_onchain_receive_and_invoice() { - val config = Config() + val config = signerConfig() val node = NodeBuilder(config).registerOrRecover(testMnemonic, null) @@ -46,7 +46,7 @@ class NodeOperationsTest { @Test fun test_node_state_returns_valid_snapshot() { - val config = Config() + val config = signerConfig() val node = NodeBuilder(config).registerOrRecover(testMnemonic, null) node.use { n -> val state = n.nodeState() diff --git a/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/SignerTestStorage.kt b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/SignerTestStorage.kt new file mode 100644 index 000000000..d1c7a34d3 --- /dev/null +++ b/libs/gl-sdk-android/lib/src/androidDeviceTest/kotlin/com/blockstream/glsdk/SignerTestStorage.kt @@ -0,0 +1,14 @@ +package com.blockstream.glsdk + +import androidx.test.platform.app.InstrumentationRegistry +import java.nio.file.Files + +internal fun signerStoragePath(): String = + Files.createTempDirectory( + InstrumentationRegistry.getInstrumentation().targetContext.filesDir.toPath(), + "glsdk-signer-", + ).toString() + +internal fun signerConfig(): Config = Config().withSignerConfig( + SignerConfig(StateSignatureMode.HARD, signerStoragePath()), +) diff --git a/libs/gl-sdk-android/lib/src/commonTest/kotlin/com/blockstream/glsdk/CommonTest.kt b/libs/gl-sdk-android/lib/src/commonTest/kotlin/com/blockstream/glsdk/CommonTest.kt index eb532c52e..6b752e762 100644 --- a/libs/gl-sdk-android/lib/src/commonTest/kotlin/com/blockstream/glsdk/CommonTest.kt +++ b/libs/gl-sdk-android/lib/src/commonTest/kotlin/com/blockstream/glsdk/CommonTest.kt @@ -1,13 +1,16 @@ package com.blockstream.glsdk +import kotlin.random.Random import kotlin.test.Test +import okio.FileSystem class CommonTest { @Test fun test_signer() { val mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" - val signer = Signer(mnemonic) + val path = FileSystem.SYSTEM_TEMPORARY_DIRECTORY / "glsdk-signer-${Random.nextLong()}" + val signer = Signer(mnemonic, path.toString()) signer.start() } } diff --git a/libs/gl-sdk-android/lib/src/nativeTest/kotlin/com/blockstream/glsdk/NativeTest.kt b/libs/gl-sdk-android/lib/src/nativeTest/kotlin/com/blockstream/glsdk/NativeTest.kt index 994032f61..3ab0b4714 100644 --- a/libs/gl-sdk-android/lib/src/nativeTest/kotlin/com/blockstream/glsdk/NativeTest.kt +++ b/libs/gl-sdk-android/lib/src/nativeTest/kotlin/com/blockstream/glsdk/NativeTest.kt @@ -1,13 +1,16 @@ package com.blockstream.glsdk +import kotlin.random.Random import kotlin.test.Test +import okio.FileSystem class NativeTest { @Test fun test_signer() { val mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" - val signer = Signer(mnemonic) + val path = FileSystem.SYSTEM_TEMPORARY_DIRECTORY / "glsdk-signer-${Random.nextLong()}" + val signer = Signer(mnemonic, path.toString()) signer.start() } } diff --git a/libs/gl-sdk-cli/src/scheduler.rs b/libs/gl-sdk-cli/src/scheduler.rs index be80f99fc..7d11dfa1e 100644 --- a/libs/gl-sdk-cli/src/scheduler.rs +++ b/libs/gl-sdk-cli/src/scheduler.rs @@ -1,4 +1,4 @@ -use crate::error::{Error, Result}; +use crate::error::Result; use crate::util::{self, DataDir}; use clap::Subcommand; @@ -30,7 +30,7 @@ fn register( let signer = match util::read_secret(data_dir) { Ok(secret) => { eprintln!("Secret already exists, using it"); - util::signer_from_secret(secret)? + util::signer_from_secret(secret, data_dir)? } Err(_) => { let mnemonic = bip39::Mnemonic::generate(12)?; @@ -38,7 +38,7 @@ fn register( util::write_phrase(data_dir, &phrase)?; eprintln!("New mnemonic generated and saved"); eprintln!("Recovery phrase: {phrase}"); - glsdk::Signer::new(phrase).map_err(Error::Sdk)? + util::signer_from_secret(util::Secret::Phrase(phrase), data_dir)? } }; let scheduler = glsdk::Scheduler::new(network)?; diff --git a/libs/gl-sdk-cli/src/util.rs b/libs/gl-sdk-cli/src/util.rs index 0c2b1d1dc..eba8c9694 100644 --- a/libs/gl-sdk-cli/src/util.rs +++ b/libs/gl-sdk-cli/src/util.rs @@ -46,15 +46,21 @@ pub fn read_secret(data_dir: &DataDir) -> Result { Ok(Secret::Seed(raw)) } -pub fn signer_from_secret(secret: Secret) -> Result { +pub fn signer_from_secret(secret: Secret, data_dir: &DataDir) -> Result { + let path = data_dir + .0 + .join("device-state") + .into_os_string() + .into_string() + .map_err(|_| Error::Other("device storage path must be valid UTF-8".into()))?; match secret { - Secret::Phrase(phrase) => glsdk::Signer::new(phrase).map_err(Error::Sdk), - Secret::Seed(seed) => glsdk::Signer::new_from_seed(seed).map_err(Error::Sdk), + Secret::Phrase(phrase) => glsdk::Signer::new(phrase, path).map_err(Error::Sdk), + Secret::Seed(seed) => glsdk::Signer::new_from_seed(seed, path).map_err(Error::Sdk), } } pub fn make_signer(data_dir: &DataDir) -> Result { - signer_from_secret(read_secret(data_dir)?) + signer_from_secret(read_secret(data_dir)?, data_dir) } pub fn write_phrase(data_dir: &DataDir, phrase: &str) -> Result<()> { diff --git a/libs/gl-sdk-napi/README.md b/libs/gl-sdk-napi/README.md index 6a6bf5e61..a99cd2316 100644 --- a/libs/gl-sdk-napi/README.md +++ b/libs/gl-sdk-napi/README.md @@ -96,9 +96,9 @@ class GreenlightApp { private signer: Signer; private node: Node | null = null; - constructor(phrase: string, network: Network) { + constructor(phrase: string, network: Network, deviceStoragePath: string) { this.scheduler = new Scheduler(network); - this.signer = new Signer(phrase); + this.signer = new Signer(phrase, deviceStoragePath); console.log(`✓ Signer created. Node ID: ${this.signer.nodeId().toString('hex')}`); } @@ -197,7 +197,7 @@ async function quickStart(): Promise { const network: Network = 'regtest'; console.log('=== Greenlight SDK Demo ==='); - const app = new GreenlightApp(phrase, network); + const app = new GreenlightApp(phrase, network, './greenlight-data/device-state'); try { await app.registerOrRecover(); @@ -298,4 +298,4 @@ npm publish --access public - [Greenlight Documentation](https://blockstream.github.io/greenlight/) - [napi-rs Documentation](https://napi.rs/) - [Prebuilt Binary Support Matrix](https://github.com/napi-rs/napi-rs?tab=readme-ov-file#msrv) -- [Features Table](https://github.com/napi-rs/napi-rs?tab=readme-ov-file#features-table) \ No newline at end of file +- [Features Table](https://github.com/napi-rs/napi-rs?tab=readme-ov-file#features-table) diff --git a/libs/gl-sdk-napi/src/lib.rs b/libs/gl-sdk-napi/src/lib.rs index 887de054a..e105825c7 100644 --- a/libs/gl-sdk-napi/src/lib.rs +++ b/libs/gl-sdk-napi/src/lib.rs @@ -584,9 +584,9 @@ impl Signer { /// # Arguments /// * `phrase` - BIP39 mnemonic phrase (12 or 24 words) #[napi(constructor)] - pub fn new(phrase: String) -> Result { - // Constructor stays sync — pure key derivation, no I/O - let inner = GlSigner::new(phrase).map_err(|e| Error::from_reason(e.to_string()))?; + pub fn new(phrase: String, device_storage_path: String) -> Result { + let inner = GlSigner::new(phrase, device_storage_path) + .map_err(|e| Error::from_reason(e.to_string()))?; Ok(Self { inner }) } diff --git a/libs/gl-sdk-napi/tests/basic.spec.ts b/libs/gl-sdk-napi/tests/basic.spec.ts index 357834061..5e491852d 100644 --- a/libs/gl-sdk-napi/tests/basic.spec.ts +++ b/libs/gl-sdk-napi/tests/basic.spec.ts @@ -1,3 +1,4 @@ +import { signerStoragePath } from './test.helper.js'; import * as crypto from 'crypto'; import * as bip39 from 'bip39'; import { Credentials, Scheduler, Signer, Node } from '../index.js'; @@ -7,7 +8,7 @@ describe('Greenlight node', () => { const scheduler = new Scheduler('regtest'); const rand: Buffer = crypto.randomBytes(16); const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - const signer = new Signer(MNEMONIC); + const signer = new Signer(MNEMONIC, signerStoragePath()); const handle = await signer.start(); const nodeId = signer.nodeId(); expect(Buffer.isBuffer(nodeId)).toBe(true); diff --git a/libs/gl-sdk-napi/tests/eventstream.spec.ts b/libs/gl-sdk-napi/tests/eventstream.spec.ts index b41fd4768..3a46e9e2c 100644 --- a/libs/gl-sdk-napi/tests/eventstream.spec.ts +++ b/libs/gl-sdk-napi/tests/eventstream.spec.ts @@ -1,7 +1,7 @@ import * as crypto from 'crypto'; import * as bip39 from 'bip39'; import { Credentials, Scheduler, Signer, Node, NodeEventStream, NodeEvent, InvoicePaidEvent, Handle } from '../index.js'; -import { fundWallet, getGLNode } from './test.helper.js'; +import { fundWallet, getGLNode, signerStoragePath } from './test.helper.js'; describe('NodeEvent (type contract)', () => { it('NodeEvent and InvoicePaidEvent are assignable from NAPI-generated types', () => { @@ -92,7 +92,7 @@ describe('NodeEventStream (integration)', () => { it('next returns null after the node is stopped', async () => { const mnemonic2 = bip39.entropyToMnemonic(crypto.randomBytes(16).toString('hex')); - const signer2 = new Signer(mnemonic2); + const signer2 = new Signer(mnemonic2, signerStoragePath()); const handle2 = await signer2.start(); const credentials2 = await scheduler.register(signer2); let node2 = new Node(credentials2); diff --git a/libs/gl-sdk-napi/tests/misc.spec.ts b/libs/gl-sdk-napi/tests/misc.spec.ts index bbccdfd50..d30deb946 100644 --- a/libs/gl-sdk-napi/tests/misc.spec.ts +++ b/libs/gl-sdk-napi/tests/misc.spec.ts @@ -1,3 +1,4 @@ +import { signerStoragePath } from './test.helper.js'; import * as crypto from 'crypto'; import * as bip39 from 'bip39'; import { Credentials, Scheduler, Signer, Node } from '../index.js'; @@ -20,14 +21,14 @@ describe('Signer', () => { it('can be constructed from a mnemonic', async () => { const rand: Buffer = crypto.randomBytes(16); const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - const signer = new Signer(MNEMONIC); + const signer = new Signer(MNEMONIC, signerStoragePath()); expect(signer).toBeTruthy(); }); it('can return a node id', async () => { const rand: Buffer = crypto.randomBytes(16); const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - const signer = new Signer(MNEMONIC); + const signer = new Signer(MNEMONIC, signerStoragePath()); const nodeId = signer.nodeId(); expect(Buffer.isBuffer(nodeId)).toBe(true); @@ -37,8 +38,8 @@ describe('Signer', () => { it('returns consistent node id for same mnemonic', async () => { const rand: Buffer = crypto.randomBytes(16); const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - const signer1 = new Signer(MNEMONIC); - const signer2 = new Signer(MNEMONIC); + const signer1 = new Signer(MNEMONIC, signerStoragePath()); + const signer2 = new Signer(MNEMONIC, signerStoragePath()); const nodeId1 = signer1.nodeId(); const nodeId2 = signer2.nodeId(); @@ -49,7 +50,7 @@ describe('Signer', () => { it('can be constructed with different mnemonics', async () => { const rand2: Buffer = crypto.randomBytes(16); const MNEMONIC2: string = bip39.entropyToMnemonic(rand2.toString("hex")); - const signer = new Signer(MNEMONIC2); + const signer = new Signer(MNEMONIC2, signerStoragePath()); expect(signer).toBeTruthy(); const nodeId = signer.nodeId(); @@ -79,7 +80,7 @@ describe('Integration: scheduler and signer', () => { const rand: Buffer = crypto.randomBytes(16); const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); scheduler = new Scheduler('regtest'); - signer = new Signer(MNEMONIC); + signer = new Signer(MNEMONIC, signerStoragePath()); credentials = await scheduler.register(signer); node = new Node(credentials); }); diff --git a/libs/gl-sdk-napi/tests/test.helper.ts b/libs/gl-sdk-napi/tests/test.helper.ts index 84da1b05d..56b68ff96 100644 --- a/libs/gl-sdk-napi/tests/test.helper.ts +++ b/libs/gl-sdk-napi/tests/test.helper.ts @@ -1,8 +1,12 @@ import * as fs from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; import * as crypto from 'crypto'; import * as bip39 from 'bip39'; import { Credentials, Scheduler, Signer, Node, Handle } from '../index.js'; +export const signerStoragePath = () => fs.mkdtempSync(join(tmpdir(), 'glsdk-signer-')); + export const lspInfo = () => ({ rpcSocket: process.env.LSP_RPC_SOCKET!, nodeId: process.env.LSP_NODE_ID!, @@ -38,7 +42,7 @@ export async function fundWallet(node: Node, amountSats = 100_000_000): Promise< export async function getGLNode(scheduler: Scheduler, connectToLSP: boolean = true): Promise<{ node: Node; handle: Handle }> { const mnemonic = bip39.entropyToMnemonic(crypto.randomBytes(16).toString('hex')); const secret = bip39.mnemonicToSeedSync(mnemonic); - const signer = new Signer(mnemonic); + const signer = new Signer(mnemonic, signerStoragePath()); let credentials: Credentials; if (connectToLSP) { const testSetupServerUrl = process.env.TEST_SETUP_SERVER_URL!; diff --git a/libs/gl-sdk/CHANGELOG.md b/libs/gl-sdk/CHANGELOG.md index d387c7f9d..baf8e4bfb 100644 --- a/libs/gl-sdk/CHANGELOG.md +++ b/libs/gl-sdk/CHANGELOG.md @@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed +- Hard and Soft modes require a persistent storage path for standalone signers and signing `NodeBuilder` calls. - `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. - iOS (Kotlin and Swift): a Rust panic in the SDK reaches the app as an exception instead of aborting it, as it already does on Android. The Android and iOS libraries unwind on panic, unlike the workspace's release profile. diff --git a/libs/gl-sdk/bindings/glsdk.rb b/libs/gl-sdk/bindings/glsdk.rb index cf0111603..a1cfcde8a 100644 --- a/libs/gl-sdk/bindings/glsdk.rb +++ b/libs/gl-sdk/bindings/glsdk.rb @@ -1010,7 +1010,7 @@ module UniFFILib [:pointer, RustCallStatus.by_ref], :void attach_function :uniffi_glsdk_fn_constructor_signer_new, - [RustBuffer.by_value, RustCallStatus.by_ref], + [RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], :pointer attach_function :uniffi_glsdk_fn_method_signer_authenticate, [:pointer, :pointer, RustCallStatus.by_ref], @@ -1631,10 +1631,11 @@ def uniffi_clone_pointer() def self.uniffi_lower(inst) return inst.uniffi_clone_pointer() end - def initialize(phrase) + def initialize(phrase, device_storage_path) phrase = Glsdk::uniffi_utf8(phrase) - - pointer = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_signer_new,RustBuffer.allocFromString(phrase)) + device_storage_path = Glsdk::uniffi_utf8(device_storage_path) + + pointer = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_signer_new,RustBuffer.allocFromString(phrase),RustBuffer.allocFromString(device_storage_path)) @pointer = pointer ObjectSpace.define_finalizer(self, self.class.uniffi_define_finalizer_by_pointer(pointer, self.object_id)) end diff --git a/libs/gl-sdk/bindings/glsdk.swift b/libs/gl-sdk/bindings/glsdk.swift index b73cc5352..70a5af23c 100644 --- a/libs/gl-sdk/bindings/glsdk.swift +++ b/libs/gl-sdk/bindings/glsdk.swift @@ -551,7 +551,7 @@ public protocol ConfigProtocol: AnyObject, Sendable { func withNetwork(network: Network) -> Config /** - * Configure all signers started by NodeBuilder with this Config. + * Configure all signers started by NodeBuilder, including their required storage path. */ func withSignerConfig(signerConfig: SignerConfig) -> Config @@ -642,7 +642,7 @@ open func withNetwork(network: Network) -> Config { } /** - * Configure all signers started by NodeBuilder with this Config. + * Configure all signers started by NodeBuilder, including their required storage path. */ open func withSignerConfig(signerConfig: SignerConfig) -> Config { return try! FfiConverterTypeConfig_lift(try! rustCall() { @@ -2608,11 +2608,12 @@ open class Signer: SignerProtocol, @unchecked Sendable { public func uniffiClonePointer() -> UnsafeMutableRawPointer { return try! rustCall { uniffi_glsdk_fn_clone_signer(self.pointer, $0) } } -public convenience init(phrase: String)throws { +public convenience init(phrase: String, deviceStoragePath: String)throws { let pointer = try rustCallWithError(FfiConverterTypeError_lift) { uniffi_glsdk_fn_constructor_signer_new( - FfiConverterString.lower(phrase),$0 + FfiConverterString.lower(phrase), + FfiConverterString.lower(deviceStoragePath),$0 ) } self.init(unsafeFromRawPointer: pointer) @@ -2627,10 +2628,11 @@ public convenience init(phrase: String)throws { } -public static func newFromSeed(seed: Data)throws -> Signer { +public static func newFromSeed(seed: Data, deviceStoragePath: String)throws -> Signer { return try FfiConverterTypeSigner_lift(try rustCallWithError(FfiConverterTypeError_lift) { uniffi_glsdk_fn_constructor_signer_new_from_seed( - FfiConverterData.lower(seed),$0 + FfiConverterData.lower(seed), + FfiConverterString.lower(deviceStoragePath),$0 ) }) } @@ -6930,8 +6932,7 @@ public func FfiConverterTypeSendResponse_lower(_ value: SendResponse) -> RustBuf 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. + * Persistent directory shared across restarts. Required in Hard and Soft modes. */ public var deviceStoragePath: String? @@ -6939,8 +6940,7 @@ public struct SignerConfig { // 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. + * Persistent directory shared across restarts. Required in Hard and Soft modes. */deviceStoragePath: String?) { self.stateSignatureMode = stateSignatureMode self.deviceStoragePath = deviceStoragePath @@ -9833,7 +9833,7 @@ 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) { + if (uniffi_glsdk_checksum_method_config_with_signer_config() != 57802) { return InitializationResult.apiChecksumMismatch } if (uniffi_glsdk_checksum_method_credentials_node_id() != 16312) { @@ -9965,10 +9965,10 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_constructor_scheduler_new() != 15239) { return InitializationResult.apiChecksumMismatch } - if (uniffi_glsdk_checksum_constructor_signer_new() != 62159) { + if (uniffi_glsdk_checksum_constructor_signer_new() != 57832) { return InitializationResult.apiChecksumMismatch } - if (uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 6776) { + if (uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 18435) { return InitializationResult.apiChecksumMismatch } if (uniffi_glsdk_checksum_constructor_signer_new_from_seed_with_config() != 11623) { diff --git a/libs/gl-sdk/bindings/glsdkFFI.h b/libs/gl-sdk/bindings/glsdkFFI.h index 5f1d98764..e4eb97632 100644 --- a/libs/gl-sdk/bindings/glsdkFFI.h +++ b/libs/gl-sdk/bindings/glsdkFFI.h @@ -589,12 +589,12 @@ void uniffi_glsdk_fn_free_signer(void*_Nonnull ptr, RustCallStatus *_Nonnull out #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW #define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW -void*_Nonnull uniffi_glsdk_fn_constructor_signer_new(RustBuffer phrase, RustCallStatus *_Nonnull out_status +void*_Nonnull uniffi_glsdk_fn_constructor_signer_new(RustBuffer phrase, RustBuffer device_storage_path, RustCallStatus *_Nonnull out_status ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_FROM_SEED #define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_FROM_SEED -void*_Nonnull uniffi_glsdk_fn_constructor_signer_new_from_seed(RustBuffer seed, RustCallStatus *_Nonnull out_status +void*_Nonnull uniffi_glsdk_fn_constructor_signer_new_from_seed(RustBuffer seed, RustBuffer device_storage_path, RustCallStatus *_Nonnull out_status ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW_FROM_SEED_WITH_CONFIG diff --git a/libs/gl-sdk/glsdk/glsdk.py b/libs/gl-sdk/glsdk/glsdk.py index 014bbc6f1..4edeeb5c3 100644 --- a/libs/gl-sdk/glsdk/glsdk.py +++ b/libs/gl-sdk/glsdk/glsdk.py @@ -472,7 +472,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_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: + if lib.uniffi_glsdk_checksum_method_config_with_signer_config() != 57802: 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") @@ -560,9 +560,9 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_constructor_scheduler_new() != 15239: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_constructor_signer_new() != 62159: + if lib.uniffi_glsdk_checksum_constructor_signer_new() != 57832: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 6776: + if lib.uniffi_glsdk_checksum_constructor_signer_new_from_seed() != 18435: 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") @@ -1044,11 +1044,13 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): ) _UniffiLib.uniffi_glsdk_fn_free_signer.restype = None _UniffiLib.uniffi_glsdk_fn_constructor_signer_new.argtypes = ( + _UniffiRustBuffer, _UniffiRustBuffer, ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_constructor_signer_new.restype = ctypes.c_void_p _UniffiLib.uniffi_glsdk_fn_constructor_signer_new_from_seed.argtypes = ( + _UniffiRustBuffer, _UniffiRustBuffer, ctypes.POINTER(_UniffiRustCallStatus), ) @@ -4385,8 +4387,7 @@ class SignerConfig: 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. + Persistent directory shared across restarts. Required in Hard and Soft modes. """ def __init__(self, *, state_signature_mode: "StateSignatureMode", device_storage_path: "typing.Optional[str]"): @@ -7173,7 +7174,7 @@ def with_network(self, network: "Network"): raise NotImplementedError def with_signer_config(self, signer_config: "SignerConfig"): """ - Configure all signers started by NodeBuilder with this Config. + Configure all signers started by NodeBuilder, including their required storage path. """ raise NotImplementedError @@ -7241,7 +7242,7 @@ 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. + Configure all signers started by NodeBuilder, including their required storage path. """ _UniffiConverterTypeSignerConfig.check_lower(signer_config) @@ -8948,11 +8949,14 @@ def start(self, ): # Signer is a Rust-only trait - it's a wrapper around a Rust implementation. class Signer(): _pointer: ctypes.c_void_p - def __init__(self, phrase: "str"): + def __init__(self, phrase: "str",device_storage_path: "str"): _UniffiConverterString.check_lower(phrase) + _UniffiConverterString.check_lower(device_storage_path) + self._pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_signer_new, - _UniffiConverterString.lower(phrase)) + _UniffiConverterString.lower(phrase), + _UniffiConverterString.lower(device_storage_path)) def __del__(self): # In case of partial initialization of instances. @@ -8972,12 +8976,15 @@ def _make_instance_(cls, pointer): inst._pointer = pointer return inst @classmethod - def new_from_seed(cls, seed: "bytes"): + def new_from_seed(cls, seed: "bytes",device_storage_path: "str"): _UniffiConverterBytes.check_lower(seed) + + _UniffiConverterString.check_lower(device_storage_path) # 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, - _UniffiConverterBytes.lower(seed)) + _UniffiConverterBytes.lower(seed), + _UniffiConverterString.lower(device_storage_path)) return cls._make_instance_(pointer) @classmethod diff --git a/libs/gl-sdk/src/config.rs b/libs/gl-sdk/src/config.rs index 34dcbdc61..d70e984e3 100644 --- a/libs/gl-sdk/src/config.rs +++ b/libs/gl-sdk/src/config.rs @@ -82,7 +82,13 @@ mod tests { #[test] fn configured_signers_use_migration_settings_without_changing_the_original_config() { - let base = Config::new().with_network(Network::REGTEST); + let dir = tempfile::tempdir().unwrap(); + let base = Config::new() + .with_network(Network::REGTEST) + .with_signer_config(SignerConfig { + device_storage_path: Some(dir.path().to_str().unwrap().to_owned()), + ..Default::default() + }); let migration = base.with_signer_config(SignerConfig { state_signature_mode: StateSignatureMode::Soft, device_storage_path: None, diff --git a/libs/gl-sdk/src/lib.rs b/libs/gl-sdk/src/lib.rs index 74ca218f0..945b29fa5 100644 --- a/libs/gl-sdk/src/lib.rs +++ b/libs/gl-sdk/src/lib.rs @@ -179,11 +179,8 @@ fn schedule_node( let network = config.network; let nobody = config.nobody(); - let seed_for_async = seed.clone(); - let config_for_async = config.clone(); - let credentials = util::exec(async move { - let signer = config_for_async.create_signer(seed_for_async, nobody.clone())?; - + let signer = config.create_signer(seed, nobody.clone())?; + let (credentials, authenticated_signer) = util::exec(async move { let scheduler = gl_client::scheduler::Scheduler::new(network, nobody) .await .map_err(|e| Error::other(e.to_string()))?; @@ -207,11 +204,11 @@ fn schedule_node( } }; - credentials::Credentials::load(creds_bytes) + let credentials = credentials::Credentials::load(creds_bytes)?; + let signer = signer.with_credentials(credentials.inner.clone()); + Ok::<_, Error>((credentials, signer)) })?; - 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)?; Ok(Arc::new(node)) diff --git a/libs/gl-sdk/src/signer.rs b/libs/gl-sdk/src/signer.rs index 853a50a25..7e237732a 100644 --- a/libs/gl-sdk/src/signer.rs +++ b/libs/gl-sdk/src/signer.rs @@ -5,17 +5,20 @@ use tracing; #[derive(uniffi::Object, Clone)] 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()) + pub fn new(phrase: String, device_storage_path: String) -> Result { + Self::new_with_config( + phrase, + SignerConfig { + device_storage_path: Some(device_storage_path), + ..Default::default() + }, + ) } #[uniffi::constructor()] @@ -26,8 +29,14 @@ impl Signer { } #[uniffi::constructor()] - pub fn new_from_seed(seed: Vec) -> Result { - Self::new_from_seed_with_config(seed, SignerConfig::default()) + pub fn new_from_seed(seed: Vec, device_storage_path: String) -> Result { + Self::new_from_seed_with_config( + seed, + SignerConfig { + device_storage_path: Some(device_storage_path), + ..Default::default() + }, + ) } #[uniffi::constructor()] @@ -36,36 +45,18 @@ impl Signer { let config = config.to_client()?; let inner = gl_client::signer::Signer::new_with_config( - seed.clone(), + seed, gl_client::bitcoin::Network::Bitcoin, credentials, - config.clone(), + config, ) .map_err(|e| Error::other(format!("{e:#}")))?; - let credentials = None; - Ok(Signer { - seed, - inner, - credentials, - config, - }) + Ok(Signer { inner }) } pub fn authenticate(&self, creds: &Credentials) -> Result { - let credentials = Some(creds.clone()); - - 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(format!("{e:#}")))?; - Ok(Signer { - inner, - credentials, - ..self.clone() + inner: self.inner.with_credentials(creds.inner.clone()), }) } diff --git a/libs/gl-sdk/src/signer_config.rs b/libs/gl-sdk/src/signer_config.rs index 1e1702956..5df660d32 100644 --- a/libs/gl-sdk/src/signer_config.rs +++ b/libs/gl-sdk/src/signer_config.rs @@ -26,27 +26,26 @@ impl From for gl_client::signer::StateSignatureMode { #[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. + /// Persistent directory shared across restarts, containing signer metadata. Required in Hard and Soft modes. 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 => { + StateSignatureMode::Hard | 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") + Error::argument("device_storage_path", "required for Hard and Soft modes") })?; Some(Arc::new(FileDeviceStorage::new(path).map_err(|e| { Error::other(format!("opening device storage: {e:#}")) })?)) } - _ => None, + StateSignatureMode::Off => None, }; Ok(gl_client::signer::SignerConfig { state_signature_mode: self.state_signature_mode.into(), @@ -61,7 +60,7 @@ mod tests { use super::*; #[test] - fn default_config_uses_hard_without_opening_storage() { + fn hard_opens_storage() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("unused"); let config = SignerConfig { @@ -74,20 +73,22 @@ mod tests { config.state_signature_mode, gl_client::signer::StateSignatureMode::Hard ); - assert!(config.device_storage.is_none()); - assert!(!path.exists()); + assert!(config.device_storage.is_some()); + assert!(path.is_dir()); } #[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, + fn hard_and_soft_require_a_nonempty_storage_path() { + for mode in [StateSignatureMode::Hard, StateSignatureMode::Soft] { + for path in [None, Some(String::new())] { + let err = SignerConfig { + state_signature_mode: mode, + device_storage_path: path, + } + .to_client() + .unwrap_err(); + assert!(matches!(err, Error::Argument { .. })); } - .to_client() - .unwrap_err(); - assert!(matches!(err, Error::Argument { .. })); } } diff --git a/libs/gl-sdk/tests/conftest.py b/libs/gl-sdk/tests/conftest.py new file mode 100644 index 000000000..4f83e9a8e --- /dev/null +++ b/libs/gl-sdk/tests/conftest.py @@ -0,0 +1,11 @@ +import glsdk +import pytest + + +@pytest.fixture +def sdk_config(nobody_id, tmp_path): + cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) + signer_config = glsdk.SignerConfig( + glsdk.StateSignatureMode.HARD, str(tmp_path / "device-state") + ) + return glsdk.Config().with_developer_cert(cert).with_signer_config(signer_config) diff --git a/libs/gl-sdk/tests/test_auth_api.py b/libs/gl-sdk/tests/test_auth_api.py index 9c75f6d6e..70f8e6ba7 100644 --- a/libs/gl-sdk/tests/test_auth_api.py +++ b/libs/gl-sdk/tests/test_auth_api.py @@ -47,102 +47,84 @@ def test_config_chaining(self): class TestRegister: """Test the register() free function.""" - def test_register_returns_node(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) + def test_register_returns_node(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) assert node is not None assert isinstance(node, glsdk.Node) node.disconnect() - def test_register_credentials_roundtrip(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) + def test_register_credentials_roundtrip(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) creds = node.credentials() assert isinstance(creds, bytes) assert len(creds) > 0 node.disconnect() - def test_register_bad_mnemonic(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_register_bad_mnemonic(self, scheduler, sdk_config): with pytest.raises(glsdk.Error.PhraseCorrupted): - glsdk.NodeBuilder(config).register("not a valid mnemonic", None) + glsdk.NodeBuilder(sdk_config).register("not a valid mnemonic", None) class TestRecover: """Test the recover() free function.""" - def test_recover_after_register(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_recover_after_register(self, scheduler, sdk_config): # Register first - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) node1.disconnect() # Recover with same mnemonic - node2 = glsdk.NodeBuilder(config).recover(MNEMONIC) + node2 = glsdk.NodeBuilder(sdk_config).recover(MNEMONIC) assert node2 is not None assert isinstance(node2, glsdk.Node) creds = node2.credentials() assert len(creds) > 0 node2.disconnect() - def test_recover_nonexistent_node(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_recover_nonexistent_node(self, scheduler, sdk_config): with pytest.raises(glsdk.Error.NoSuchNode): - glsdk.NodeBuilder(config).recover(MNEMONIC) + glsdk.NodeBuilder(sdk_config).recover(MNEMONIC) class TestConnect: """Test the connect() free function.""" - def test_connect_with_saved_credentials(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_connect_with_saved_credentials(self, scheduler, sdk_config): # Register and save credentials - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) saved_creds = node1.credentials() node1.disconnect() # Connect with saved credentials - node2 = glsdk.NodeBuilder(config).connect(saved_creds, MNEMONIC) + node2 = glsdk.NodeBuilder(sdk_config).connect(saved_creds, MNEMONIC) assert node2 is not None assert isinstance(node2, glsdk.Node) node2.disconnect() - def test_connect_bad_mnemonic(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_connect_bad_mnemonic(self, scheduler, sdk_config): with pytest.raises(glsdk.Error.PhraseCorrupted): - glsdk.NodeBuilder(config).connect(b"some-creds", "bad mnemonic") + glsdk.NodeBuilder(sdk_config).connect(b"some-creds", "bad mnemonic") class TestRegisterOrRecover: """Test the register_or_recover() free function.""" - def test_registers_when_no_node_exists(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_registers_when_no_node_exists(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) assert node is not None assert isinstance(node, glsdk.Node) node.disconnect() - def test_recovers_when_node_exists(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_recovers_when_node_exists(self, scheduler, sdk_config): # Register first - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) node1.disconnect() # register_or_recover should recover - node2 = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + node2 = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) assert node2 is not None assert isinstance(node2, glsdk.Node) node2.disconnect() @@ -151,17 +133,13 @@ def test_recovers_when_node_exists(self, scheduler, nobody_id): class TestDisconnect: """Test the disconnect() method.""" - def test_disconnect_stops_signer(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) + def test_disconnect_stops_signer(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) # Should not raise node.disconnect() - def test_disconnect_idempotent(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) + def test_disconnect_idempotent(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) node.disconnect() # Second disconnect should not raise node.disconnect() @@ -170,46 +148,40 @@ def test_disconnect_idempotent(self, scheduler, nobody_id): class TestDuplicateRegister: """Test that registering the same node twice fails.""" - def test_duplicate_register(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_duplicate_register(self, scheduler, sdk_config): # Register once - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) node1.disconnect() # Register again with same mnemonic should fail with pytest.raises(glsdk.Error.DuplicateNode): - glsdk.NodeBuilder(config).register(MNEMONIC, None) + glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) class TestConnectBadCredentials: """Test that connecting with invalid credentials fails.""" - def test_connect_empty_credentials(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) + def test_connect_empty_credentials(self, scheduler, sdk_config): # Empty credentials should fail (Credentials.load returns nobody creds, # but the signer won't be able to authenticate with them) with pytest.raises(glsdk.Error): - glsdk.NodeBuilder(config).connect(b"", MNEMONIC) + glsdk.NodeBuilder(sdk_config).connect(b"", MNEMONIC) class TestMultipleNodes: """Test running multiple nodes simultaneously.""" - def test_two_nodes_independent(self, scheduler, nobody_id): + def test_two_nodes_independent(self, scheduler, sdk_config): """Two nodes from different mnemonics can run simultaneously.""" - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) mnemonic_2 = ( "zoo zoo zoo zoo zoo zoo " "zoo zoo zoo zoo zoo wrong" ) - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) - node2 = glsdk.NodeBuilder(config).register(mnemonic_2, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) + node2 = glsdk.NodeBuilder(sdk_config).register(mnemonic_2, None) assert node1 is not None assert node2 is not None @@ -228,11 +200,9 @@ def test_two_nodes_independent(self, scheduler, nobody_id): class TestDisconnectBlocksRpc: """Test that RPC calls fail after disconnect.""" - def test_credentials_still_works_after_disconnect(self, scheduler, nobody_id): + def test_credentials_still_works_after_disconnect(self, scheduler, sdk_config): """credentials() should work even after disconnect since it's local data.""" - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) node.disconnect() # credentials() is local, should still work creds = node.credentials() @@ -242,13 +212,11 @@ def test_credentials_still_works_after_disconnect(self, scheduler, nobody_id): class TestLowLevelCredentials: """Test that Node created via low-level API exposes credentials.""" - def test_node_new_stores_credentials(self, scheduler, nobody_id): + def test_node_new_stores_credentials(self, scheduler, sdk_config): """Node::new(creds) should allow calling node.credentials().""" - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) # Register to get valid credentials - node1 = glsdk.NodeBuilder(config).register(MNEMONIC, None) + node1 = glsdk.NodeBuilder(sdk_config).register(MNEMONIC, None) saved_creds = node1.credentials() node1.disconnect() diff --git a/libs/gl-sdk/tests/test_basic.py b/libs/gl-sdk/tests/test_basic.py index 1899b7ddc..0d375d3f0 100644 --- a/libs/gl-sdk/tests/test_basic.py +++ b/libs/gl-sdk/tests/test_basic.py @@ -83,14 +83,15 @@ def test_scheduler_with_developer_cert(): assert isinstance(scheduler_with_cert, glsdk.Scheduler) -def test_register_with_developer_cert(scheduler, nobody_id): +def test_register_with_developer_cert(scheduler, nobody_id, tmp_path): """Test that register works when using an explicit DeveloperCert.""" # Load the test nobody cert/key from the fixture's byte attributes dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) signer = glsdk.Signer( "abandon abandon abandon abandon abandon abandon " - "abandon abandon abandon abandon abandon about" + "abandon abandon abandon abandon abandon about", + str(tmp_path / "device-state"), ) s = glsdk.Scheduler(glsdk.Network.BITCOIN).with_developer_cert(dev_cert) creds = s.register(signer, code=None) @@ -98,10 +99,11 @@ def test_register_with_developer_cert(scheduler, nobody_id): assert isinstance(creds, glsdk.Credentials) -def test_register_and_auth(scheduler, clients): +def test_register_and_auth(scheduler, clients, tmp_path): signer = glsdk.Signer( "abandon abandon abandon abandon abandon abandon " - "abandon abandon abandon abandon abandon about" + "abandon abandon abandon abandon abandon about", + str(tmp_path / "device-state"), ) # Now use the signer to sign up a new node: diff --git a/libs/gl-sdk/tests/test_list_payments.py b/libs/gl-sdk/tests/test_list_payments.py index 4465416fd..475bbdba4 100644 --- a/libs/gl-sdk/tests/test_list_payments.py +++ b/libs/gl-sdk/tests/test_list_payments.py @@ -70,10 +70,8 @@ class TestListInvoicesMethod: def test_node_has_list_invoices_method(self): assert hasattr(glsdk.Node, "list_invoices") - def test_list_invoices_empty(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_list_invoices_empty(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) result = node.list_invoices( label=None, invstring=None, payment_hash=None, offer_id=None, index=None, start=None, limit=None, @@ -117,10 +115,8 @@ class TestListPaysMethod: def test_node_has_list_pays_method(self): assert hasattr(glsdk.Node, "list_pays") - def test_list_pays_empty(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_list_pays_empty(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) result = node.list_pays( bolt11=None, payment_hash=None, status=None, index=None, start=None, limit=None, @@ -239,10 +235,8 @@ class TestListPaymentsMethod: def test_node_has_list_payments_method(self): assert hasattr(glsdk.Node, "list_payments") - def test_list_payments_empty(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_list_payments_empty(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) req = glsdk.ListPaymentsRequest( filters=None, from_timestamp=None, to_timestamp=None, include_failures=None, offset=None, limit=None, @@ -256,10 +250,8 @@ def test_list_payments_empty(self, scheduler, nobody_id): class TestListInvoicesIntegration: """Test that created invoices appear in list_invoices and list_payments.""" - def test_created_invoice_appears_in_list_invoices(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_created_invoice_appears_in_list_invoices(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) label = str(uuid.uuid4()) node.receive(label=label, description="coffee", amount_msat=10_000_000) @@ -277,13 +269,11 @@ def test_created_invoice_appears_in_list_invoices(self, scheduler, nobody_id): assert matching[0].destination_pubkey is not None node.disconnect() - def test_unpaid_invoices_excluded(self, scheduler, nobody_id): + def test_unpaid_invoices_excluded(self, scheduler, sdk_config): """list_payments returns only paid invoices on the received side. Open / expired invoices live behind list_invoices() for direct inspection.""" - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) label = str(uuid.uuid4()) node.receive(label=label, description="tea", amount_msat=5_000_000) @@ -303,10 +293,8 @@ def test_unpaid_invoices_excluded(self, scheduler, nobody_id): ) node.disconnect() - def test_type_filter_received_only(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_type_filter_received_only(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) label = str(uuid.uuid4()) node.receive(label=label, description="tea", amount_msat=5_000_000) diff --git a/libs/gl-sdk/tests/test_lnurl.py b/libs/gl-sdk/tests/test_lnurl.py index ed7bfbf06..52eef455f 100644 --- a/libs/gl-sdk/tests/test_lnurl.py +++ b/libs/gl-sdk/tests/test_lnurl.py @@ -28,15 +28,6 @@ CHANNEL_SATS = 1_000_000 # 1M sats -def make_sdk_node(nobody_id, scheduler): - """Register a GL node via the SDK and return it with signer running.""" - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - config = config.with_network(glsdk.Network.REGTEST) - node = glsdk.NodeBuilder(config).register(MNEMONIC, None) - return node, config - - def fund_and_connect(node_factory, bitcoind, lnurl_service): """Create a relay node with channels to the LNURL service node. @@ -262,9 +253,10 @@ def test_lnurl_pay_with_message_success_action( @pytest.fixture -def funded_sdk_node(scheduler, nobody_id, node_factory, bitcoind, lnurl_service): +def funded_sdk_node(scheduler, sdk_config, node_factory, bitcoind, lnurl_service): relay = fund_and_connect(node_factory, bitcoind, lnurl_service) - node, _ = make_sdk_node(nobody_id, scheduler) + config = sdk_config.with_network(glsdk.Network.REGTEST) + node = glsdk.NodeBuilder(config).register(MNEMONIC, None) credentials = glclient.Credentials.from_bytes(node.credentials()) gl_node = glclient.Scheduler(network="regtest", creds=credentials).node() relay_id = relay.info["id"] diff --git a/libs/gl-sdk/tests/test_node_methods.py b/libs/gl-sdk/tests/test_node_methods.py index 4890ca651..d20713f51 100644 --- a/libs/gl-sdk/tests/test_node_methods.py +++ b/libs/gl-sdk/tests/test_node_methods.py @@ -303,10 +303,8 @@ class TestNodeStateMethod: def test_node_has_node_state_method(self): assert hasattr(glsdk.Node, "node_state") - def test_node_state_returns_valid_snapshot(self, scheduler, nobody_id): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + def test_node_state_returns_valid_snapshot(self, scheduler, sdk_config): + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) state = node.node_state() assert isinstance(state, glsdk.NodeState) # Node id is a lowercase hex pubkey (33 bytes → 66 chars). @@ -330,11 +328,9 @@ def test_node_has_generate_diagnostic_data_method(self): assert hasattr(glsdk.Node, "generate_diagnostic_data") def test_generate_diagnostic_data_returns_well_formed_envelope( - self, scheduler, nobody_id + self, scheduler, sdk_config ): - dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) - config = glsdk.Config().with_developer_cert(dev_cert) - node = glsdk.NodeBuilder(config).register_or_recover(MNEMONIC, None) + node = glsdk.NodeBuilder(sdk_config).register_or_recover(MNEMONIC, None) blob = node.generate_diagnostic_data() assert isinstance(blob, str) diff --git a/libs/gl-sdk/tests/test_scheduler.py b/libs/gl-sdk/tests/test_scheduler.py index ad4095286..2791afce5 100644 --- a/libs/gl-sdk/tests/test_scheduler.py +++ b/libs/gl-sdk/tests/test_scheduler.py @@ -5,8 +5,8 @@ from gltesting.fixtures import * -def test_register(scheduler, clients): - signer = glsdk.Signer(" ".join(["abandon"] * 11 + ["about"])) +def test_register(scheduler, clients, tmp_path): + signer = glsdk.Signer(" ".join(["abandon"] * 11 + ["about"]), str(tmp_path / "device-state")) signer.start() # Check that the derived node_id matches the Signer seed phrase. diff --git a/libs/gl-sdk/tests/test_signer_config.py b/libs/gl-sdk/tests/test_signer_config.py index d13f99634..a1ee56550 100644 --- a/libs/gl-sdk/tests/test_signer_config.py +++ b/libs/gl-sdk/tests/test_signer_config.py @@ -16,9 +16,11 @@ def migration_config(path=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 +def test_default_signer_constructors_open_storage(tmp_path): + path = tmp_path / "device-state" + assert len(glsdk.Signer(MNEMONIC, str(path)).node_id()) == 33 + assert len(glsdk.Signer.new_from_seed(b"\x00" * 32, str(path)).node_id()) == 33 + assert path.is_dir() @pytest.mark.parametrize("from_seed", [False, True]) @@ -33,18 +35,12 @@ def test_configured_signer_constructors(from_seed, tmp_path): assert path.is_dir() -def test_authentication_preserves_migration_storage(tmp_path): +def test_authentication_keeps_the_signer_identity(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( diff --git a/libs/gl-testing/gltesting/clients.py b/libs/gl-testing/gltesting/clients.py index 3552e3ebe..a22399a48 100644 --- a/libs/gl-testing/gltesting/clients.py +++ b/libs/gl-testing/gltesting/clients.py @@ -109,7 +109,10 @@ def signer(self) -> glclient.Signer: have_certs = keypath.exists() self.directory.mkdir(exist_ok=True) - signer = glclient.Signer(secret, NETWORK, self.creds()) + signer = glclient.Signer( + secret, NETWORK, self.creds(), + device_storage_path=str(self.directory / "device-state"), + ) return signer