diff --git a/Cargo.lock b/Cargo.lock index 3e4c145b9..02589f5a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,6 +252,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "async-compat" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1ba85bc55464dcbf728b56d97e119d673f4cf9062be330a9a26f3acf504a590" +dependencies = [ + "futures-core", + "futures-io", + "once_cell", + "pin-project-lite", + "tokio", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -1642,12 +1655,15 @@ dependencies = [ "hex", "lightning-invoice", "once_cell", + "reqwest", + "serde_json", "thiserror 2.0.17", "tokio", "tonic 0.11.0", "tracing", "uniffi", "url", + "zeroize", ] [[package]] @@ -3455,6 +3471,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "webpki-roots", "winreg", ] @@ -4781,6 +4798,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38a9a27529ccff732f8efddb831b65b1e07f7dea3fd4cacd4a35a8c4b253b98" dependencies = [ "anyhow", + "async-compat", "bytes", "once_cell", "static_assertions", @@ -5147,6 +5165,12 @@ dependencies = [ "untrusted 0.9.0", ] +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + [[package]] name = "weedle2" version = "5.0.0" diff --git a/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/LnurlParseTest.kt b/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/LnurlParseTest.kt index d3384c891..9d6c319fa 100644 --- a/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/LnurlParseTest.kt +++ b/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/LnurlParseTest.kt @@ -1,10 +1,14 @@ -// Instrumented tests for parse_input() LNURL handling. -// Covers LNURL bech32 strings, lightning addresses, prefix handling, -// and error cases. Pure parsing only — no node, no network. +// Instrumented tests for parse_input() error-before-HTTP cases on +// LNURL / Lightning Address inputs and the LUD-04 tag=login fast path. +// +// Successful resolution of LNURL-pay / LNURL-withdraw requires a +// reachable LNURL service and is covered by gl-testing integration +// tests, not by Android instrumented tests. package com.blockstream.glsdk import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlinx.coroutines.runBlocking import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith @@ -12,81 +16,69 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LnurlParseTest { - // LNURL bech32 encoding of https://service.com/lnurl (LUD-01 example). - private val lnurlBech32 = - "LNURL1DP68GURN8GHJ7CMFWP5X2UNSW4HXKTNRDAKJ7CTSDYHHVVF0D3H82UNV9UCSAXQZE2" + // 32 zero bytes — a syntactically valid k1. + private val zeroK1 = + "0000000000000000000000000000000000000000000000000000000000000000" - // ============================================================ - // LNURL bech32 parsing - // ============================================================ - - @Test - fun parse_lnurl_bech32_uppercase() { - val result = parseInput(lnurlBech32) - assertTrue( - "Expected LnUrl, got $result", - result is InputType.LnUrl, - ) + @Test(expected = Exception::class) + fun parse_invalid_lnurl_bech32_returns_error(): Unit = runBlocking { + parseInput("LNURL1INVALIDDATA") } - @Test - fun parse_lnurl_bech32_lowercase() { - val result = parseInput(lnurlBech32.lowercase()) - assertTrue( - "Expected LnUrl, got $result", - result is InputType.LnUrl, - ) + @Test(expected = Exception::class) + fun parse_lightning_address_no_dot_in_domain_returns_error(): Unit = runBlocking { + parseInput("user@localhost") } - @Test - fun parse_lnurl_with_lightning_prefix() { - val result = parseInput("lightning:$lnurlBech32") - assertTrue( - "Expected LnUrl, got $result", - result is InputType.LnUrl, - ) + @Test(expected = Exception::class) + fun parse_lightning_address_empty_local_part_returns_error(): Unit = runBlocking { + parseInput("@example.com") } @Test(expected = Exception::class) - fun parse_invalid_lnurl_bech32_returns_error() { - parseInput("LNURL1INVALIDDATA") + fun parse_lightning_address_empty_domain_returns_error(): Unit = runBlocking { + parseInput("user@") } // ============================================================ - // Lightning address parsing + // LUD-04 tag=login — classified offline (no HTTP fetch) // ============================================================ @Test - fun parse_lightning_address_simple() { - val result = parseInput("user@example.com") + fun parse_lnurl_auth_url_classifies_as_lnurlauth() = runBlocking { + val url = "https://service.example.com/auth?tag=login&k1=$zeroK1" + val result = parseInput(url) assertTrue( - "Expected LnUrlAddress, got $result", - result is InputType.LnUrlAddress, + "Expected LnUrlAuth, got $result", + result is InputType.LnUrlAuth, ) - assertEquals("user@example.com", (result as InputType.LnUrlAddress).address) + val data = (result as InputType.LnUrlAuth).data + assertEquals(zeroK1, data.k1) + assertEquals("service.example.com", data.domain) + assertNull(data.action) + assertEquals(url, data.url) } @Test - fun parse_lightning_address_with_symbols() { - val result = parseInput("sat.oshi-99@example.com") - assertTrue( - "Expected LnUrlAddress, got $result", - result is InputType.LnUrlAddress, - ) + fun parse_lnurl_auth_url_captures_action() = runBlocking { + val url = "https://x.com/a?tag=login&k1=$zeroK1&action=register" + val result = parseInput(url) + assertTrue(result is InputType.LnUrlAuth) + assertEquals("register", (result as InputType.LnUrlAuth).data.action) } @Test(expected = Exception::class) - fun parse_lightning_address_no_dot_in_domain_returns_error() { - parseInput("user@localhost") + fun parse_lnurl_auth_rejects_missing_k1(): Unit = runBlocking { + parseInput("https://x.com/a?tag=login") } @Test(expected = Exception::class) - fun parse_lightning_address_empty_local_part_returns_error() { - parseInput("@example.com") + fun parse_lnurl_auth_rejects_short_k1(): Unit = runBlocking { + parseInput("https://x.com/a?tag=login&k1=deadbeef") } @Test(expected = Exception::class) - fun parse_lightning_address_empty_domain_returns_error() { - parseInput("user@") + fun parse_lnurl_auth_rejects_unknown_action(): Unit = runBlocking { + parseInput("https://x.com/a?tag=login&k1=$zeroK1&action=bogus") } -} \ No newline at end of file +} diff --git a/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/ParseInputTest.kt b/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/ParseInputTest.kt index eb27f57d0..838a79b06 100644 --- a/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/ParseInputTest.kt +++ b/libs/gl-sdk-android/lib/src/androidInstrumentedTest/kotlin/com/blockstream/glsdk/ParseInputTest.kt @@ -1,9 +1,12 @@ // Instrumented tests for parse_input(). -// Tests BOLT11 invoice parsing, node ID parsing, and error cases. +// Tests BOLT11 invoice parsing, node ID parsing, and error cases that +// resolve without HTTP. LNURL / Lightning Address paths are exercised +// in gl-testing integration tests against a live LNURL fixture. package com.blockstream.glsdk import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlinx.coroutines.runBlocking import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith @@ -27,18 +30,21 @@ class ParseInputTest { // ============================================================ @Test - fun parse_valid_node_id() { + fun parse_valid_node_id() = runBlocking { val result = parseInput(validNodeId) - assertNotNull(result) + assertTrue( + "Expected NodeId, got $result", + result is InputType.NodeId, + ) } @Test(expected = Exception::class) - fun parse_invalid_hex_returns_error() { + fun parse_invalid_hex_returns_error(): Unit = runBlocking { parseInput("not_valid_hex_at_all_but_66_chars_long_xxxxxxxxxxxxxxxxxxxxxxxxxxx") } @Test(expected = Exception::class) - fun parse_wrong_prefix_returns_error() { + fun parse_wrong_prefix_returns_error(): Unit = runBlocking { parseInput("04eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619") } @@ -47,21 +53,30 @@ class ParseInputTest { // ============================================================ @Test - fun parse_valid_bolt11() { + fun parse_valid_bolt11() = runBlocking { val result = parseInput(bolt11Invoice) - assertNotNull(result) + assertTrue( + "Expected Bolt11, got $result", + result is InputType.Bolt11, + ) } @Test - fun parse_bolt11_with_lightning_prefix() { + fun parse_bolt11_with_lightning_prefix() = runBlocking { val result = parseInput("lightning:$bolt11Invoice") - assertNotNull(result) + assertTrue( + "Expected Bolt11, got $result", + result is InputType.Bolt11, + ) } @Test - fun parse_bolt11_with_uppercase_prefix() { + fun parse_bolt11_with_uppercase_prefix() = runBlocking { val result = parseInput("LIGHTNING:$bolt11Invoice") - assertNotNull(result) + assertTrue( + "Expected Bolt11, got $result", + result is InputType.Bolt11, + ) } // ============================================================ @@ -69,12 +84,12 @@ class ParseInputTest { // ============================================================ @Test(expected = Exception::class) - fun parse_empty_string_returns_error() { + fun parse_empty_string_returns_error(): Unit = runBlocking { parseInput("") } @Test(expected = Exception::class) - fun parse_garbage_returns_error() { + fun parse_garbage_returns_error(): Unit = runBlocking { parseInput("hello world") } } diff --git a/libs/gl-sdk-napi/README.md b/libs/gl-sdk-napi/README.md index 6a6bf5e61..f620c9f91 100644 --- a/libs/gl-sdk-napi/README.md +++ b/libs/gl-sdk-napi/README.md @@ -86,46 +86,24 @@ gl-sdk-napi/ **Streaming**: streamNodeEvents() runs as a background task — call startEventStream(node) without await so it listens for events concurrently while your app continues calling other node methods. When you call node.stop(), next() returns null and the loop exits cleanly. ```typescript -import { Scheduler, Signer, Node, Credentials, OnchainReceiveResponse, NodeEvent, NodeEventStream } from '@greenlightcln/glsdk'; +import { Config, Node, NodeEvent, NodeEventStream, registerOrRecover } from '@greenlightcln/glsdk'; type Network = 'bitcoin' | 'regtest'; class GreenlightApp { - private credentials: Credentials | null = null; - private scheduler: Scheduler; - private signer: Signer; + private config: Config; + private mnemonic: string; private node: Node | null = null; constructor(phrase: string, network: Network) { - this.scheduler = new Scheduler(network); - this.signer = new Signer(phrase); - console.log(`✓ Signer created. Node ID: ${this.signer.nodeId().toString('hex')}`); + this.config = new Config().withNetwork(network); + this.mnemonic = phrase; } - async registerOrRecover(inviteCode?: string): Promise { - try { - console.log('Attempting to register node...'); - this.credentials = await this.scheduler.register(this.signer, inviteCode || ''); - console.log('✓ Node registered successfully'); - } catch (e: any) { - const match = e.message.match(/message: "([^"]+)"/); - console.error(`✗ Registration failed: ${match ? match[1] : e.message}`); - console.log('Attempting recovery...'); - try { - this.credentials = await this.scheduler.recover(this.signer); - console.log('✓ Node recovered successfully'); - } catch (recoverError) { - console.error('✗ Recovery failed:', recoverError); - throw recoverError; - } - } - } - - createNode(): Node { - if (!this.credentials) { throw new Error('Must register/recover before creating node'); } - console.log('Creating node instance...'); - this.node = new Node(this.credentials); - console.log('✓ Node created'); + async registerOrRecover(inviteCode?: string): Promise { + console.log('Attempting register-or-recover...'); + this.node = await registerOrRecover(this.mnemonic, inviteCode, this.config); + console.log('✓ Node ready'); return this.node; } diff --git a/libs/gl-sdk-napi/package-lock.json b/libs/gl-sdk-napi/package-lock.json index a64414f10..573bf5939 100644 --- a/libs/gl-sdk-napi/package-lock.json +++ b/libs/gl-sdk-napi/package-lock.json @@ -1,12 +1,12 @@ { "name": "@greenlightcln/glsdk", - "version": "0.0.3", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@greenlightcln/glsdk", - "version": "0.0.3", + "version": "0.1.0", "license": "MIT", "devDependencies": { "@jest/globals": "^30.2.0", diff --git a/libs/gl-sdk-napi/src/lib.rs b/libs/gl-sdk-napi/src/lib.rs index 56155146d..de8f8dcd2 100644 --- a/libs/gl-sdk-napi/src/lib.rs +++ b/libs/gl-sdk-napi/src/lib.rs @@ -7,14 +7,18 @@ use napi_derive::napi; use glsdk::{ // Enum types for conversion ChannelState as GlChannelState, + Config as GlConfig, Credentials as GlCredentials, DeveloperCert as GlDeveloperCert, Handle as GlHandle, + InputType as GlInputType, + LnUrlCallbackStatus as GlLnUrlCallbackStatus, Network as GlNetwork, Node as GlNode, NodeEvent as GlNodeEvent, NodeEventStream as GlNodeEventStream, OutputStatus as GlOutputStatus, + ParsedInvoice as GlParsedInvoice, Scheduler as GlScheduler, Signer as GlSigner, }; @@ -183,6 +187,64 @@ pub struct FundChannel { pub channel_id: Option, } +// ============================================================================ +// Input Parsing Types +// ============================================================================ + +#[napi(object)] +pub struct ParsedInvoice { + pub bolt11: String, + pub payee_pubkey: Option, + pub payment_hash: Buffer, + pub description: Option, + /// Amount in millisatoshis (i64 for JS), `None` for any-amount invoices. + pub amount_msat: Option, + /// Seconds from creation until the invoice expires. + pub expiry: i64, + /// Unix timestamp (seconds) when the invoice was created. + pub timestamp: i64, +} + +/// Parsed input. Discriminated by `type` field. Exactly one of the +/// variant fields (`bolt11`, `node_id`, `lnurl_pay`, `lnurl_withdraw`, +/// `lnurl_auth`) is populated based on the discriminant. +#[napi(object)] +pub struct InputType { + /// "bolt11" | "node_id" | "lnurl_pay" | "lnurl_withdraw" | "lnurl_auth" + pub r#type: String, + /// Present when type == "bolt11" + pub bolt11: Option, + /// Present when type == "node_id" + pub node_id: Option, + /// Present when type == "lnurl_pay" + pub lnurl_pay: Option, + /// Present when type == "lnurl_withdraw" + pub lnurl_withdraw: Option, + /// Present when type == "lnurl_auth" + pub lnurl_auth: Option, +} + +#[napi(object)] +pub struct LnUrlAuthRequestData { + /// Hex-encoded 32-byte challenge from the service. + pub k1: String, + /// One of "register" | "login" | "link" | "auth", or null. + pub action: Option, + /// Domain of the service (for user-facing confirmation prompts). + pub domain: String, + /// Full URL of the LNURL-auth service. + pub url: String, +} + +/// Result of an LNURL-auth callback (LUD-04). Discriminated by `type`. +#[napi(object)] +pub struct LnUrlCallbackStatus { + /// "ok" | "error" + pub r#type: String, + /// Present when type == "error" + pub error: Option, +} + // ============================================================================ // LNURL Types // ============================================================================ @@ -212,17 +274,6 @@ pub struct LnUrlWithdrawRequestData { pub lnurl: String, } -/// Result of resolving an LNURL. Discriminated by `type` field. -#[napi(object)] -pub struct ResolvedLnUrl { - /// "pay" or "withdraw" - pub r#type: String, - /// Present when type == "pay" - pub pay: Option, - /// Present when type == "withdraw" - pub withdraw: Option, -} - #[napi(object)] pub struct LnUrlPayRequest { pub data: LnUrlPayRequestData, @@ -332,6 +383,11 @@ pub struct Handle { inner: GlHandle, } +#[napi] +pub struct Config { + inner: std::sync::Arc, +} + #[napi] pub struct Node { inner: std::sync::Arc, @@ -559,20 +615,109 @@ impl NodeEventStream { } #[napi] -impl Node { - /// Create a new node connection - /// - /// # Arguments - /// * `credentials` - Device credentials +impl Config { + /// Create a `Config` with default settings: BITCOIN network, no + /// developer certificate. #[napi(constructor)] - pub fn new(credentials: &Credentials) -> Result { - // Constructor stays sync — connection is established lazily - let inner = - GlNode::new(&credentials.inner).map_err(|e| Error::from_reason(e.to_string()))?; + pub fn new() -> Self { + Self { inner: std::sync::Arc::new(GlConfig::new()) } + } - Ok(Self { inner: std::sync::Arc::new(inner) }) + /// Return a new Config with the given developer certificate. + #[napi] + pub fn with_developer_cert(&self, cert: &DeveloperCert) -> Config { + let updated = self.inner.with_developer_cert(&cert.inner); + // `Arc` from gl-sdk → unwrap and re-wrap so napi + // owns its own Arc. + Self { + inner: std::sync::Arc::new((*updated).clone()), + } } + /// Return a new Config with the given network ("bitcoin" | + /// "regtest"). + #[napi] + pub fn with_network(&self, network: String) -> Result { + let gl_network = match network.to_lowercase().as_str() { + "bitcoin" => GlNetwork::BITCOIN, + "regtest" => GlNetwork::REGTEST, + _ => { + return Err(Error::from_reason(format!( + "Invalid network: {}. Must be 'bitcoin' or 'regtest'", + network + ))) + } + }; + let updated = self.inner.with_network(gl_network); + Ok(Self { + inner: std::sync::Arc::new((*updated).clone()), + }) + } +} + +/// Register a new Greenlight node and return a connected Node with +/// the SDK signer running. +#[napi] +pub async fn register( + mnemonic: String, + invite_code: Option, + config: &Config, +) -> Result { + let cfg = config.inner.clone(); + let arc = tokio::task::spawn_blocking(move || { + glsdk::register(mnemonic, invite_code, &cfg).map_err(|e| Error::from_reason(e.to_string())) + }) + .await + .map_err(|e| Error::from_reason(e.to_string()))??; + Ok(Node { inner: arc }) +} + +/// Recover credentials for an existing Greenlight node and return a +/// connected Node with the SDK signer running. +#[napi] +pub async fn recover(mnemonic: String, config: &Config) -> Result { + let cfg = config.inner.clone(); + let arc = tokio::task::spawn_blocking(move || { + glsdk::recover(mnemonic, &cfg).map_err(|e| Error::from_reason(e.to_string())) + }) + .await + .map_err(|e| Error::from_reason(e.to_string()))??; + Ok(Node { inner: arc }) +} + +/// Connect to an existing Greenlight node using saved credentials. +#[napi] +pub async fn connect(mnemonic: String, credentials: Buffer, config: &Config) -> Result { + let cfg = config.inner.clone(); + let creds_bytes = credentials.to_vec(); + let arc = tokio::task::spawn_blocking(move || { + glsdk::connect(mnemonic, creds_bytes, &cfg).map_err(|e| Error::from_reason(e.to_string())) + }) + .await + .map_err(|e| Error::from_reason(e.to_string()))??; + Ok(Node { inner: arc }) +} + +/// Try to recover an existing node; if none exists, register a new one. +#[napi] +pub async fn register_or_recover( + mnemonic: String, + invite_code: Option, + config: &Config, +) -> Result { + let cfg = config.inner.clone(); + let arc = tokio::task::spawn_blocking(move || { + glsdk::register_or_recover(mnemonic, invite_code, &cfg) + .map_err(|e| Error::from_reason(e.to_string())) + }) + .await + .map_err(|e| Error::from_reason(e.to_string()))??; + Ok(Node { inner: arc }) +} + +#[napi] +impl Node { + /// Stop the node if it is currently running #[napi] pub async fn stop(&self) -> Result<()> { @@ -586,6 +731,26 @@ impl Node { .map_err(|e| Error::from_reason(e.to_string()))? } + /// Disconnect from the node and stop the SDK signer if running. + /// Also scrubs the LNURL-auth namespace key from memory. Safe to + /// call multiple times. + #[napi] + pub fn disconnect(&self) -> Result<()> { + self.inner + .disconnect() + .map_err(|e| Error::from_reason(e.to_string())) + } + + /// Return the serialized credentials so the wallet can persist + /// them and reuse via `connect(mnemonic, credentials, config)`. + #[napi] + pub fn credentials(&self) -> Result { + self.inner + .credentials() + .map(Buffer::from) + .map_err(|e| Error::from_reason(e.to_string())) + } + /// Receive a payment (generate invoice with JIT channel support) /// /// # Arguments @@ -855,28 +1020,10 @@ impl Node { // ── LNURL methods ─────────────────────────────────────────── - /// Resolve an LNURL or Lightning Address to its endpoint data. - /// - /// Accepts an LNURL bech32 string, a decoded URL, or a Lightning - /// Address (user@domain). - #[napi] - pub async fn resolve_lnurl(&self, input: String) -> Result { - let inner = self.inner.clone(); - let resolved = tokio::task::spawn_blocking(move || { - inner - .resolve_lnurl(input) - .map_err(|e| Error::from_reason(e.to_string())) - }) - .await - .map_err(|e| Error::from_reason(e.to_string()))??; - - Ok(napi_resolved_lnurl_from_gl(resolved)) - } - /// Execute an LNURL-pay flow. /// - /// Call `resolve_lnurl()` first, then pass the pay data with a - /// chosen amount. + /// Build the request from `LnUrlPayRequestData` (obtained out of + /// band) and a chosen amount. #[napi] pub async fn lnurl_pay(&self, request: LnUrlPayRequest) -> Result { let inner = self.inner.clone(); @@ -894,8 +1041,8 @@ impl Node { /// Execute an LNURL-withdraw flow. /// - /// Call `resolve_lnurl()` first, then pass the withdraw data with - /// a chosen amount. + /// Build the request from `LnUrlWithdrawRequestData` (obtained out + /// of band) and a chosen amount. #[napi] pub async fn lnurl_withdraw(&self, request: LnUrlWithdrawRequest) -> Result { let inner = self.inner.clone(); @@ -910,6 +1057,31 @@ impl Node { Ok(napi_lnurl_withdraw_result_from_gl(result)) } + + /// Execute an LNURL-auth (LUD-04) callback. + /// + /// Uses the LNURL-auth namespace xpriv (`m/138'`) that the Node + /// derived once from the BIP39 seed at register/recover/connect + /// time. `Node` never re-touches the seed; the namespace xpriv is + /// scrubbed on disconnect/drop. Returns an error when the Node + /// was constructed without a mnemonic. + #[napi] + pub async fn lnurl_auth( + &self, + request: LnUrlAuthRequestData, + ) -> Result { + let inner = self.inner.clone(); + let gl_request = gl_lnurl_auth_request_data_from_napi(request); + let status = tokio::task::spawn_blocking(move || { + inner + .lnurl_auth(gl_request) + .map_err(|e| Error::from_reason(e.to_string())) + }) + .await + .map_err(|e| Error::from_reason(e.to_string()))??; + + Ok(napi_lnurl_callback_status_from_gl(status)) + } } // ============================================================================ @@ -964,9 +1136,21 @@ fn output_status_to_string(status: &GlOutputStatus) -> String { } // ============================================================================ -// LNURL Conversion Helpers +// Input Parsing Conversion Helpers // ============================================================================ +fn napi_parsed_invoice_from_gl(invoice: GlParsedInvoice) -> ParsedInvoice { + ParsedInvoice { + bolt11: invoice.bolt11, + payee_pubkey: invoice.payee_pubkey.map(Buffer::from), + payment_hash: Buffer::from(invoice.payment_hash), + description: invoice.description, + amount_msat: invoice.amount_msat.map(|v| v as i64), + expiry: invoice.expiry as i64, + timestamp: invoice.timestamp as i64, + } +} + fn napi_pay_request_data_from_gl(data: glsdk::LnUrlPayRequestData) -> LnUrlPayRequestData { LnUrlPayRequestData { callback: data.callback, @@ -992,21 +1176,106 @@ fn napi_withdraw_request_data_from_gl( } } -fn napi_resolved_lnurl_from_gl(resolved: glsdk::ResolvedLnUrl) -> ResolvedLnUrl { - match resolved { - glsdk::ResolvedLnUrl::Pay { data } => ResolvedLnUrl { - r#type: "pay".to_string(), - pay: Some(napi_pay_request_data_from_gl(data)), - withdraw: None, +fn napi_input_type_from_gl(input: GlInputType) -> InputType { + match input { + GlInputType::Bolt11 { invoice } => InputType { + r#type: "bolt11".to_string(), + bolt11: Some(napi_parsed_invoice_from_gl(invoice)), + node_id: None, + lnurl_pay: None, + lnurl_withdraw: None, + lnurl_auth: None, + }, + GlInputType::NodeId { node_id } => InputType { + r#type: "node_id".to_string(), + bolt11: None, + node_id: Some(node_id), + lnurl_pay: None, + lnurl_withdraw: None, + lnurl_auth: None, }, - glsdk::ResolvedLnUrl::Withdraw { data } => ResolvedLnUrl { - r#type: "withdraw".to_string(), - pay: None, - withdraw: Some(napi_withdraw_request_data_from_gl(data)), + GlInputType::LnUrlPay { data } => InputType { + r#type: "lnurl_pay".to_string(), + bolt11: None, + node_id: None, + lnurl_pay: Some(napi_pay_request_data_from_gl(data)), + lnurl_withdraw: None, + lnurl_auth: None, }, + GlInputType::LnUrlWithdraw { data } => InputType { + r#type: "lnurl_withdraw".to_string(), + bolt11: None, + node_id: None, + lnurl_pay: None, + lnurl_withdraw: Some(napi_withdraw_request_data_from_gl(data)), + lnurl_auth: None, + }, + GlInputType::LnUrlAuth { data } => InputType { + r#type: "lnurl_auth".to_string(), + bolt11: None, + node_id: None, + lnurl_pay: None, + lnurl_withdraw: None, + lnurl_auth: Some(napi_lnurl_auth_request_data_from_gl(data)), + }, + } +} + +fn napi_lnurl_auth_request_data_from_gl( + data: glsdk::LnUrlAuthRequestData, +) -> LnUrlAuthRequestData { + LnUrlAuthRequestData { + k1: data.k1, + action: data.action, + domain: data.domain, + url: data.url, + } +} + +fn gl_lnurl_auth_request_data_from_napi( + data: LnUrlAuthRequestData, +) -> glsdk::LnUrlAuthRequestData { + glsdk::LnUrlAuthRequestData { + k1: data.k1, + action: data.action, + domain: data.domain, + url: data.url, } } +fn napi_lnurl_callback_status_from_gl(status: GlLnUrlCallbackStatus) -> LnUrlCallbackStatus { + match status { + GlLnUrlCallbackStatus::Ok => LnUrlCallbackStatus { + r#type: "ok".to_string(), + error: None, + }, + GlLnUrlCallbackStatus::ErrorStatus { data } => LnUrlCallbackStatus { + r#type: "error".to_string(), + error: Some(LnUrlErrorData { reason: data.reason }), + }, + } +} + +/// Parse and resolve any supported input. +/// +/// For LNURL bech32 strings and Lightning Addresses this performs the +/// HTTP GET to the LNURL endpoint and returns typed pay or withdraw +/// request data. For BOLT11 invoices and node IDs it returns +/// immediately without I/O. +/// +/// Strips `lightning:` / `LIGHTNING:` prefixes automatically. +#[napi] +pub async fn parse_input(input: String) -> Result { + let resolved = glsdk::parse_input(input) + .await + .map_err(|e| Error::from_reason(e.to_string()))?; + Ok(napi_input_type_from_gl(resolved)) +} + +// ============================================================================ +// LNURL Conversion Helpers +// ============================================================================ + fn gl_pay_request_data_from_napi(data: LnUrlPayRequestData) -> glsdk::LnUrlPayRequestData { glsdk::LnUrlPayRequestData { callback: data.callback, diff --git a/libs/gl-sdk-napi/tests/basic.spec.ts b/libs/gl-sdk-napi/tests/basic.spec.ts index 357834061..16aa1846e 100644 --- a/libs/gl-sdk-napi/tests/basic.spec.ts +++ b/libs/gl-sdk-napi/tests/basic.spec.ts @@ -1,21 +1,15 @@ import * as crypto from 'crypto'; import * as bip39 from 'bip39'; -import { Credentials, Scheduler, Signer, Node } from '../index.js'; +import { Config, register } from '../index.js'; describe('Greenlight node', () => { - it('can be setup', async () => { - const scheduler = new Scheduler('regtest'); + it('can be set up via register()', async () => { const rand: Buffer = crypto.randomBytes(16); - const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - const signer = new Signer(MNEMONIC); - const handle = await signer.start(); - const nodeId = signer.nodeId(); - expect(Buffer.isBuffer(nodeId)).toBe(true); - expect(nodeId.length).toBeGreaterThan(0); - const credentials = await scheduler.register(signer); - const node = new Node(credentials); + const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString('hex')); + const config = new Config().withNetwork('regtest'); + const node = await register(MNEMONIC, undefined, config); expect(node).toBeTruthy(); - handle.stop(); + node.disconnect(); await node.stop(); }); }); diff --git a/libs/gl-sdk-napi/tests/eventstream.spec.ts b/libs/gl-sdk-napi/tests/eventstream.spec.ts index b41fd4768..91b73e8b8 100644 --- a/libs/gl-sdk-napi/tests/eventstream.spec.ts +++ b/libs/gl-sdk-napi/tests/eventstream.spec.ts @@ -1,13 +1,14 @@ import * as crypto from 'crypto'; import * as bip39 from 'bip39'; -import { Credentials, Scheduler, Signer, Node, NodeEventStream, NodeEvent, InvoicePaidEvent, Handle } from '../index.js'; +import { Config, Node, NodeEventStream, NodeEvent, InvoicePaidEvent, register } from '../index.js'; import { fundWallet, getGLNode } from './test.helper.js'; +const REGTEST = () => new Config().withNetwork('regtest'); + describe('NodeEvent (type contract)', () => { it('NodeEvent and InvoicePaidEvent are assignable from NAPI-generated types', () => { - // This is a compile-time check only. If the NAPI bindings change the - // field names or types, tsc will fail here before Jest even runs. - // The runtime assertion is intentionally trivial. + // Compile-time check: if NAPI bindings change the field names or + // types, tsc will fail here before Jest even runs. const details: InvoicePaidEvent = { paymentHash: Buffer.from('deadbeef', 'hex'), bolt11: 'lnbcrt1...', @@ -17,8 +18,6 @@ describe('NodeEvent (type contract)', () => { }; const event: NodeEvent = { eventType: 'invoice_paid', invoicePaid: details }; - // Only assert what tsc cannot: that the import itself resolved and - // the constructed value is truthy (i.e. the module loaded correctly). expect(event).toBeDefined(); }); }); @@ -28,12 +27,10 @@ describe('NodeEvent (type contract)', () => { // ============================================================================ describe('NodeEventStream (integration)', () => { - let scheduler: Scheduler = new Scheduler('regtest'); let node: Node; - let handle: Handle; beforeAll(async () => { - ({node, handle } = await getGLNode(scheduler, false) as { node: Node; handle: Handle }); + ({ node } = await getGLNode(new (require('../index.js').Scheduler)('regtest'), false)); try { const probe = await node.streamNodeEvents(); void probe; @@ -45,12 +42,12 @@ describe('NodeEventStream (integration)', () => { afterAll(async () => { if (node) { - handle.stop(); - await node.stop(); + try { node.disconnect(); } catch {} + try { await node.stop(); } catch {} } }); - it('does not throw error on future unknown event type', () => { + it('does not throw on a future unknown event type', () => { const unknownEvent: NodeEvent = { eventType: 'new_future_event' as string, invoicePaid: undefined }; expect(() => { @@ -71,13 +68,12 @@ describe('NodeEventStream (integration)', () => { it('next resolves to null or a well-formed NodeEvent within 2 seconds', async () => { const stream: NodeEventStream = await node.streamNodeEvents(); - // Race next() against a 2 s timeout — no live events is fine here. const result = await Promise.race([ stream.next(), new Promise(resolve => setTimeout(() => resolve(null), 2_000)), ]); - if (result === null) return; // timed out, no events — acceptable + if (result === null) return; expect(result).toHaveProperty('eventType'); expect(typeof result.eventType).toBe('string'); @@ -92,60 +88,53 @@ 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 handle2 = await signer2.start(); - const credentials2 = await scheduler.register(signer2); - let node2 = new Node(credentials2); + let node2: Node | null = await register(mnemonic2, undefined, REGTEST()); const stream: NodeEventStream = await node2.streamNodeEvents(); await node2.stop(); const result = await stream.next(); expect(result).toBeNull(); - node2 = new Node(credentials2); - handle2.stop() - await node2.stop(); + try { node2.disconnect(); } catch {} + node2 = null; }); it.skip('receives real invoice_paid event', async () => { - await fundWallet(node, 500_000_000); - const { node: node2, handle: handle2 } = await getGLNode(scheduler, true) as { node: Node; handle: Handle }; - const stream: NodeEventStream = await node.streamNodeEvents(); - const label = `jest-${Date.now()}`; - const receiveRes = await node.receive(label, 'jest event stream test', 1_000); - const sendResponse = await node2.send(receiveRes.bolt11); - expect(sendResponse).toBeTruthy(); - - let paid: NodeEvent | null = null; - const deadline = Date.now() + 10_000; - - while (Date.now() < deadline) { - const event = await Promise.race([ - stream.next(), - new Promise(resolve => - setTimeout(() => resolve(null), deadline - Date.now()) - ), - ]); - - if (event === null) break; - if (event.eventType === 'invoice_paid') { paid = event; break; } - } - - expect(paid).not.toBeNull(); - expect(paid!.eventType).toBe('invoice_paid'); - - const p = paid!.invoicePaid!; - expect(p).toBeDefined(); - expect(Buffer.isBuffer(p.paymentHash)).toBe(true); - expect(p.paymentHash.length).toBeGreaterThan(0); - expect(Buffer.isBuffer(p.preimage)).toBe(true); - expect(p.preimage.length).toBeGreaterThan(0); - expect(p.bolt11).toBe(receiveRes.bolt11); - expect(p.label).toBe(label); - expect(typeof p.amountMsat).toBe('number'); - expect(p.amountMsat).toBeGreaterThan(0); - handle2.stop(); - await node2.stop(); - }, - 15_000 // extended timeout for payment round-trip - ); + await fundWallet(node, 500_000_000); + const { node: node2 } = await getGLNode(new (require('../index.js').Scheduler)('regtest'), true); + const stream: NodeEventStream = await node.streamNodeEvents(); + const label = `jest-${Date.now()}`; + const receiveRes = await node.receive(label, 'jest event stream test', 1_000); + const sendResponse = await node2.send(receiveRes.bolt11); + expect(sendResponse).toBeTruthy(); + + let paid: NodeEvent | null = null; + const deadline = Date.now() + 10_000; + + while (Date.now() < deadline) { + const event = await Promise.race([ + stream.next(), + new Promise(resolve => + setTimeout(() => resolve(null), deadline - Date.now()) + ), + ]); + + if (event === null) break; + if (event.eventType === 'invoice_paid') { paid = event; break; } + } + expect(paid).not.toBeNull(); + expect(paid!.eventType).toBe('invoice_paid'); + + const p = paid!.invoicePaid!; + expect(p).toBeDefined(); + expect(Buffer.isBuffer(p.paymentHash)).toBe(true); + expect(p.paymentHash.length).toBeGreaterThan(0); + expect(Buffer.isBuffer(p.preimage)).toBe(true); + expect(p.preimage.length).toBeGreaterThan(0); + expect(p.bolt11).toBe(receiveRes.bolt11); + expect(p.label).toBe(label); + expect(typeof p.amountMsat).toBe('number'); + expect(p.amountMsat).toBeGreaterThan(0); + try { node2.disconnect(); } catch {} + await node2.stop(); + }, 15_000); }); diff --git a/libs/gl-sdk-napi/tests/misc.spec.ts b/libs/gl-sdk-napi/tests/misc.spec.ts index bbccdfd50..81c5b5d06 100644 --- a/libs/gl-sdk-napi/tests/misc.spec.ts +++ b/libs/gl-sdk-napi/tests/misc.spec.ts @@ -1,6 +1,16 @@ import * as crypto from 'crypto'; import * as bip39 from 'bip39'; -import { Credentials, Scheduler, Signer, Node } from '../index.js'; +import { + Config, + Credentials, + Node, + Signer, + connect, + recover, + register, +} from '../index.js'; + +const REGTEST = () => new Config().withNetwork('regtest'); describe('Credentials', () => { it('can save and load raw credentials', async () => { @@ -19,14 +29,14 @@ describe('Credentials', () => { 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 MNEMONIC: string = bip39.entropyToMnemonic(rand.toString('hex')); const signer = new Signer(MNEMONIC); 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 MNEMONIC: string = bip39.entropyToMnemonic(rand.toString('hex')); const signer = new Signer(MNEMONIC); const nodeId = signer.nodeId(); @@ -36,7 +46,7 @@ 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 MNEMONIC: string = bip39.entropyToMnemonic(rand.toString('hex')); const signer1 = new Signer(MNEMONIC); const signer2 = new Signer(MNEMONIC); @@ -45,61 +55,67 @@ describe('Signer', () => { expect(nodeId1.equals(nodeId2)).toBe(true); }); +}); - 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); - expect(signer).toBeTruthy(); - - const nodeId = signer.nodeId(); - expect(Buffer.isBuffer(nodeId)).toBe(true); +describe('Config', () => { + it('defaults to bitcoin network and has no developer cert', () => { + const config = new Config(); + expect(config).toBeTruthy(); }); -}); -describe('Scheduler', () => { - it('can be constructed for regtest', async () => { - const scheduler = new Scheduler('regtest'); - expect(scheduler).toBeTruthy(); + it('produces a regtest-network Config via withNetwork', () => { + const config = new Config().withNetwork('regtest'); + expect(config).toBeTruthy(); }); - it('can be constructed for bitcoin mainnet', async () => { - const scheduler = new Scheduler('bitcoin'); - expect(scheduler).toBeTruthy(); + it('rejects invalid network strings', () => { + expect(() => new Config().withNetwork('mars')).toThrow(); }); }); -describe('Integration: scheduler and signer', () => { - let scheduler: Scheduler; - let signer: Signer; - let credentials: Credentials; - let node: Node; +describe('Integration: register / recover / connect', () => { + let mnemonic: string; + let registeredNode: Node | null = null; - beforeAll(async () => { - const rand: Buffer = crypto.randomBytes(16); - const MNEMONIC: string = bip39.entropyToMnemonic(rand.toString("hex")); - scheduler = new Scheduler('regtest'); - signer = new Signer(MNEMONIC); - credentials = await scheduler.register(signer); - node = new Node(credentials); + beforeAll(() => { + mnemonic = bip39.entropyToMnemonic(crypto.randomBytes(16).toString('hex')); }); - it('can recover credentials', async () => { - if (node) { await node.stop(); } - const recovered = await scheduler.recover(signer); - expect(recovered).toBeInstanceOf(Credentials); - expect((await recovered.save()).length).toBeGreaterThan(0); + afterAll(async () => { + if (registeredNode) { + try { registeredNode.disconnect(); } catch {} + try { await registeredNode.stop(); } catch {} + } + }); + + it('register returns a connected Node and exposes credentials', async () => { + registeredNode = await register(mnemonic, undefined, REGTEST()); + expect(registeredNode).toBeTruthy(); + + const creds = registeredNode.credentials(); + expect(Buffer.isBuffer(creds)).toBe(true); + expect(creds.length).toBeGreaterThan(0); }); - it('handles registration of existing node (falls back to recovery)', async () => { - try { - if (node) { await node.stop(); } - // Trying to register the same signer again should throw an error, which we catch to then test recovery - const credentials2 = await scheduler.register(signer); - expect(credentials2).toBeInstanceOf(Credentials); - } catch (e) { - const recovered = await scheduler.recover(signer); - expect(recovered).toBeInstanceOf(Credentials); + it('recover returns a Node for an already-registered mnemonic', async () => { + if (registeredNode) { + registeredNode.disconnect(); + await registeredNode.stop(); + registeredNode = null; } + const recovered = await recover(mnemonic, REGTEST()); + expect(recovered).toBeTruthy(); + registeredNode = recovered; + }); + + it('connect works with saved credentials and the same mnemonic', async () => { + const savedCreds = registeredNode!.credentials(); + registeredNode!.disconnect(); + await registeredNode!.stop(); + registeredNode = null; + + const reconnected = await connect(mnemonic, savedCreds, REGTEST()); + expect(reconnected).toBeTruthy(); + registeredNode = reconnected; }); }); diff --git a/libs/gl-sdk-napi/tests/node.spec.ts b/libs/gl-sdk-napi/tests/node.spec.ts index d5df58c39..7944a7026 100644 --- a/libs/gl-sdk-napi/tests/node.spec.ts +++ b/libs/gl-sdk-napi/tests/node.spec.ts @@ -1,9 +1,9 @@ -import { Handle, Node, Scheduler } from '../index.js'; -import { getGLNode, fundWallet, getLspInvoice } from './test.helper'; +import { Node, Scheduler } from '../index.js'; +import { getGLNode, fundWallet, getLspInvoice, SdkNode } from './test.helper'; describe('Node', () => { let scheduler: Scheduler = new Scheduler('regtest'); - let glNodes: Array<{ node: Node; handle: Handle }> = []; + let glNodes: SdkNode[] = []; let node: Node; beforeEach(async () => { @@ -12,9 +12,9 @@ describe('Node', () => { }); afterEach(async () => { - for (const { node: n, handle: h } of glNodes) { - h.stop(); - await n.stop(); + for (const { node: n } of glNodes) { + try { n.disconnect(); } catch {} + try { await n.stop(); } catch {} } glNodes = []; }); @@ -110,7 +110,7 @@ describe('Node', () => { describe('calls onchainSend', () => { it('can send specific amount on-chain', async () => { await fundWallet(node, 500_000_000); - const extraGLNode = await getGLNode(scheduler, true) as { node: Node; handle: Handle }; + const extraGLNode = await getGLNode(scheduler, true); glNodes.push(extraGLNode); const destAddress = (await extraGLNode.node.onchainReceive()).bech32; const response = await node.onchainSend(destAddress, '10000sat'); @@ -119,7 +119,7 @@ describe('Node', () => { it('can attempt to send all funds on-chain', async () => { await fundWallet(node, 500_000_000); - const extraGLNode = await getGLNode(scheduler, true) as { node: Node; handle: Handle }; + const extraGLNode = await getGLNode(scheduler, true); glNodes.push(extraGLNode); const destAddress = (await extraGLNode.node.onchainReceive()).bech32; const response = await node.onchainSend(destAddress, 'all'); @@ -129,7 +129,7 @@ describe('Node', () => { describe('calls receive', () => { it('can create invoice with amount', async () => { - const extraGLNode = await getGLNode(scheduler, true) as { node: Node; handle: Handle }; + const extraGLNode = await getGLNode(scheduler, true); glNodes.push(extraGLNode); const label = `test-${Date.now()}`; const description = 'Test payment'; diff --git a/libs/gl-sdk-napi/tests/parse-input.spec.ts b/libs/gl-sdk-napi/tests/parse-input.spec.ts new file mode 100644 index 000000000..f924fce58 --- /dev/null +++ b/libs/gl-sdk-napi/tests/parse-input.spec.ts @@ -0,0 +1,81 @@ +import { parseInput } from '../index.js'; + +const VALID_NODE_ID = + '02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'; + +const BOLT11_INVOICE = + 'lnbc110n1p38q3gtpp5ypz09jrd8p993snjwnm68cph4ftwp22le34xd4r8ftspwshxhm' + + 'nsdqqxqyjw5qcqpxsp5htlg8ydpywvsa7h3u4hdn77ehs4z4e844em0apjyvmqfkzqhh' + + 'd2q9qgsqqqyssqszpxzxt9uuqzymr7zxcdccj5g69s8q7zzjs7sgxn9ejhnvdh6gqjcy' + + '22mss2yexunagm5r2gqczh8k24cwrqml3njskm548aruhpwssq9nvrvz'; + +describe('parseInput', () => { + describe('BOLT11 invoices (no HTTP)', () => { + it('classifies a valid BOLT11 invoice', async () => { + const result = await parseInput(BOLT11_INVOICE); + expect(result.type).toBe('bolt11'); + expect(result.bolt11).toBeDefined(); + expect(result.bolt11!.bolt11).toBe(BOLT11_INVOICE); + }); + + it('strips a lowercase lightning: prefix', async () => { + const result = await parseInput(`lightning:${BOLT11_INVOICE}`); + expect(result.type).toBe('bolt11'); + }); + + it('strips an uppercase LIGHTNING: prefix', async () => { + const result = await parseInput(`LIGHTNING:${BOLT11_INVOICE}`); + expect(result.type).toBe('bolt11'); + }); + }); + + describe('node IDs (no HTTP)', () => { + it('classifies a valid compressed pubkey', async () => { + const result = await parseInput(VALID_NODE_ID); + expect(result.type).toBe('node_id'); + expect(result.nodeId).toBe(VALID_NODE_ID); + }); + + it('rejects a 66-char string that is not valid hex', async () => { + await expect( + parseInput('not_valid_hex_at_all_but_66_chars_long_xxxxxxxxxxxxxxxxxxxxxxxxxxx'), + ).rejects.toThrow(); + }); + + it('rejects an uncompressed (0x04) pubkey', async () => { + await expect( + parseInput('04eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'), + ).rejects.toThrow(); + }); + }); + + describe('error cases that resolve before HTTP', () => { + it('rejects empty input', async () => { + await expect(parseInput('')).rejects.toThrow(); + }); + + it('rejects whitespace-only input', async () => { + await expect(parseInput(' ')).rejects.toThrow(); + }); + + it('rejects unrecognized garbage', async () => { + await expect(parseInput('hello world')).rejects.toThrow(); + }); + + it('rejects an invalid LNURL bech32 string before HTTP', async () => { + await expect(parseInput('LNURL1INVALIDDATA')).rejects.toThrow(); + }); + + it('rejects a malformed Lightning Address (no dot in domain)', async () => { + await expect(parseInput('user@localhost')).rejects.toThrow(); + }); + + it('rejects an empty local-part Lightning Address', async () => { + await expect(parseInput('@example.com')).rejects.toThrow(); + }); + + it('rejects an empty domain Lightning Address', async () => { + await expect(parseInput('user@')).rejects.toThrow(); + }); + }); +}); diff --git a/libs/gl-sdk-napi/tests/test.helper.ts b/libs/gl-sdk-napi/tests/test.helper.ts index 84da1b05d..a60d4a34e 100644 --- a/libs/gl-sdk-napi/tests/test.helper.ts +++ b/libs/gl-sdk-napi/tests/test.helper.ts @@ -1,7 +1,7 @@ import * as fs from 'fs'; import * as crypto from 'crypto'; import * as bip39 from 'bip39'; -import { Credentials, Scheduler, Signer, Node, Handle } from '../index.js'; +import { Config, Credentials, Scheduler, Node, register, connect } from '../index.js'; export const lspInfo = () => ({ rpcSocket: process.env.LSP_RPC_SOCKET!, @@ -35,15 +35,31 @@ export async function fundWallet(node: Node, amountSats = 100_000_000): Promise< throw new Error('fundNode timed out waiting for node to detect funds'); } -export async function getGLNode(scheduler: Scheduler, connectToLSP: boolean = true): Promise<{ node: Node; handle: Handle }> { +/** A fully-connected SDK node with the SDK signer running. The SDK + * manages the signer internally; call `node.disconnect()` to stop + * it. The `mnemonic` is returned so callers that need cryptographic + * derivations (e.g. LNURL-auth happens internally on Node, but tests + * may want to assert against the same seed) can re-use it. */ +export interface SdkNode { + node: Node; + mnemonic: string; +} + +export async function getGLNode( + _scheduler: Scheduler, + connectToLSP: boolean = true, +): Promise { const mnemonic = bip39.entropyToMnemonic(crypto.randomBytes(16).toString('hex')); - const secret = bip39.mnemonicToSeedSync(mnemonic); - const signer = new Signer(mnemonic); - let credentials: Credentials; + const config = new Config().withNetwork('regtest'); + if (connectToLSP) { const testSetupServerUrl = process.env.TEST_SETUP_SERVER_URL!; if (!testSetupServerUrl) throw new Error('TEST_SETUP_SERVER_URL not set'); + // Test-setup server registers a node with the same seed and links + // it to the LSP. We then `connect` from the JS side using the + // mnemonic that derives that same seed. + const secret = bip39.mnemonicToSeedSync(mnemonic); const res = await fetch(`${testSetupServerUrl}/connect-to-lsp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -51,11 +67,13 @@ export async function getGLNode(scheduler: Scheduler, connectToLSP: boolean = tr }); if (!res.ok) throw new Error(`Failed to connect node to LSP: ${await res.text()}`); const { creds_path } = await res.json(); - credentials = await Credentials.load(fs.readFileSync(creds_path)); - } else { - credentials = await scheduler.register(signer); + const credsBytes = fs.readFileSync(creds_path); + const node = await connect(mnemonic, credsBytes, config); + return { node, mnemonic }; } - return { node: new Node(credentials), handle: await signer.start() }; + + const node = await register(mnemonic, undefined, config); + return { node, mnemonic }; } export async function getLspInvoice(amountMsat: number = 0): Promise { @@ -79,3 +97,7 @@ export async function getBitcoinAddress(): Promise { const resJson = await res.json(); return resJson.address; } + +// Re-export `Credentials` so tests that need to load credentials +// directly (without going through register/connect) keep compiling. +export { Credentials }; diff --git a/libs/gl-sdk/CHANGELOG.md b/libs/gl-sdk/CHANGELOG.md index 26b1fab85..deabcabeb 100644 --- a/libs/gl-sdk/CHANGELOG.md +++ b/libs/gl-sdk/CHANGELOG.md @@ -6,6 +6,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## Unreleased +### Added + +- `Node::lnurl_auth(request)` implementing LNURL-auth (LUD-04 / LUD-05). Derives the per-domain linking key on-the-fly from a hardened `m/138'` xpriv that the Node derives once from the BIP39 seed at register/recover/connect time. The seed itself is never retained on `Node`; the stored namespace xpriv lives in `Zeroizing` and is scrubbed on `disconnect()` or `Drop`. `m/138'` is hardened, so the stored material cannot be used to derive any other wallet key (lightning channels, on-chain funds) — the blast radius is restricted to LNURL-auth identities. +- LUD-05 derivation uses the 32-byte private key at `m/138'/0` as the HMAC key, matching the mainstream wallet convention (Phoenix, Mutiny, Zeus, BlueWallet) for cross-wallet identity portability at LNURL-auth services. +- `InputType::LnUrlAuth { data: LnUrlAuthRequestData }` returned by `parse_input` when the URL carries `tag=login`. Detection is offline — no HTTP fetch is made for classification. +- `LnUrlCallbackStatus` and `LnUrlAuthRequestData` types. + +### Changed + +- `parse_input()` is now `async` and resolves LNURL bech32 strings and Lightning Addresses end-to-end over HTTP, returning typed pay or withdraw request data. BOLT11 invoices and node IDs still resolve without I/O. +- `InputType` variants now: `Bolt11`, `NodeId`, `LnUrlPay`, `LnUrlWithdraw`, `LnUrlAuth`. Replaces the previous `LnUrl` / `LnUrlAddress` intermediate-state variants. + +### Removed + +- `Node::resolve_lnurl()` and the `ResolvedLnUrl` enum. Use `parse_input()` to obtain `LnUrlPayRequestData` / `LnUrlWithdrawRequestData` directly, then call `Node::lnurl_pay()` / `Node::lnurl_withdraw()`. + ## [0.2.0] - 2026-04-02 ### Added diff --git a/libs/gl-sdk/Cargo.toml b/libs/gl-sdk/Cargo.toml index 51d2481ab..cfec3b17b 100644 --- a/libs/gl-sdk/Cargo.toml +++ b/libs/gl-sdk/Cargo.toml @@ -17,12 +17,15 @@ gl-client = { version = "0.4.0", path = "../gl-client" } hex = "0.4" lightning-invoice = "0.33" once_cell = "1.21.3" +reqwest = { version = "0.11", default-features = false, features = ["rustls-tls"] } +serde_json = "1" thiserror = "2.0.17" tokio = { version = "1", features = ["sync"] } tonic.workspace = true tracing = { version = "0.1.43", features = ["async-await", "log"] } -uniffi = { version = "0.29.4" } +uniffi = { version = "0.29.4", features = ["tokio"] } url = "2" +zeroize = "1.8" [build-dependencies] uniffi = { version = "0.29.4", features = [ "build" ] } diff --git a/libs/gl-sdk/glsdk/glsdk.py b/libs/gl-sdk/glsdk/glsdk.py index 72227636e..ea7195db3 100644 --- a/libs/gl-sdk/glsdk/glsdk.py +++ b/libs/gl-sdk/glsdk/glsdk.py @@ -27,6 +27,7 @@ import itertools import traceback import typing +import asyncio import platform # Used for default argument values @@ -462,6 +463,8 @@ def _uniffi_check_contract_api_version(lib): def _uniffi_check_api_checksums(lib): if lib.uniffi_glsdk_checksum_func_connect() != 43555: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_func_parse_input() != 43159: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_func_recover() != 39257: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_func_register() != 39628: @@ -478,7 +481,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_node_credentials() != 39165: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_node_disconnect() != 43626: + if lib.uniffi_glsdk_checksum_method_node_disconnect() != 35611: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_node_get_info() != 39460: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -494,9 +497,15 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_node_list_peers() != 29567: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_node_onchain_receive() != 57530: + if lib.uniffi_glsdk_checksum_method_node_lnurl_auth() != 37374: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_lnurl_pay() != 61306: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_lnurl_withdraw() != 61467: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_onchain_receive() != 46432: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_node_onchain_send() != 44346: + if lib.uniffi_glsdk_checksum_method_node_onchain_send() != 12590: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_node_receive() != 39761: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -526,8 +535,6 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_constructor_developercert_new() != 57793: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_constructor_node_new() != 7003: - 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: @@ -727,11 +734,6 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_free_node.restype = None -_UniffiLib.uniffi_glsdk_fn_constructor_node_new.argtypes = ( - ctypes.c_void_p, - ctypes.POINTER(_UniffiRustCallStatus), -) -_UniffiLib.uniffi_glsdk_fn_constructor_node_new.restype = ctypes.c_void_p _UniffiLib.uniffi_glsdk_fn_method_node_credentials.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -791,6 +793,24 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_method_node_list_peers.restype = _UniffiRustBuffer +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_auth.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_auth.restype = _UniffiRustBuffer +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_pay.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_pay.restype = _UniffiRustBuffer +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_withdraw.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_withdraw.restype = _UniffiRustBuffer _UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -920,6 +940,10 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_func_connect.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_func_parse_input.argtypes = ( + _UniffiRustBuffer, +) +_UniffiLib.uniffi_glsdk_fn_func_parse_input.restype = ctypes.c_uint64 _UniffiLib.uniffi_glsdk_fn_func_recover.argtypes = ( _UniffiRustBuffer, ctypes.c_void_p, @@ -1211,6 +1235,9 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): _UniffiLib.uniffi_glsdk_checksum_func_connect.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_func_connect.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_func_parse_input.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_func_parse_input.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_func_recover.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_func_recover.restype = ctypes.c_uint16 @@ -1259,6 +1286,15 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): _UniffiLib.uniffi_glsdk_checksum_method_node_list_peers.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_node_list_peers.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_auth.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_auth.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_pay.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_pay.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_withdraw.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_lnurl_withdraw.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.restype = ctypes.c_uint16 @@ -1307,9 +1343,6 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): _UniffiLib.uniffi_glsdk_checksum_constructor_developercert_new.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_constructor_developercert_new.restype = ctypes.c_uint16 -_UniffiLib.uniffi_glsdk_checksum_constructor_node_new.argtypes = ( -) -_UniffiLib.uniffi_glsdk_checksum_constructor_node_new.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_constructor_scheduler_new.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_constructor_scheduler_new.restype = ctypes.c_uint16 @@ -2127,552 +2160,1270 @@ def write(value, buf): _UniffiConverterSequenceTypePeer.write(value.peers, buf) -class OnchainReceiveResponse: - bech32: "str" - p2tr: "str" - def __init__(self, *, bech32: "str", p2tr: "str"): - self.bech32 = bech32 - self.p2tr = p2tr +class LnUrlAuthRequestData: + """ + Data from an LNURL-auth endpoint (LUD-04). + + Returned inside `InputType::LnUrlAuth` after `parse_input` classifies + a `tag=login` LNURL. Because the tag is carried in the URL query + string, no HTTP fetch is needed for classification — the callback is + only hit when the user approves the auth via `Node::lnurl_auth`. + """ + + k1: "str" + """ + Hex-encoded 32-byte challenge from the service. + """ + + action: "typing.Optional[str]" + """ + One of `register`, `login`, `link`, `auth`. None if the service + did not specify an `action` query parameter. + """ + + domain: "str" + """ + Domain of the LNURL-auth service, to be shown to the user when + asking for auth confirmation per LUD-04. + """ + + url: "str" + """ + Full URL of the LNURL-auth service including its query string. + Used internally as the callback target after signing. + """ + + def __init__(self, *, k1: "str", action: "typing.Optional[str]", domain: "str", url: "str"): + self.k1 = k1 + self.action = action + self.domain = domain + self.url = url def __str__(self): - return "OnchainReceiveResponse(bech32={}, p2tr={})".format(self.bech32, self.p2tr) + return "LnUrlAuthRequestData(k1={}, action={}, domain={}, url={})".format(self.k1, self.action, self.domain, self.url) def __eq__(self, other): - if self.bech32 != other.bech32: + if self.k1 != other.k1: return False - if self.p2tr != other.p2tr: + if self.action != other.action: + return False + if self.domain != other.domain: + return False + if self.url != other.url: return False return True -class _UniffiConverterTypeOnchainReceiveResponse(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlAuthRequestData(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return OnchainReceiveResponse( - bech32=_UniffiConverterString.read(buf), - p2tr=_UniffiConverterString.read(buf), + return LnUrlAuthRequestData( + k1=_UniffiConverterString.read(buf), + action=_UniffiConverterOptionalString.read(buf), + domain=_UniffiConverterString.read(buf), + url=_UniffiConverterString.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterString.check_lower(value.bech32) - _UniffiConverterString.check_lower(value.p2tr) + _UniffiConverterString.check_lower(value.k1) + _UniffiConverterOptionalString.check_lower(value.action) + _UniffiConverterString.check_lower(value.domain) + _UniffiConverterString.check_lower(value.url) @staticmethod def write(value, buf): - _UniffiConverterString.write(value.bech32, buf) - _UniffiConverterString.write(value.p2tr, buf) + _UniffiConverterString.write(value.k1, buf) + _UniffiConverterOptionalString.write(value.action, buf) + _UniffiConverterString.write(value.domain, buf) + _UniffiConverterString.write(value.url, buf) -class OnchainSendResponse: - tx: "bytes" - txid: "bytes" - psbt: "str" - def __init__(self, *, tx: "bytes", txid: "bytes", psbt: "str"): - self.tx = tx - self.txid = txid - self.psbt = psbt +class LnUrlErrorData: + """ + Error returned by an LNURL service endpoint. + """ + + reason: "str" + def __init__(self, *, reason: "str"): + self.reason = reason def __str__(self): - return "OnchainSendResponse(tx={}, txid={}, psbt={})".format(self.tx, self.txid, self.psbt) + return "LnUrlErrorData(reason={})".format(self.reason) def __eq__(self, other): - if self.tx != other.tx: - return False - if self.txid != other.txid: - return False - if self.psbt != other.psbt: + if self.reason != other.reason: return False return True -class _UniffiConverterTypeOnchainSendResponse(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlErrorData(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return OnchainSendResponse( - tx=_UniffiConverterBytes.read(buf), - txid=_UniffiConverterBytes.read(buf), - psbt=_UniffiConverterString.read(buf), + return LnUrlErrorData( + reason=_UniffiConverterString.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterBytes.check_lower(value.tx) - _UniffiConverterBytes.check_lower(value.txid) - _UniffiConverterString.check_lower(value.psbt) + _UniffiConverterString.check_lower(value.reason) @staticmethod def write(value, buf): - _UniffiConverterBytes.write(value.tx, buf) - _UniffiConverterBytes.write(value.txid, buf) - _UniffiConverterString.write(value.psbt, buf) + _UniffiConverterString.write(value.reason, buf) -class Pay: - payment_hash: "bytes" - status: "PayStatus" - destination_pubkey: "typing.Optional[bytes]" - amount_msat: "typing.Optional[int]" - amount_sent_msat: "typing.Optional[int]" - label: "typing.Optional[str]" - bolt11: "typing.Optional[str]" - description: "typing.Optional[str]" - bolt12: "typing.Optional[str]" - preimage: "typing.Optional[bytes]" - created_at: "int" - completed_at: "typing.Optional[int]" - number_of_parts: "typing.Optional[int]" - def __init__(self, *, payment_hash: "bytes", status: "PayStatus", destination_pubkey: "typing.Optional[bytes]", amount_msat: "typing.Optional[int]", amount_sent_msat: "typing.Optional[int]", label: "typing.Optional[str]", bolt11: "typing.Optional[str]", description: "typing.Optional[str]", bolt12: "typing.Optional[str]", preimage: "typing.Optional[bytes]", created_at: "int", completed_at: "typing.Optional[int]", number_of_parts: "typing.Optional[int]"): +class LnUrlPayErrorData: + """ + Details of a failed LNURL-pay attempt on the pay phase. + """ + + payment_hash: "str" + """ + Hex-encoded payment hash of the invoice the service returned. + """ + + reason: "str" + """ + Human-readable reason the pay attempt failed. + """ + + def __init__(self, *, payment_hash: "str", reason: "str"): self.payment_hash = payment_hash - self.status = status - self.destination_pubkey = destination_pubkey - self.amount_msat = amount_msat - self.amount_sent_msat = amount_sent_msat - self.label = label - self.bolt11 = bolt11 - self.description = description - self.bolt12 = bolt12 - self.preimage = preimage - self.created_at = created_at - self.completed_at = completed_at - self.number_of_parts = number_of_parts + self.reason = reason def __str__(self): - return "Pay(payment_hash={}, status={}, destination_pubkey={}, amount_msat={}, amount_sent_msat={}, label={}, bolt11={}, description={}, bolt12={}, preimage={}, created_at={}, completed_at={}, number_of_parts={})".format(self.payment_hash, self.status, self.destination_pubkey, self.amount_msat, self.amount_sent_msat, self.label, self.bolt11, self.description, self.bolt12, self.preimage, self.created_at, self.completed_at, self.number_of_parts) + return "LnUrlPayErrorData(payment_hash={}, reason={})".format(self.payment_hash, self.reason) def __eq__(self, other): if self.payment_hash != other.payment_hash: return False - if self.status != other.status: - return False - if self.destination_pubkey != other.destination_pubkey: - return False - if self.amount_msat != other.amount_msat: - return False - if self.amount_sent_msat != other.amount_sent_msat: - return False - if self.label != other.label: - return False - if self.bolt11 != other.bolt11: - return False - if self.description != other.description: - return False - if self.bolt12 != other.bolt12: - return False - if self.preimage != other.preimage: - return False - if self.created_at != other.created_at: - return False - if self.completed_at != other.completed_at: - return False - if self.number_of_parts != other.number_of_parts: + if self.reason != other.reason: return False return True -class _UniffiConverterTypePay(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlPayErrorData(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return Pay( - payment_hash=_UniffiConverterBytes.read(buf), - status=_UniffiConverterTypePayStatus.read(buf), - destination_pubkey=_UniffiConverterOptionalBytes.read(buf), - amount_msat=_UniffiConverterOptionalUInt64.read(buf), - amount_sent_msat=_UniffiConverterOptionalUInt64.read(buf), - label=_UniffiConverterOptionalString.read(buf), - bolt11=_UniffiConverterOptionalString.read(buf), - description=_UniffiConverterOptionalString.read(buf), - bolt12=_UniffiConverterOptionalString.read(buf), - preimage=_UniffiConverterOptionalBytes.read(buf), - created_at=_UniffiConverterUInt64.read(buf), - completed_at=_UniffiConverterOptionalUInt64.read(buf), - number_of_parts=_UniffiConverterOptionalUInt64.read(buf), + return LnUrlPayErrorData( + payment_hash=_UniffiConverterString.read(buf), + reason=_UniffiConverterString.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterBytes.check_lower(value.payment_hash) - _UniffiConverterTypePayStatus.check_lower(value.status) - _UniffiConverterOptionalBytes.check_lower(value.destination_pubkey) - _UniffiConverterOptionalUInt64.check_lower(value.amount_msat) - _UniffiConverterOptionalUInt64.check_lower(value.amount_sent_msat) - _UniffiConverterOptionalString.check_lower(value.label) - _UniffiConverterOptionalString.check_lower(value.bolt11) - _UniffiConverterOptionalString.check_lower(value.description) - _UniffiConverterOptionalString.check_lower(value.bolt12) - _UniffiConverterOptionalBytes.check_lower(value.preimage) - _UniffiConverterUInt64.check_lower(value.created_at) - _UniffiConverterOptionalUInt64.check_lower(value.completed_at) - _UniffiConverterOptionalUInt64.check_lower(value.number_of_parts) + _UniffiConverterString.check_lower(value.payment_hash) + _UniffiConverterString.check_lower(value.reason) @staticmethod def write(value, buf): - _UniffiConverterBytes.write(value.payment_hash, buf) - _UniffiConverterTypePayStatus.write(value.status, buf) - _UniffiConverterOptionalBytes.write(value.destination_pubkey, buf) - _UniffiConverterOptionalUInt64.write(value.amount_msat, buf) - _UniffiConverterOptionalUInt64.write(value.amount_sent_msat, buf) - _UniffiConverterOptionalString.write(value.label, buf) - _UniffiConverterOptionalString.write(value.bolt11, buf) - _UniffiConverterOptionalString.write(value.description, buf) - _UniffiConverterOptionalString.write(value.bolt12, buf) - _UniffiConverterOptionalBytes.write(value.preimage, buf) - _UniffiConverterUInt64.write(value.created_at, buf) - _UniffiConverterOptionalUInt64.write(value.completed_at, buf) - _UniffiConverterOptionalUInt64.write(value.number_of_parts, buf) + _UniffiConverterString.write(value.payment_hash, buf) + _UniffiConverterString.write(value.reason, buf) -class Payment: - id: "str" - payment_type: "PaymentType" - payment_time: "int" +class LnUrlPayRequest: + """ + Request to execute an LNURL-pay flow. + + Combines the resolved service data with the user's chosen amount. + """ + + data: "LnUrlPayRequestData" + """ + The resolved pay request data from `parse_input()`. + """ + amount_msat: "int" - fee_msat: "int" - status: "PaymentStatus" - description: "typing.Optional[str]" - bolt11: "typing.Optional[str]" - preimage: "typing.Optional[bytes]" - destination: "typing.Optional[bytes]" - def __init__(self, *, id: "str", payment_type: "PaymentType", payment_time: "int", amount_msat: "int", fee_msat: "int", status: "PaymentStatus", description: "typing.Optional[str]", bolt11: "typing.Optional[str]", preimage: "typing.Optional[bytes]", destination: "typing.Optional[bytes]"): - self.id = id - self.payment_type = payment_type - self.payment_time = payment_time + """ + Amount to pay in millisatoshis. + """ + + comment: "typing.Optional[str]" + """ + Optional comment to send with the payment. + """ + + validate_success_action_url: "typing.Optional[bool]" + """ + When true (the default), a URL success action is rejected if its + domain differs from the callback's domain. + + This is a wallet-side safety convention, not a LUD-09 requirement: + LUD-09 does not mandate same-domain URLs, but a divergent domain + can be used to phish users, so the SDK rejects it by default. + Set to `Some(false)` only if you have a specific reason to trust + cross-domain success-action URLs from this service. + """ + + def __init__(self, *, data: "LnUrlPayRequestData", amount_msat: "int", comment: "typing.Optional[str]", validate_success_action_url: "typing.Optional[bool]"): + self.data = data self.amount_msat = amount_msat - self.fee_msat = fee_msat - self.status = status - self.description = description - self.bolt11 = bolt11 - self.preimage = preimage - self.destination = destination + self.comment = comment + self.validate_success_action_url = validate_success_action_url def __str__(self): - return "Payment(id={}, payment_type={}, payment_time={}, amount_msat={}, fee_msat={}, status={}, description={}, bolt11={}, preimage={}, destination={})".format(self.id, self.payment_type, self.payment_time, self.amount_msat, self.fee_msat, self.status, self.description, self.bolt11, self.preimage, self.destination) + return "LnUrlPayRequest(data={}, amount_msat={}, comment={}, validate_success_action_url={})".format(self.data, self.amount_msat, self.comment, self.validate_success_action_url) def __eq__(self, other): - if self.id != other.id: - return False - if self.payment_type != other.payment_type: - return False - if self.payment_time != other.payment_time: + if self.data != other.data: return False if self.amount_msat != other.amount_msat: return False - if self.fee_msat != other.fee_msat: - return False - if self.status != other.status: - return False - if self.description != other.description: - return False - if self.bolt11 != other.bolt11: - return False - if self.preimage != other.preimage: + if self.comment != other.comment: return False - if self.destination != other.destination: + if self.validate_success_action_url != other.validate_success_action_url: return False return True -class _UniffiConverterTypePayment(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlPayRequest(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return Payment( - id=_UniffiConverterString.read(buf), - payment_type=_UniffiConverterTypePaymentType.read(buf), - payment_time=_UniffiConverterUInt64.read(buf), + return LnUrlPayRequest( + data=_UniffiConverterTypeLnUrlPayRequestData.read(buf), amount_msat=_UniffiConverterUInt64.read(buf), - fee_msat=_UniffiConverterUInt64.read(buf), - status=_UniffiConverterTypePaymentStatus.read(buf), - description=_UniffiConverterOptionalString.read(buf), - bolt11=_UniffiConverterOptionalString.read(buf), - preimage=_UniffiConverterOptionalBytes.read(buf), - destination=_UniffiConverterOptionalBytes.read(buf), + comment=_UniffiConverterOptionalString.read(buf), + validate_success_action_url=_UniffiConverterOptionalBool.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterString.check_lower(value.id) - _UniffiConverterTypePaymentType.check_lower(value.payment_type) - _UniffiConverterUInt64.check_lower(value.payment_time) + _UniffiConverterTypeLnUrlPayRequestData.check_lower(value.data) _UniffiConverterUInt64.check_lower(value.amount_msat) - _UniffiConverterUInt64.check_lower(value.fee_msat) - _UniffiConverterTypePaymentStatus.check_lower(value.status) - _UniffiConverterOptionalString.check_lower(value.description) - _UniffiConverterOptionalString.check_lower(value.bolt11) - _UniffiConverterOptionalBytes.check_lower(value.preimage) - _UniffiConverterOptionalBytes.check_lower(value.destination) + _UniffiConverterOptionalString.check_lower(value.comment) + _UniffiConverterOptionalBool.check_lower(value.validate_success_action_url) @staticmethod def write(value, buf): - _UniffiConverterString.write(value.id, buf) - _UniffiConverterTypePaymentType.write(value.payment_type, buf) - _UniffiConverterUInt64.write(value.payment_time, buf) + _UniffiConverterTypeLnUrlPayRequestData.write(value.data, buf) _UniffiConverterUInt64.write(value.amount_msat, buf) - _UniffiConverterUInt64.write(value.fee_msat, buf) - _UniffiConverterTypePaymentStatus.write(value.status, buf) - _UniffiConverterOptionalString.write(value.description, buf) - _UniffiConverterOptionalString.write(value.bolt11, buf) - _UniffiConverterOptionalBytes.write(value.preimage, buf) - _UniffiConverterOptionalBytes.write(value.destination, buf) + _UniffiConverterOptionalString.write(value.comment, buf) + _UniffiConverterOptionalBool.write(value.validate_success_action_url, buf) -class Peer: - id: "bytes" - connected: "bool" - num_channels: "typing.Optional[int]" - netaddr: "typing.List[str]" - remote_addr: "typing.Optional[str]" - features: "typing.Optional[bytes]" - def __init__(self, *, id: "bytes", connected: "bool", num_channels: "typing.Optional[int]", netaddr: "typing.List[str]", remote_addr: "typing.Optional[str]", features: "typing.Optional[bytes]"): - self.id = id - self.connected = connected - self.num_channels = num_channels - self.netaddr = netaddr - self.remote_addr = remote_addr - self.features = features +class LnUrlPayRequestData: + """ + Data from an LNURL-pay endpoint (LUD-06). - def __str__(self): - return "Peer(id={}, connected={}, num_channels={}, netaddr={}, remote_addr={}, features={})".format(self.id, self.connected, self.num_channels, self.netaddr, self.remote_addr, self.features) + Contains the service's accepted amount range and metadata. + Returned inside `InputType::LnUrlPay` after `parse_input` resolves + an LNURL or Lightning Address. + """ - def __eq__(self, other): - if self.id != other.id: - return False - if self.connected != other.connected: - return False - if self.num_channels != other.num_channels: - return False - if self.netaddr != other.netaddr: - return False - if self.remote_addr != other.remote_addr: - return False - if self.features != other.features: - return False - return True + callback: "str" + """ + The callback URL to request an invoice from. + """ -class _UniffiConverterTypePeer(_UniffiConverterRustBuffer): - @staticmethod - def read(buf): - return Peer( - id=_UniffiConverterBytes.read(buf), - connected=_UniffiConverterBool.read(buf), - num_channels=_UniffiConverterOptionalUInt32.read(buf), - netaddr=_UniffiConverterSequenceString.read(buf), - remote_addr=_UniffiConverterOptionalString.read(buf), - features=_UniffiConverterOptionalBytes.read(buf), - ) + min_sendable: "int" + """ + Minimum amount the service accepts, in millisatoshis. + """ - @staticmethod - def check_lower(value): - _UniffiConverterBytes.check_lower(value.id) - _UniffiConverterBool.check_lower(value.connected) - _UniffiConverterOptionalUInt32.check_lower(value.num_channels) - _UniffiConverterSequenceString.check_lower(value.netaddr) - _UniffiConverterOptionalString.check_lower(value.remote_addr) - _UniffiConverterOptionalBytes.check_lower(value.features) + max_sendable: "int" + """ + Maximum amount the service accepts, in millisatoshis. + """ - @staticmethod - def write(value, buf): - _UniffiConverterBytes.write(value.id, buf) - _UniffiConverterBool.write(value.connected, buf) - _UniffiConverterOptionalUInt32.write(value.num_channels, buf) - _UniffiConverterSequenceString.write(value.netaddr, buf) - _UniffiConverterOptionalString.write(value.remote_addr, buf) - _UniffiConverterOptionalBytes.write(value.features, buf) + metadata: "str" + """ + Raw metadata JSON string (array of `["mime", "content"]` pairs). + """ + comment_allowed: "int" + """ + Maximum comment length the service accepts. 0 means no comments. + """ -class PeerChannel: - peer_id: "bytes" - peer_connected: "bool" - state: "ChannelState" - short_channel_id: "typing.Optional[str]" - channel_id: "typing.Optional[bytes]" - funding_txid: "typing.Optional[bytes]" - funding_outnum: "typing.Optional[int]" - to_us_msat: "typing.Optional[int]" - total_msat: "typing.Optional[int]" - spendable_msat: "typing.Optional[int]" - receivable_msat: "typing.Optional[int]" - def __init__(self, *, peer_id: "bytes", peer_connected: "bool", state: "ChannelState", short_channel_id: "typing.Optional[str]", channel_id: "typing.Optional[bytes]", funding_txid: "typing.Optional[bytes]", funding_outnum: "typing.Optional[int]", to_us_msat: "typing.Optional[int]", total_msat: "typing.Optional[int]", spendable_msat: "typing.Optional[int]", receivable_msat: "typing.Optional[int]"): - self.peer_id = peer_id - self.peer_connected = peer_connected - self.state = state - self.short_channel_id = short_channel_id - self.channel_id = channel_id - self.funding_txid = funding_txid - self.funding_outnum = funding_outnum - self.to_us_msat = to_us_msat - self.total_msat = total_msat - self.spendable_msat = spendable_msat - self.receivable_msat = receivable_msat + description: "str" + """ + Human-readable description extracted from metadata. + """ + + lnurl: "str" + """ + The original LNURL or lightning address that was resolved. + """ + + def __init__(self, *, callback: "str", min_sendable: "int", max_sendable: "int", metadata: "str", comment_allowed: "int", description: "str", lnurl: "str"): + self.callback = callback + self.min_sendable = min_sendable + self.max_sendable = max_sendable + self.metadata = metadata + self.comment_allowed = comment_allowed + self.description = description + self.lnurl = lnurl def __str__(self): - return "PeerChannel(peer_id={}, peer_connected={}, state={}, short_channel_id={}, channel_id={}, funding_txid={}, funding_outnum={}, to_us_msat={}, total_msat={}, spendable_msat={}, receivable_msat={})".format(self.peer_id, self.peer_connected, self.state, self.short_channel_id, self.channel_id, self.funding_txid, self.funding_outnum, self.to_us_msat, self.total_msat, self.spendable_msat, self.receivable_msat) + return "LnUrlPayRequestData(callback={}, min_sendable={}, max_sendable={}, metadata={}, comment_allowed={}, description={}, lnurl={})".format(self.callback, self.min_sendable, self.max_sendable, self.metadata, self.comment_allowed, self.description, self.lnurl) def __eq__(self, other): - if self.peer_id != other.peer_id: - return False - if self.peer_connected != other.peer_connected: - return False - if self.state != other.state: - return False - if self.short_channel_id != other.short_channel_id: - return False - if self.channel_id != other.channel_id: + if self.callback != other.callback: return False - if self.funding_txid != other.funding_txid: + if self.min_sendable != other.min_sendable: return False - if self.funding_outnum != other.funding_outnum: + if self.max_sendable != other.max_sendable: return False - if self.to_us_msat != other.to_us_msat: + if self.metadata != other.metadata: return False - if self.total_msat != other.total_msat: + if self.comment_allowed != other.comment_allowed: return False - if self.spendable_msat != other.spendable_msat: + if self.description != other.description: return False - if self.receivable_msat != other.receivable_msat: + if self.lnurl != other.lnurl: return False return True -class _UniffiConverterTypePeerChannel(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlPayRequestData(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return PeerChannel( - peer_id=_UniffiConverterBytes.read(buf), - peer_connected=_UniffiConverterBool.read(buf), - state=_UniffiConverterTypeChannelState.read(buf), - short_channel_id=_UniffiConverterOptionalString.read(buf), - channel_id=_UniffiConverterOptionalBytes.read(buf), - funding_txid=_UniffiConverterOptionalBytes.read(buf), - funding_outnum=_UniffiConverterOptionalUInt32.read(buf), - to_us_msat=_UniffiConverterOptionalUInt64.read(buf), - total_msat=_UniffiConverterOptionalUInt64.read(buf), - spendable_msat=_UniffiConverterOptionalUInt64.read(buf), - receivable_msat=_UniffiConverterOptionalUInt64.read(buf), + return LnUrlPayRequestData( + callback=_UniffiConverterString.read(buf), + min_sendable=_UniffiConverterUInt64.read(buf), + max_sendable=_UniffiConverterUInt64.read(buf), + metadata=_UniffiConverterString.read(buf), + comment_allowed=_UniffiConverterUInt64.read(buf), + description=_UniffiConverterString.read(buf), + lnurl=_UniffiConverterString.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterBytes.check_lower(value.peer_id) - _UniffiConverterBool.check_lower(value.peer_connected) - _UniffiConverterTypeChannelState.check_lower(value.state) - _UniffiConverterOptionalString.check_lower(value.short_channel_id) - _UniffiConverterOptionalBytes.check_lower(value.channel_id) - _UniffiConverterOptionalBytes.check_lower(value.funding_txid) - _UniffiConverterOptionalUInt32.check_lower(value.funding_outnum) - _UniffiConverterOptionalUInt64.check_lower(value.to_us_msat) - _UniffiConverterOptionalUInt64.check_lower(value.total_msat) - _UniffiConverterOptionalUInt64.check_lower(value.spendable_msat) - _UniffiConverterOptionalUInt64.check_lower(value.receivable_msat) + _UniffiConverterString.check_lower(value.callback) + _UniffiConverterUInt64.check_lower(value.min_sendable) + _UniffiConverterUInt64.check_lower(value.max_sendable) + _UniffiConverterString.check_lower(value.metadata) + _UniffiConverterUInt64.check_lower(value.comment_allowed) + _UniffiConverterString.check_lower(value.description) + _UniffiConverterString.check_lower(value.lnurl) @staticmethod def write(value, buf): - _UniffiConverterBytes.write(value.peer_id, buf) - _UniffiConverterBool.write(value.peer_connected, buf) - _UniffiConverterTypeChannelState.write(value.state, buf) - _UniffiConverterOptionalString.write(value.short_channel_id, buf) - _UniffiConverterOptionalBytes.write(value.channel_id, buf) - _UniffiConverterOptionalBytes.write(value.funding_txid, buf) - _UniffiConverterOptionalUInt32.write(value.funding_outnum, buf) - _UniffiConverterOptionalUInt64.write(value.to_us_msat, buf) - _UniffiConverterOptionalUInt64.write(value.total_msat, buf) - _UniffiConverterOptionalUInt64.write(value.spendable_msat, buf) - _UniffiConverterOptionalUInt64.write(value.receivable_msat, buf) + _UniffiConverterString.write(value.callback, buf) + _UniffiConverterUInt64.write(value.min_sendable, buf) + _UniffiConverterUInt64.write(value.max_sendable, buf) + _UniffiConverterString.write(value.metadata, buf) + _UniffiConverterUInt64.write(value.comment_allowed, buf) + _UniffiConverterString.write(value.description, buf) + _UniffiConverterString.write(value.lnurl, buf) -class ReceiveResponse: - bolt11: "str" - opening_fee_msat: "int" +class LnUrlPaySuccessData: """ - The fee charged by the LSP for opening a JIT channel, in - millisatoshi. This is 0 if no JIT channel was needed. + Successful LNURL-pay result data. """ - def __init__(self, *, bolt11: "str", opening_fee_msat: "int"): - self.bolt11 = bolt11 - self.opening_fee_msat = opening_fee_msat + payment_preimage: "str" + """ + The payment preimage (proof of payment), hex-encoded. + """ + + success_action: "typing.Optional[SuccessActionProcessed]" + """ + Optional success action from the service (LUD-09). + """ + + def __init__(self, *, payment_preimage: "str", success_action: "typing.Optional[SuccessActionProcessed]"): + self.payment_preimage = payment_preimage + self.success_action = success_action def __str__(self): - return "ReceiveResponse(bolt11={}, opening_fee_msat={})".format(self.bolt11, self.opening_fee_msat) + return "LnUrlPaySuccessData(payment_preimage={}, success_action={})".format(self.payment_preimage, self.success_action) def __eq__(self, other): - if self.bolt11 != other.bolt11: + if self.payment_preimage != other.payment_preimage: return False - if self.opening_fee_msat != other.opening_fee_msat: + if self.success_action != other.success_action: return False return True -class _UniffiConverterTypeReceiveResponse(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlPaySuccessData(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return ReceiveResponse( - bolt11=_UniffiConverterString.read(buf), - opening_fee_msat=_UniffiConverterUInt64.read(buf), + return LnUrlPaySuccessData( + payment_preimage=_UniffiConverterString.read(buf), + success_action=_UniffiConverterOptionalTypeSuccessActionProcessed.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterString.check_lower(value.bolt11) - _UniffiConverterUInt64.check_lower(value.opening_fee_msat) + _UniffiConverterString.check_lower(value.payment_preimage) + _UniffiConverterOptionalTypeSuccessActionProcessed.check_lower(value.success_action) @staticmethod def write(value, buf): - _UniffiConverterString.write(value.bolt11, buf) - _UniffiConverterUInt64.write(value.opening_fee_msat, buf) + _UniffiConverterString.write(value.payment_preimage, buf) + _UniffiConverterOptionalTypeSuccessActionProcessed.write(value.success_action, buf) -class SendResponse: - status: "PayStatus" - preimage: "bytes" - payment_hash: "bytes" - destination_pubkey: "typing.Optional[bytes]" +class LnUrlWithdrawRequest: + """ + Request to execute an LNURL-withdraw flow. + + Combines the resolved service data with the user's chosen amount. + """ + + data: "LnUrlWithdrawRequestData" + """ + The resolved withdraw request data from `parse_input()`. + """ + amount_msat: "int" - amount_sent_msat: "int" - parts: "int" - def __init__(self, *, status: "PayStatus", preimage: "bytes", payment_hash: "bytes", destination_pubkey: "typing.Optional[bytes]", amount_msat: "int", amount_sent_msat: "int", parts: "int"): - self.status = status - self.preimage = preimage - self.payment_hash = payment_hash - self.destination_pubkey = destination_pubkey + """ + Amount to withdraw in millisatoshis. + """ + + description: "typing.Optional[str]" + """ + Optional description for the invoice (overrides default). + """ + + def __init__(self, *, data: "LnUrlWithdrawRequestData", amount_msat: "int", description: "typing.Optional[str]"): + self.data = data self.amount_msat = amount_msat - self.amount_sent_msat = amount_sent_msat - self.parts = parts + self.description = description def __str__(self): - return "SendResponse(status={}, preimage={}, payment_hash={}, destination_pubkey={}, amount_msat={}, amount_sent_msat={}, parts={})".format(self.status, self.preimage, self.payment_hash, self.destination_pubkey, self.amount_msat, self.amount_sent_msat, self.parts) + return "LnUrlWithdrawRequest(data={}, amount_msat={}, description={})".format(self.data, self.amount_msat, self.description) def __eq__(self, other): - if self.status != other.status: - return False - if self.preimage != other.preimage: - return False - if self.payment_hash != other.payment_hash: - return False - if self.destination_pubkey != other.destination_pubkey: + if self.data != other.data: return False if self.amount_msat != other.amount_msat: return False - if self.amount_sent_msat != other.amount_sent_msat: - return False - if self.parts != other.parts: + if self.description != other.description: return False return True -class _UniffiConverterTypeSendResponse(_UniffiConverterRustBuffer): +class _UniffiConverterTypeLnUrlWithdrawRequest(_UniffiConverterRustBuffer): @staticmethod def read(buf): - return SendResponse( - status=_UniffiConverterTypePayStatus.read(buf), - preimage=_UniffiConverterBytes.read(buf), - payment_hash=_UniffiConverterBytes.read(buf), - destination_pubkey=_UniffiConverterOptionalBytes.read(buf), + return LnUrlWithdrawRequest( + data=_UniffiConverterTypeLnUrlWithdrawRequestData.read(buf), amount_msat=_UniffiConverterUInt64.read(buf), - amount_sent_msat=_UniffiConverterUInt64.read(buf), - parts=_UniffiConverterUInt32.read(buf), + description=_UniffiConverterOptionalString.read(buf), ) @staticmethod def check_lower(value): - _UniffiConverterTypePayStatus.check_lower(value.status) - _UniffiConverterBytes.check_lower(value.preimage) - _UniffiConverterBytes.check_lower(value.payment_hash) - _UniffiConverterOptionalBytes.check_lower(value.destination_pubkey) + _UniffiConverterTypeLnUrlWithdrawRequestData.check_lower(value.data) _UniffiConverterUInt64.check_lower(value.amount_msat) - _UniffiConverterUInt64.check_lower(value.amount_sent_msat) + _UniffiConverterOptionalString.check_lower(value.description) + + @staticmethod + def write(value, buf): + _UniffiConverterTypeLnUrlWithdrawRequestData.write(value.data, buf) + _UniffiConverterUInt64.write(value.amount_msat, buf) + _UniffiConverterOptionalString.write(value.description, buf) + + +class LnUrlWithdrawRequestData: + """ + Data from an LNURL-withdraw endpoint (LUD-03). + + Contains the service's accepted withdrawal range and session key. + Returned inside `InputType::LnUrlWithdraw` after `parse_input` + resolves an LNURL. + """ + + callback: "str" + """ + The callback URL to submit the invoice to. + """ + + k1: "str" + """ + Ephemeral secret linking this wallet session to the service. + """ + + default_description: "str" + """ + Default description for the invoice. + """ + + min_withdrawable: "int" + """ + Minimum withdrawable amount in millisatoshis. + """ + + max_withdrawable: "int" + """ + Maximum withdrawable amount in millisatoshis. + """ + + lnurl: "str" + """ + The original LNURL that was resolved. + """ + + def __init__(self, *, callback: "str", k1: "str", default_description: "str", min_withdrawable: "int", max_withdrawable: "int", lnurl: "str"): + self.callback = callback + self.k1 = k1 + self.default_description = default_description + self.min_withdrawable = min_withdrawable + self.max_withdrawable = max_withdrawable + self.lnurl = lnurl + + def __str__(self): + return "LnUrlWithdrawRequestData(callback={}, k1={}, default_description={}, min_withdrawable={}, max_withdrawable={}, lnurl={})".format(self.callback, self.k1, self.default_description, self.min_withdrawable, self.max_withdrawable, self.lnurl) + + def __eq__(self, other): + if self.callback != other.callback: + return False + if self.k1 != other.k1: + return False + if self.default_description != other.default_description: + return False + if self.min_withdrawable != other.min_withdrawable: + return False + if self.max_withdrawable != other.max_withdrawable: + return False + if self.lnurl != other.lnurl: + return False + return True + +class _UniffiConverterTypeLnUrlWithdrawRequestData(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return LnUrlWithdrawRequestData( + callback=_UniffiConverterString.read(buf), + k1=_UniffiConverterString.read(buf), + default_description=_UniffiConverterString.read(buf), + min_withdrawable=_UniffiConverterUInt64.read(buf), + max_withdrawable=_UniffiConverterUInt64.read(buf), + lnurl=_UniffiConverterString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.callback) + _UniffiConverterString.check_lower(value.k1) + _UniffiConverterString.check_lower(value.default_description) + _UniffiConverterUInt64.check_lower(value.min_withdrawable) + _UniffiConverterUInt64.check_lower(value.max_withdrawable) + _UniffiConverterString.check_lower(value.lnurl) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.callback, buf) + _UniffiConverterString.write(value.k1, buf) + _UniffiConverterString.write(value.default_description, buf) + _UniffiConverterUInt64.write(value.min_withdrawable, buf) + _UniffiConverterUInt64.write(value.max_withdrawable, buf) + _UniffiConverterString.write(value.lnurl, buf) + + +class LnUrlWithdrawSuccessData: + """ + Successful LNURL-withdraw result data. + """ + + invoice: "str" + """ + The BOLT11 invoice that was submitted for withdrawal. + """ + + def __init__(self, *, invoice: "str"): + self.invoice = invoice + + def __str__(self): + return "LnUrlWithdrawSuccessData(invoice={})".format(self.invoice) + + def __eq__(self, other): + if self.invoice != other.invoice: + return False + return True + +class _UniffiConverterTypeLnUrlWithdrawSuccessData(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return LnUrlWithdrawSuccessData( + invoice=_UniffiConverterString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.invoice) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.invoice, buf) + + +class OnchainReceiveResponse: + """ + A pair of on-chain addresses for receiving funds. + """ + + bech32: "str" + """ + SegWit v0 (bech32) address — starts with `bc1q` on mainnet. + """ + + p2tr: "str" + """ + Taproot (bech32m) address — starts with `bc1p` on mainnet. + """ + + def __init__(self, *, bech32: "str", p2tr: "str"): + self.bech32 = bech32 + self.p2tr = p2tr + + def __str__(self): + return "OnchainReceiveResponse(bech32={}, p2tr={})".format(self.bech32, self.p2tr) + + def __eq__(self, other): + if self.bech32 != other.bech32: + return False + if self.p2tr != other.p2tr: + return False + return True + +class _UniffiConverterTypeOnchainReceiveResponse(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return OnchainReceiveResponse( + bech32=_UniffiConverterString.read(buf), + p2tr=_UniffiConverterString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.bech32) + _UniffiConverterString.check_lower(value.p2tr) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.bech32, buf) + _UniffiConverterString.write(value.p2tr, buf) + + +class OnchainSendResponse: + """ + Result of an on-chain send. The transaction has already been broadcast. + """ + + tx: "bytes" + """ + The raw signed transaction bytes. + """ + + txid: "bytes" + """ + The transaction ID (32 bytes, reversed byte order as is standard). + """ + + psbt: "str" + """ + The transaction as a Partially Signed Bitcoin Transaction string. + """ + + def __init__(self, *, tx: "bytes", txid: "bytes", psbt: "str"): + self.tx = tx + self.txid = txid + self.psbt = psbt + + def __str__(self): + return "OnchainSendResponse(tx={}, txid={}, psbt={})".format(self.tx, self.txid, self.psbt) + + def __eq__(self, other): + if self.tx != other.tx: + return False + if self.txid != other.txid: + return False + if self.psbt != other.psbt: + return False + return True + +class _UniffiConverterTypeOnchainSendResponse(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return OnchainSendResponse( + tx=_UniffiConverterBytes.read(buf), + txid=_UniffiConverterBytes.read(buf), + psbt=_UniffiConverterString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterBytes.check_lower(value.tx) + _UniffiConverterBytes.check_lower(value.txid) + _UniffiConverterString.check_lower(value.psbt) + + @staticmethod + def write(value, buf): + _UniffiConverterBytes.write(value.tx, buf) + _UniffiConverterBytes.write(value.txid, buf) + _UniffiConverterString.write(value.psbt, buf) + + +class ParsedInvoice: + """ + Parsed BOLT11 invoice with extracted fields. + """ + + bolt11: "str" + """ + The original invoice string. + """ + + payee_pubkey: "typing.Optional[bytes]" + """ + 33-byte recipient public key, recovered from the invoice signature. + """ + + payment_hash: "bytes" + """ + 32-byte payment hash identifying this payment. + """ + + description: "typing.Optional[str]" + """ + Invoice description. None if the invoice uses a description hash. + """ + + amount_msat: "typing.Optional[int]" + """ + Requested amount in millisatoshis. None for "any amount" invoices. + """ + + expiry: "int" + """ + Seconds from creation until the invoice expires. + """ + + timestamp: "int" + """ + Unix timestamp (seconds) when the invoice was created. + """ + + def __init__(self, *, bolt11: "str", payee_pubkey: "typing.Optional[bytes]", payment_hash: "bytes", description: "typing.Optional[str]", amount_msat: "typing.Optional[int]", expiry: "int", timestamp: "int"): + self.bolt11 = bolt11 + self.payee_pubkey = payee_pubkey + self.payment_hash = payment_hash + self.description = description + self.amount_msat = amount_msat + self.expiry = expiry + self.timestamp = timestamp + + def __str__(self): + return "ParsedInvoice(bolt11={}, payee_pubkey={}, payment_hash={}, description={}, amount_msat={}, expiry={}, timestamp={})".format(self.bolt11, self.payee_pubkey, self.payment_hash, self.description, self.amount_msat, self.expiry, self.timestamp) + + def __eq__(self, other): + if self.bolt11 != other.bolt11: + return False + if self.payee_pubkey != other.payee_pubkey: + return False + if self.payment_hash != other.payment_hash: + return False + if self.description != other.description: + return False + if self.amount_msat != other.amount_msat: + return False + if self.expiry != other.expiry: + return False + if self.timestamp != other.timestamp: + return False + return True + +class _UniffiConverterTypeParsedInvoice(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return ParsedInvoice( + bolt11=_UniffiConverterString.read(buf), + payee_pubkey=_UniffiConverterOptionalBytes.read(buf), + payment_hash=_UniffiConverterBytes.read(buf), + description=_UniffiConverterOptionalString.read(buf), + amount_msat=_UniffiConverterOptionalUInt64.read(buf), + expiry=_UniffiConverterUInt64.read(buf), + timestamp=_UniffiConverterUInt64.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.bolt11) + _UniffiConverterOptionalBytes.check_lower(value.payee_pubkey) + _UniffiConverterBytes.check_lower(value.payment_hash) + _UniffiConverterOptionalString.check_lower(value.description) + _UniffiConverterOptionalUInt64.check_lower(value.amount_msat) + _UniffiConverterUInt64.check_lower(value.expiry) + _UniffiConverterUInt64.check_lower(value.timestamp) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.bolt11, buf) + _UniffiConverterOptionalBytes.write(value.payee_pubkey, buf) + _UniffiConverterBytes.write(value.payment_hash, buf) + _UniffiConverterOptionalString.write(value.description, buf) + _UniffiConverterOptionalUInt64.write(value.amount_msat, buf) + _UniffiConverterUInt64.write(value.expiry, buf) + _UniffiConverterUInt64.write(value.timestamp, buf) + + +class Pay: + payment_hash: "bytes" + status: "PayStatus" + destination_pubkey: "typing.Optional[bytes]" + amount_msat: "typing.Optional[int]" + amount_sent_msat: "typing.Optional[int]" + label: "typing.Optional[str]" + bolt11: "typing.Optional[str]" + description: "typing.Optional[str]" + bolt12: "typing.Optional[str]" + preimage: "typing.Optional[bytes]" + created_at: "int" + completed_at: "typing.Optional[int]" + number_of_parts: "typing.Optional[int]" + def __init__(self, *, payment_hash: "bytes", status: "PayStatus", destination_pubkey: "typing.Optional[bytes]", amount_msat: "typing.Optional[int]", amount_sent_msat: "typing.Optional[int]", label: "typing.Optional[str]", bolt11: "typing.Optional[str]", description: "typing.Optional[str]", bolt12: "typing.Optional[str]", preimage: "typing.Optional[bytes]", created_at: "int", completed_at: "typing.Optional[int]", number_of_parts: "typing.Optional[int]"): + self.payment_hash = payment_hash + self.status = status + self.destination_pubkey = destination_pubkey + self.amount_msat = amount_msat + self.amount_sent_msat = amount_sent_msat + self.label = label + self.bolt11 = bolt11 + self.description = description + self.bolt12 = bolt12 + self.preimage = preimage + self.created_at = created_at + self.completed_at = completed_at + self.number_of_parts = number_of_parts + + def __str__(self): + return "Pay(payment_hash={}, status={}, destination_pubkey={}, amount_msat={}, amount_sent_msat={}, label={}, bolt11={}, description={}, bolt12={}, preimage={}, created_at={}, completed_at={}, number_of_parts={})".format(self.payment_hash, self.status, self.destination_pubkey, self.amount_msat, self.amount_sent_msat, self.label, self.bolt11, self.description, self.bolt12, self.preimage, self.created_at, self.completed_at, self.number_of_parts) + + def __eq__(self, other): + if self.payment_hash != other.payment_hash: + return False + if self.status != other.status: + return False + if self.destination_pubkey != other.destination_pubkey: + return False + if self.amount_msat != other.amount_msat: + return False + if self.amount_sent_msat != other.amount_sent_msat: + return False + if self.label != other.label: + return False + if self.bolt11 != other.bolt11: + return False + if self.description != other.description: + return False + if self.bolt12 != other.bolt12: + return False + if self.preimage != other.preimage: + return False + if self.created_at != other.created_at: + return False + if self.completed_at != other.completed_at: + return False + if self.number_of_parts != other.number_of_parts: + return False + return True + +class _UniffiConverterTypePay(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return Pay( + payment_hash=_UniffiConverterBytes.read(buf), + status=_UniffiConverterTypePayStatus.read(buf), + destination_pubkey=_UniffiConverterOptionalBytes.read(buf), + amount_msat=_UniffiConverterOptionalUInt64.read(buf), + amount_sent_msat=_UniffiConverterOptionalUInt64.read(buf), + label=_UniffiConverterOptionalString.read(buf), + bolt11=_UniffiConverterOptionalString.read(buf), + description=_UniffiConverterOptionalString.read(buf), + bolt12=_UniffiConverterOptionalString.read(buf), + preimage=_UniffiConverterOptionalBytes.read(buf), + created_at=_UniffiConverterUInt64.read(buf), + completed_at=_UniffiConverterOptionalUInt64.read(buf), + number_of_parts=_UniffiConverterOptionalUInt64.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterBytes.check_lower(value.payment_hash) + _UniffiConverterTypePayStatus.check_lower(value.status) + _UniffiConverterOptionalBytes.check_lower(value.destination_pubkey) + _UniffiConverterOptionalUInt64.check_lower(value.amount_msat) + _UniffiConverterOptionalUInt64.check_lower(value.amount_sent_msat) + _UniffiConverterOptionalString.check_lower(value.label) + _UniffiConverterOptionalString.check_lower(value.bolt11) + _UniffiConverterOptionalString.check_lower(value.description) + _UniffiConverterOptionalString.check_lower(value.bolt12) + _UniffiConverterOptionalBytes.check_lower(value.preimage) + _UniffiConverterUInt64.check_lower(value.created_at) + _UniffiConverterOptionalUInt64.check_lower(value.completed_at) + _UniffiConverterOptionalUInt64.check_lower(value.number_of_parts) + + @staticmethod + def write(value, buf): + _UniffiConverterBytes.write(value.payment_hash, buf) + _UniffiConverterTypePayStatus.write(value.status, buf) + _UniffiConverterOptionalBytes.write(value.destination_pubkey, buf) + _UniffiConverterOptionalUInt64.write(value.amount_msat, buf) + _UniffiConverterOptionalUInt64.write(value.amount_sent_msat, buf) + _UniffiConverterOptionalString.write(value.label, buf) + _UniffiConverterOptionalString.write(value.bolt11, buf) + _UniffiConverterOptionalString.write(value.description, buf) + _UniffiConverterOptionalString.write(value.bolt12, buf) + _UniffiConverterOptionalBytes.write(value.preimage, buf) + _UniffiConverterUInt64.write(value.created_at, buf) + _UniffiConverterOptionalUInt64.write(value.completed_at, buf) + _UniffiConverterOptionalUInt64.write(value.number_of_parts, buf) + + +class Payment: + id: "str" + payment_type: "PaymentType" + payment_time: "int" + amount_msat: "int" + fee_msat: "int" + status: "PaymentStatus" + description: "typing.Optional[str]" + bolt11: "typing.Optional[str]" + preimage: "typing.Optional[bytes]" + destination: "typing.Optional[bytes]" + def __init__(self, *, id: "str", payment_type: "PaymentType", payment_time: "int", amount_msat: "int", fee_msat: "int", status: "PaymentStatus", description: "typing.Optional[str]", bolt11: "typing.Optional[str]", preimage: "typing.Optional[bytes]", destination: "typing.Optional[bytes]"): + self.id = id + self.payment_type = payment_type + self.payment_time = payment_time + self.amount_msat = amount_msat + self.fee_msat = fee_msat + self.status = status + self.description = description + self.bolt11 = bolt11 + self.preimage = preimage + self.destination = destination + + def __str__(self): + return "Payment(id={}, payment_type={}, payment_time={}, amount_msat={}, fee_msat={}, status={}, description={}, bolt11={}, preimage={}, destination={})".format(self.id, self.payment_type, self.payment_time, self.amount_msat, self.fee_msat, self.status, self.description, self.bolt11, self.preimage, self.destination) + + def __eq__(self, other): + if self.id != other.id: + return False + if self.payment_type != other.payment_type: + return False + if self.payment_time != other.payment_time: + return False + if self.amount_msat != other.amount_msat: + return False + if self.fee_msat != other.fee_msat: + return False + if self.status != other.status: + return False + if self.description != other.description: + return False + if self.bolt11 != other.bolt11: + return False + if self.preimage != other.preimage: + return False + if self.destination != other.destination: + return False + return True + +class _UniffiConverterTypePayment(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return Payment( + id=_UniffiConverterString.read(buf), + payment_type=_UniffiConverterTypePaymentType.read(buf), + payment_time=_UniffiConverterUInt64.read(buf), + amount_msat=_UniffiConverterUInt64.read(buf), + fee_msat=_UniffiConverterUInt64.read(buf), + status=_UniffiConverterTypePaymentStatus.read(buf), + description=_UniffiConverterOptionalString.read(buf), + bolt11=_UniffiConverterOptionalString.read(buf), + preimage=_UniffiConverterOptionalBytes.read(buf), + destination=_UniffiConverterOptionalBytes.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.id) + _UniffiConverterTypePaymentType.check_lower(value.payment_type) + _UniffiConverterUInt64.check_lower(value.payment_time) + _UniffiConverterUInt64.check_lower(value.amount_msat) + _UniffiConverterUInt64.check_lower(value.fee_msat) + _UniffiConverterTypePaymentStatus.check_lower(value.status) + _UniffiConverterOptionalString.check_lower(value.description) + _UniffiConverterOptionalString.check_lower(value.bolt11) + _UniffiConverterOptionalBytes.check_lower(value.preimage) + _UniffiConverterOptionalBytes.check_lower(value.destination) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.id, buf) + _UniffiConverterTypePaymentType.write(value.payment_type, buf) + _UniffiConverterUInt64.write(value.payment_time, buf) + _UniffiConverterUInt64.write(value.amount_msat, buf) + _UniffiConverterUInt64.write(value.fee_msat, buf) + _UniffiConverterTypePaymentStatus.write(value.status, buf) + _UniffiConverterOptionalString.write(value.description, buf) + _UniffiConverterOptionalString.write(value.bolt11, buf) + _UniffiConverterOptionalBytes.write(value.preimage, buf) + _UniffiConverterOptionalBytes.write(value.destination, buf) + + +class Peer: + id: "bytes" + connected: "bool" + num_channels: "typing.Optional[int]" + netaddr: "typing.List[str]" + remote_addr: "typing.Optional[str]" + features: "typing.Optional[bytes]" + def __init__(self, *, id: "bytes", connected: "bool", num_channels: "typing.Optional[int]", netaddr: "typing.List[str]", remote_addr: "typing.Optional[str]", features: "typing.Optional[bytes]"): + self.id = id + self.connected = connected + self.num_channels = num_channels + self.netaddr = netaddr + self.remote_addr = remote_addr + self.features = features + + def __str__(self): + return "Peer(id={}, connected={}, num_channels={}, netaddr={}, remote_addr={}, features={})".format(self.id, self.connected, self.num_channels, self.netaddr, self.remote_addr, self.features) + + def __eq__(self, other): + if self.id != other.id: + return False + if self.connected != other.connected: + return False + if self.num_channels != other.num_channels: + return False + if self.netaddr != other.netaddr: + return False + if self.remote_addr != other.remote_addr: + return False + if self.features != other.features: + return False + return True + +class _UniffiConverterTypePeer(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return Peer( + id=_UniffiConverterBytes.read(buf), + connected=_UniffiConverterBool.read(buf), + num_channels=_UniffiConverterOptionalUInt32.read(buf), + netaddr=_UniffiConverterSequenceString.read(buf), + remote_addr=_UniffiConverterOptionalString.read(buf), + features=_UniffiConverterOptionalBytes.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterBytes.check_lower(value.id) + _UniffiConverterBool.check_lower(value.connected) + _UniffiConverterOptionalUInt32.check_lower(value.num_channels) + _UniffiConverterSequenceString.check_lower(value.netaddr) + _UniffiConverterOptionalString.check_lower(value.remote_addr) + _UniffiConverterOptionalBytes.check_lower(value.features) + + @staticmethod + def write(value, buf): + _UniffiConverterBytes.write(value.id, buf) + _UniffiConverterBool.write(value.connected, buf) + _UniffiConverterOptionalUInt32.write(value.num_channels, buf) + _UniffiConverterSequenceString.write(value.netaddr, buf) + _UniffiConverterOptionalString.write(value.remote_addr, buf) + _UniffiConverterOptionalBytes.write(value.features, buf) + + +class PeerChannel: + peer_id: "bytes" + peer_connected: "bool" + state: "ChannelState" + short_channel_id: "typing.Optional[str]" + channel_id: "typing.Optional[bytes]" + funding_txid: "typing.Optional[bytes]" + funding_outnum: "typing.Optional[int]" + to_us_msat: "typing.Optional[int]" + total_msat: "typing.Optional[int]" + spendable_msat: "typing.Optional[int]" + receivable_msat: "typing.Optional[int]" + def __init__(self, *, peer_id: "bytes", peer_connected: "bool", state: "ChannelState", short_channel_id: "typing.Optional[str]", channel_id: "typing.Optional[bytes]", funding_txid: "typing.Optional[bytes]", funding_outnum: "typing.Optional[int]", to_us_msat: "typing.Optional[int]", total_msat: "typing.Optional[int]", spendable_msat: "typing.Optional[int]", receivable_msat: "typing.Optional[int]"): + self.peer_id = peer_id + self.peer_connected = peer_connected + self.state = state + self.short_channel_id = short_channel_id + self.channel_id = channel_id + self.funding_txid = funding_txid + self.funding_outnum = funding_outnum + self.to_us_msat = to_us_msat + self.total_msat = total_msat + self.spendable_msat = spendable_msat + self.receivable_msat = receivable_msat + + def __str__(self): + return "PeerChannel(peer_id={}, peer_connected={}, state={}, short_channel_id={}, channel_id={}, funding_txid={}, funding_outnum={}, to_us_msat={}, total_msat={}, spendable_msat={}, receivable_msat={})".format(self.peer_id, self.peer_connected, self.state, self.short_channel_id, self.channel_id, self.funding_txid, self.funding_outnum, self.to_us_msat, self.total_msat, self.spendable_msat, self.receivable_msat) + + def __eq__(self, other): + if self.peer_id != other.peer_id: + return False + if self.peer_connected != other.peer_connected: + return False + if self.state != other.state: + return False + if self.short_channel_id != other.short_channel_id: + return False + if self.channel_id != other.channel_id: + return False + if self.funding_txid != other.funding_txid: + return False + if self.funding_outnum != other.funding_outnum: + return False + if self.to_us_msat != other.to_us_msat: + return False + if self.total_msat != other.total_msat: + return False + if self.spendable_msat != other.spendable_msat: + return False + if self.receivable_msat != other.receivable_msat: + return False + return True + +class _UniffiConverterTypePeerChannel(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return PeerChannel( + peer_id=_UniffiConverterBytes.read(buf), + peer_connected=_UniffiConverterBool.read(buf), + state=_UniffiConverterTypeChannelState.read(buf), + short_channel_id=_UniffiConverterOptionalString.read(buf), + channel_id=_UniffiConverterOptionalBytes.read(buf), + funding_txid=_UniffiConverterOptionalBytes.read(buf), + funding_outnum=_UniffiConverterOptionalUInt32.read(buf), + to_us_msat=_UniffiConverterOptionalUInt64.read(buf), + total_msat=_UniffiConverterOptionalUInt64.read(buf), + spendable_msat=_UniffiConverterOptionalUInt64.read(buf), + receivable_msat=_UniffiConverterOptionalUInt64.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterBytes.check_lower(value.peer_id) + _UniffiConverterBool.check_lower(value.peer_connected) + _UniffiConverterTypeChannelState.check_lower(value.state) + _UniffiConverterOptionalString.check_lower(value.short_channel_id) + _UniffiConverterOptionalBytes.check_lower(value.channel_id) + _UniffiConverterOptionalBytes.check_lower(value.funding_txid) + _UniffiConverterOptionalUInt32.check_lower(value.funding_outnum) + _UniffiConverterOptionalUInt64.check_lower(value.to_us_msat) + _UniffiConverterOptionalUInt64.check_lower(value.total_msat) + _UniffiConverterOptionalUInt64.check_lower(value.spendable_msat) + _UniffiConverterOptionalUInt64.check_lower(value.receivable_msat) + + @staticmethod + def write(value, buf): + _UniffiConverterBytes.write(value.peer_id, buf) + _UniffiConverterBool.write(value.peer_connected, buf) + _UniffiConverterTypeChannelState.write(value.state, buf) + _UniffiConverterOptionalString.write(value.short_channel_id, buf) + _UniffiConverterOptionalBytes.write(value.channel_id, buf) + _UniffiConverterOptionalBytes.write(value.funding_txid, buf) + _UniffiConverterOptionalUInt32.write(value.funding_outnum, buf) + _UniffiConverterOptionalUInt64.write(value.to_us_msat, buf) + _UniffiConverterOptionalUInt64.write(value.total_msat, buf) + _UniffiConverterOptionalUInt64.write(value.spendable_msat, buf) + _UniffiConverterOptionalUInt64.write(value.receivable_msat, buf) + + +class ReceiveResponse: + bolt11: "str" + opening_fee_msat: "int" + """ + The fee charged by the LSP for opening a JIT channel, in + millisatoshi. This is 0 if no JIT channel was needed. + """ + + def __init__(self, *, bolt11: "str", opening_fee_msat: "int"): + self.bolt11 = bolt11 + self.opening_fee_msat = opening_fee_msat + + def __str__(self): + return "ReceiveResponse(bolt11={}, opening_fee_msat={})".format(self.bolt11, self.opening_fee_msat) + + def __eq__(self, other): + if self.bolt11 != other.bolt11: + return False + if self.opening_fee_msat != other.opening_fee_msat: + return False + return True + +class _UniffiConverterTypeReceiveResponse(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return ReceiveResponse( + bolt11=_UniffiConverterString.read(buf), + opening_fee_msat=_UniffiConverterUInt64.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterString.check_lower(value.bolt11) + _UniffiConverterUInt64.check_lower(value.opening_fee_msat) + + @staticmethod + def write(value, buf): + _UniffiConverterString.write(value.bolt11, buf) + _UniffiConverterUInt64.write(value.opening_fee_msat, buf) + + +class SendResponse: + status: "PayStatus" + preimage: "bytes" + payment_hash: "bytes" + destination_pubkey: "typing.Optional[bytes]" + amount_msat: "int" + amount_sent_msat: "int" + parts: "int" + def __init__(self, *, status: "PayStatus", preimage: "bytes", payment_hash: "bytes", destination_pubkey: "typing.Optional[bytes]", amount_msat: "int", amount_sent_msat: "int", parts: "int"): + self.status = status + self.preimage = preimage + self.payment_hash = payment_hash + self.destination_pubkey = destination_pubkey + self.amount_msat = amount_msat + self.amount_sent_msat = amount_sent_msat + self.parts = parts + + def __str__(self): + return "SendResponse(status={}, preimage={}, payment_hash={}, destination_pubkey={}, amount_msat={}, amount_sent_msat={}, parts={})".format(self.status, self.preimage, self.payment_hash, self.destination_pubkey, self.amount_msat, self.amount_sent_msat, self.parts) + + def __eq__(self, other): + if self.status != other.status: + return False + if self.preimage != other.preimage: + return False + if self.payment_hash != other.payment_hash: + return False + if self.destination_pubkey != other.destination_pubkey: + return False + if self.amount_msat != other.amount_msat: + return False + if self.amount_sent_msat != other.amount_sent_msat: + return False + if self.parts != other.parts: + return False + return True + +class _UniffiConverterTypeSendResponse(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return SendResponse( + status=_UniffiConverterTypePayStatus.read(buf), + preimage=_UniffiConverterBytes.read(buf), + payment_hash=_UniffiConverterBytes.read(buf), + destination_pubkey=_UniffiConverterOptionalBytes.read(buf), + amount_msat=_UniffiConverterUInt64.read(buf), + amount_sent_msat=_UniffiConverterUInt64.read(buf), + parts=_UniffiConverterUInt32.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiConverterTypePayStatus.check_lower(value.status) + _UniffiConverterBytes.check_lower(value.preimage) + _UniffiConverterBytes.check_lower(value.payment_hash) + _UniffiConverterOptionalBytes.check_lower(value.destination_pubkey) + _UniffiConverterUInt64.check_lower(value.amount_msat) + _UniffiConverterUInt64.check_lower(value.amount_sent_msat) _UniffiConverterUInt32.check_lower(value.parts) @staticmethod @@ -2929,75 +3680,296 @@ def read(buf): _UniffiConverterString.read(buf), ) if variant == 2: - return Error.NoSuchNode( + return Error.NoSuchNode( + _UniffiConverterString.read(buf), + ) + if variant == 3: + return Error.UnparseableCreds( + ) + if variant == 4: + return Error.PhraseCorrupted( + ) + if variant == 5: + return Error.Rpc( + _UniffiConverterString.read(buf), + ) + if variant == 6: + return Error.Argument( + _UniffiConverterString.read(buf), + _UniffiConverterString.read(buf), + ) + if variant == 7: + return Error.Other( + _UniffiConverterString.read(buf), + ) + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if isinstance(value, Error.DuplicateNode): + _UniffiConverterString.check_lower(value._values[0]) + return + if isinstance(value, Error.NoSuchNode): + _UniffiConverterString.check_lower(value._values[0]) + return + if isinstance(value, Error.UnparseableCreds): + return + if isinstance(value, Error.PhraseCorrupted): + return + if isinstance(value, Error.Rpc): + _UniffiConverterString.check_lower(value._values[0]) + return + if isinstance(value, Error.Argument): + _UniffiConverterString.check_lower(value._values[0]) + _UniffiConverterString.check_lower(value._values[1]) + return + if isinstance(value, Error.Other): + _UniffiConverterString.check_lower(value._values[0]) + return + + @staticmethod + def write(value, buf): + if isinstance(value, Error.DuplicateNode): + buf.write_i32(1) + _UniffiConverterString.write(value._values[0], buf) + if isinstance(value, Error.NoSuchNode): + buf.write_i32(2) + _UniffiConverterString.write(value._values[0], buf) + if isinstance(value, Error.UnparseableCreds): + buf.write_i32(3) + if isinstance(value, Error.PhraseCorrupted): + buf.write_i32(4) + if isinstance(value, Error.Rpc): + buf.write_i32(5) + _UniffiConverterString.write(value._values[0], buf) + if isinstance(value, Error.Argument): + buf.write_i32(6) + _UniffiConverterString.write(value._values[0], buf) + _UniffiConverterString.write(value._values[1], buf) + if isinstance(value, Error.Other): + buf.write_i32(7) + _UniffiConverterString.write(value._values[0], buf) + + + + + +class InputType: + """ + The result of `parse_input`: a fully-resolved input ready for the + caller's next action. LNURL bech32 strings and Lightning Addresses + are resolved over HTTP into typed pay or withdraw request data; + LNURL-auth endpoints are classified from the URL query string + without an HTTP fetch. + """ + + def __init__(self): + raise RuntimeError("InputType cannot be instantiated directly") + + # Each enum variant is a nested class of the enum itself. + class BOLT11: + """ + A BOLT11 Lightning invoice. No HTTP was performed. + """ + + invoice: "ParsedInvoice" + + def __init__(self,invoice: "ParsedInvoice"): + self.invoice = invoice + + def __str__(self): + return "InputType.BOLT11(invoice={})".format(self.invoice) + + def __eq__(self, other): + if not other.is_BOLT11(): + return False + if self.invoice != other.invoice: + return False + return True + + class NODE_ID: + """ + A Lightning node public key. No HTTP was performed. + """ + + node_id: "str" + + def __init__(self,node_id: "str"): + self.node_id = node_id + + def __str__(self): + return "InputType.NODE_ID(node_id={})".format(self.node_id) + + def __eq__(self, other): + if not other.is_NODE_ID(): + return False + if self.node_id != other.node_id: + return False + return True + + class LN_URL_PAY: + """ + An LNURL-pay endpoint with the service's parameters fetched. + """ + + data: "LnUrlPayRequestData" + + def __init__(self,data: "LnUrlPayRequestData"): + self.data = data + + def __str__(self): + return "InputType.LN_URL_PAY(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_LN_URL_PAY(): + return False + if self.data != other.data: + return False + return True + + class LN_URL_WITHDRAW: + """ + An LNURL-withdraw endpoint with the service's parameters fetched. + """ + + data: "LnUrlWithdrawRequestData" + + def __init__(self,data: "LnUrlWithdrawRequestData"): + self.data = data + + def __str__(self): + return "InputType.LN_URL_WITHDRAW(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_LN_URL_WITHDRAW(): + return False + if self.data != other.data: + return False + return True + + class LN_URL_AUTH: + """ + An LNURL-auth (LUD-04) challenge. No HTTP was performed — + classification comes from the `tag=login` URL query parameter. + """ + + data: "LnUrlAuthRequestData" + + def __init__(self,data: "LnUrlAuthRequestData"): + self.data = data + + def __str__(self): + return "InputType.LN_URL_AUTH(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_LN_URL_AUTH(): + return False + if self.data != other.data: + return False + return True + + + + # For each variant, we have `is_NAME` and `is_name` methods for easily checking + # whether an instance is that variant. + def is_BOLT11(self) -> bool: + return isinstance(self, InputType.BOLT11) + def is_bolt11(self) -> bool: + return isinstance(self, InputType.BOLT11) + def is_NODE_ID(self) -> bool: + return isinstance(self, InputType.NODE_ID) + def is_node_id(self) -> bool: + return isinstance(self, InputType.NODE_ID) + def is_LN_URL_PAY(self) -> bool: + return isinstance(self, InputType.LN_URL_PAY) + def is_ln_url_pay(self) -> bool: + return isinstance(self, InputType.LN_URL_PAY) + def is_LN_URL_WITHDRAW(self) -> bool: + return isinstance(self, InputType.LN_URL_WITHDRAW) + def is_ln_url_withdraw(self) -> bool: + return isinstance(self, InputType.LN_URL_WITHDRAW) + def is_LN_URL_AUTH(self) -> bool: + return isinstance(self, InputType.LN_URL_AUTH) + def is_ln_url_auth(self) -> bool: + return isinstance(self, InputType.LN_URL_AUTH) + + +# Now, a little trick - we make each nested variant class be a subclass of the main +# enum class, so that method calls and instance checks etc will work intuitively. +# We might be able to do this a little more neatly with a metaclass, but this'll do. +InputType.BOLT11 = type("InputType.BOLT11", (InputType.BOLT11, InputType,), {}) # type: ignore +InputType.NODE_ID = type("InputType.NODE_ID", (InputType.NODE_ID, InputType,), {}) # type: ignore +InputType.LN_URL_PAY = type("InputType.LN_URL_PAY", (InputType.LN_URL_PAY, InputType,), {}) # type: ignore +InputType.LN_URL_WITHDRAW = type("InputType.LN_URL_WITHDRAW", (InputType.LN_URL_WITHDRAW, InputType,), {}) # type: ignore +InputType.LN_URL_AUTH = type("InputType.LN_URL_AUTH", (InputType.LN_URL_AUTH, InputType,), {}) # type: ignore + + + + +class _UniffiConverterTypeInputType(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return InputType.BOLT11( + _UniffiConverterTypeParsedInvoice.read(buf), + ) + if variant == 2: + return InputType.NODE_ID( _UniffiConverterString.read(buf), ) if variant == 3: - return Error.UnparseableCreds( + return InputType.LN_URL_PAY( + _UniffiConverterTypeLnUrlPayRequestData.read(buf), ) if variant == 4: - return Error.PhraseCorrupted( + return InputType.LN_URL_WITHDRAW( + _UniffiConverterTypeLnUrlWithdrawRequestData.read(buf), ) if variant == 5: - return Error.Rpc( - _UniffiConverterString.read(buf), - ) - if variant == 6: - return Error.Argument( - _UniffiConverterString.read(buf), - _UniffiConverterString.read(buf), - ) - if variant == 7: - return Error.Other( - _UniffiConverterString.read(buf), + return InputType.LN_URL_AUTH( + _UniffiConverterTypeLnUrlAuthRequestData.read(buf), ) raise InternalError("Raw enum value doesn't match any cases") @staticmethod def check_lower(value): - if isinstance(value, Error.DuplicateNode): - _UniffiConverterString.check_lower(value._values[0]) + if value.is_BOLT11(): + _UniffiConverterTypeParsedInvoice.check_lower(value.invoice) return - if isinstance(value, Error.NoSuchNode): - _UniffiConverterString.check_lower(value._values[0]) - return - if isinstance(value, Error.UnparseableCreds): + if value.is_NODE_ID(): + _UniffiConverterString.check_lower(value.node_id) return - if isinstance(value, Error.PhraseCorrupted): - return - if isinstance(value, Error.Rpc): - _UniffiConverterString.check_lower(value._values[0]) + if value.is_LN_URL_PAY(): + _UniffiConverterTypeLnUrlPayRequestData.check_lower(value.data) return - if isinstance(value, Error.Argument): - _UniffiConverterString.check_lower(value._values[0]) - _UniffiConverterString.check_lower(value._values[1]) + if value.is_LN_URL_WITHDRAW(): + _UniffiConverterTypeLnUrlWithdrawRequestData.check_lower(value.data) return - if isinstance(value, Error.Other): - _UniffiConverterString.check_lower(value._values[0]) + if value.is_LN_URL_AUTH(): + _UniffiConverterTypeLnUrlAuthRequestData.check_lower(value.data) return + raise ValueError(value) @staticmethod def write(value, buf): - if isinstance(value, Error.DuplicateNode): + if value.is_BOLT11(): buf.write_i32(1) - _UniffiConverterString.write(value._values[0], buf) - if isinstance(value, Error.NoSuchNode): + _UniffiConverterTypeParsedInvoice.write(value.invoice, buf) + if value.is_NODE_ID(): buf.write_i32(2) - _UniffiConverterString.write(value._values[0], buf) - if isinstance(value, Error.UnparseableCreds): + _UniffiConverterString.write(value.node_id, buf) + if value.is_LN_URL_PAY(): buf.write_i32(3) - if isinstance(value, Error.PhraseCorrupted): + _UniffiConverterTypeLnUrlPayRequestData.write(value.data, buf) + if value.is_LN_URL_WITHDRAW(): buf.write_i32(4) - if isinstance(value, Error.Rpc): + _UniffiConverterTypeLnUrlWithdrawRequestData.write(value.data, buf) + if value.is_LN_URL_AUTH(): buf.write_i32(5) - _UniffiConverterString.write(value._values[0], buf) - if isinstance(value, Error.Argument): - buf.write_i32(6) - _UniffiConverterString.write(value._values[0], buf) - _UniffiConverterString.write(value._values[1], buf) - if isinstance(value, Error.Other): - buf.write_i32(7) - _UniffiConverterString.write(value._values[0], buf) + _UniffiConverterTypeLnUrlAuthRequestData.write(value.data, buf) + + @@ -3049,41 +4021,403 @@ def write(value, buf): -class ListIndex(enum.Enum): - """ - Index field used by CLN's paginated list RPCs. - """ +class ListIndex(enum.Enum): + """ + Index field used by CLN's paginated list RPCs. + """ + + CREATED = 0 + + UPDATED = 1 + + + +class _UniffiConverterTypeListIndex(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return ListIndex.CREATED + if variant == 2: + return ListIndex.UPDATED + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value == ListIndex.CREATED: + return + if value == ListIndex.UPDATED: + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value == ListIndex.CREATED: + buf.write_i32(1) + if value == ListIndex.UPDATED: + buf.write_i32(2) + + + + + + + +class LnUrlCallbackStatus: + """ + Result of an LNURL-auth callback (LUD-04). + """ + + def __init__(self): + raise RuntimeError("LnUrlCallbackStatus cannot be instantiated directly") + + # Each enum variant is a nested class of the enum itself. + class OK: + """ + The service accepted the signed challenge. + """ + + + def __init__(self,): + pass + + def __str__(self): + return "LnUrlCallbackStatus.OK()".format() + + def __eq__(self, other): + if not other.is_OK(): + return False + return True + + class ERROR_STATUS: + """ + The service rejected the signed challenge. + """ + + data: "LnUrlErrorData" + + def __init__(self,data: "LnUrlErrorData"): + self.data = data + + def __str__(self): + return "LnUrlCallbackStatus.ERROR_STATUS(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_ERROR_STATUS(): + return False + if self.data != other.data: + return False + return True + + + + # For each variant, we have `is_NAME` and `is_name` methods for easily checking + # whether an instance is that variant. + def is_OK(self) -> bool: + return isinstance(self, LnUrlCallbackStatus.OK) + def is_ok(self) -> bool: + return isinstance(self, LnUrlCallbackStatus.OK) + def is_ERROR_STATUS(self) -> bool: + return isinstance(self, LnUrlCallbackStatus.ERROR_STATUS) + def is_error_status(self) -> bool: + return isinstance(self, LnUrlCallbackStatus.ERROR_STATUS) + + +# Now, a little trick - we make each nested variant class be a subclass of the main +# enum class, so that method calls and instance checks etc will work intuitively. +# We might be able to do this a little more neatly with a metaclass, but this'll do. +LnUrlCallbackStatus.OK = type("LnUrlCallbackStatus.OK", (LnUrlCallbackStatus.OK, LnUrlCallbackStatus,), {}) # type: ignore +LnUrlCallbackStatus.ERROR_STATUS = type("LnUrlCallbackStatus.ERROR_STATUS", (LnUrlCallbackStatus.ERROR_STATUS, LnUrlCallbackStatus,), {}) # type: ignore + + + + +class _UniffiConverterTypeLnUrlCallbackStatus(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return LnUrlCallbackStatus.OK( + ) + if variant == 2: + return LnUrlCallbackStatus.ERROR_STATUS( + _UniffiConverterTypeLnUrlErrorData.read(buf), + ) + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value.is_OK(): + return + if value.is_ERROR_STATUS(): + _UniffiConverterTypeLnUrlErrorData.check_lower(value.data) + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value.is_OK(): + buf.write_i32(1) + if value.is_ERROR_STATUS(): + buf.write_i32(2) + _UniffiConverterTypeLnUrlErrorData.write(value.data, buf) + + + + + + + +class LnUrlPayResult: + """ + Result of an LNURL-pay operation. + """ + + def __init__(self): + raise RuntimeError("LnUrlPayResult cannot be instantiated directly") + + # Each enum variant is a nested class of the enum itself. + class ENDPOINT_SUCCESS: + """ + Payment succeeded. + """ + + data: "LnUrlPaySuccessData" + + def __init__(self,data: "LnUrlPaySuccessData"): + self.data = data + + def __str__(self): + return "LnUrlPayResult.ENDPOINT_SUCCESS(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_ENDPOINT_SUCCESS(): + return False + if self.data != other.data: + return False + return True + + class ENDPOINT_ERROR: + """ + The LNURL service returned an error before the invoice was paid. + """ + + data: "LnUrlErrorData" + + def __init__(self,data: "LnUrlErrorData"): + self.data = data + + def __str__(self): + return "LnUrlPayResult.ENDPOINT_ERROR(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_ENDPOINT_ERROR(): + return False + if self.data != other.data: + return False + return True + + class PAY_ERROR: + """ + The invoice was fetched successfully but paying it failed. + """ + + data: "LnUrlPayErrorData" + + def __init__(self,data: "LnUrlPayErrorData"): + self.data = data + + def __str__(self): + return "LnUrlPayResult.PAY_ERROR(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_PAY_ERROR(): + return False + if self.data != other.data: + return False + return True + + + + # For each variant, we have `is_NAME` and `is_name` methods for easily checking + # whether an instance is that variant. + def is_ENDPOINT_SUCCESS(self) -> bool: + return isinstance(self, LnUrlPayResult.ENDPOINT_SUCCESS) + def is_endpoint_success(self) -> bool: + return isinstance(self, LnUrlPayResult.ENDPOINT_SUCCESS) + def is_ENDPOINT_ERROR(self) -> bool: + return isinstance(self, LnUrlPayResult.ENDPOINT_ERROR) + def is_endpoint_error(self) -> bool: + return isinstance(self, LnUrlPayResult.ENDPOINT_ERROR) + def is_PAY_ERROR(self) -> bool: + return isinstance(self, LnUrlPayResult.PAY_ERROR) + def is_pay_error(self) -> bool: + return isinstance(self, LnUrlPayResult.PAY_ERROR) + + +# Now, a little trick - we make each nested variant class be a subclass of the main +# enum class, so that method calls and instance checks etc will work intuitively. +# We might be able to do this a little more neatly with a metaclass, but this'll do. +LnUrlPayResult.ENDPOINT_SUCCESS = type("LnUrlPayResult.ENDPOINT_SUCCESS", (LnUrlPayResult.ENDPOINT_SUCCESS, LnUrlPayResult,), {}) # type: ignore +LnUrlPayResult.ENDPOINT_ERROR = type("LnUrlPayResult.ENDPOINT_ERROR", (LnUrlPayResult.ENDPOINT_ERROR, LnUrlPayResult,), {}) # type: ignore +LnUrlPayResult.PAY_ERROR = type("LnUrlPayResult.PAY_ERROR", (LnUrlPayResult.PAY_ERROR, LnUrlPayResult,), {}) # type: ignore + + + + +class _UniffiConverterTypeLnUrlPayResult(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return LnUrlPayResult.ENDPOINT_SUCCESS( + _UniffiConverterTypeLnUrlPaySuccessData.read(buf), + ) + if variant == 2: + return LnUrlPayResult.ENDPOINT_ERROR( + _UniffiConverterTypeLnUrlErrorData.read(buf), + ) + if variant == 3: + return LnUrlPayResult.PAY_ERROR( + _UniffiConverterTypeLnUrlPayErrorData.read(buf), + ) + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value.is_ENDPOINT_SUCCESS(): + _UniffiConverterTypeLnUrlPaySuccessData.check_lower(value.data) + return + if value.is_ENDPOINT_ERROR(): + _UniffiConverterTypeLnUrlErrorData.check_lower(value.data) + return + if value.is_PAY_ERROR(): + _UniffiConverterTypeLnUrlPayErrorData.check_lower(value.data) + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value.is_ENDPOINT_SUCCESS(): + buf.write_i32(1) + _UniffiConverterTypeLnUrlPaySuccessData.write(value.data, buf) + if value.is_ENDPOINT_ERROR(): + buf.write_i32(2) + _UniffiConverterTypeLnUrlErrorData.write(value.data, buf) + if value.is_PAY_ERROR(): + buf.write_i32(3) + _UniffiConverterTypeLnUrlPayErrorData.write(value.data, buf) + + + + + + + +class LnUrlWithdrawResult: + """ + Result of an LNURL-withdraw operation. + """ + + def __init__(self): + raise RuntimeError("LnUrlWithdrawResult cannot be instantiated directly") + + # Each enum variant is a nested class of the enum itself. + class OK: + """ + The service accepted our invoice and will pay it. + """ + + data: "LnUrlWithdrawSuccessData" + + def __init__(self,data: "LnUrlWithdrawSuccessData"): + self.data = data + + def __str__(self): + return "LnUrlWithdrawResult.OK(data={})".format(self.data) + + def __eq__(self, other): + if not other.is_OK(): + return False + if self.data != other.data: + return False + return True + + class ERROR_STATUS: + """ + The LNURL service returned an error. + """ + + data: "LnUrlErrorData" + + def __init__(self,data: "LnUrlErrorData"): + self.data = data + + def __str__(self): + return "LnUrlWithdrawResult.ERROR_STATUS(data={})".format(self.data) - CREATED = 0 + def __eq__(self, other): + if not other.is_ERROR_STATUS(): + return False + if self.data != other.data: + return False + return True - UPDATED = 1 + # For each variant, we have `is_NAME` and `is_name` methods for easily checking + # whether an instance is that variant. + def is_OK(self) -> bool: + return isinstance(self, LnUrlWithdrawResult.OK) + def is_ok(self) -> bool: + return isinstance(self, LnUrlWithdrawResult.OK) + def is_ERROR_STATUS(self) -> bool: + return isinstance(self, LnUrlWithdrawResult.ERROR_STATUS) + def is_error_status(self) -> bool: + return isinstance(self, LnUrlWithdrawResult.ERROR_STATUS) + + +# Now, a little trick - we make each nested variant class be a subclass of the main +# enum class, so that method calls and instance checks etc will work intuitively. +# We might be able to do this a little more neatly with a metaclass, but this'll do. +LnUrlWithdrawResult.OK = type("LnUrlWithdrawResult.OK", (LnUrlWithdrawResult.OK, LnUrlWithdrawResult,), {}) # type: ignore +LnUrlWithdrawResult.ERROR_STATUS = type("LnUrlWithdrawResult.ERROR_STATUS", (LnUrlWithdrawResult.ERROR_STATUS, LnUrlWithdrawResult,), {}) # type: ignore + -class _UniffiConverterTypeListIndex(_UniffiConverterRustBuffer): + + +class _UniffiConverterTypeLnUrlWithdrawResult(_UniffiConverterRustBuffer): @staticmethod def read(buf): variant = buf.read_i32() if variant == 1: - return ListIndex.CREATED + return LnUrlWithdrawResult.OK( + _UniffiConverterTypeLnUrlWithdrawSuccessData.read(buf), + ) if variant == 2: - return ListIndex.UPDATED + return LnUrlWithdrawResult.ERROR_STATUS( + _UniffiConverterTypeLnUrlErrorData.read(buf), + ) raise InternalError("Raw enum value doesn't match any cases") @staticmethod def check_lower(value): - if value == ListIndex.CREATED: + if value.is_OK(): + _UniffiConverterTypeLnUrlWithdrawSuccessData.check_lower(value.data) return - if value == ListIndex.UPDATED: + if value.is_ERROR_STATUS(): + _UniffiConverterTypeLnUrlErrorData.check_lower(value.data) return raise ValueError(value) @staticmethod def write(value, buf): - if value == ListIndex.CREATED: + if value.is_OK(): buf.write_i32(1) - if value == ListIndex.UPDATED: + _UniffiConverterTypeLnUrlWithdrawSuccessData.write(value.data, buf) + if value.is_ERROR_STATUS(): buf.write_i32(2) + _UniffiConverterTypeLnUrlErrorData.write(value.data, buf) @@ -3455,6 +4789,169 @@ def write(value, buf): + + +class SuccessActionProcessed: + """ + A processed success action from an LNURL-pay callback. + + For Message and Url this is passed through as-is. For Aes the + ciphertext has been decrypted using the payment preimage. + """ + + def __init__(self): + raise RuntimeError("SuccessActionProcessed cannot be instantiated directly") + + # Each enum variant is a nested class of the enum itself. + class MESSAGE: + """ + Display a message to the user. + """ + + message: "str" + + def __init__(self,message: "str"): + self.message = message + + def __str__(self): + return "SuccessActionProcessed.MESSAGE(message={})".format(self.message) + + def __eq__(self, other): + if not other.is_MESSAGE(): + return False + if self.message != other.message: + return False + return True + + class URL: + """ + Display a URL to the user. + """ + + description: "str" + url: "str" + + def __init__(self,description: "str", url: "str"): + self.description = description + self.url = url + + def __str__(self): + return "SuccessActionProcessed.URL(description={}, url={})".format(self.description, self.url) + + def __eq__(self, other): + if not other.is_URL(): + return False + if self.description != other.description: + return False + if self.url != other.url: + return False + return True + + class AES: + """ + Decrypted AES payload (LUD-10). + """ + + description: "str" + plaintext: "str" + + def __init__(self,description: "str", plaintext: "str"): + self.description = description + self.plaintext = plaintext + + def __str__(self): + return "SuccessActionProcessed.AES(description={}, plaintext={})".format(self.description, self.plaintext) + + def __eq__(self, other): + if not other.is_AES(): + return False + if self.description != other.description: + return False + if self.plaintext != other.plaintext: + return False + return True + + + + # For each variant, we have `is_NAME` and `is_name` methods for easily checking + # whether an instance is that variant. + def is_MESSAGE(self) -> bool: + return isinstance(self, SuccessActionProcessed.MESSAGE) + def is_message(self) -> bool: + return isinstance(self, SuccessActionProcessed.MESSAGE) + def is_URL(self) -> bool: + return isinstance(self, SuccessActionProcessed.URL) + def is_url(self) -> bool: + return isinstance(self, SuccessActionProcessed.URL) + def is_AES(self) -> bool: + return isinstance(self, SuccessActionProcessed.AES) + def is_aes(self) -> bool: + return isinstance(self, SuccessActionProcessed.AES) + + +# Now, a little trick - we make each nested variant class be a subclass of the main +# enum class, so that method calls and instance checks etc will work intuitively. +# We might be able to do this a little more neatly with a metaclass, but this'll do. +SuccessActionProcessed.MESSAGE = type("SuccessActionProcessed.MESSAGE", (SuccessActionProcessed.MESSAGE, SuccessActionProcessed,), {}) # type: ignore +SuccessActionProcessed.URL = type("SuccessActionProcessed.URL", (SuccessActionProcessed.URL, SuccessActionProcessed,), {}) # type: ignore +SuccessActionProcessed.AES = type("SuccessActionProcessed.AES", (SuccessActionProcessed.AES, SuccessActionProcessed,), {}) # type: ignore + + + + +class _UniffiConverterTypeSuccessActionProcessed(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return SuccessActionProcessed.MESSAGE( + _UniffiConverterString.read(buf), + ) + if variant == 2: + return SuccessActionProcessed.URL( + _UniffiConverterString.read(buf), + _UniffiConverterString.read(buf), + ) + if variant == 3: + return SuccessActionProcessed.AES( + _UniffiConverterString.read(buf), + _UniffiConverterString.read(buf), + ) + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value.is_MESSAGE(): + _UniffiConverterString.check_lower(value.message) + return + if value.is_URL(): + _UniffiConverterString.check_lower(value.description) + _UniffiConverterString.check_lower(value.url) + return + if value.is_AES(): + _UniffiConverterString.check_lower(value.description) + _UniffiConverterString.check_lower(value.plaintext) + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value.is_MESSAGE(): + buf.write_i32(1) + _UniffiConverterString.write(value.message, buf) + if value.is_URL(): + buf.write_i32(2) + _UniffiConverterString.write(value.description, buf) + _UniffiConverterString.write(value.url, buf) + if value.is_AES(): + buf.write_i32(3) + _UniffiConverterString.write(value.description, buf) + _UniffiConverterString.write(value.plaintext, buf) + + + + + class _UniffiConverterOptionalUInt32(_UniffiConverterRustBuffer): @classmethod def check_lower(cls, value): @@ -3671,6 +5168,33 @@ def read(cls, buf): +class _UniffiConverterOptionalTypeSuccessActionProcessed(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiConverterTypeSuccessActionProcessed.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiConverterTypeSuccessActionProcessed.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiConverterTypeSuccessActionProcessed.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + + + class _UniffiConverterOptionalSequenceTypePaymentTypeFilter(_UniffiConverterRustBuffer): @classmethod def check_lower(cls, value): @@ -4300,6 +5824,10 @@ def disconnect(self, ): Disconnects from the node and stops the signer if running. After disconnect, all RPC methods will return an error. Safe to call multiple times. + + Also scrubs the LNURL-auth namespace xpriv from memory; a + subsequent `lnurl_auth` call on a disconnected Node will + error rather than silently using stale key material. """ raise NotImplementedError @@ -4364,10 +5892,83 @@ def list_peers(self, ): status. """ + raise NotImplementedError + def lnurl_auth(self, request: "LnUrlAuthRequestData"): + """ + Execute an LNURL-auth callback (LUD-04). + + Derives the LUD-05 linking key for `request.domain` from the + node's LNURL-auth namespace xpriv (`m/138'`), signs the + service's `k1` challenge, and posts the signed callback. + + The namespace xpriv is derived once at register/recover/connect + time from the BIP39 seed and stored in `Zeroizing` on the + Node. Because `m/138'` is a hardened path, this stored key + material cannot be used to derive any other wallet key + (lightning channels, on-chain funds) — it is restricted to + LNURL-auth identities. It is scrubbed when the Node is + disconnected or dropped. + + Returns an error when the Node was constructed directly from + credentials without a mnemonic (`Node::new(credentials)`) and + thus has no LNURL-auth namespace key, or when `disconnect()` + has already scrubbed the key. + """ + + raise NotImplementedError + def lnurl_pay(self, request: "LnUrlPayRequest"): + """ + Execute an LNURL-pay flow (LUD-06). + + Sends the chosen amount (and optional comment) to the service's + callback, receives and validates a BOLT11 invoice, pays it, and + processes any success action (LUD-09/10). + + Call the top-level `parse_input` first to obtain the + `LnUrlPayRequestData`, then build an `LnUrlPayRequest` with the + user's chosen amount. + """ + + raise NotImplementedError + def lnurl_withdraw(self, request: "LnUrlWithdrawRequest"): + """ + Execute an LNURL-withdraw flow (LUD-03). + + Creates an invoice on this node for the requested amount, sends + it to the service's callback URL, and the service pays it + asynchronously. + + Call the top-level `parse_input` first to obtain the + `LnUrlWithdrawRequestData`, then build an `LnUrlWithdrawRequest` + with the user's chosen amount. + """ + raise NotImplementedError def onchain_receive(self, ): + """ + Generate a fresh on-chain Bitcoin address for receiving funds. + + Returns both a bech32 (SegWit v0) and a p2tr (Taproot) address. + Either can be shared with a sender. Deposited funds will appear + in `node_state().onchain_balance_msat` once confirmed. + """ + raise NotImplementedError def onchain_send(self, destination: "str",amount_or_all: "str"): + """ + Send bitcoin on-chain to a destination address. + + # Arguments + * `destination` — A Bitcoin address (bech32, p2sh, or p2tr). + * `amount_or_all` — Amount to send. Accepts: + - `"50000"` or `"50000sat"` — 50,000 satoshis + - `"50000msat"` — 50,000 millisatoshis + - `"all"` — sweep the entire on-chain balance + + Returns the raw transaction, txid, and PSBT once broadcast. + The transaction is broadcast immediately — this is not a dry run. + """ + raise NotImplementedError def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]"): """ @@ -4414,11 +6015,9 @@ class Node(): """ _pointer: ctypes.c_void_p - def __init__(self, credentials: "Credentials"): - _UniffiConverterTypeCredentials.check_lower(credentials) - - self._pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_node_new, - _UniffiConverterTypeCredentials.lower(credentials)) + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") def __del__(self): # In case of partial initialization of instances. @@ -4458,6 +6057,10 @@ def disconnect(self, ) -> None: Disconnects from the node and stops the signer if running. After disconnect, all RPC methods will return an error. Safe to call multiple times. + + Also scrubs the LNURL-auth namespace xpriv from memory; a + subsequent `lnurl_auth` call on a disconnected Node will + error rather than silently using stale key material. """ _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_disconnect,self._uniffi_clone_pointer(),) @@ -4620,7 +6223,96 @@ def list_peers(self, ) -> "ListPeersResponse": + def lnurl_auth(self, request: "LnUrlAuthRequestData") -> "LnUrlCallbackStatus": + """ + Execute an LNURL-auth callback (LUD-04). + + Derives the LUD-05 linking key for `request.domain` from the + node's LNURL-auth namespace xpriv (`m/138'`), signs the + service's `k1` challenge, and posts the signed callback. + + The namespace xpriv is derived once at register/recover/connect + time from the BIP39 seed and stored in `Zeroizing` on the + Node. Because `m/138'` is a hardened path, this stored key + material cannot be used to derive any other wallet key + (lightning channels, on-chain funds) — it is restricted to + LNURL-auth identities. It is scrubbed when the Node is + disconnected or dropped. + + Returns an error when the Node was constructed directly from + credentials without a mnemonic (`Node::new(credentials)`) and + thus has no LNURL-auth namespace key, or when `disconnect()` + has already scrubbed the key. + """ + + _UniffiConverterTypeLnUrlAuthRequestData.check_lower(request) + + return _UniffiConverterTypeLnUrlCallbackStatus.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_auth,self._uniffi_clone_pointer(), + _UniffiConverterTypeLnUrlAuthRequestData.lower(request)) + ) + + + + + + def lnurl_pay(self, request: "LnUrlPayRequest") -> "LnUrlPayResult": + """ + Execute an LNURL-pay flow (LUD-06). + + Sends the chosen amount (and optional comment) to the service's + callback, receives and validates a BOLT11 invoice, pays it, and + processes any success action (LUD-09/10). + + Call the top-level `parse_input` first to obtain the + `LnUrlPayRequestData`, then build an `LnUrlPayRequest` with the + user's chosen amount. + """ + + _UniffiConverterTypeLnUrlPayRequest.check_lower(request) + + return _UniffiConverterTypeLnUrlPayResult.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_pay,self._uniffi_clone_pointer(), + _UniffiConverterTypeLnUrlPayRequest.lower(request)) + ) + + + + + + def lnurl_withdraw(self, request: "LnUrlWithdrawRequest") -> "LnUrlWithdrawResult": + """ + Execute an LNURL-withdraw flow (LUD-03). + + Creates an invoice on this node for the requested amount, sends + it to the service's callback URL, and the service pays it + asynchronously. + + Call the top-level `parse_input` first to obtain the + `LnUrlWithdrawRequestData`, then build an `LnUrlWithdrawRequest` + with the user's chosen amount. + """ + + _UniffiConverterTypeLnUrlWithdrawRequest.check_lower(request) + + return _UniffiConverterTypeLnUrlWithdrawResult.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_lnurl_withdraw,self._uniffi_clone_pointer(), + _UniffiConverterTypeLnUrlWithdrawRequest.lower(request)) + ) + + + + + def onchain_receive(self, ) -> "OnchainReceiveResponse": + """ + Generate a fresh on-chain Bitcoin address for receiving funds. + + Returns both a bech32 (SegWit v0) and a p2tr (Taproot) address. + Either can be shared with a sender. Deposited funds will appear + in `node_state().onchain_balance_msat` once confirmed. + """ + return _UniffiConverterTypeOnchainReceiveResponse.lift( _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive,self._uniffi_clone_pointer(),) ) @@ -4630,6 +6322,20 @@ def onchain_receive(self, ) -> "OnchainReceiveResponse": def onchain_send(self, destination: "str",amount_or_all: "str") -> "OnchainSendResponse": + """ + Send bitcoin on-chain to a destination address. + + # Arguments + * `destination` — A Bitcoin address (bech32, p2sh, or p2tr). + * `amount_or_all` — Amount to send. Accepts: + - `"50000"` or `"50000sat"` — 50,000 satoshis + - `"50000msat"` — 50,000 millisatoshis + - `"all"` — sweep the entire on-chain balance + + Returns the raw transaction, txid, and PSBT once broadcast. + The transaction is broadcast immediately — this is not a dry run. + """ + _UniffiConverterString.check_lower(destination) _UniffiConverterString.check_lower(amount_or_all) @@ -5079,7 +6785,69 @@ def read(cls, buf: _UniffiRustBuffer): def write(cls, value: SignerProtocol, buf: _UniffiRustBuffer): buf.write_u64(cls.lower(value)) -# Async support +# Async support# RustFuturePoll values +_UNIFFI_RUST_FUTURE_POLL_READY = 0 +_UNIFFI_RUST_FUTURE_POLL_MAYBE_READY = 1 + +# Stores futures for _uniffi_continuation_callback +_UniffiContinuationHandleMap = _UniffiHandleMap() + +_UNIFFI_GLOBAL_EVENT_LOOP = None + +""" +Set the event loop to use for async functions + +This is needed if some async functions run outside of the eventloop, for example: + - A non-eventloop thread is spawned, maybe from `EventLoop.run_in_executor` or maybe from the + Rust code spawning its own thread. + - The Rust code calls an async callback method from a sync callback function, using something + like `pollster` to block on the async call. + +In this case, we need an event loop to run the Python async function, but there's no eventloop set +for the thread. Use `uniffi_set_event_loop` to force an eventloop to be used in this case. +""" +def uniffi_set_event_loop(eventloop: asyncio.BaseEventLoop): + global _UNIFFI_GLOBAL_EVENT_LOOP + _UNIFFI_GLOBAL_EVENT_LOOP = eventloop + +def _uniffi_get_event_loop(): + if _UNIFFI_GLOBAL_EVENT_LOOP is not None: + return _UNIFFI_GLOBAL_EVENT_LOOP + else: + return asyncio.get_running_loop() + +# Continuation callback for async functions +# lift the return value or error and resolve the future, causing the async function to resume. +@_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK +def _uniffi_continuation_callback(future_ptr, poll_code): + (eventloop, future) = _UniffiContinuationHandleMap.remove(future_ptr) + eventloop.call_soon_threadsafe(_uniffi_set_future_result, future, poll_code) + +def _uniffi_set_future_result(future, poll_code): + if not future.cancelled(): + future.set_result(poll_code) + +async def _uniffi_rust_call_async(rust_future, ffi_poll, ffi_complete, ffi_free, lift_func, error_ffi_converter): + try: + eventloop = _uniffi_get_event_loop() + + # Loop and poll until we see a _UNIFFI_RUST_FUTURE_POLL_READY value + while True: + future = eventloop.create_future() + ffi_poll( + rust_future, + _uniffi_continuation_callback, + _UniffiContinuationHandleMap.insert((eventloop, future)), + ) + poll_code = await future + if poll_code == _UNIFFI_RUST_FUTURE_POLL_READY: + break + + return lift_func( + _uniffi_rust_call_with_error(error_ffi_converter, ffi_complete, rust_future) + ) + finally: + ffi_free(rust_future) def connect(mnemonic: "str",credentials: "bytes",config: "Config") -> "Node": """ @@ -5097,6 +6865,34 @@ def connect(mnemonic: "str",credentials: "bytes",config: "Config") -> "Node": _UniffiConverterBytes.lower(credentials), _UniffiConverterTypeConfig.lower(config))) +async def parse_input(input: "str") -> "InputType": + + """ + Parse and resolve any supported input in one async call. + + For LNURL bech32 strings and Lightning Addresses this performs the + HTTP GET to the LNURL endpoint and returns typed pay or withdraw + request data. For BOLT11 invoices and node IDs it returns + immediately without I/O. + + Strips `lightning:` / `LIGHTNING:` prefixes automatically. + """ + + _UniffiConverterString.check_lower(input) + + return await _uniffi_rust_call_async( + _UniffiLib.uniffi_glsdk_fn_func_parse_input( + _UniffiConverterString.lower(input)), + _UniffiLib.ffi_glsdk_rust_future_poll_rust_buffer, + _UniffiLib.ffi_glsdk_rust_future_complete_rust_buffer, + _UniffiLib.ffi_glsdk_rust_future_free_rust_buffer, + # lift function + _UniffiConverterTypeInputType.lift, + + # Error FFI converter +_UniffiConverterTypeError, + + ) def recover(mnemonic: "str",config: "Config") -> "Node": """ @@ -5156,8 +6952,12 @@ def register_or_recover(mnemonic: "str",invite_code: "typing.Optional[str]",conf "InternalError", "ChannelState", "Error", + "InputType", "InvoiceStatus", "ListIndex", + "LnUrlCallbackStatus", + "LnUrlPayResult", + "LnUrlWithdrawResult", "Network", "NodeEvent", "OutputStatus", @@ -5165,6 +6965,7 @@ def register_or_recover(mnemonic: "str",invite_code: "typing.Optional[str]",conf "PaymentStatus", "PaymentType", "PaymentTypeFilter", + "SuccessActionProcessed", "FundChannel", "FundOutput", "GetInfoResponse", @@ -5176,8 +6977,18 @@ def register_or_recover(mnemonic: "str",invite_code: "typing.Optional[str]",conf "ListPaysResponse", "ListPeerChannelsResponse", "ListPeersResponse", + "LnUrlAuthRequestData", + "LnUrlErrorData", + "LnUrlPayErrorData", + "LnUrlPayRequest", + "LnUrlPayRequestData", + "LnUrlPaySuccessData", + "LnUrlWithdrawRequest", + "LnUrlWithdrawRequestData", + "LnUrlWithdrawSuccessData", "OnchainReceiveResponse", "OnchainSendResponse", + "ParsedInvoice", "Pay", "Payment", "Peer", @@ -5185,6 +6996,7 @@ def register_or_recover(mnemonic: "str",invite_code: "typing.Optional[str]",conf "ReceiveResponse", "SendResponse", "connect", + "parse_input", "recover", "register", "register_or_recover", diff --git a/libs/gl-sdk/src/auth.rs b/libs/gl-sdk/src/auth.rs new file mode 100644 index 000000000..9444f71c6 --- /dev/null +++ b/libs/gl-sdk/src/auth.rs @@ -0,0 +1,256 @@ +// LNURL-auth (LUD-04 / LUD-05) implementation. +// +// `Node` stores the encoded `m/138'` extended private key — derived +// once from the BIP39 seed at register/recover/connect time. The seed +// itself is never retained. From that namespace xpriv, both the +// hashing key (`m/138'/0`) and the per-domain linking key +// (`m/138'/`) are derived inside `lnurl_auth`. +// +// `m/138'` is a hardened path, so its xpriv cannot be used to derive +// any other wallet keys (lightning channels, on-chain). Compromise of +// the stored material affects only LNURL-auth identities. + +use gl_client::bitcoin::bip32::{ChildNumber, Xpriv}; +use gl_client::bitcoin::hashes::hmac::{Hmac, HmacEngine}; +use gl_client::bitcoin::hashes::{sha256, Hash, HashEngine}; +use gl_client::bitcoin::secp256k1::{Message, PublicKey, Secp256k1}; +use gl_client::bitcoin::Network; +use zeroize::Zeroizing; + +use crate::lnurl::{LnUrlAuthRequestData, LnUrlCallbackStatus, LnUrlErrorData}; +use crate::Error; + +/// Derive the encoded `m/138'` extended private key from a BIP39 +/// mnemonic. The mnemonic is consumed only for the duration of this +/// call — the seed is wrapped in `Zeroizing` and scrubbed on return. +/// +/// The returned bytes are the standard 78-byte BIP32 serialization of +/// the xpriv at `m/138'`. Callers wrap them in `Zeroizing>` +/// when persisting on a `Node` so they are scrubbed on disconnect or +/// drop. +pub(crate) fn derive_lnurl_auth_namespace_xpriv(seed: &[u8]) -> Result, Error> { + // Network choice does not affect derived secret bytes — only the + // version prefix when the xpriv is serialised. We pick Bitcoin + // canonically; downstream `decode` accepts the same prefix. + let master = Xpriv::new_master(Network::Bitcoin, seed) + .map_err(|e| Error::Other(format!("BIP32 master derivation failed: {e}")))?; + let secp = Secp256k1::new(); + let path: [ChildNumber; 1] = [ChildNumber::from_hardened_idx(138) + .map_err(|e| Error::Other(format!("BIP32 child index error: {e}")))?]; + let namespace = master + .derive_priv(&secp, &path) + .map_err(|e| Error::Other(format!("BIP32 m/138' derivation failed: {e}")))?; + Ok(namespace.encode().to_vec()) +} + +/// Same as [`derive_lnurl_auth_namespace_xpriv`] but takes the +/// mnemonic directly and scrubs the intermediate seed on return. +pub(crate) fn derive_lnurl_auth_namespace_xpriv_from_mnemonic( + mnemonic: &str, +) -> Result, Error> { + use bip39::Mnemonic; + use std::str::FromStr; + let phrase = Mnemonic::from_str(mnemonic).map_err(|_| Error::PhraseCorrupted())?; + let seed = Zeroizing::new(phrase.to_seed_normalized("").to_vec()); + derive_lnurl_auth_namespace_xpriv(&seed) +} + +/// Sign the service's `k1` challenge using the LUD-05 linking key +/// derived from the supplied `m/138'` xpriv, and POST the callback. +pub(crate) async fn perform_lnurl_auth( + namespace_xpriv: &[u8], + request: &LnUrlAuthRequestData, +) -> Result { + let namespace = Xpriv::decode(namespace_xpriv) + .map_err(|e| Error::Other(format!("LNURL-auth namespace xpriv invalid: {e}")))?; + let secp = Secp256k1::new(); + + // Step 1: derive the LUD-05 hashing key at m/138'/0 (relative to + // the namespace, that's just /0). HMAC the domain with its + // 32-byte secret to produce 16 bytes of derivation tail. + let hashing_path: [ChildNumber; 1] = [ChildNumber::from(0)]; + let hashing_xpriv = namespace + .derive_priv(&secp, &hashing_path) + .map_err(|e| Error::Other(format!("BIP32 hashing-key derivation failed: {e}")))?; + let hashing_key = hashing_xpriv.private_key.secret_bytes(); + + let mut engine = HmacEngine::::new(&hashing_key); + engine.input(request.domain.as_bytes()); + let hmac = Hmac::::from_engine(engine); + let bytes = hmac.as_byte_array(); + + // Step 2: derive the linking key at m/138'//// + // (relative to the namespace, that's //.../). + let linking_path: Vec = vec![ + ChildNumber::from(u32::from_be_bytes(bytes[0..4].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[4..8].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[8..12].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[12..16].try_into().unwrap())), + ]; + let linking_xpriv = namespace + .derive_priv(&secp, &linking_path) + .map_err(|e| Error::Other(format!("BIP32 linking-key derivation failed: {e}")))?; + let linking_secret = linking_xpriv.private_key; + let linking_pubkey = PublicKey::from_secret_key(&secp, &linking_secret); + + // Step 3: sign k1 with the linking key. + let challenge = hex::decode(&request.k1) + .map_err(|e| Error::Other(format!("LNURL-auth k1 not hex: {e}")))?; + let message = Message::from_digest_slice(&challenge) + .map_err(|e| Error::Other(format!("LNURL-auth k1 not a 32-byte message: {e}")))?; + let sig = secp.sign_ecdsa(&message, &linking_secret); + + // Step 4: POST the signed callback per LUD-04. + let mut callback = url::Url::parse(&request.url) + .map_err(|e| Error::Other(format!("Invalid LNURL-auth URL: {e}")))?; + callback + .query_pairs_mut() + .append_pair("sig", &hex::encode(sig.serialize_der())) + .append_pair("key", &linking_pubkey.to_string()); + + let response = reqwest::get(callback) + .await + .map_err(|e| Error::Other(format!("LNURL-auth callback failed: {e}")))?; + let body = response + .text() + .await + .map_err(|e| Error::Other(format!("LNURL-auth response read failed: {e}")))?; + parse_callback_status(&body) +} + +fn parse_callback_status(body: &str) -> Result { + // LUD-04 success body is {"status":"OK"}; failure is + // {"status":"ERROR","reason":"..."}. + let value: serde_json::Value = serde_json::from_str(body) + .map_err(|e| Error::Other(format!("LNURL-auth response not JSON: {e}")))?; + let status = value + .get("status") + .and_then(|s| s.as_str()) + .ok_or_else(|| Error::Other(format!("LNURL-auth response missing status: {body}")))?; + match status { + "OK" => Ok(LnUrlCallbackStatus::Ok), + "ERROR" => { + let reason = value + .get("reason") + .and_then(|s| s.as_str()) + .unwrap_or("(no reason given)") + .to_string(); + Ok(LnUrlCallbackStatus::ErrorStatus { + data: LnUrlErrorData { reason }, + }) + } + other => Err(Error::Other(format!( + "LNURL-auth response unknown status '{other}'" + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // BIP39 test vector (all "abandon" + "about"). + const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon abandon about"; + + #[test] + fn namespace_xpriv_is_deterministic_for_same_mnemonic() { + let a = derive_lnurl_auth_namespace_xpriv_from_mnemonic(MNEMONIC).unwrap(); + let b = derive_lnurl_auth_namespace_xpriv_from_mnemonic(MNEMONIC).unwrap(); + assert_eq!(a, b); + assert_eq!(a.len(), 78); + } + + /// Fixed test vector: locks in the LUD-05 derivation convention + /// (32-byte private key as HMAC key, m/138' namespace) for the + /// "abandon ... about" BIP39 vector at domain "example.com". Any + /// change to the path computation or the HMAC-key choice breaks + /// this assertion — that is intentional, since either is a + /// one-way protocol break for any user already authenticated to a + /// service. + #[test] + fn linking_pubkey_matches_known_vector() { + let namespace = derive_lnurl_auth_namespace_xpriv_from_mnemonic(MNEMONIC).unwrap(); + let pubkey = compute_linking_pubkey_for_test(&namespace, "example.com").unwrap(); + assert_eq!( + pubkey.to_string(), + "039ae11fab821ec79815b327ba882e4dac5a046fe36bf6f5eed8b79c57f0b5d4fe", + ); + } + + #[test] + fn rejects_invalid_mnemonic() { + let err = derive_lnurl_auth_namespace_xpriv_from_mnemonic("not a real mnemonic") + .err() + .expect("expected error"); + matches!(err, Error::PhraseCorrupted()) + .then_some(()) + .expect("expected PhraseCorrupted"); + } + + #[test] + fn perform_rejects_invalid_namespace_xpriv() { + let req = LnUrlAuthRequestData { + k1: "00".repeat(32), + action: None, + domain: "x.com".to_string(), + url: "https://x.com/a?tag=login&k1=00".to_string(), + }; + let err = crate::util::exec(perform_lnurl_auth(&[0u8; 16], &req)) + .err() + .expect("expected error"); + match err { + Error::Other(msg) => assert!(msg.contains("namespace xpriv invalid")), + other => panic!("expected Other error, got {other:?}"), + } + } + + #[test] + fn parse_callback_status_ok() { + let s = parse_callback_status(r#"{"status":"OK"}"#).unwrap(); + matches!(s, LnUrlCallbackStatus::Ok) + .then_some(()) + .expect("expected Ok variant"); + } + + #[test] + fn parse_callback_status_error() { + let s = parse_callback_status(r#"{"status":"ERROR","reason":"nope"}"#).unwrap(); + match s { + LnUrlCallbackStatus::ErrorStatus { data } => assert_eq!(data.reason, "nope"), + _ => panic!("expected ErrorStatus"), + } + } + + #[test] + fn parse_callback_status_missing_field() { + assert!(parse_callback_status(r#"{"reason":"nope"}"#).is_err()); + assert!(parse_callback_status("not json").is_err()); + } + + /// Test helper that mirrors the derivation logic inside + /// `perform_lnurl_auth` so we can compute a stable vector without + /// performing an HTTP callback. + fn compute_linking_pubkey_for_test( + namespace_xpriv: &[u8], + domain: &str, + ) -> Result { + let namespace = Xpriv::decode(namespace_xpriv).unwrap(); + let secp = Secp256k1::new(); + let hashing = namespace + .derive_priv(&secp, &[ChildNumber::from(0)]) + .unwrap(); + let mut engine = HmacEngine::::new(&hashing.private_key.secret_bytes()); + engine.input(domain.as_bytes()); + let hmac = Hmac::::from_engine(engine); + let bytes = hmac.as_byte_array(); + let linking_path: Vec = vec![ + ChildNumber::from(u32::from_be_bytes(bytes[0..4].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[4..8].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[8..12].try_into().unwrap())), + ChildNumber::from(u32::from_be_bytes(bytes[12..16].try_into().unwrap())), + ]; + let linking = namespace.derive_priv(&secp, &linking_path).unwrap(); + Ok(PublicKey::from_secret_key(&secp, &linking.private_key)) + } +} diff --git a/libs/gl-sdk/src/input.rs b/libs/gl-sdk/src/input.rs index 5f6c7778d..f77c67b54 100644 --- a/libs/gl-sdk/src/input.rs +++ b/libs/gl-sdk/src/input.rs @@ -1,7 +1,11 @@ // Input parsing for BOLT11 invoices, Lightning node IDs, LNURL // strings, and Lightning Addresses. -// Works offline — no node connection or HTTP calls needed. +// +// `parse_input` is async and resolves LNURL endpoints over HTTP, +// returning a fully-typed `InputType` ready for the caller's next +// action (display the invoice, build a pay/withdraw request, etc.). +use crate::lnurl::{LnUrlAuthRequestData, LnUrlPayRequestData, LnUrlWithdrawRequestData}; use crate::Error; /// Parsed BOLT11 invoice with extracted fields. @@ -23,28 +27,59 @@ pub struct ParsedInvoice { pub timestamp: u64, } -/// The result of parsing user input. +/// The result of `parse_input`: a fully-resolved input ready for the +/// caller's next action. LNURL bech32 strings and Lightning Addresses +/// are resolved over HTTP into typed pay or withdraw request data; +/// LNURL-auth endpoints are classified from the URL query string +/// without an HTTP fetch. #[derive(Clone, uniffi::Enum)] pub enum InputType { - /// A BOLT11 Lightning invoice. + /// A BOLT11 Lightning invoice. No HTTP was performed. Bolt11 { invoice: ParsedInvoice }, - /// A Lightning node public key (66 hex characters, 33 bytes compressed). + /// A Lightning node public key. No HTTP was performed. NodeId { node_id: String }, - /// An LNURL bech32 string (LUD-01). The `url` field contains the - /// decoded URL. Call `Node::resolve_lnurl()` to determine whether - /// this is a pay or withdraw endpoint. - LnUrl { url: String }, - /// A Lightning Address (LUD-16), e.g. `user@domain.com`. - /// Call `Node::resolve_lnurl()` to resolve it to a pay request. + /// An LNURL-pay endpoint with the service's parameters fetched. + LnUrlPay { data: LnUrlPayRequestData }, + /// An LNURL-withdraw endpoint with the service's parameters fetched. + LnUrlWithdraw { data: LnUrlWithdrawRequestData }, + /// An LNURL-auth (LUD-04) challenge. No HTTP was performed — + /// classification comes from the `tag=login` URL query parameter. + LnUrlAuth { data: LnUrlAuthRequestData }, +} + +/// Classify the input string offline before deciding whether to make +/// an HTTP request. Internal — `parse_input` is the public entry point. +enum Classification { + Bolt11(ParsedInvoice), + NodeId(String), + LnUrl { decoded_url: String, original: String }, LnUrlAddress { address: String }, } -/// Parse a string and identify its type. +/// Parse and resolve any supported input in one async call. +/// +/// Identifies BOLT11 invoices, node IDs, LNURL bech32 strings, and +/// Lightning Addresses. For LNURL and Lightning Address inputs, +/// performs the HTTP GET and returns the typed pay or withdraw request +/// data. For BOLT11 and node IDs, returns immediately without I/O. /// -/// Recognizes BOLT11 invoices, node IDs, LNURL bech32 strings, and -/// Lightning Addresses. Strips `lightning:` / `LIGHTNING:` prefixes -/// automatically. Works offline — no node connection needed. -pub fn parse_input(input: String) -> Result { +/// Strips `lightning:` / `LIGHTNING:` prefixes automatically. +pub async fn parse_input(input: String) -> Result { + match classify(&input)? { + Classification::Bolt11(invoice) => Ok(InputType::Bolt11 { invoice }), + Classification::NodeId(node_id) => Ok(InputType::NodeId { node_id }), + Classification::LnUrl { decoded_url, original } => { + resolve_lnurl_endpoint(&decoded_url, &original).await + } + Classification::LnUrlAddress { address } => { + let url = gl_client::lnurl::pay::parse_lightning_address(&address) + .map_err(|e| Error::Other(e.to_string()))?; + resolve_lnurl_endpoint(&url, &address).await + } + } +} + +fn classify(input: &str) -> Result { let trimmed = input.trim(); if trimmed.is_empty() { return Err(Error::Other("Empty input".to_string())); @@ -65,37 +100,127 @@ pub fn parse_input(input: String) -> Result { } // Try BOLT11 - if let Some(input_type) = try_parse_bolt11(stripped) { - return input_type; + if let Some(c) = try_parse_bolt11(stripped) { + return c; } // Try Lightning Address (user@domain) - if let Some(input_type) = try_parse_lightning_address(stripped) { - return Ok(input_type); + if let Some(c) = try_parse_lightning_address(stripped) { + return Ok(c); } // Try Node ID - if let Some(input_type) = try_parse_node_id(stripped) { - return Ok(input_type); + if let Some(c) = try_parse_node_id(stripped) { + return Ok(c); } Err(Error::Other("Unrecognized input".to_string())) } +async fn resolve_lnurl_endpoint(url: &str, original: &str) -> Result { + use gl_client::lnurl::models::LnUrlHttpClearnetClient; + use gl_client::lnurl::{LnUrlResponse, LNURL}; + + // LUD-04 endpoints carry tag=login in the URL query string. We can + // classify them without an HTTP fetch — the callback is hit later + // by Node::lnurl_auth once the user approves. + if let Some(auth) = try_parse_lnurl_auth(url)? { + return Ok(InputType::LnUrlAuth { data: auth }); + } + let _ = original; // reserved for future provenance fields + + let client = LNURL::new(LnUrlHttpClearnetClient::new()); + let response = client + .resolve(url) + .await + .map_err(|e| Error::Other(e.to_string()))?; + + Ok(match response { + LnUrlResponse::Pay(d) => { + let mut data: LnUrlPayRequestData = d.into(); + data.lnurl = original.to_string(); + InputType::LnUrlPay { data } + } + LnUrlResponse::Withdraw(d) => { + let mut data: LnUrlWithdrawRequestData = d.into(); + data.lnurl = original.to_string(); + InputType::LnUrlWithdraw { data } + } + }) +} + +/// Detect and parse an LNURL-auth endpoint (LUD-04) from a URL. +/// +/// Returns `Ok(Some(_))` when the URL has `tag=login`, `Ok(None)` when +/// the URL is for a different LNURL flow, and `Err` when the URL is +/// malformed or the LUD-04 fields fail validation. +fn try_parse_lnurl_auth(raw_url: &str) -> Result, Error> { + let parsed = + url::Url::parse(raw_url).map_err(|e| Error::Other(format!("Invalid LNURL URL: {e}")))?; + + let mut tag = None; + let mut k1 = None; + let mut action = None; + for (key, value) in parsed.query_pairs() { + match key.as_ref() { + "tag" => tag = Some(value.into_owned()), + "k1" => k1 = Some(value.into_owned()), + "action" => action = Some(value.into_owned()), + _ => {} + } + } + + if tag.as_deref() != Some("login") { + return Ok(None); + } + + let k1 = k1.ok_or_else(|| Error::Other("LNURL-auth URL missing k1".to_string()))?; + let k1_bytes = + hex::decode(&k1).map_err(|e| Error::Other(format!("LNURL-auth k1 not hex: {e}")))?; + if k1_bytes.len() != 32 { + return Err(Error::Other( + "LNURL-auth k1 must be 32 bytes".to_string(), + )); + } + + if let Some(a) = action.as_deref() { + if !["register", "login", "link", "auth"].contains(&a) { + return Err(Error::Other(format!( + "LNURL-auth action '{a}' is not one of register/login/link/auth" + ))); + } + } + + let domain = parsed + .domain() + .ok_or_else(|| Error::Other("LNURL-auth URL has no domain".to_string()))? + .to_string(); + + Ok(Some(LnUrlAuthRequestData { + k1, + action, + domain, + url: raw_url.to_string(), + })) +} + /// Try parsing as an LNURL bech32 string (LUD-01). /// Returns None if the input doesn't look like an LNURL. -fn try_parse_lnurl(input: &str) -> Option> { +fn try_parse_lnurl(input: &str) -> Option> { if !input.to_uppercase().starts_with("LNURL1") { return None; } match gl_client::lnurl::utils::parse_lnurl(input) { - Ok(url) => Some(Ok(InputType::LnUrl { url })), + Ok(url) => Some(Ok(Classification::LnUrl { + decoded_url: url, + original: input.to_string(), + })), Err(e) => Some(Err(Error::Other(format!("Invalid LNURL: {}", e)))), } } /// Try parsing as a Lightning Address (LUD-16): `user@domain.tld`. -fn try_parse_lightning_address(input: &str) -> Option { +fn try_parse_lightning_address(input: &str) -> Option { let parts: Vec<&str> = input.split('@').collect(); if parts.len() != 2 { return None; @@ -116,14 +241,14 @@ fn try_parse_lightning_address(input: &str) -> Option { { return None; } - Some(InputType::LnUrlAddress { + Some(Classification::LnUrlAddress { address: input.to_string(), }) } /// Try parsing as a BOLT11 invoice. Returns None if the input doesn't /// look like an invoice, or Some(Result) if it does (even if malformed). -fn try_parse_bolt11(input: &str) -> Option> { +fn try_parse_bolt11(input: &str) -> Option> { let lower = input.to_lowercase(); if !lower.starts_with("lnbc") && !lower.starts_with("lntb") && !lower.starts_with("lnbcrt") { return None; @@ -158,21 +283,19 @@ fn try_parse_bolt11(input: &str) -> Option> { .unwrap_or_default() .as_secs(); - Some(Ok(InputType::Bolt11 { - invoice: ParsedInvoice { - bolt11: input.to_string(), - payee_pubkey: Some(payee_pubkey), - payment_hash, - description, - amount_msat, - expiry, - timestamp, - }, - })) + Some(Ok(Classification::Bolt11(ParsedInvoice { + bolt11: input.to_string(), + payee_pubkey: Some(payee_pubkey), + payment_hash, + description, + amount_msat, + expiry, + timestamp, + }))) } /// Try parsing as a node ID (66-char hex → 33-byte compressed pubkey). -fn try_parse_node_id(input: &str) -> Option { +fn try_parse_node_id(input: &str) -> Option { if input.len() != 66 { return None; } @@ -184,114 +307,140 @@ fn try_parse_node_id(input: &str) -> Option { if bytes[0] != 0x02 && bytes[0] != 0x03 { return None; } - Some(InputType::NodeId { - node_id: input.to_string(), - }) + Some(Classification::NodeId(input.to_string())) } #[cfg(test)] mod tests { use super::*; - #[test] - fn test_parse_lnurl_string() { - let lnurl = "LNURL1DP68GURN8GHJ7CMFWP5X2UNSW4HXKTNRDAKJ7CTSDYHHVVF0D3H82UNV9UCSAXQZE2"; - match parse_input(lnurl.to_string()).unwrap() { - InputType::LnUrl { url } => { - assert!(url.starts_with("https://")); - } - other => panic!("Expected LnUrl, got {:?}", variant_name(&other)), + fn variant_name(t: &InputType) -> &'static str { + match t { + InputType::Bolt11 { .. } => "Bolt11", + InputType::NodeId { .. } => "NodeId", + InputType::LnUrlPay { .. } => "LnUrlPay", + InputType::LnUrlWithdraw { .. } => "LnUrlWithdraw", + InputType::LnUrlAuth { .. } => "LnUrlAuth", } } #[test] - fn test_parse_lnurl_lowercase() { - let lnurl = "lnurl1dp68gurn8ghj7cmfwp5x2unsw4hxktnrdakj7ctsdyhhvvf0d3h82unv9ucsaxqze2"; - match parse_input(lnurl.to_string()).unwrap() { - InputType::LnUrl { .. } => {} - other => panic!("Expected LnUrl, got {:?}", variant_name(&other)), + fn test_parse_input_bolt11_no_http() { + let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcsh2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqclj9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9dha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58aguqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphmsywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0vp62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh38s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5j5r6drg6k6zcqj0fcwg"; + let result = crate::util::exec(parse_input(invoice.to_string())).unwrap(); + match result { + InputType::Bolt11 { invoice: parsed } => assert_eq!(parsed.amount_msat, Some(10)), + other => panic!("Expected Bolt11, got {}", variant_name(&other)), } } #[test] - fn test_parse_lnurl_with_lightning_prefix() { - let input = "lightning:LNURL1DP68GURN8GHJ7CMFWP5X2UNSW4HXKTNRDAKJ7CTSDYHHVVF0D3H82UNV9UCSAXQZE2"; - match parse_input(input.to_string()).unwrap() { - InputType::LnUrl { .. } => {} - other => panic!("Expected LnUrl, got {:?}", variant_name(&other)), + fn test_parse_input_bolt11_with_lightning_prefix() { + let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcsh2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqclj9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9dha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58aguqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphmsywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0vp62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh38s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5j5r6drg6k6zcqj0fcwg"; + let result = crate::util::exec(parse_input(format!("lightning:{}", invoice))).unwrap(); + assert!(matches!(result, InputType::Bolt11 { .. })); + } + + #[test] + fn test_parse_input_node_id_no_http() { + let node_id = "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619"; + let result = crate::util::exec(parse_input(node_id.to_string())).unwrap(); + match result { + InputType::NodeId { node_id: id } => assert_eq!(id, node_id), + other => panic!("Expected NodeId, got {}", variant_name(&other)), } } #[test] - fn test_parse_invalid_lnurl() { - let result = parse_input("LNURL1INVALIDDATA".to_string()); + fn test_parse_input_invalid_lnurl_errors_before_http() { + let result = crate::util::exec(parse_input("LNURL1INVALIDDATA".to_string())); assert!(result.is_err()); } #[test] - fn test_parse_lightning_address() { - match parse_input("user@example.com".to_string()).unwrap() { - InputType::LnUrlAddress { address } => { - assert_eq!(address, "user@example.com"); - } - other => panic!("Expected LnUrlAddress, got {:?}", variant_name(&other)), - } + fn test_parse_input_address_with_no_dot_in_domain_errors() { + let result = crate::util::exec(parse_input("user@localhost".to_string())); + assert!(result.is_err()); } #[test] - fn test_parse_lightning_address_with_symbols() { - // LUD-16 allows a-z0-9-_. - match parse_input("sat.oshi-99@example.com".to_string()).unwrap() { - InputType::LnUrlAddress { address } => { - assert_eq!(address, "sat.oshi-99@example.com"); - } - other => panic!("Expected LnUrlAddress, got {:?}", variant_name(&other)), - } + fn test_parse_input_empty_address_parts_errors() { + assert!(crate::util::exec(parse_input("@example.com".to_string())).is_err()); + assert!(crate::util::exec(parse_input("user@".to_string())).is_err()); } #[test] - fn test_parse_lightning_address_no_dot_in_domain() { - // "user@localhost" is not a valid Lightning Address - let result = parse_input("user@localhost".to_string()); - // Should fall through to "Unrecognized input" - assert!(result.is_err()); + fn test_parse_input_unrecognized_errors() { + assert!(crate::util::exec(parse_input("hello world".to_string())).is_err()); + assert!(crate::util::exec(parse_input("".to_string())).is_err()); + assert!(crate::util::exec(parse_input(" ".to_string())).is_err()); + assert!(crate::util::exec(parse_input( + "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string() + )) + .is_err()); } + // 32 zero bytes hex-encoded — a syntactically valid k1. + const ZERO_K1: &str = + "0000000000000000000000000000000000000000000000000000000000000000"; + #[test] - fn test_parse_lightning_address_empty_parts() { - assert!(parse_input("@example.com".to_string()).is_err()); - assert!(parse_input("user@".to_string()).is_err()); + fn test_try_parse_lnurl_auth_classifies_login_url_without_http() { + let url = format!("https://service.example.com/auth?tag=login&k1={ZERO_K1}"); + let parsed = try_parse_lnurl_auth(&url).unwrap().expect("expected Some"); + assert_eq!(parsed.k1, ZERO_K1); + assert_eq!(parsed.domain, "service.example.com"); + assert!(parsed.action.is_none()); + assert_eq!(parsed.url, url); } #[test] - fn test_existing_bolt11_still_works() { - // A known valid mainnet invoice - let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcsh2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqclj9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9dha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58aguqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphmsywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0vp62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh38s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5j5r6drg6k6zcqj0fcwg"; - match parse_input(invoice.to_string()).unwrap() { - InputType::Bolt11 { invoice: parsed } => { - assert_eq!(parsed.amount_msat, Some(10)); - } - other => panic!("Expected Bolt11, got {:?}", variant_name(&other)), - } + fn test_try_parse_lnurl_auth_captures_action() { + let url = format!("https://x.com/a?tag=login&k1={ZERO_K1}&action=register"); + let parsed = try_parse_lnurl_auth(&url).unwrap().expect("expected Some"); + assert_eq!(parsed.action.as_deref(), Some("register")); } #[test] - fn test_existing_node_id_still_works() { - // A compressed pubkey (starts with 02 or 03) - let node_id = "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619"; - match parse_input(node_id.to_string()).unwrap() { - InputType::NodeId { node_id: id } => assert_eq!(id, node_id), - other => panic!("Expected NodeId, got {:?}", variant_name(&other)), - } + fn test_try_parse_lnurl_auth_returns_none_for_non_login_tag() { + let url = format!("https://x.com/p?tag=payRequest&k1={ZERO_K1}"); + assert!(try_parse_lnurl_auth(&url).unwrap().is_none()); } - /// Helper for readable test failures. - fn variant_name(input: &InputType) -> &'static str { - match input { - InputType::Bolt11 { .. } => "Bolt11", - InputType::NodeId { .. } => "NodeId", - InputType::LnUrl { .. } => "LnUrl", - InputType::LnUrlAddress { .. } => "LnUrlAddress", - } + #[test] + fn test_try_parse_lnurl_auth_returns_none_when_no_tag() { + assert!(try_parse_lnurl_auth("https://x.com/something") + .unwrap() + .is_none()); + } + + #[test] + fn test_try_parse_lnurl_auth_rejects_missing_k1() { + assert!(try_parse_lnurl_auth("https://x.com/a?tag=login").is_err()); + } + + #[test] + fn test_try_parse_lnurl_auth_rejects_short_k1() { + assert!(try_parse_lnurl_auth("https://x.com/a?tag=login&k1=deadbeef").is_err()); + } + + #[test] + fn test_try_parse_lnurl_auth_rejects_unknown_action() { + let url = format!("https://x.com/a?tag=login&k1={ZERO_K1}&action=bogus"); + assert!(try_parse_lnurl_auth(&url).is_err()); + } + + #[test] + fn test_parse_input_invalid_node_id_errors() { + // 66 chars but starts with 0x04 (uncompressed pubkey prefix) + assert!(crate::util::exec(parse_input( + "04eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619".to_string() + )) + .is_err()); + // 66 non-hex chars + assert!(crate::util::exec(parse_input( + "not_valid_hex_at_all_but_66_chars_long_xxxxxxxxxxxxxxxxxxxxxxxxxxx".to_string() + )) + .is_err()); } } diff --git a/libs/gl-sdk/src/lib.rs b/libs/gl-sdk/src/lib.rs index dab3ac875..c431666db 100644 --- a/libs/gl-sdk/src/lib.rs +++ b/libs/gl-sdk/src/lib.rs @@ -24,6 +24,7 @@ pub enum Error { Other(String), } +mod auth; mod config; mod credentials; mod input; @@ -46,9 +47,10 @@ pub use crate::{ }, input::{InputType, ParsedInvoice}, lnurl::{ - LnUrlErrorData, LnUrlPayRequest, LnUrlPayRequestData, LnUrlPayResult, - LnUrlPaySuccessData, LnUrlWithdrawRequest, LnUrlWithdrawRequestData, - LnUrlWithdrawResult, LnUrlWithdrawSuccessData, ResolvedLnUrl, SuccessActionProcessed, + LnUrlAuthRequestData, LnUrlCallbackStatus, LnUrlErrorData, LnUrlPayRequest, + LnUrlPayRequestData, LnUrlPayResult, LnUrlPaySuccessData, LnUrlWithdrawRequest, + LnUrlWithdrawRequestData, LnUrlWithdrawResult, LnUrlWithdrawSuccessData, + SuccessActionProcessed, }, scheduler::Scheduler, signer::{Handle, Signer}, @@ -71,6 +73,13 @@ fn schedule_node( let network = config.network; let nobody = config.nobody(); + // Derive the LNURL-auth namespace xpriv (m/138') from the seed + // once, before the seed is moved into the Signer. The xpriv is + // wrapped in Zeroizing so it scrubs when the Node is dropped or + // disconnected. + let lnurl_auth_xpriv = + zeroize::Zeroizing::new(auth::derive_lnurl_auth_namespace_xpriv(&seed)?); + let seed_for_async = seed.clone(); let credentials = util::exec(async move { let signer = @@ -108,7 +117,7 @@ fn schedule_node( .map_err(|e| Error::Other(e.to_string()))?; let handle = signer::Handle::spawn(authenticated_signer); - let node = node::Node::with_signer(credentials, handle, network)?; + let node = node::Node::new(credentials, handle, network, lnurl_auth_xpriv)?; Ok(Arc::new(node)) } @@ -193,12 +202,15 @@ pub fn connect( let network = config.network; let creds = credentials::Credentials::load(credentials)?; + let lnurl_auth_xpriv = + zeroize::Zeroizing::new(auth::derive_lnurl_auth_namespace_xpriv(&seed)?); + let authenticated_signer = gl_client::signer::Signer::new(seed, network, creds.inner.clone()) .map_err(|e| Error::Other(e.to_string()))?; let handle = signer::Handle::spawn(authenticated_signer); - let node = node::Node::with_signer(creds, handle, network)?; + let node = node::Node::new(creds, handle, network, lnurl_auth_xpriv)?; Ok(Arc::new(node)) } @@ -216,15 +228,20 @@ pub fn register_or_recover( } } -/// Parse a string and identify whether it's a BOLT11 invoice or a node ID. +/// Parse and resolve any supported input in one async call. +/// +/// For LNURL bech32 strings and Lightning Addresses this performs the +/// HTTP GET to the LNURL endpoint and returns typed pay or withdraw +/// request data. For BOLT11 invoices and node IDs it returns +/// immediately without I/O. /// /// Strips `lightning:` / `LIGHTNING:` prefixes automatically. -/// Works offline — no node connection needed. -#[uniffi::export] -pub fn parse_input(input: String) -> Result { - input::parse_input(input) +#[uniffi::export(async_runtime = "tokio")] +pub async fn parse_input(input: String) -> Result { + input::parse_input(input).await } + #[derive(uniffi::Enum, Debug)] pub enum Network { BITCOIN, diff --git a/libs/gl-sdk/src/lnurl.rs b/libs/gl-sdk/src/lnurl.rs index 5ff01ecd3..f101c5b88 100644 --- a/libs/gl-sdk/src/lnurl.rs +++ b/libs/gl-sdk/src/lnurl.rs @@ -9,19 +9,41 @@ use gl_client::lnurl::models as wire; // ── Resolved endpoint data ────────────────────────────────────────── -/// Result of resolving an LNURL or lightning address via HTTP. +/// Data from an LNURL-auth endpoint (LUD-04). +/// +/// Returned inside `InputType::LnUrlAuth` after `parse_input` classifies +/// a `tag=login` LNURL. Because the tag is carried in the URL query +/// string, no HTTP fetch is needed for classification — the callback is +/// only hit when the user approves the auth via `Node::lnurl_auth`. +#[derive(Clone, uniffi::Record)] +pub struct LnUrlAuthRequestData { + /// Hex-encoded 32-byte challenge from the service. + pub k1: String, + /// One of `register`, `login`, `link`, `auth`. None if the service + /// did not specify an `action` query parameter. + pub action: Option, + /// Domain of the LNURL-auth service, to be shown to the user when + /// asking for auth confirmation per LUD-04. + pub domain: String, + /// Full URL of the LNURL-auth service including its query string. + /// Used internally as the callback target after signing. + pub url: String, +} + +/// Result of an LNURL-auth callback (LUD-04). #[derive(Clone, uniffi::Enum)] -pub enum ResolvedLnUrl { - /// The endpoint is an LNURL-pay service (LUD-06). - Pay { data: LnUrlPayRequestData }, - /// The endpoint is an LNURL-withdraw service (LUD-03). - Withdraw { data: LnUrlWithdrawRequestData }, +pub enum LnUrlCallbackStatus { + /// The service accepted the signed challenge. + Ok, + /// The service rejected the signed challenge. + ErrorStatus { data: LnUrlErrorData }, } /// Data from an LNURL-pay endpoint (LUD-06). /// /// Contains the service's accepted amount range and metadata. -/// Returned inside `ResolvedLnUrl::Pay` after resolving an LNURL. +/// Returned inside `InputType::LnUrlPay` after `parse_input` resolves +/// an LNURL or Lightning Address. #[derive(Clone, uniffi::Record)] pub struct LnUrlPayRequestData { /// The callback URL to request an invoice from. @@ -43,7 +65,8 @@ pub struct LnUrlPayRequestData { /// Data from an LNURL-withdraw endpoint (LUD-03). /// /// Contains the service's accepted withdrawal range and session key. -/// Returned inside `ResolvedLnUrl::Withdraw` after resolving an LNURL. +/// Returned inside `InputType::LnUrlWithdraw` after `parse_input` +/// resolves an LNURL. #[derive(Clone, uniffi::Record)] pub struct LnUrlWithdrawRequestData { /// The callback URL to submit the invoice to. @@ -67,7 +90,7 @@ pub struct LnUrlWithdrawRequestData { /// Combines the resolved service data with the user's chosen amount. #[derive(Clone, uniffi::Record)] pub struct LnUrlPayRequest { - /// The resolved pay request data from `resolve_lnurl()`. + /// The resolved pay request data from `parse_input()`. pub data: LnUrlPayRequestData, /// Amount to pay in millisatoshis. pub amount_msat: u64, @@ -89,7 +112,7 @@ pub struct LnUrlPayRequest { /// Combines the resolved service data with the user's chosen amount. #[derive(Clone, uniffi::Record)] pub struct LnUrlWithdrawRequest { - /// The resolved withdraw request data from `resolve_lnurl()`. + /// The resolved withdraw request data from `parse_input()`. pub data: LnUrlWithdrawRequestData, /// Amount to withdraw in millisatoshis. pub amount_msat: u64, @@ -215,19 +238,6 @@ impl From for SuccessActionProcessed { } } -impl From for ResolvedLnUrl { - fn from(r: gl_client::lnurl::LnUrlResponse) -> Self { - match r { - gl_client::lnurl::LnUrlResponse::Pay(data) => ResolvedLnUrl::Pay { - data: data.into(), - }, - gl_client::lnurl::LnUrlResponse::Withdraw(data) => ResolvedLnUrl::Withdraw { - data: data.into(), - }, - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/libs/gl-sdk/src/node.rs b/libs/gl-sdk/src/node.rs index 4032641f7..0cb8abdbc 100644 --- a/libs/gl-sdk/src/node.rs +++ b/libs/gl-sdk/src/node.rs @@ -20,32 +20,17 @@ pub struct Node { signer_handle: Option, disconnected: AtomicBool, network: gl_client::bitcoin::Network, + /// LUD-05 namespace xpriv (`m/138'`) encoded as 78 bytes, derived + /// once from the BIP39 seed at register/recover/connect time. + /// `None` for nodes constructed directly from credentials without + /// a mnemonic — those cannot perform LNURL-auth. The + /// `Zeroizing` wrapper scrubs the bytes on drop, and `disconnect` + /// + `Drop for Node` take the Option to scrub eagerly. + lnurl_auth_xpriv: Mutex>>>, } #[uniffi::export] impl Node { - #[uniffi::constructor()] - pub fn new(credentials: &Credentials) -> Result { - let node_id = credentials - .inner - .node_id() - .map_err(|_e| Error::UnparseableCreds())?; - let inner = ClientNode::new(node_id, credentials.inner.clone()) - .expect("infallible client instantiation"); - - let cln_client = OnceCell::const_new(); - let gl_client = OnceCell::const_new(); - Ok(Node { - inner, - cln_client, - gl_client, - stored_credentials: Some(credentials.clone()), - signer_handle: None, - disconnected: AtomicBool::new(false), - network: gl_client::bitcoin::Network::Bitcoin, - }) - } - /// Stop the node if it is currently running. pub fn stop(&self) -> Result<(), Error> { self.check_connected()?; @@ -74,11 +59,17 @@ impl Node { /// Disconnects from the node and stops the signer if running. /// After disconnect, all RPC methods will return an error. /// Safe to call multiple times. + /// + /// Also scrubs the LNURL-auth namespace xpriv from memory; a + /// subsequent `lnurl_auth` call on a disconnected Node will + /// error rather than silently using stale key material. pub fn disconnect(&self) -> Result<(), Error> { self.disconnected.store(true, Ordering::Relaxed); if let Some(ref handle) = self.signer_handle { handle.try_stop(); } + // Take the option, dropping the Zeroizing>: scrubs. + let _ = self.lnurl_auth_xpriv.lock().unwrap().take(); Ok(()) } @@ -454,62 +445,15 @@ impl Node { // ── LNURL methods ─────────────────────────────────────────── - /// Resolve an LNURL or Lightning Address to its endpoint data. - /// - /// Performs the HTTP GET to the LNURL endpoint and returns the - /// typed request data. The result tells you whether this is a - /// pay or withdraw request, and includes the service's parameters. - /// - /// Accepts an LNURL bech32 string, a decoded URL (from - /// `parse_input()`), or a Lightning Address (`user@domain`). - pub fn resolve_lnurl( - &self, - input: String, - ) -> Result { - use gl_client::lnurl::models::LnUrlHttpClearnetClient; - use gl_client::lnurl::LNURL; - - let lnurl_client = LNURL::new(LnUrlHttpClearnetClient::new()); - let trimmed = input.trim(); - - // Determine the URL to fetch - let url = if trimmed.contains('@') { - gl_client::lnurl::pay::parse_lightning_address(trimmed) - .map_err(|e| Error::Other(e.to_string()))? - } else if trimmed.to_uppercase().starts_with("LNURL1") { - gl_client::lnurl::utils::parse_lnurl(trimmed) - .map_err(|e| Error::Other(e.to_string()))? - } else { - // Assume it's already a decoded URL - trimmed.to_string() - }; - - let response = exec(lnurl_client.resolve(&url)) - .map_err(|e| Error::Other(e.to_string()))?; - - let mut resolved: crate::lnurl::ResolvedLnUrl = response.into(); - - // Preserve the original input as the lnurl field - match &mut resolved { - crate::lnurl::ResolvedLnUrl::Pay { data } => { - data.lnurl = trimmed.to_string(); - } - crate::lnurl::ResolvedLnUrl::Withdraw { data } => { - data.lnurl = trimmed.to_string(); - } - } - - Ok(resolved) - } - /// Execute an LNURL-pay flow (LUD-06). /// /// Sends the chosen amount (and optional comment) to the service's /// callback, receives and validates a BOLT11 invoice, pays it, and /// processes any success action (LUD-09/10). /// - /// Call `resolve_lnurl()` first to get the `LnUrlPayRequestData`, - /// then build an `LnUrlPayRequest` with the user's chosen amount. + /// Call the top-level `parse_input` first to obtain the + /// `LnUrlPayRequestData`, then build an `LnUrlPayRequest` with the + /// user's chosen amount. pub fn lnurl_pay( &self, request: crate::lnurl::LnUrlPayRequest, @@ -608,8 +552,9 @@ impl Node { /// it to the service's callback URL, and the service pays it /// asynchronously. /// - /// Call `resolve_lnurl()` first to get the `LnUrlWithdrawRequestData`, - /// then build an `LnUrlWithdrawRequest` with the user's chosen amount. + /// Call the top-level `parse_input` first to obtain the + /// `LnUrlWithdrawRequestData`, then build an `LnUrlWithdrawRequest` + /// with the user's chosen amount. pub fn lnurl_withdraw( &self, request: crate::lnurl::LnUrlWithdrawRequest, @@ -651,6 +596,44 @@ impl Node { }), } } + + /// Execute an LNURL-auth callback (LUD-04). + /// + /// Derives the LUD-05 linking key for `request.domain` from the + /// node's LNURL-auth namespace xpriv (`m/138'`), signs the + /// service's `k1` challenge, and posts the signed callback. + /// + /// The namespace xpriv is derived once at register/recover/connect + /// time from the BIP39 seed and stored in `Zeroizing` on the + /// Node. Because `m/138'` is a hardened path, this stored key + /// material cannot be used to derive any other wallet key + /// (lightning channels, on-chain funds) — it is restricted to + /// LNURL-auth identities. It is scrubbed when the Node is + /// disconnected or dropped, after which `lnurl_auth` errors. + pub fn lnurl_auth( + &self, + request: crate::lnurl::LnUrlAuthRequestData, + ) -> Result { + self.check_connected()?; + let guard = self.lnurl_auth_xpriv.lock().unwrap(); + let xpriv = guard.as_deref().ok_or_else(|| { + Error::Other("LNURL-auth namespace key has been scrubbed".to_string()) + })?; + exec(crate::auth::perform_lnurl_auth(xpriv, &request)) + } +} + +impl Drop for Node { + fn drop(&mut self) { + // Defensive scrub for callers who drop the Node without + // calling `disconnect()` first. The Zeroizing> in the + // Option scrubs as it is dropped; `take()` triggers that + // immediately rather than waiting for the Mutex itself to + // drop with the Node. + if let Ok(mut guard) = self.lnurl_auth_xpriv.lock() { + guard.take(); + } + } } /// Returns a human-readable reason if the invoice's BOLT-11 currency @@ -739,12 +722,18 @@ impl Node { Ok(()) } - /// Internal constructor used by the high-level register/recover/connect functions. - /// Creates a Node with credentials and signer handle attached. - pub(crate) fn with_signer( + /// Canonical constructor. + /// + /// Crate-private — UniFFI consumers reach this via the top-level + /// `register` / `recover` / `connect` / `register_or_recover` free + /// functions. Those resolve the credentials, spawn the SDK + /// signer, and derive the LNURL-auth namespace xpriv from the + /// seed before calling here. + pub(crate) fn new( credentials: Credentials, handle: Handle, network: gl_client::bitcoin::Network, + lnurl_auth_xpriv: zeroize::Zeroizing>, ) -> Result { let node_id = credentials .inner @@ -763,6 +752,7 @@ impl Node { signer_handle: Some(handle), disconnected: AtomicBool::new(false), network, + lnurl_auth_xpriv: Mutex::new(Some(lnurl_auth_xpriv)), }) } diff --git a/libs/gl-sdk/tests/test_auth_api.py b/libs/gl-sdk/tests/test_auth_api.py index 2a0b8e71f..f891403c6 100644 --- a/libs/gl-sdk/tests/test_auth_api.py +++ b/libs/gl-sdk/tests/test_auth_api.py @@ -239,21 +239,3 @@ def test_credentials_still_works_after_disconnect(self, scheduler, nobody_id): assert len(creds) > 0 -class TestLowLevelCredentials: - """Test that Node created via low-level API exposes credentials.""" - - def test_node_new_stores_credentials(self, scheduler, nobody_id): - """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.register(MNEMONIC, None, config) - saved_creds = node1.credentials() - node1.disconnect() - - # Create node via low-level API - creds_obj = glsdk.Credentials.load(saved_creds) - node2 = glsdk.Node(creds_obj) - roundtripped = node2.credentials() - assert len(roundtripped) > 0 diff --git a/libs/gl-sdk/tests/test_basic.py b/libs/gl-sdk/tests/test_basic.py index 1899b7ddc..954be1b6f 100644 --- a/libs/gl-sdk/tests/test_basic.py +++ b/libs/gl-sdk/tests/test_basic.py @@ -48,13 +48,15 @@ def test_credentials_multiple_loads(): assert all(isinstance(c, glsdk.Credentials) for c in [creds1, creds2, creds3]) -def test_node_creation_fails_with_empty_creds(): - """Test that creating a Node with empty credentials fails as expected.""" - creds = glsdk.Credentials.load(b"") - - # Node creation should fail with these invalid credentials +def test_connect_fails_with_empty_creds(): + """Connecting with empty credentials must error.""" + config = glsdk.Config() + mnemonic = ( + "abandon abandon abandon abandon abandon abandon " + "abandon abandon abandon abandon abandon about" + ) with pytest.raises(glsdk.Error): - node = glsdk.Node(creds) + glsdk.connect(mnemonic, b"", config) def test_developer_cert_construction(): diff --git a/libs/gl-sdk/tests/test_lnurl.py b/libs/gl-sdk/tests/test_lnurl.py index 5c59b98bb..be6b71953 100644 --- a/libs/gl-sdk/tests/test_lnurl.py +++ b/libs/gl-sdk/tests/test_lnurl.py @@ -8,12 +8,31 @@ gl_sdk_node ── channel ── relay ── channel ── service_node (LNURL server) """ +import asyncio +import hashlib + +import pytest + from gltesting.fixtures import * # noqa: F401, F403 from pyln.testing.utils import wait_for import glsdk +def _bip39_seed(mnemonic: str) -> bytes: + """Derive the BIP39 seed bytes (no passphrase) from a mnemonic. + + Matches `bip39::Mnemonic::to_seed_normalized("")` on the Rust side + used by `glsdk.register/recover/connect`. Lets us seed the + gl-client `clients.new(secret=...)` fixture with the same bytes + so credentials produced via that path authenticate with + `glsdk.connect(mnemonic, ...)`. + """ + return hashlib.pbkdf2_hmac( + "sha512", mnemonic.encode("utf-8"), b"mnemonic", 2048, 64 + ) + + MNEMONIC = ( "abandon abandon abandon abandon abandon abandon " "abandon abandon abandon abandon abandon about" @@ -62,71 +81,150 @@ def fund_and_connect(node_factory, bitcoind, lnurl_service): return relay -def test_resolve_lnurl_pay( - scheduler, nobody_id, node_factory, bitcoind, lnurl_service -): - """Resolve an LNURL-pay endpoint via the SDK.""" - sdk_node, config = make_sdk_node(nobody_id, scheduler) +def test_parse_input_lnurl_pay(lnurl_service): + """parse_input on an LNURL-pay URL returns LnUrlPay with fetched data.""" + resolved = asyncio.run(glsdk.parse_input(lnurl_service.pay_url)) - try: - resolved = sdk_node.resolve_lnurl(lnurl_service.pay_url) - - assert isinstance(resolved, glsdk.ResolvedLnUrl.PAY) - data = resolved.data - assert data.min_sendable == lnurl_service.min_sendable - assert data.max_sendable == lnurl_service.max_sendable - assert len(data.description) > 0 - assert data.callback.startswith(lnurl_service.base_url) - finally: - sdk_node.disconnect() + assert isinstance(resolved, glsdk.InputType.LN_URL_PAY) + data = resolved.data + assert data.min_sendable == lnurl_service.min_sendable + assert data.max_sendable == lnurl_service.max_sendable + assert len(data.description) > 0 + assert data.callback.startswith(lnurl_service.base_url) + assert data.lnurl == lnurl_service.pay_url -def test_resolve_lnurl_withdraw( - scheduler, nobody_id, node_factory, bitcoind, lnurl_service -): - """Resolve an LNURL-withdraw endpoint via the SDK.""" - sdk_node, config = make_sdk_node(nobody_id, scheduler) +def test_parse_input_lnurl_withdraw(lnurl_service): + """parse_input on an LNURL-withdraw URL returns LnUrlWithdraw with fetched data.""" + resolved = asyncio.run(glsdk.parse_input(lnurl_service.withdraw_url)) - try: - resolved = sdk_node.resolve_lnurl(lnurl_service.withdraw_url) + assert isinstance(resolved, glsdk.InputType.LN_URL_WITHDRAW) + data = resolved.data + assert data.min_withdrawable == lnurl_service.min_withdrawable + assert data.max_withdrawable == lnurl_service.max_withdrawable + assert len(data.k1) > 0 + assert data.lnurl == lnurl_service.withdraw_url - assert isinstance(resolved, glsdk.ResolvedLnUrl.WITHDRAW) - data = resolved.data - assert data.min_withdrawable == lnurl_service.min_withdrawable - assert data.max_withdrawable == lnurl_service.max_withdrawable - assert len(data.k1) > 0 - finally: - sdk_node.disconnect() +def test_parse_input_lightning_address_url(lnurl_service): + """parse_input on a well-known LUD-16 URL returns LnUrlPay.""" + resolved = asyncio.run(glsdk.parse_input(lnurl_service.lightning_address_url)) -def test_resolve_lightning_address_url( - scheduler, nobody_id, node_factory, bitcoind, lnurl_service -): - """Resolve a Lightning Address well-known URL (LUD-16).""" + assert isinstance(resolved, glsdk.InputType.LN_URL_PAY) + assert resolved.data.min_sendable == lnurl_service.min_sendable + assert resolved.data.lnurl == lnurl_service.lightning_address_url + + +def test_parse_input_lnurl_auth_no_http(lnurl_service): + """parse_input on a tag=login URL classifies as LnUrlAuth without HTTP.""" + auth_url = lnurl_service.auth_url(action="login") + resolved = asyncio.run(glsdk.parse_input(auth_url)) + + assert isinstance(resolved, glsdk.InputType.LN_URL_AUTH) + data = resolved.data + assert data.action == "login" + assert data.domain == lnurl_service.domain + assert data.url == auth_url + assert len(data.k1) == 64 # 32 bytes hex + # Server should not have logged a callback — classification is offline. + assert len(lnurl_service.auth_callbacks) == 0 + + +def test_lnurl_auth_end_to_end(scheduler, nobody_id, lnurl_service): + """Register an SDK node, parse an auth URL, sign + post, expect OK.""" sdk_node, config = make_sdk_node(nobody_id, scheduler) try: - resolved = sdk_node.resolve_lnurl(lnurl_service.lightning_address_url) + auth_url = lnurl_service.auth_url(action="login") + resolved = asyncio.run(glsdk.parse_input(auth_url)) + assert isinstance(resolved, glsdk.InputType.LN_URL_AUTH) + + result = sdk_node.lnurl_auth(resolved.data) + + assert isinstance(result, glsdk.LnUrlCallbackStatus.OK) + assert len(lnurl_service.auth_callbacks) == 1 + cb = lnurl_service.auth_callbacks[0] + assert cb["k1"] == resolved.data.k1 + # 33-byte compressed pubkey hex = 66 chars; DER sig is 70-72 bytes. + assert len(cb["key"]) == 66 + assert len(cb["sig"]) >= 140 # 70+ bytes hex - assert isinstance(resolved, glsdk.ResolvedLnUrl.PAY) - data = resolved.data - assert data.min_sendable == lnurl_service.min_sendable + +def test_lnurl_auth_yields_stable_pubkey_per_domain(scheduler, nobody_id, lnurl_service): + """Two auth calls against the same service yield the same linking pubkey.""" + sdk_node, _ = make_sdk_node(nobody_id, scheduler) + + try: + for _ in range(2): + url = lnurl_service.auth_url(action="login") + resolved = asyncio.run(glsdk.parse_input(url)) + result = sdk_node.lnurl_auth(resolved.data) + assert isinstance(result, glsdk.LnUrlCallbackStatus.OK) + + first_key = lnurl_service.auth_callbacks[0]["key"] + second_key = lnurl_service.auth_callbacks[1]["key"] + assert first_key == second_key, ( + "linking pubkey should be deterministic per (mnemonic, domain)" + ) finally: sdk_node.disconnect() +def test_lnurl_auth_after_disconnect_errors(scheduler, nobody_id, lnurl_service): + """Calling lnurl_auth after disconnect must error — namespace key scrubbed.""" + sdk_node, _ = make_sdk_node(nobody_id, scheduler) + auth_url = lnurl_service.auth_url(action="login") + resolved = asyncio.run(glsdk.parse_input(auth_url)) + + sdk_node.disconnect() + + with pytest.raises(glsdk.Error): + sdk_node.lnurl_auth(resolved.data) + assert len(lnurl_service.auth_callbacks) == 0 + + +def test_parse_input_bolt11_no_http(lnurl_service): + """parse_input on a BOLT11 invoice returns Bolt11 without touching HTTP.""" + invoice = ( + "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45t" + "qcsh2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tn" + "k2zunwj5jalqtyxqulh0l5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw" + "3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993h5pcm4dxzpvttgza8zhkqxpgffc" + "rf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqclj9424x9m8" + "h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrz" + "jqwldmj9dha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqq" + "yqqqqlgqqqqjcqq9qrzjqf9e58aguqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmu" + "wvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphmsywntrrhqjcraumvc4y6r8" + "v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0vp62" + "g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqq" + "qqqzsqygarl9fh38s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5" + "m7ke54n2d5sym4xcmxtl8238xxvw5h5h5j5r6drg6k6zcqj0fcwg" + ) + resolved = asyncio.run(glsdk.parse_input(invoice)) + + assert isinstance(resolved, glsdk.InputType.BOLT11) + assert resolved.invoice.amount_msat == 10 + # No callback recorded on the LNURL service since we never hit it. + assert len(lnurl_service.pay_callbacks) == 0 + assert len(lnurl_service.withdraw_callbacks) == 0 + + def test_lnurl_pay_end_to_end( scheduler, nobody_id, clients, node_factory, bitcoind, lnurl_service ): """Full LNURL-pay flow: resolve → pay → verify. Uses a GL SDK node with outbound liquidity to pay an LNURL service. + Channel setup uses the low-level gl-client `clients` fixture + (gl-sdk doesn't expose `connect_peer`/`fund_channel`); afterwards + we hand over to the SDK-managed signer via `glsdk.connect`. """ - # Use the low-level client to set up channels, since the SDK node - # doesn't expose connect_peer / fund_channel directly. relay = fund_and_connect(node_factory, bitcoind, lnurl_service) - c = clients.new() + # Seed the gl-client clients fixture with the BIP39 seed of MNEMONIC + # so its credentials authenticate with `glsdk.connect(MNEMONIC, ...)` + # later on. + c = clients.new(secret=_bip39_seed(MNEMONIC)) c.register(configure=True) gl1 = c.node() s = c.signer().run_in_thread() @@ -154,19 +252,23 @@ def test_lnurl_pay_end_to_end( ) ) - # Now build an SDK-level Node for LNURL operations + # Hand over to the SDK signer: stop the gl-client signer first so + # only one signer is connected to the Greenlight node, then open + # the SDK Node via `connect` using the same mnemonic. creds_bytes = c.creds().to_bytes() - sdk_node = glsdk.Node(glsdk.Credentials.load(creds_bytes)) + s.shutdown() + + dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) + config = glsdk.Config().with_developer_cert(dev_cert) + sdk_node = glsdk.connect(MNEMONIC, creds_bytes, config) try: - # Resolve - resolved = sdk_node.resolve_lnurl(lnurl_service.pay_url) - assert isinstance(resolved, glsdk.ResolvedLnUrl.PAY) + resolved = asyncio.run(glsdk.parse_input(lnurl_service.pay_url)) + assert isinstance(resolved, glsdk.InputType.LN_URL_PAY) pay_data = resolved.data amount_msat = 50_000 # 50 sats - # Pay result = sdk_node.lnurl_pay( glsdk.LnUrlPayRequest( data=pay_data, @@ -178,7 +280,6 @@ def test_lnurl_pay_end_to_end( assert isinstance(result, glsdk.LnUrlPayResult.ENDPOINT_SUCCESS) assert len(result.data.payment_preimage) == 64 # hex-encoded 32 bytes - # Verify the LNURL server saw the callback assert len(lnurl_service.pay_callbacks) == 1 assert lnurl_service.pay_callbacks[0]["amount_msat"] == amount_msat finally: @@ -196,7 +297,7 @@ def test_lnurl_pay_with_message_success_action( relay = fund_and_connect(node_factory, bitcoind, lnurl_service) - c = clients.new() + c = clients.new(secret=_bip39_seed(MNEMONIC)) c.register(configure=True) gl1 = c.node() s = c.signer().run_in_thread() @@ -223,10 +324,15 @@ def test_lnurl_pay_with_message_success_action( ) creds_bytes = c.creds().to_bytes() - sdk_node = glsdk.Node(glsdk.Credentials.load(creds_bytes)) + s.shutdown() + + dev_cert = glsdk.DeveloperCert(nobody_id.cert_chain, nobody_id.private_key) + config = glsdk.Config().with_developer_cert(dev_cert) + sdk_node = glsdk.connect(MNEMONIC, creds_bytes, config) try: - resolved = sdk_node.resolve_lnurl(lnurl_service.pay_url) + resolved = asyncio.run(glsdk.parse_input(lnurl_service.pay_url)) + assert isinstance(resolved, glsdk.InputType.LN_URL_PAY) pay_data = resolved.data result = sdk_node.lnurl_pay( diff --git a/libs/gl-sdk/tests/test_parse_input.py b/libs/gl-sdk/tests/test_parse_input.py index 30089b8d3..d08a41907 100644 --- a/libs/gl-sdk/tests/test_parse_input.py +++ b/libs/gl-sdk/tests/test_parse_input.py @@ -1,8 +1,12 @@ -"""Tests for the parse_input() free function. +"""Tests for the async parse_input() free function. -Verifies BOLT11 invoice and node ID parsing from arbitrary string input. +Covers BOLT11 invoice and node ID parsing — paths that complete without +HTTP. LNURL and Lightning Address parsing are exercised in +test_lnurl.py against the live LNURL fixture. """ +import asyncio + import pytest import glsdk @@ -19,6 +23,10 @@ VALID_NODE_ID = "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619" +def parse(input_str): + return asyncio.run(glsdk.parse_input(input_str)) + + class TestParseInputTypes: """Test that parse_input types exist in the bindings.""" @@ -33,69 +41,67 @@ def test_parse_input_function_exists(self): class TestParseInputNodeId: - """Test node ID parsing.""" + """Test node ID parsing — no HTTP required.""" def test_parse_valid_node_id(self): - result = glsdk.parse_input(VALID_NODE_ID) - assert isinstance(result, glsdk.InputType) - - def test_parse_node_id_returns_correct_value(self): - result = glsdk.parse_input(VALID_NODE_ID) - # Access the NodeId variant - assert result.is_node_id() if hasattr(result, 'is_node_id') else True - # UniFFI enums in Python: check the variant - assert hasattr(result, 'node_id') or hasattr(result, 'invoice') + result = parse(VALID_NODE_ID) + assert isinstance(result, glsdk.InputType.NODE_ID) + assert result.node_id == VALID_NODE_ID def test_invalid_hex_returns_error(self): with pytest.raises(glsdk.Error): - glsdk.parse_input("not_valid_hex_at_all_but_66_chars_long_xxxxxxxxxxxxxxxxxxxxxxxxxxx") + parse("not_valid_hex_at_all_but_66_chars_long_xxxxxxxxxxxxxxxxxxxxxxxxxxx") def test_wrong_length_hex_returns_error(self): with pytest.raises(glsdk.Error): - glsdk.parse_input("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283") + parse("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283") def test_wrong_prefix_hex_returns_error(self): # 04 prefix = uncompressed pubkey, not valid for Lightning with pytest.raises(glsdk.Error): - glsdk.parse_input("04eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619") + parse("04eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619") class TestParseInputBolt11: - """Test BOLT11 invoice parsing.""" + """Test BOLT11 invoice parsing — no HTTP required.""" def test_parse_valid_bolt11(self): - result = glsdk.parse_input(BOLT11_INVOICE) - assert isinstance(result, glsdk.InputType) + result = parse(BOLT11_INVOICE) + assert isinstance(result, glsdk.InputType.BOLT11) def test_parse_bolt11_with_lightning_prefix(self): - result = glsdk.parse_input("lightning:" + BOLT11_INVOICE) - assert isinstance(result, glsdk.InputType) + result = parse("lightning:" + BOLT11_INVOICE) + assert isinstance(result, glsdk.InputType.BOLT11) def test_parse_bolt11_with_uppercase_prefix(self): - result = glsdk.parse_input("LIGHTNING:" + BOLT11_INVOICE) - assert isinstance(result, glsdk.InputType) + result = parse("LIGHTNING:" + BOLT11_INVOICE) + assert isinstance(result, glsdk.InputType.BOLT11) def test_parse_bolt11_with_whitespace(self): - result = glsdk.parse_input(" " + BOLT11_INVOICE + " ") - assert isinstance(result, glsdk.InputType) + result = parse(" " + BOLT11_INVOICE + " ") + assert isinstance(result, glsdk.InputType.BOLT11) class TestParseInputErrors: - """Test error cases.""" + """Test error cases that don't require HTTP.""" def test_empty_string_returns_error(self): with pytest.raises(glsdk.Error): - glsdk.parse_input("") + parse("") def test_whitespace_only_returns_error(self): with pytest.raises(glsdk.Error): - glsdk.parse_input(" ") + parse(" ") def test_garbage_returns_error(self): with pytest.raises(glsdk.Error): - glsdk.parse_input("hello world") + parse("hello world") def test_bitcoin_address_returns_error(self): # We don't support bitcoin addresses yet with pytest.raises(glsdk.Error): - glsdk.parse_input("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4") + parse("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4") + + def test_invalid_lnurl_bech32_errors_before_http(self): + with pytest.raises(glsdk.Error): + parse("LNURL1INVALIDDATA") diff --git a/libs/gl-testing/gltesting/clients.py b/libs/gl-testing/gltesting/clients.py index 3552e3ebe..aae325aa6 100644 --- a/libs/gl-testing/gltesting/clients.py +++ b/libs/gl-testing/gltesting/clients.py @@ -42,7 +42,13 @@ def __init__( if secret is not None: self.log.debug("Initializing hsm_secret with provided secret") - assert len(secret) == 32 + # gl-client's Signer accepts arbitrary-length seeds. We accept + # 32 bytes (legacy raw-secret callers) and 64 bytes (BIP39 + # standard seeds, so tests can share a seed with gl-sdk's + # mnemonic-derived flow). + assert len(secret) in (32, 64), ( + f"hsm_secret must be 32 or 64 bytes, got {len(secret)}" + ) with (self.directory / "hsm_secret").open(mode="wb") as f: f.write(secret) diff --git a/libs/gl-testing/gltesting/lnurl_server.py b/libs/gl-testing/gltesting/lnurl_server.py index e95366bd1..ac7c90fe3 100644 --- a/libs/gl-testing/gltesting/lnurl_server.py +++ b/libs/gl-testing/gltesting/lnurl_server.py @@ -26,6 +26,7 @@ class LnurlServer: GET /.well-known/lnurlp/{username} → LUD-16 (same payRequest) GET /lnurlw → LUD-03 withdrawRequest response GET /lnurlw/callback?k1=&pr= → service pays the invoice + GET /auth?tag=login&k1=&sig=&key= → LUD-04 verify signature """ def __init__( @@ -71,9 +72,13 @@ def __init__( # Each withdraw session issues a fresh k1 and remembers it until consumed self._pending_withdrawals: dict[str, dict] = {} + # LUD-04 auth challenges issued by `auth_url(...)`, indexed by k1 + self._pending_auth: dict[str, dict] = {} + # Logs of all incoming callback requests — tests inspect these self.pay_callbacks: list[dict] = [] self.withdraw_callbacks: list[dict] = [] + self.auth_callbacks: list[dict] = [] # ── URLs ────────────────────────────────────────────────── @@ -97,6 +102,20 @@ def lightning_address_url(self) -> str: def withdraw_url(self) -> str: return f"{self.base_url}/lnurlw" + def auth_url(self, action: str | None = None) -> str: + """Issue a fresh LUD-04 auth challenge and return its full URL. + + The k1 is generated here and remembered server-side so the + signed callback can be verified. `action` can be one of + register/login/link/auth (or None to omit). + """ + k1 = secrets.token_hex(32) # 32 bytes = 64 hex chars + self._pending_auth[k1] = {"used": False, "action": action} + url = f"{self.base_url}/auth?tag=login&k1={k1}" + if action is not None: + url += f"&action={action}" + return url + # ── Lifecycle ──────────────────────────────────────────── def start(self): @@ -188,6 +207,31 @@ def handle_withdraw_callback(self, k1: str, invoice: str) -> dict: return {"status": "OK"} + def handle_auth_callback(self, k1: str, sig_hex: str, key_hex: str) -> dict: + """Verify the LUD-04 ECDSA signature over k1 with the linking key.""" + self.auth_callbacks.append({"k1": k1, "sig": sig_hex, "key": key_hex}) + + session = self._pending_auth.get(k1) + if session is None: + return {"status": "ERROR", "reason": f"unknown k1: {k1}"} + if session["used"]: + return {"status": "ERROR", "reason": "k1 already used"} + + try: + from coincurve import PublicKey + + key_bytes = bytes.fromhex(key_hex) + sig_der = bytes.fromhex(sig_hex) + challenge = bytes.fromhex(k1) + pubkey = PublicKey(key_bytes) + if not pubkey.verify(sig_der, challenge, hasher=None): + return {"status": "ERROR", "reason": "invalid signature"} + except Exception as e: + return {"status": "ERROR", "reason": f"verify failed: {e}"} + + session["used"] = True + return {"status": "OK"} + def _handler_factory(server: LnurlServer): """Build a BaseHTTPRequestHandler class bound to a specific server. @@ -263,6 +307,18 @@ def do_GET(self): self._reply_json(200, server.handle_withdraw_callback(k1, pr)) return + if path == "/auth": + k1 = query.get("k1", [None])[0] + sig = query.get("sig", [None])[0] + key = query.get("key", [None])[0] + if not k1 or not sig or not key: + self._reply_json( + 200, {"status": "ERROR", "reason": "missing k1/sig/key"} + ) + return + self._reply_json(200, server.handle_auth_callback(k1, sig, key)) + return + self.send_response(404) self.end_headers() except Exception as e: