gl-sdk 0.4.0

High-level SDK for Greenlight with UniFFI language bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::collections::HashMap;

uniffi::setup_scaffolding!();

#[derive(uniffi::Error, thiserror::Error, Debug)]
pub enum Error {
    #[error("{msg}")]
    DuplicateNode {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    NoSuchNode {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    UnparseableCreds {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    PhraseCorrupted {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    Rpc {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    Argument {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },

    #[error("{msg}")]
    Other {
        code: i32,
        msg: String,
        values: HashMap<String, String>,
    },
}

impl Error {
    pub fn duplicate_node(node_id: impl Into<String>) -> Self {
        let node_id = node_id.into();
        Error::DuplicateNode {
            code: 1000,
            msg: format!(
                "There is already a node for node_id={node_id}, maybe you want to recover?"
            ),
            values: HashMap::from([("node_id".into(), node_id)]),
        }
    }

    pub fn no_such_node(node_id: impl Into<String>) -> Self {
        let node_id = node_id.into();
        Error::NoSuchNode {
            code: 1001,
            msg: format!(
                "There is no node with node_id={node_id}, maybe you need to register first?"
            ),
            values: HashMap::from([("node_id".into(), node_id)]),
        }
    }

    pub fn unparseable_creds() -> Self {
        Error::UnparseableCreds {
            code: 1100,
            msg: "The provided credentials could not be parsed, please recover.".into(),
            values: HashMap::new(),
        }
    }

    pub fn phrase_corrupted() -> Self {
        Error::PhraseCorrupted {
            code: 1101,
            msg: "The passphrase you provided fails the checksum".into(),
            values: HashMap::new(),
        }
    }

    pub fn rpc(detail: impl Into<String>) -> Self {
        let detail = detail.into();
        Error::Rpc {
            code: 2000,
            msg: format!("Error calling the rpc: {detail}"),
            values: HashMap::from([("detail".into(), detail)]),
        }
    }

    pub fn argument(arg_name: impl Into<String>, arg_value: impl Into<String>) -> Self {
        let arg_name = arg_name.into();
        let arg_value = arg_value.into();
        Error::Argument {
            code: 3000,
            msg: format!("Invalid argument: {arg_name}={arg_value}"),
            values: HashMap::from([
                ("arg_name".into(), arg_name),
                ("arg_value".into(), arg_value),
            ]),
        }
    }

    pub fn other(detail: impl Into<String>) -> Self {
        let detail = detail.into();
        Error::Other {
            code: 9000,
            msg: format!("Generic error: {detail}"),
            values: HashMap::from([("detail".into(), detail)]),
        }
    }
}

mod config;
mod credentials;
mod input;
mod lnurl;
mod logging;
mod node;
mod node_builder;
mod scheduler;
mod signer;
mod util;

pub use crate::{
    config::Config,
    credentials::{Credentials, DeveloperCert},
    node::{
        ChannelState, FundChannel, FundOutput, GetInfoResponse, Invoice,
        InvoicePaidEvent, InvoiceStatus, ListFundsResponse, ListIndex, ListInvoicesResponse,
        ListPaymentsRequest, ListPeerChannelsResponse, ListPaysResponse, ListPeersResponse,
        Node, NodeEvent, NodeEventListener, NodeEventStream, NodeState, OnchainBalanceState,
        OnchainFeeRates, OnchainReceiveResponse, OnchainSendResponse, Outpoint, OutputStatus,
        Pay, PayStatus, Payment, PaymentStatus, PaymentType, PaymentTypeFilter, Peer,
        PeerChannel, PreparedOnchainSend, ReceiveResponse, SendResponse,
    },
    input::{ParsedInput, ParsedInvoice, ResolvedInput},
    logging::{LogEntry, LogLevel, LogListener},
    lnurl::{
        LnUrlErrorData, LnUrlPayRequest, LnUrlPayRequestData, LnUrlPayResult,
        LnUrlPaySuccessData, LnUrlWithdrawRequest, LnUrlWithdrawRequestData,
        LnUrlWithdrawResult, LnUrlWithdrawSuccessData, SuccessActionProcessed,
    },
    node_builder::NodeBuilder,
    scheduler::Scheduler,
    signer::{Handle, Signer},
};

/// Which scheduler operation to perform.
enum SchedulerAction {
    Register { invite_code: Option<String> },
    Recover,
}

/// Shared implementation for register and recover flows.
fn schedule_node(
    seed: Vec<u8>,
    config: &config::Config,
    action: SchedulerAction,
) -> Result<std::sync::Arc<node::Node>, Error> {
    use std::sync::Arc;

    let network = config.network;
    let nobody = config.nobody();

    let seed_for_async = seed.clone();
    let credentials = util::exec(async move {
        let signer =
            gl_client::signer::Signer::new(seed_for_async, network, nobody.clone())
                .map_err(|e| Error::other(e.to_string()))?;

        let scheduler = gl_client::scheduler::Scheduler::new(network, nobody)
            .await
            .map_err(|e| Error::other(e.to_string()))?;

        let node_id_hex = hex::encode(signer.node_id());

        let creds_bytes = match action {
            SchedulerAction::Register { invite_code } => {
                scheduler
                    .register(&signer, invite_code)
                    .await
                    .map_err(|e| map_scheduler_error(e, &node_id_hex))?
                    .creds
            }
            SchedulerAction::Recover => {
                scheduler
                    .recover(&signer)
                    .await
                    .map_err(|e| map_scheduler_error(e, &node_id_hex))?
                    .creds
            }
        };

        credentials::Credentials::load(creds_bytes)
    })?;

    let authenticated_signer =
        gl_client::signer::Signer::new(seed, network, credentials.inner.clone())
            .map_err(|e| Error::other(e.to_string()))?;

    let handle = signer::Handle::spawn(authenticated_signer);
    let node = node::Node::with_signer(credentials, handle, network)?;
    Ok(Arc::new(node))
}

/// Map scheduler errors to specific Error variants.
/// First tries tonic status codes, then falls back to error message matching.
fn map_scheduler_error(e: anyhow::Error, node_id_hex: &str) -> Error {
    // Walk the error chain looking for a tonic::Status with a specific code
    for cause in e.chain() {
        if let Some(status) = cause.downcast_ref::<tonic::Status>() {
            match status.code() {
                tonic::Code::AlreadyExists => {
                    return Error::duplicate_node(node_id_hex.to_string())
                }
                tonic::Code::NotFound => return Error::no_such_node(node_id_hex.to_string()),
                // Don't return here — the tonic status might be a generic
                // wrapper (e.g. Internal/Unknown) around a more specific
                // error. Fall through to string matching.
                _ => {}
            }
        }
    }

    // Fall back to checking the full error message for known patterns.
    let msg = e.to_string();
    if msg.contains("NOT_FOUND")
        || msg.contains("no rows returned")
        || msg.contains("Recovery failed")
    {
        Error::no_such_node(node_id_hex.to_string())
    } else if msg.contains("ALREADY_EXISTS") {
        Error::duplicate_node(node_id_hex.to_string())
    } else {
        Error::other(msg)
    }
}

/// Parse a BIP39 mnemonic into a seed.
fn parse_mnemonic(mnemonic: &str) -> Result<Vec<u8>, Error> {
    use bip39::Mnemonic;
    use std::str::FromStr;
    let phrase = Mnemonic::from_str(mnemonic).map_err(|_e| Error::phrase_corrupted())?;
    Ok(phrase.to_seed_normalized("").to_vec())
}

/// Crate-internal: connect using saved credentials. The builder
/// (`NodeBuilder::connect`) is the public entry point.
pub(crate) fn connect_internal(
    mnemonic: String,
    credentials: Vec<u8>,
    config: &config::Config,
) -> Result<std::sync::Arc<node::Node>, Error> {
    use std::sync::Arc;

    let seed = parse_mnemonic(&mnemonic)?;
    let network = config.network;
    let creds = credentials::Credentials::load(credentials)?;

    let authenticated_signer =
        gl_client::signer::Signer::new(seed, network, creds.inner.clone())
            .map_err(|e| Error::other(e.to_string()))?;

    let handle = signer::Handle::spawn(authenticated_signer);
    let node = node::Node::with_signer(creds, handle, network)?;
    Ok(Arc::new(node))
}

/// Crate-internal: register a fresh node. The builder
/// (`NodeBuilder::register`) is the public entry point.
pub(crate) fn register_internal(
    mnemonic: String,
    invite_code: Option<String>,
    config: &config::Config,
) -> Result<std::sync::Arc<node::Node>, Error> {
    let seed = parse_mnemonic(&mnemonic)?;
    schedule_node(seed, config, SchedulerAction::Register { invite_code })
}

/// Crate-internal: recover an existing node. The builder
/// (`NodeBuilder::recover`) is the public entry point.
pub(crate) fn recover_internal(
    mnemonic: String,
    config: &config::Config,
) -> Result<std::sync::Arc<node::Node>, Error> {
    let seed = parse_mnemonic(&mnemonic)?;
    schedule_node(seed, config, SchedulerAction::Recover)
}

/// Crate-internal: register-or-recover. The builder
/// (`NodeBuilder::register_or_recover`) is the public entry point.
pub(crate) fn register_or_recover_internal(
    mnemonic: String,
    invite_code: Option<String>,
    config: &config::Config,
) -> Result<std::sync::Arc<node::Node>, Error> {
    match recover_internal(mnemonic.clone(), config) {
        Ok(node) => Ok(node),
        Err(Error::NoSuchNode { .. }) => register_internal(mnemonic, invite_code, config),
        Err(e) => Err(e),
    }
}

/// Crate-internal: connect signerless — credentials only, no
/// SDK-side signer spawned. Used by `NodeBuilder::connect` when no
/// mnemonic is set.
///
/// Signing-required RPCs (`pay`, `receive` JIT-channel, etc.) rely
/// on a signer running elsewhere — typically the CLN node's local
/// signer or a paired device. This is the supported model for
/// signerless clients (browser extensions, paired devices, hardware
/// signers held outside the SDK process).
pub(crate) fn connect_signerless_internal(
    credentials: Vec<u8>,
    _config: &config::Config,
) -> Result<std::sync::Arc<node::Node>, Error> {
    use std::sync::Arc;
    let creds = credentials::Credentials::load(credentials)?;
    let node = node::Node::signerless(creds)?;
    Ok(Arc::new(node))
}

/// Synchronously classify the input. **No HTTP, no I/O.**
///
/// Recognises BOLT11 invoices, node IDs, LNURL bech32 strings, and
/// Lightning Addresses. Strips `lightning:` / `LIGHTNING:` prefixes
/// automatically. LNURL inputs are decoded to their underlying URL
/// but **not fetched** — the caller chooses whether to resolve
/// further (via `resolve_input`) or to surface the URL to the user
/// as-is.
///
/// Use this for offline operations like clipboard validation or
/// invoice sanity checks. Use `resolve_input` for the QR-scan flow
/// where you want the resolved pay/withdraw data in one call.
#[uniffi::export]
pub fn parse_input(input: String) -> Result<input::ParsedInput, Error> {
    input::parse_input(input)
}

/// Classify and resolve the input.
///
/// Internally calls `parse_input` for offline classification, then
/// for LNURL bech32 strings and Lightning Addresses 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.
///
/// # Blocking
///
/// This function blocks the calling thread while any network I/O
/// completes. The SDK exposes a **synchronous-only** public API so
/// that every language binding (Python, Kotlin, Swift, Ruby, C++)
/// works without requiring an async runtime on the caller side.
/// Async work is executed internally on a shared Tokio runtime
/// managed by the SDK.
#[uniffi::export]
pub fn resolve_input(input: String) -> Result<input::ResolvedInput, Error> {
    util::exec(async { input::resolve_input(input).await })
}

/// Set up SDK logging. Call once before any other SDK function.
///
/// The listener receives all log messages from the SDK and the
/// underlying Greenlight client library. Call once, as early as
/// possible, so early logs are captured. Returns an error if a logger
/// has already been installed in this process. To change the filter
/// after installation, use `set_log_level`.
#[uniffi::export]
pub fn set_logger(
    level: logging::LogLevel,
    listener: Box<dyn logging::LogListener>,
) -> Result<(), Error> {
    logging::set_logger(level, listener)
}

/// Change the log filter at runtime without reinstalling the listener.
#[uniffi::export]
pub fn set_log_level(level: logging::LogLevel) {
    logging::set_log_level(level)
}

#[derive(uniffi::Enum, Debug)]
pub enum Network {
    BITCOIN,
    REGTEST,
}

impl From<Network> for gl_client::bitcoin::Network {
    fn from(n: Network) -> gl_client::bitcoin::Network {
        match n {
            Network::BITCOIN => gl_client::bitcoin::Network::Bitcoin,
            Network::REGTEST => gl_client::bitcoin::Network::Regtest,
        }
    }
}