Skip to main content

lexe/
wallet.rs

1use std::{
2    cmp::Ordering, collections::HashMap, path::PathBuf, sync::Mutex,
3    time::Duration,
4};
5
6use anyhow::{Context, anyhow, ensure};
7use bitcoin::address::NetworkUnchecked;
8use lexe_api::{
9    def::{UserBackendApi, UserGatewayApi, UserNodeRunApi},
10    models::command::{self, GetUpdatedPayments, PaymentIdStruct},
11    revocable_clients,
12    types::{
13        bounded_string::BoundedString,
14        payments::{
15            PaymentCreatedIndex, PaymentDirection, PaymentId, PaymentKind,
16            PaymentRail, PaymentStatus,
17        },
18        username::{Username, UsernameStruct},
19    },
20};
21use lexe_common::{
22    api::{
23        auth::{
24            UserSignupRequestWire, UserSignupRequestWireV1,
25            UserSignupRequestWireV2,
26        },
27        user::NodePkProof,
28    },
29    constants,
30    ln::{amount::Amount, channel::UserChannelId, network::Network},
31};
32use lexe_crypto::rng::SysRng;
33use lexe_node_client::client::{GatewayClient, NodeClient};
34use lexe_payment_uri::{
35    self, Bip321Uri, ClaimMethod, EmailLikeAddress, Lnurl, PaymentMethod,
36    PaymentUri, PaymentUriMethod, PaymentUriMethods,
37    bip353::{self, Bip353Client},
38    lnurl::LnurlClient,
39};
40use tokio::sync::OnceCell;
41use tracing::{debug, info, instrument, warn};
42
43use crate::{
44    config::{
45        WalletEnvConfig, WalletEnvDbConfig, WalletUserConfig,
46        WalletUserDbConfig,
47    },
48    payments_bus::{PaymentsBus, WalletUpdatesApi},
49    types::{
50        auth::{ClientCredentials, CredentialsRef, RootSeed, UserPk},
51        command::{
52            AnalyzeRequest, AnalyzeResponse, BudgetInfo, CancelPaymentRequest,
53            CashAppBuyRequest, CashAppBuyResponse, ChannelDetails,
54            CheckAddressResponse, ClaimableDetails, ClientInfo,
55            ClientInfoResponse, CloseChannelRequest, CreateClientRequest,
56            CreateClientResponse, CreateInvoiceRequest, CreateInvoiceResponse,
57            CreateOfferRequest, CreateOfferResponse, CreatePayerProofRequest,
58            CreatePayerProofResponse, GetClientInfoResponse,
59            GetExclusiveAddressResponse, GetHumanBitcoinAddressResponse,
60            GetNextUnusedAddressResponse, GetPaymentByIdRequest,
61            GetPaymentRequest, GetPaymentResponse, GetUpdatedPaymentsRequest,
62            GetUpdatedPaymentsResponse, ListChannelsResponse,
63            ListClientsResponse, ListPaymentsResponse, NodeInfo,
64            OpenChannelRequest, OpenChannelResponse, PayInvoiceRequest,
65            PayLnurlRequest, PayOfferRequest, PayOnchainPreflightRequest,
66            PayOnchainPreflightResponse, PayOnchainRequest, PayRequest,
67            PayableDetails, PaymentSyncSummary, RevokeClientRequest,
68            UpdateClientRequest, UpdatePersonalNoteRequest,
69            WaitForNextPaymentRequest, WaitForNextPaymentResponse,
70            WaitForPaymentUpdateRequest, WithdrawLnurlRequest,
71        },
72        payment::{Order, Payment, PaymentFilter, PaymentUpdatedIndex},
73    },
74    unstable::{
75        ffs::DiskFs, payments_db::PaymentsDb, provision, wallet_db::WalletDb,
76    },
77    wallet::payment_cache::PaymentCache,
78};
79
80/// Default number of payments per page.
81const DEFAULT_LIST_LIMIT: usize = 100;
82
83/// Top-level handle to a Lexe wallet.
84pub struct LexeWallet {
85    user_config: WalletUserConfig,
86
87    store: WalletStore,
88    payments_bus: OnceCell<PaymentsBus>,
89
90    /// In-memory cache for [`Self::get_next_unused_address`].
91    next_unused_address: Mutex<Option<CachedUnusedAddress>>,
92
93    gateway_client: GatewayClient,
94    node_client: NodeClient,
95    bip353_client: Bip353Client,
96    lnurl_client: LnurlClient,
97}
98
99/// Local stores for a wallet. If persistence is enabled, `Db` is used;
100/// otherwise `Cache` is used.
101enum WalletStore {
102    /// A persisted local DB. Used by wallets created via `fresh`, `load`, or
103    /// `load_or_fresh`.
104    Db(Box<WalletDb<DiskFs>>),
105    /// In-memory caches. Used by wallets created via `without_db`.
106    Cache(Box<WalletCache>),
107}
108
109/// The in-memory stores of a wallet without local persistence.
110struct WalletCache {
111    payments: tokio::sync::RwLock<PaymentCache>,
112    /// Each checked address's `synced_block_height`, kept only for this
113    /// wallet's lifetime.
114    address_synced_block_heights: Mutex<HashMap<bitcoin::Address, u32>>,
115}
116
117impl WalletStore {
118    /// The `synced_block_height` from `address`'s last `check_address`.
119    fn address_synced_block_height(
120        &self,
121        address: &bitcoin::Address,
122    ) -> Option<u32> {
123        match self {
124            Self::Db(db) =>
125                db.address_synced_block_height(&address.to_string()),
126            Self::Cache(cache) => cache
127                .address_synced_block_heights
128                .lock()
129                .unwrap()
130                .get(address)
131                .copied(),
132        }
133    }
134
135    /// Record `address`'s `synced_block_height`, persisting it if this store
136    /// is persistent.
137    fn set_address_synced_block_height(
138        &self,
139        address: bitcoin::Address,
140        synced_block_height: u32,
141    ) -> anyhow::Result<()> {
142        match self {
143            Self::Db(db) => db.set_address_synced_block_height(
144                &address.to_string(),
145                synced_block_height,
146            ),
147            Self::Cache(cache) => {
148                cache
149                    .address_synced_block_heights
150                    .lock()
151                    .unwrap()
152                    .insert(address, synced_block_height);
153                Ok(())
154            }
155        }
156    }
157}
158
159/// A cached [`get_next_unused_address`] result, along with the latest payment
160/// update index at fetch time.
161///
162/// [`get_next_unused_address`]: LexeWallet::get_next_unused_address
163struct CachedUnusedAddress {
164    address: bitcoin::Address<bitcoin::address::NetworkUnchecked>,
165    latest_update: Option<PaymentUpdatedIndex>,
166}
167
168// TODO(max): Consider what happens if someone provides *both* a client
169// credential and a root seed for the same user. Do we need locks for the dbs?
170
171impl LexeWallet {
172    // --- Constructors --- //
173
174    /// Create a fresh [`LexeWallet`], deleting any existing database state for
175    /// this user. Data for other users and environments is not affected.
176    ///
177    /// It is recommended to always pass the same `lexe_data_dir`,
178    /// regardless of which environment we're in (dev/staging/prod) and which
179    /// user this [`LexeWallet`] is for. Users and environments will not
180    /// interfere with each other as all data is namespaced internally.
181    /// Defaults to `~/.lexe` if not specified.
182    #[instrument(skip_all, name = "(fresh)")]
183    pub fn fresh(
184        env_config: WalletEnvConfig,
185        credentials: CredentialsRef<'_>,
186        lexe_data_dir: Option<PathBuf>,
187    ) -> anyhow::Result<Self> {
188        let lexe_data_dir =
189            lexe_data_dir.map_or_else(crate::default_lexe_data_dir, Ok)?;
190        let env_db_config =
191            WalletEnvDbConfig::new(env_config.wallet_env, lexe_data_dir);
192        let user_db_config =
193            WalletUserDbConfig::from_credentials(credentials, env_db_config)?;
194
195        let db = WalletDb::fresh(user_db_config)
196            .context("Failed to create fresh wallet db")?;
197
198        let (
199            user_config,
200            gateway_client,
201            node_client,
202            bip353_client,
203            lnurl_client,
204        ) = Self::build_clients(env_config, credentials)?;
205
206        Ok(Self {
207            user_config,
208            store: WalletStore::Db(Box::new(db)),
209            payments_bus: OnceCell::new(),
210            next_unused_address: Mutex::new(None),
211            gateway_client,
212            node_client,
213            bip353_client,
214            lnurl_client,
215        })
216    }
217
218    /// Load an existing [`LexeWallet`] with persistence from `lexe_data_dir`.
219    /// Returns [`None`] if no local data exists, in which case you should use
220    /// [`fresh`] to create the wallet and local data cache.
221    ///
222    /// If you are authenticating with [`RootSeed`]s and this returns [`None`],
223    /// you should call [`signup`] after creating the wallet if you're not sure
224    /// whether the user has been signed up with Lexe.
225    ///
226    /// It is recommended to always pass the same `lexe_data_dir`,
227    /// regardless of which environment we're in (dev/staging/prod) and which
228    /// user this [`LexeWallet`] is for. Users and environments will not
229    /// interfere with each other as all data is namespaced internally.
230    /// Defaults to `~/.lexe` if not specified.
231    ///
232    /// [`fresh`]: LexeWallet::fresh
233    /// [`signup`]: LexeWallet::signup
234    #[instrument(skip_all, name = "(load)")]
235    pub fn load(
236        env_config: WalletEnvConfig,
237        credentials: CredentialsRef<'_>,
238        lexe_data_dir: Option<PathBuf>,
239    ) -> anyhow::Result<Option<Self>> {
240        let lexe_data_dir =
241            lexe_data_dir.map_or_else(crate::default_lexe_data_dir, Ok)?;
242        let env_db_config =
243            WalletEnvDbConfig::new(env_config.wallet_env, lexe_data_dir);
244        let user_db_config =
245            WalletUserDbConfig::from_credentials(credentials, env_db_config)?;
246
247        let maybe_db = WalletDb::load(user_db_config)
248            .context("Failed to load wallet db")?;
249        let db = match maybe_db {
250            Some(d) => d,
251            None => return Ok(None),
252        };
253
254        let (
255            user_config,
256            gateway_client,
257            node_client,
258            bip353_client,
259            lnurl_client,
260        ) = Self::build_clients(env_config, credentials)?;
261
262        Ok(Some(Self {
263            user_config,
264            store: WalletStore::Db(Box::new(db)),
265            payments_bus: OnceCell::new(),
266            next_unused_address: Mutex::new(None),
267            gateway_client,
268            node_client,
269            bip353_client,
270            lnurl_client,
271        }))
272    }
273
274    /// Load an existing [`LexeWallet`] with persistence from `lexe_data_dir`,
275    /// or create a fresh one if no local data exists. If you are authenticating
276    /// with client credentials, this is generally what you want to use.
277    ///
278    /// It is recommended to always pass the same `lexe_data_dir`,
279    /// regardless of which environment we're in (dev/staging/prod) and which
280    /// user this [`LexeWallet`] is for. Users and environments will not
281    /// interfere with each other as all data is namespaced internally.
282    /// Defaults to `~/.lexe` if not specified.
283    #[instrument(skip_all, name = "(load-or-fresh)")]
284    pub fn load_or_fresh(
285        env_config: WalletEnvConfig,
286        credentials: CredentialsRef<'_>,
287        lexe_data_dir: Option<PathBuf>,
288    ) -> anyhow::Result<Self> {
289        let lexe_data_dir =
290            lexe_data_dir.map_or_else(crate::default_lexe_data_dir, Ok)?;
291        let env_db_config =
292            WalletEnvDbConfig::new(env_config.wallet_env, lexe_data_dir);
293        let user_db_config =
294            WalletUserDbConfig::from_credentials(credentials, env_db_config)?;
295
296        let db = WalletDb::load_or_fresh(user_db_config)
297            .context("Failed to load or create wallet db")?;
298
299        let (
300            user_config,
301            gateway_client,
302            node_client,
303            bip353_client,
304            lnurl_client,
305        ) = Self::build_clients(env_config, credentials)?;
306
307        Ok(Self {
308            user_config,
309            store: WalletStore::Db(Box::new(db)),
310            payments_bus: OnceCell::new(),
311            next_unused_address: Mutex::new(None),
312            gateway_client,
313            node_client,
314            bip353_client,
315            lnurl_client,
316        })
317    }
318
319    /// Create a [`LexeWallet`] without any persistence. It is recommended to
320    /// use [`fresh`] or [`load`] instead, to initialize with persistence.
321    ///
322    /// Node operations (invoices, payments, node info) work normally.
323    /// Local payment cache operations ([`sync_payments`], [`list_payments`],
324    /// [`clear_payments`]) are not available and will return an error.
325    ///
326    /// [`fresh`]: LexeWallet::fresh
327    /// [`load`]: LexeWallet::load
328    /// [`sync_payments`]: LexeWallet::sync_payments
329    /// [`list_payments`]: LexeWallet::list_payments
330    /// [`clear_payments`]: LexeWallet::clear_payments
331    #[instrument(skip_all, name = "(without-db)")]
332    pub fn without_db(
333        env_config: WalletEnvConfig,
334        credentials: CredentialsRef<'_>,
335    ) -> anyhow::Result<Self> {
336        let (
337            user_config,
338            gateway_client,
339            node_client,
340            bip353_client,
341            lnurl_client,
342        ) = Self::build_clients(env_config, credentials)?;
343
344        Ok(Self {
345            user_config,
346            store: WalletStore::Cache(Box::new(WalletCache {
347                payments: tokio::sync::RwLock::new(PaymentCache::new()),
348                address_synced_block_heights: Mutex::new(HashMap::new()),
349            })),
350            payments_bus: OnceCell::new(),
351            next_unused_address: Mutex::new(None),
352            gateway_client,
353            node_client,
354            bip353_client,
355            lnurl_client,
356        })
357    }
358
359    /// Helper to construct the required clients.
360    fn build_clients(
361        env_config: WalletEnvConfig,
362        credentials: CredentialsRef<'_>,
363    ) -> anyhow::Result<(
364        WalletUserConfig,
365        GatewayClient,
366        NodeClient,
367        Bip353Client,
368        LnurlClient,
369    )> {
370        let user_pk = credentials.user_pk().context(
371            "Client credentials are out of date. \
372             Please create a new one from within the Lexe wallet app.",
373        )?;
374
375        let user_config = WalletUserConfig {
376            user_pk,
377            env_config: env_config.clone(),
378        };
379
380        let gateway_client = GatewayClient::new(
381            env_config.wallet_env.deploy_env,
382            env_config.gateway_url.clone(),
383            env_config.user_agent.clone(),
384        )
385        .context("Failed to build GatewayClient")?;
386
387        let mut rng = SysRng::new();
388        let node_client = NodeClient::new(
389            &mut rng,
390            env_config.wallet_env.use_sgx,
391            env_config.wallet_env.deploy_env,
392            gateway_client.clone(),
393            credentials.to_unstable(),
394        )
395        .context("Failed to build NodeClient")?;
396
397        let bip353_client = Bip353Client::new(bip353::GOOGLE_DOH_ENDPOINT)
398            .context("Failed to build BIP353 client")?;
399
400        let lnurl_client = LnurlClient::new(env_config.wallet_env.deploy_env)
401            .context("Failed to build LNURL client")?;
402
403        Ok((
404            user_config,
405            gateway_client,
406            node_client,
407            bip353_client,
408            lnurl_client,
409        ))
410    }
411
412    // --- Store helpers --- //
413
414    /// Returns a reference to the [`WalletDb`], or an error if local
415    /// persistence is disabled for this wallet.
416    fn require_db(&self) -> anyhow::Result<&WalletDb<DiskFs>> {
417        match &self.store {
418            WalletStore::Db(db) => Ok(db),
419            WalletStore::Cache(_) =>
420                Err(anyhow!("Local persistence is disabled for this wallet")),
421        }
422    }
423
424    /// Returns a reference to the [`PaymentsDb`], or an error if local
425    /// persistence is disabled for this wallet.
426    fn require_payments_db(&self) -> anyhow::Result<&PaymentsDb<DiskFs>> {
427        self.require_db().map(WalletDb::payments_db)
428    }
429
430    async fn payments_bus(&self) -> anyhow::Result<&PaymentsBus> {
431        self.payments_bus
432            .get_or_try_init(|| async {
433                let latest_update = self.latest_payment_update().await?;
434                Ok(PaymentsBus::new(latest_update))
435            })
436            .await
437    }
438
439    /// From the local db if we have one, otherwise from the gateway.
440    async fn latest_payment_update(
441        &self,
442    ) -> anyhow::Result<Option<PaymentUpdatedIndex>> {
443        match self.payments_db() {
444            Some(payments_db) => Ok(payments_db.latest_updated_index()),
445            None => self.node_client.latest_payment_update().await,
446        }
447    }
448
449    // --- DB accessors (unstable) --- //
450
451    /// Returns `true` if local persistence is enabled for this wallet.
452    pub fn persistence_enabled(&self) -> bool {
453        matches!(self.store, WalletStore::Db(_))
454    }
455
456    /// Get a reference to the [`WalletDb`].
457    ///
458    /// Returns [`None`] if local persistence is disabled for this wallet.
459    #[cfg(feature = "unstable")]
460    pub fn db(&self) -> Option<&WalletDb<DiskFs>> {
461        self.require_db().ok()
462    }
463
464    cfg_if::cfg_if! {
465        if #[cfg(feature = "unstable")] {
466            /// Get a reference to the payments database.
467            /// This is the primary data source for constructing a payments
468            /// list UI.
469            ///
470            /// Returns [`None`] if local persistence is disabled for this
471            /// wallet.
472            pub fn payments_db(&self) -> Option<&PaymentsDb<DiskFs>> {
473                match &self.store {
474                    WalletStore::Db(db) => Some(db.payments_db()),
475                    WalletStore::Cache(_) => None,
476                }
477            }
478        } else {
479            /// Get a reference to the payments database.
480            /// This is the primary data source for constructing a payments
481            /// list UI.
482            ///
483            /// Returns [`None`] if local persistence is disabled for this
484            /// wallet.
485            pub(crate) fn payments_db(&self) -> Option<&PaymentsDb<DiskFs>> {
486                match &self.store {
487                    WalletStore::Db(db) => Some(db.payments_db()),
488                    WalletStore::Cache(_) => None,
489                }
490            }
491        }
492    }
493
494    // --- Client accessors --- //
495
496    /// Get a reference to the user's wallet configuration.
497    pub fn user_config(&self) -> &WalletUserConfig {
498        &self.user_config
499    }
500
501    /// Get a reference to the [`GatewayClient`].
502    #[cfg(feature = "unstable")]
503    pub fn gateway_client(&self) -> &GatewayClient {
504        &self.gateway_client
505    }
506
507    /// Get a reference to the [`NodeClient`].
508    #[cfg(feature = "unstable")]
509    pub fn node_client(&self) -> &NodeClient {
510        &self.node_client
511    }
512
513    /// Get a reference to the [`Bip353Client`].
514    #[cfg(feature = "unstable")]
515    pub fn bip353_client(&self) -> &Bip353Client {
516        &self.bip353_client
517    }
518
519    /// Get a reference to the [`LnurlClient`].
520    #[cfg(feature = "unstable")]
521    pub fn lnurl_client(&self) -> &LnurlClient {
522        &self.lnurl_client
523    }
524
525    // --- Node management --- //
526
527    /// Registers this user with Lexe, then provisions the node.
528    /// This method must be called after the user's [`LexeWallet`] has been
529    /// created for the first time, otherwise subsequent requests will fail.
530    ///
531    /// It is only necessary to call this method once, ever, per user, but it
532    /// is also okay to call this method even if the user has already been
533    /// signed up; in other words, this method is idempotent.
534    ///
535    /// After a successful signup, make sure the user's root seed has been
536    /// persisted somewhere! Without access to their root seed, your user will
537    /// lose their funds forever. If adding Lexe to a broader wallet, a good
538    /// strategy is to derive Lexe's [`RootSeed`] from your own root seed.
539    ///
540    /// - `partner_pk`: Set to your company's [`UserPk`] to earn a share of this
541    ///   wallet's fees.
542    #[instrument(skip_all, name = "(signup)")]
543    pub async fn signup(
544        &self,
545        root_seed: &RootSeed,
546        partner_pk: Option<UserPk>,
547    ) -> anyhow::Result<()> {
548        let allow_gvfs_access = false;
549        let backup_password = None;
550        let google_auth_code = None;
551
552        self.signup_inner(
553            root_seed,
554            partner_pk,
555            allow_gvfs_access,
556            backup_password,
557            google_auth_code,
558        )
559        .await
560    }
561
562    /// [`signup`](Self::signup) but with extra parameters generally only used
563    /// by the Lexe App.
564    #[cfg(feature = "unstable")]
565    #[instrument(skip_all, name = "(signup-custom)")]
566    pub async fn signup_custom(
567        &self,
568        root_seed: &RootSeed,
569        partner_pk: Option<UserPk>,
570        allow_gvfs_access: bool,
571        backup_password: Option<&str>,
572        google_auth_code: Option<String>,
573    ) -> anyhow::Result<()> {
574        self.signup_inner(
575            root_seed,
576            partner_pk,
577            allow_gvfs_access,
578            backup_password,
579            google_auth_code,
580        )
581        .await
582    }
583
584    // Inner implementation shared by both stable and unstable APIs.
585    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
586    async fn signup_inner(
587        &self,
588        root_seed: &RootSeed,
589        partner_pk: Option<UserPk>,
590        allow_gvfs_access: bool,
591        backup_password: Option<&str>,
592        google_auth_code: Option<String>,
593    ) -> anyhow::Result<()> {
594        // Derive keys and build signup request
595        let user_key_pair = root_seed.unstable().derive_user_key_pair();
596        let node_key_pair = root_seed.unstable().derive_node_key_pair();
597        let node_pk_proof = NodePkProof::sign(&node_key_pair);
598
599        let signup_req = UserSignupRequestWire::V2(UserSignupRequestWireV2 {
600            v1: UserSignupRequestWireV1::new(node_pk_proof),
601            partner: partner_pk.map(UserPk::unstable),
602        });
603        let signed_signup_req = user_key_pair
604            .sign_struct(&signup_req)
605            .map(|(_buf, signed)| signed)
606            .expect("Should never fail to serialize UserSignupRequestWire");
607
608        // Register with backend
609        self.gateway_client
610            .signup_v2(&signed_signup_req)
611            .await
612            .context("Failed to signup user")?;
613
614        // Encrypt seed if backup password provided.
615        // NOTE: This is very slow; 600K HMAC iterations!
616        let encrypted_seed = backup_password
617            .map(|password| root_seed.password_encrypt(password))
618            .transpose()
619            .context("Could not encrypt root seed under password")?;
620
621        // Initial provisioning
622        let credentials = CredentialsRef::from(root_seed);
623        self.provision_inner(
624            credentials,
625            allow_gvfs_access,
626            encrypted_seed,
627            google_auth_code,
628        )
629        .await
630        .context("Initial provision failed")?;
631
632        Ok(())
633    }
634
635    /// Ensures the wallet is provisioned to all recent trusted releases.
636    /// This should be called every time the wallet is loaded, to ensure the
637    /// node is running the most up-to-date enclave software.
638    ///
639    /// This fetches the current enclaves from the gateway, computes which
640    /// releases need to be provisioned, and provisions them.
641    #[instrument(skip_all, name = "(provision)")]
642    pub async fn provision(
643        &self,
644        credentials: CredentialsRef<'_>,
645    ) -> anyhow::Result<()> {
646        self.provision_inner(
647            credentials,
648            false, // allow_gvfs_access
649            None,  // encrypted_seed
650            None,  // google_auth_code
651        )
652        .await
653    }
654
655    /// [`provision`](Self::provision) but with extra parameters generally only
656    /// used by the Lexe App.
657    #[cfg(feature = "unstable")]
658    #[instrument(skip_all, name = "(provision-custom)")]
659    pub async fn provision_custom(
660        &self,
661        credentials: CredentialsRef<'_>,
662        allow_gvfs_access: bool,
663        encrypted_seed: Option<Vec<u8>>,
664        google_auth_code: Option<String>,
665    ) -> anyhow::Result<()> {
666        self.provision_inner(
667            credentials,
668            allow_gvfs_access,
669            encrypted_seed,
670            google_auth_code,
671        )
672        .await
673    }
674
675    // Inner implementation shared by both stable and unstable APIs.
676    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
677    async fn provision_inner(
678        &self,
679        credentials: CredentialsRef<'_>,
680        allow_gvfs_access: bool,
681        encrypted_seed: Option<Vec<u8>>,
682        google_auth_code: Option<String>,
683    ) -> anyhow::Result<()> {
684        // Only RootSeed can sign; delegated provisioning not implemented yet.
685        let CredentialsRef::RootSeed(_root_seed_ref) = credentials else {
686            return Err(anyhow!(
687                "Delegated provisioning is not implemented yet"
688            ));
689        };
690
691        let wallet_env = self.user_config.env_config.wallet_env;
692
693        // Get a bearer token for authentication.
694        let token = self
695            .node_client
696            .get_gateway_proxy_token()
697            .await
698            .context("Could not get bearer token")?;
699
700        // Build request with our trusted measurements.
701        let req = command::EnclavesToProvisionRequest {
702            trusted_measurements: provision::LATEST_TRUSTED_MEASUREMENTS
703                .clone(),
704        };
705
706        let enclaves_to_provision = self
707            .gateway_client
708            .enclaves_to_provision(&req, token)
709            .await
710            .context("Could not fetch enclaves to provision")?;
711
712        // Client-side verification: ensure backend only returned enclaves we
713        // trust. Skip in dev mode since measurements are mocked.
714        if wallet_env.deploy_env.is_staging_or_prod() {
715            let all_trusted =
716                enclaves_to_provision.enclaves.iter().all(|enclave| {
717                    provision::LATEST_TRUSTED_MEASUREMENTS
718                        .contains(&enclave.measurement)
719                });
720            ensure!(all_trusted, "Backend returned untrusted enclaves:");
721        }
722
723        if enclaves_to_provision.enclaves.is_empty() {
724            debug!("Already provisioned to all recent releases");
725            return Ok(());
726        }
727
728        info!("Provisioning enclaves: {enclaves_to_provision}");
729
730        match credentials {
731            CredentialsRef::RootSeed(root_seed_ref) => {
732                let root_seed = provision::clone_root_seed(root_seed_ref);
733
734                provision::provision_all(
735                    self.node_client.clone(),
736                    enclaves_to_provision.enclaves,
737                    root_seed,
738                    wallet_env,
739                    google_auth_code,
740                    allow_gvfs_access,
741                    encrypted_seed,
742                )
743                .await
744                .context("Root seed provision_all failed")?;
745            }
746            // TODO(max): Implement delegated provisioning
747            CredentialsRef::ClientCredentials(_) =>
748                return Err(anyhow!(
749                    "Delegated provisioning is not implemented yet"
750                )),
751        }
752
753        Ok(())
754    }
755
756    /// Get information about this Lexe node, including balance and channels.
757    #[instrument(skip_all, name = "(node-info)")]
758    pub async fn node_info(&self) -> anyhow::Result<NodeInfo> {
759        self.node_client
760            .node_info()
761            .await
762            .map(NodeInfo::from)
763            .context("Failed to get node info")
764    }
765
766    // --- Paying and receiving Bitcoin --- //
767
768    /// Get information about a Bitcoin or Lightning payment string, including:
769    /// - `payable`: The payable string encoding the payment method.
770    /// - `method`: The [`PaymentMethod`] struct encapsulating information
771    ///   specific to the payment method (e.g. payment hash, metadata, etc...)
772    /// - `amount`/`min_amount`/`max_amount`: The amount constraints requested
773    ///   by the receiver.
774    ///
775    /// See [`PayableDetails`] for all fields.
776    ///
777    /// The following encodings are supported:
778    ///   - BIP 321 URI: `bitcoin:bc1...`
779    ///   - Lightning URI: `lightning:ln...`
780    ///   - BOLT 11 invoice: `lnbc1...`
781    ///   - BOLT 12 offer: `lno1...`
782    ///   - Onchain bitcoin address: `bc1...`
783    ///   - Human Bitcoin Address: `â‚¿username@lexe.app`
784    ///   - Lightning Address: `username@lexe.app`
785    ///   - LNURL: `lnurl1...` or `lnurlp://domain.com/path`
786    ///   - Lexe link: `https://lexe.app/pay?to=...` or `lexe:...`
787    ///
788    /// Within the encodings, the following payment methods are supported:
789    ///   - BOLT 11 invoice
790    ///   - BOLT 12 offer
791    ///   - Bitcoin address
792    ///   - Lightning Address
793    ///   - LNURL
794    // Sync the encodings list with `pay`
795    #[instrument(skip_all, name = "(analyze)")]
796    pub async fn analyze(
797        &self,
798        req: AnalyzeRequest,
799    ) -> anyhow::Result<AnalyzeResponse> {
800        let network = self.user_config().env_config.wallet_env.network;
801        let payment_uri = PaymentUri::parse(&req.payment_string)?;
802
803        let PaymentUriMethods {
804            payment_methods,
805            claim_methods,
806            auth_methods,
807        } = lexe_payment_uri::resolve(
808            &self.bip353_client,
809            &self.lnurl_client,
810            network,
811            payment_uri,
812        )
813        .await
814        .context("Failed to resolve payment methods.")?;
815        if payment_methods.is_empty() && claim_methods.is_empty() {
816            let kind = auth_methods
817                .first()
818                .expect("resolve() ensures at least one method")
819                .kind();
820            return Err(anyhow!(
821                "Not a payment string: it is a {kind} request"
822            ));
823        }
824
825        let payables = payment_methods
826            .into_iter()
827            .map(|method| match &method {
828                PaymentMethod::Onchain {
829                    address,
830                    amount,
831                    label,
832                    message,
833                } => {
834                    let amount = *amount;
835                    let payable = if amount.is_some()
836                        || label.is_some()
837                        || message.is_some()
838                    {
839                        let bip_321_uri = Bip321Uri {
840                            onchain: vec![address.clone().into_unchecked()],
841                            amount,
842                            label: label.clone(),
843                            message: message.clone(),
844                            ..Default::default()
845                        };
846                        bip_321_uri.to_string()
847                    } else {
848                        address.to_string()
849                    };
850
851                    let description = message.to_owned();
852                    let min_amount = None;
853                    let max_amount = None;
854                    let expires_at = None;
855
856                    PayableDetails {
857                        payable,
858                        method,
859                        description,
860                        amount,
861                        min_amount,
862                        max_amount,
863                        expires_at,
864                    }
865                }
866                PaymentMethod::Invoice {
867                    invoice,
868                    lud12_comment,
869                } => {
870                    // Keep the LUD-12 comment so `pay` records it
871                    let payable = match lud12_comment {
872                        None => invoice.to_string(),
873                        Some(_) => {
874                            let bip_321_uri = Bip321Uri {
875                                invoice: Some(invoice.clone()),
876                                lud12_comment: lud12_comment.clone(),
877                                ..Default::default()
878                            };
879                            bip_321_uri.to_string()
880                        }
881                    };
882                    let description =
883                        invoice.description_str().map(str::to_owned);
884                    let amount = invoice.amount();
885                    let min_amount = None;
886                    let max_amount = None;
887                    let expires_at = invoice.expires_at().ok();
888
889                    PayableDetails {
890                        payable,
891                        method,
892                        description,
893                        amount,
894                        min_amount,
895                        max_amount,
896                        expires_at,
897                    }
898                }
899                PaymentMethod::Offer {
900                    offer,
901                    bip321_amount,
902                    human_bitcoin_address: _,
903                } => {
904                    let payable = match bip321_amount {
905                        None => offer.to_string(),
906                        Some(amount) => {
907                            let bip_321_uri = Bip321Uri {
908                                amount: Some(*amount),
909                                offer: Some(offer.clone()),
910                                ..Default::default()
911                            };
912                            bip_321_uri.to_string()
913                        }
914                    };
915
916                    let description = offer.description().map(str::to_owned);
917                    let amount = *bip321_amount;
918                    let min_amount = amount
919                        .is_none()
920                        .then_some(offer.min_amount())
921                        .flatten();
922                    let max_amount = None;
923                    let expires_at = offer.expires_at();
924
925                    PayableDetails {
926                        payable,
927                        method,
928                        description,
929                        amount,
930                        min_amount,
931                        max_amount,
932                        expires_at,
933                    }
934                }
935                PaymentMethod::LnurlPay {
936                    pay_request,
937                    lnurl,
938                    lightning_address: _,
939                } => {
940                    let payable = lnurl.to_string();
941                    let description = pay_request
942                        .metadata
943                        .long_description
944                        .to_owned()
945                        .or_else(|| {
946                            Some(pay_request.metadata.description.to_owned())
947                        });
948                    let amount = None;
949                    let min_amount = Some(pay_request.min_sendable);
950                    let max_amount = Some(pay_request.max_sendable);
951                    let expires_at = None;
952
953                    PayableDetails {
954                        payable,
955                        method,
956                        description,
957                        amount,
958                        min_amount,
959                        max_amount,
960                        expires_at,
961                    }
962                }
963            })
964            .collect();
965
966        let claimables = claim_methods
967            .into_iter()
968            .map(|method| match &method {
969                ClaimMethod::LnurlWithdraw {
970                    lnurl,
971                    withdraw_request,
972                } => {
973                    let claimable = lnurl.to_string();
974                    let description =
975                        Some(withdraw_request.default_description.to_owned());
976                    let min_amount = Some(withdraw_request.min_withdrawable);
977                    let max_amount = Some(withdraw_request.max_withdrawable);
978
979                    ClaimableDetails {
980                        claimable,
981                        method,
982                        description,
983                        min_amount,
984                        max_amount,
985                    }
986                }
987            })
988            .collect();
989
990        Ok(AnalyzeResponse {
991            payables,
992            claimables,
993        })
994    }
995
996    /// Pay any string which encodes a Bitcoin or Lightning payment method.
997    ///
998    /// If there exist multiple encoded payment methods, one best recommended
999    /// payment method will be chosen.
1000    ///
1001    /// Returns the resulting [`Payment`] once it reaches a terminal state
1002    /// (completed or failed). Exception: onchain sends return immediately with
1003    /// the payment still in `Pending` state, since on-chain confirmation takes
1004    /// ~1 hour.
1005    ///
1006    /// For finer control over how to pay, consider first using
1007    /// [`analyze`](Self::analyze) to resolve the contents of the
1008    /// payable string, then invoking the specific `pay` function for the
1009    /// payment method of choice: [`pay_invoice`](Self::pay_invoice),
1010    /// [`pay_offer`](Self::pay_offer), etc.
1011    ///
1012    /// The following encodings are supported:
1013    ///   - BIP 321 URI: `bitcoin:bc1...`
1014    ///   - Lightning URI: `lightning:ln...`
1015    ///   - BOLT 11 invoice: `lnbc1...`
1016    ///   - BOLT 12 offer: `lno1...`
1017    ///   - Onchain bitcoin address: `bc1...`
1018    ///   - Human Bitcoin Address: `â‚¿username@lexe.app`
1019    ///   - Lightning Address: `username@lexe.app`
1020    ///   - LNURL: `lnurl1...` or `lnurlp://domain.com/path`
1021    ///   - Lexe link: `https://lexe.app/pay?to=...` or `lexe:...`
1022    ///
1023    /// See [`PaymentMethod`] for more details on supported payment methods.
1024    // Sync the encodings list with `analyze`
1025    #[instrument(skip_all, name = "(pay)")]
1026    pub async fn pay(&self, req: PayRequest) -> anyhow::Result<Payment> {
1027        let PayRequest {
1028            payable,
1029            amount,
1030            message,
1031            personal_note,
1032        } = req;
1033
1034        // Validate note fields against Lexe's limits before any resolution
1035        let message = message
1036            .map(BoundedString::new)
1037            .transpose()
1038            .context("Invalid message")?;
1039        let personal_note = personal_note
1040            .map(BoundedString::new)
1041            .transpose()
1042            .context("Invalid personal note")?;
1043
1044        // Parse the string
1045        let payment_uri = PaymentUri::parse(&payable)
1046            .context("Failed to parse payable string")?;
1047
1048        // Error messages tied to the method can appear unrelated to the og URI;
1049        // "I analyzed LNURL, why is it talking about BOLT11 invoice?"
1050        let uri_err_context = match &payment_uri {
1051            PaymentUri::Bip321Uri(_) => "Failed to pay BIP321 URL",
1052            PaymentUri::LightningUri(_) => "Failed to pay Lightning URI",
1053            PaymentUri::Invoice(_) => "Failed to pay invoice",
1054            PaymentUri::Offer(_) => "Failed to pay offer",
1055            PaymentUri::Address(_) => "Failed to pay onchain address",
1056            PaymentUri::EmailLikeAddress(_) =>
1057                "Failed to pay HBA or Lightning Address",
1058            PaymentUri::Lnurl(_) => "Failed to pay LNURL",
1059            PaymentUri::LexeConnect(_) =>
1060                return Err(anyhow!("A LexeConnect request is not payable")),
1061            PaymentUri::LexePayUrl(_) | PaymentUri::LexeUri(_) =>
1062                "Failed to pay Lexe link",
1063        };
1064
1065        // Resolve into best payment method
1066        let bip353_client = &self.bip353_client;
1067        let lnurl_client = &self.lnurl_client;
1068        let network = self.user_config().env_config.wallet_env.network;
1069        let best_payment_method = lexe_payment_uri::resolve_best(
1070            bip353_client,
1071            lnurl_client,
1072            network,
1073            payment_uri,
1074        )
1075        .await?
1076        .payment_method
1077        .context("No payment method found")?;
1078
1079        // Validate and pay via the method-specific `pay_*` function
1080        self.pay_inner(best_payment_method, amount, message, personal_note)
1081            .await
1082            .context(uri_err_context)
1083    }
1084
1085    /// Pay the given [`PaymentMethod`] and return the resulting [`Payment`].
1086    //
1087    // This fn is extracted only so we can add uri_err_context above.
1088    async fn pay_inner(
1089        &self,
1090        best_method: PaymentMethod,
1091        amount: Option<Amount>,
1092        message: Option<BoundedString>,
1093        personal_note: Option<BoundedString>,
1094    ) -> anyhow::Result<Payment> {
1095        match best_method {
1096            PaymentMethod::Invoice {
1097                invoice,
1098                lud12_comment,
1099            } => {
1100                let fallback_amount = match (invoice.amount(), amount) {
1101                    (Some(amt), Some(given)) if amt != given =>
1102                        return Err(anyhow!(
1103                            "Given amount ({given} sats) doesn't match invoice \
1104                             amount ({amt} sats)"
1105                        )),
1106                    (Some(_), _) => None,
1107                    (None, Some(amt)) => Some(amt),
1108                    (None, None) =>
1109                        return Err(anyhow!(
1110                            "A payment amount must be provided for amountless \
1111                             invoices"
1112                        )),
1113                };
1114
1115                if message.is_some() {
1116                    warn!(
1117                        "BOLT 11 invoices do not support messages. \
1118                         The recipient will not see your message."
1119                    );
1120                }
1121
1122                // TODO(nicole): Consider reusing the preflighted route by
1123                // having `analyze` return a `state` field for the caller to
1124                // pass back into `pay`.
1125                let req = PayInvoiceRequest {
1126                    invoice,
1127                    fallback_amount,
1128                    lud12_comment,
1129                    personal_note: personal_note.map(BoundedString::into_inner),
1130                    partner_pk: None,
1131                    partner_prop_fee: None,
1132                    partner_base_fee: None,
1133                };
1134                self.pay_invoice(req).await
1135            }
1136            PaymentMethod::LnurlPay {
1137                pay_request,
1138                lnurl: _,
1139                lightning_address: _,
1140            } => {
1141                let amount = amount.context(
1142                    "A payment amount must be provided for LNURL payments",
1143                )?;
1144
1145                let pay_req = PayLnurlRequest {
1146                    lnurl: None,
1147                    pay_request: Some(pay_request),
1148                    amount,
1149                    message: message.map(BoundedString::into_inner),
1150                    personal_note: personal_note.map(BoundedString::into_inner),
1151                    partner_pk: None,
1152                    partner_prop_fee: None,
1153                    partner_base_fee: None,
1154                };
1155                self.pay_lnurl(pay_req).await
1156            }
1157            PaymentMethod::Offer {
1158                offer,
1159                bip321_amount,
1160                human_bitcoin_address: _,
1161            } => {
1162                let amount = match (bip321_amount, amount) {
1163                    (Some(amt), Some(given)) if amt != given =>
1164                        return Err(anyhow!(
1165                            "Given amount ({given} sats) doesn't match bip321 \
1166                             amount ({amt} sats)"
1167                        )),
1168                    (Some(amt), _) | (None, Some(amt)) => amt,
1169                    (None, None) =>
1170                        return Err(anyhow!(
1171                            "A payment amount must be provided for offers \
1172                             without a bip321-specified amount"
1173                        )),
1174                };
1175
1176                if let Some(min_amount) = offer.min_amount() {
1177                    ensure!(
1178                        min_amount <= amount,
1179                        "Given amount ({amount} sats) should be higher than the \
1180                         receiver's requested minimum amount: {min_amount} sats"
1181                    );
1182                }
1183
1184                let pay_req = PayOfferRequest {
1185                    offer,
1186                    amount,
1187                    client_payment_id: None,
1188                    message: message.map(BoundedString::into_inner),
1189                    personal_note: personal_note.map(BoundedString::into_inner),
1190                };
1191                self.pay_offer(pay_req).await
1192            }
1193            PaymentMethod::Onchain {
1194                amount: onchain_amount,
1195                address,
1196                ..
1197            } => {
1198                if message.is_some() {
1199                    warn!(
1200                        "On-chain payments do not support messages. \
1201                         The recipient will not see your message."
1202                    );
1203                }
1204
1205                let amount = match (onchain_amount, amount) {
1206                    (Some(amt), Some(given)) if amt != given =>
1207                        return Err(anyhow!(
1208                            "Given amount ({given} sats) doesn't match bip321 \
1209                             amount ({amt} sats)"
1210                        )),
1211                    (Some(amt), _) | (None, Some(amt)) => amt,
1212                    (None, None) =>
1213                        return Err(anyhow!(
1214                            "A payment amount must be provided for on-chain \
1215                             methods that don't suggest an amount"
1216                        )),
1217                };
1218
1219                let pay_req = PayOnchainRequest {
1220                    address: address.into_unchecked(),
1221                    amount,
1222                    priority: None,
1223                    client_payment_id: None,
1224                    personal_note: personal_note.map(BoundedString::into_inner),
1225                };
1226                self.pay_onchain(pay_req).await
1227            }
1228        }
1229    }
1230
1231    /// Create a BOLT 11 invoice to receive a Lightning payment.
1232    #[instrument(skip_all, name = "(create-invoice)")]
1233    pub async fn create_invoice(
1234        &self,
1235        req: CreateInvoiceRequest,
1236    ) -> anyhow::Result<CreateInvoiceResponse> {
1237        let req = command::CreateInvoiceRequest::try_from(req)?;
1238        let resp = self
1239            .node_client
1240            .create_invoice(req)
1241            .await
1242            .context("Failed to create invoice")?;
1243
1244        let index = resp.created_index.context("Node is out of date")?;
1245
1246        Ok(CreateInvoiceResponse::new(index, resp.invoice))
1247    }
1248
1249    /// Pay a BOLT 11 invoice over Lightning.
1250    ///
1251    /// Returns the resulting [`Payment`] once it reaches a terminal state
1252    /// (completed or failed).
1253    ///
1254    /// Idempotent: Safe to retry using the same `invoice.payment_hash`.
1255    /// If the payment already exists, it is returned.
1256    #[instrument(skip_all, name = "(pay-invoice)")]
1257    pub async fn pay_invoice(
1258        &self,
1259        req: PayInvoiceRequest,
1260    ) -> anyhow::Result<Payment> {
1261        let id = req.invoice.payment_id();
1262        let req = command::PayInvoiceRequest::try_from(req)?;
1263        let resp = self
1264            .node_client
1265            .pay_invoice(req)
1266            .await
1267            .context("Failed to pay invoice")?;
1268
1269        let index = PaymentCreatedIndex {
1270            created_at: resp.created_at,
1271            id,
1272        };
1273
1274        self.wait_for_payment(index, None).await
1275    }
1276
1277    /// Create a BOLT 12 offer to receive Lightning payments.
1278    ///
1279    /// Unlike invoices, offers are reusable: multiple payments can be made to
1280    /// it, including from multiple payers.
1281    #[instrument(skip_all, name = "(create-offer)")]
1282    pub async fn create_offer(
1283        &self,
1284        req: CreateOfferRequest,
1285    ) -> anyhow::Result<CreateOfferResponse> {
1286        let req = command::CreateOfferRequest::try_from(req)?;
1287        let resp = self
1288            .node_client
1289            .create_offer(req)
1290            .await
1291            .context("Failed to create offer")?;
1292
1293        Ok(CreateOfferResponse { offer: resp.offer })
1294    }
1295
1296    /// Pay a BOLT 12 offer over Lightning.
1297    ///
1298    /// Returns the resulting [`Payment`] once it reaches a terminal state
1299    /// (completed or failed).
1300    ///
1301    /// Idempotent: Safe to retry using the same `client_payment_id`.
1302    /// If the payment already exists, it is returned.
1303    #[instrument(skip_all, name = "(pay-offer)")]
1304    pub async fn pay_offer(
1305        &self,
1306        req: PayOfferRequest,
1307    ) -> anyhow::Result<Payment> {
1308        let req = req.into_unstable()?;
1309        let id = PaymentId::OfferSend(req.client_payment_id);
1310        let resp = self
1311            .node_client
1312            .pay_offer(req)
1313            .await
1314            .context("Failed to pay offer")?;
1315
1316        let index = PaymentCreatedIndex {
1317            created_at: resp.created_at,
1318            id,
1319        };
1320        self.wait_for_payment(index, None).await
1321    }
1322
1323    /// Get an unused Bitcoin address which can be used to receive on-chain
1324    /// funds.
1325    ///
1326    /// Returns an address with no payments to it as of the node's latest sync.
1327    /// Repeated calls return the same address until a payment is detected, so
1328    /// the address may have been previously issued to a different caller.
1329    /// Sending to it thus carries a small chance of address reuse.
1330    ///
1331    /// The upside, however, is that the node can afford to sync and check for
1332    /// payments to this address indefinitely. This method is thus suitable for
1333    /// peer-to-peer payments or as a possibly-reused deposit address.
1334    #[instrument(skip_all, name = "(get-next-unused-address)")]
1335    pub async fn get_next_unused_address(
1336        &self,
1337    ) -> anyhow::Result<GetNextUnusedAddressResponse> {
1338        // Ask the gateway for the latest payment update index. If it hasn't
1339        // moved since we cached an address, no payment can have used the
1340        // address, so return it without waking the node.
1341        let latest_update = self
1342            .node_client
1343            .latest_payment_update()
1344            .await
1345            .context("Failed to fetch latest payment update")?;
1346
1347        {
1348            let cache = self.next_unused_address.lock().unwrap();
1349            if let Some(cached) = cache.as_ref()
1350                && cached.latest_update == latest_update
1351            {
1352                return Ok(GetNextUnusedAddressResponse {
1353                    address: cached.address.clone(),
1354                });
1355            }
1356        }
1357
1358        let resp = self
1359            .node_client
1360            .get_next_unused_address()
1361            .await
1362            .context("Failed to get next unused address")?;
1363        let resp = GetNextUnusedAddressResponse::from(resp);
1364
1365        *self.next_unused_address.lock().unwrap() = Some(CachedUnusedAddress {
1366            address: resp.address.clone(),
1367            latest_update,
1368        });
1369
1370        Ok(resp)
1371    }
1372
1373    /// Get an exclusive Bitcoin address which can be used to receive on-chain
1374    /// funds.
1375    ///
1376    /// Every call returns a new address which has never been issued before, to
1377    /// this or any other client of this wallet, and never will be again. A
1378    /// payment to it can thus be attributed to exactly one caller, which suits
1379    /// per-invoice receives, e.g. a payment gateway issuing one address per
1380    /// invoice, or a service giving each customer their own deposit address.
1381    ///
1382    /// The node does not watch exclusive addresses for incoming payments. Funds
1383    /// sent to one are detected only when you call [`check_address`], so poll
1384    /// it for as long as you still expect a payment.
1385    ///
1386    /// If you only want to avoid address reuse, or to receive a one-off
1387    /// payment, use [`get_next_unused_address`] instead. It rotates after each
1388    /// payment, and the node watches it indefinitely.
1389    ///
1390    /// [`check_address`]: Self::check_address
1391    /// [`get_next_unused_address`]: Self::get_next_unused_address
1392    //
1393    // TODO(max): Once Lexe watches exclusive addresses after issue, replace the
1394    // "does not watch" paragraph here and in the mirrored docs with: "Lexe
1395    // watches an exclusive address for about 24 hours after it is issued.
1396    // After that, funds sent to it are detected only when you call
1397    // `check_address`, so poll it for as long as you still expect a payment."
1398    #[instrument(skip_all, name = "(get-exclusive-address)")]
1399    pub async fn get_exclusive_address(
1400        &self,
1401    ) -> anyhow::Result<GetExclusiveAddressResponse> {
1402        let resp = self
1403            .node_client
1404            .get_exclusive_address()
1405            .await
1406            .context("Failed to get exclusive address")?;
1407        Ok(GetExclusiveAddressResponse::from(resp))
1408    }
1409
1410    /// Check an address from [`get_exclusive_address`] for new payments,
1411    /// which the node does not otherwise detect. Records any payments to
1412    /// the address, then returns those that are unconfirmed, or confirmed
1413    /// at or after the previous check's block height (on the first check,
1414    /// all of them). A payment can thus be returned more than once.
1415    ///
1416    /// [`get_exclusive_address`]: Self::get_exclusive_address
1417    #[instrument(skip_all, name = "(check-address)")]
1418    pub async fn check_address(
1419        &self,
1420        address: bitcoin::Address<NetworkUnchecked>,
1421    ) -> anyhow::Result<CheckAddressResponse> {
1422        let network = self.user_config.env_config.wallet_env.network;
1423        let address = address
1424            .require_network(network.to_bitcoin())
1425            .with_context(|| format!("Address is not valid for {network}"))?;
1426        let synced_block_height =
1427            self.store.address_synced_block_height(&address);
1428
1429        let req = command::CheckAddressRequest {
1430            address: address.as_unchecked().clone(),
1431            synced_block_height,
1432        };
1433        let token = self
1434            .node_client
1435            .get_gateway_proxy_token()
1436            .await
1437            .context("Could not get bearer token")?;
1438        let resp = self
1439            .gateway_client
1440            .check_address(&req, token)
1441            .await
1442            .context("Failed to check address")?;
1443
1444        // We don't trust the gateway with payment data, so it reports only
1445        // ids and the payments themselves come from the node.
1446        let payments = match &self.store {
1447            WalletStore::Db(db) => {
1448                // We know the node has just recorded these payments, so skip
1449                // the latest_payment_update check and force a payment sync.
1450                if !resp.payment_ids.is_empty() {
1451                    db.force_sync_payments(
1452                        &self.node_client,
1453                        constants::DEFAULT_PAYMENTS_BATCH_SIZE,
1454                    )
1455                    .await?;
1456                }
1457                let payments_db = db.payments_db();
1458                resp.payment_ids
1459                    .iter()
1460                    .filter_map(|id| payments_db.get_payment_by_id(id))
1461                    .map(Payment::from)
1462                    .collect()
1463            }
1464            WalletStore::Cache(cache) => {
1465                let mut payment_cache = cache.payments.write().await;
1466                let mut payments = Vec::with_capacity(resp.payment_ids.len());
1467                for id in resp.payment_ids {
1468                    let payment = payment_cache
1469                        .get_or_fetch(id, &self.node_client)
1470                        .await?;
1471                    payments.extend(payment.cloned());
1472                }
1473                payments
1474            }
1475        };
1476
1477        if let Err(e) = self
1478            .store
1479            .set_address_synced_block_height(address, resp.synced_block_height)
1480        {
1481            // The height is only a cache, so losing it just means a wider
1482            // rescan on the next check.
1483            warn!("Failed to persist synced block height: {e:#}");
1484        }
1485
1486        Ok(CheckAddressResponse {
1487            payments,
1488            synced_block_height: resp.synced_block_height,
1489        })
1490    }
1491
1492    /// Send Bitcoin on-chain to the given address.
1493    ///
1494    /// Returns the resulting [`Payment`] without waiting for confirmations.
1495    /// On-chain sends finalize after 6 confirmations (~1 hour).
1496    ///
1497    /// Idempotent: Safe to retry using the same `client_payment_id`.
1498    /// If the payment already exists, it is returned.
1499    #[instrument(skip_all, name = "(pay-onchain)")]
1500    pub async fn pay_onchain(
1501        &self,
1502        req: PayOnchainRequest,
1503    ) -> anyhow::Result<Payment> {
1504        let req = command::PayOnchainRequest::try_from(req)?;
1505        let id = PaymentId::OnchainSend(req.client_payment_id);
1506        let resp = self
1507            .node_client
1508            .pay_onchain(req)
1509            .await
1510            .context("Failed to pay on-chain")?;
1511
1512        let index = PaymentCreatedIndex {
1513            created_at: resp.created_at,
1514            id,
1515        };
1516        self.get_payment(GetPaymentRequest { index })
1517            .await?
1518            .payment
1519            .context("Onchain payment missing right after creation")
1520    }
1521
1522    /// Preflight an on-chain send: validate the address and amount and
1523    /// estimate the fee at every priority, without sending.
1524    ///
1525    /// Send via [`pay_onchain`](Self::pay_onchain) with the chosen priority.
1526    #[instrument(skip_all, name = "(pay-onchain-preflight)")]
1527    pub async fn pay_onchain_preflight(
1528        &self,
1529        req: PayOnchainPreflightRequest,
1530    ) -> anyhow::Result<PayOnchainPreflightResponse> {
1531        let req = command::PayOnchainPreflightRequest::from(req);
1532        let resp = self
1533            .node_client
1534            .pay_onchain_preflight(req)
1535            .await
1536            .context("Failed to preflight on-chain send")?;
1537
1538        Ok(PayOnchainPreflightResponse {
1539            high_fees: resp.high.map(|est| est.amount),
1540            normal_fees: resp.normal.amount,
1541            background_fees: resp.background.amount,
1542        })
1543    }
1544
1545    /// Pay an LNURL or Lightning Address via the LNURL `payRequest` flow.
1546    ///
1547    /// Returns the resulting [`Payment`] once it reaches a terminal state
1548    /// (completed or failed).
1549    ///
1550    /// `pay_lnurl` is not currently idempotent. Each call will fetch and pay a
1551    /// different invoice.
1552    #[instrument(skip_all, name = "(pay-lnurl)")]
1553    pub async fn pay_lnurl(
1554        &self,
1555        req: PayLnurlRequest,
1556    ) -> anyhow::Result<Payment> {
1557        let message = req
1558            .message
1559            .map(BoundedString::new)
1560            .transpose()
1561            .context("Invalid message")?;
1562        let personal_note = req
1563            .personal_note
1564            .map(BoundedString::new)
1565            .transpose()
1566            .context("Invalid personal note")?;
1567
1568        // Get the pay request
1569        let pay_request = match (req.lnurl, req.pay_request) {
1570            (Some(s), None) => {
1571                // Try to parse as Lightning Address first
1572                let lnurl = if let Ok(e) = EmailLikeAddress::parse(&s) {
1573                    if e.bip353_prefix {
1574                        return Err(anyhow!(
1575                            "Expected a Lightning Address but found a \
1576                             â‚¿-prefixed BIP353 address: {s}"
1577                        ));
1578                    }
1579                    let http_url = e.lightning_address_url;
1580                    Lnurl::from_http_url(&http_url)?
1581                } else {
1582                    Lnurl::parse(&s)?
1583                };
1584
1585                self.lnurl_client
1586                    .get_pay_request(&lnurl)
1587                    .await
1588                    .context("Failed to resolve LNURL into pay request")?
1589            }
1590            (None, Some(pay_request)) => pay_request,
1591            _ =>
1592                return Err(anyhow!(
1593                    "Exactly one of `pay_request` or `lnurl` must be provided"
1594                )),
1595        };
1596
1597        // Truncate/remove the message based on `comment_allowed`
1598        let comment_allowed = pay_request.comment_allowed;
1599        let truncated_comment = message.and_then(|message| {
1600            let message_len = message.len();
1601            let Some(comment) = lexe_payment_uri::lnurl::fit_comment(
1602                message.into_inner(),
1603                comment_allowed,
1604            ) else {
1605                warn!(
1606                    "Recipient doesn't support LUD-12 comments; the recipient \
1607                     will not see your message."
1608                );
1609                return None;
1610            };
1611
1612            if comment.len() < message_len {
1613                let receiver_limit = comment_allowed.unwrap_or_default();
1614                warn!(
1615                    "Message truncated to {receiver_limit} character limit \
1616                     specified by recipient: \"{comment}\""
1617                );
1618            }
1619
1620            Some(BoundedString::new(comment).expect(
1621                "message was checked above and `fit_comment` only shortens \
1622                 it to a non-empty string, so it's still within bounds.",
1623            ))
1624        });
1625
1626        // Make the LNURL callback to get the invoice
1627        let invoice = self
1628            .lnurl_client
1629            .resolve_pay_request(
1630                &pay_request,
1631                req.amount,
1632                truncated_comment.as_deref(),
1633            )
1634            .await
1635            .context("Failed to resolve LNURL pay request")?
1636            .invoice;
1637
1638        // Pay invoice
1639        let id = invoice.payment_id();
1640        let invoice_req = command::PayInvoiceRequest {
1641            invoice,
1642            fallback_amount: None,
1643            lud12_comment: truncated_comment,
1644            personal_note,
1645            kind: PaymentKind::Invoice,
1646            ldk_route: None,
1647            partner_pk: req.partner_pk.map(|pk| pk.unstable()),
1648            partner_prop_fee: req.partner_prop_fee,
1649            partner_base_fee: req.partner_base_fee,
1650        };
1651        let invoice_resp = self
1652            .node_client
1653            .pay_invoice(invoice_req)
1654            .await
1655            .context("Failed to pay invoice from LNURL pay request")?;
1656
1657        let index = PaymentCreatedIndex {
1658            created_at: invoice_resp.created_at,
1659            id,
1660        };
1661
1662        self.wait_for_payment(index, None).await
1663    }
1664
1665    /// Withdraw an LNURL via the `withdrawRequest` flow.
1666    ///
1667    /// Returns the resulting [`Payment`] once the withdrawal reaches a
1668    /// terminal state (completed or failed).
1669    #[instrument(skip_all, name = "(withdraw-lnurl)")]
1670    pub async fn withdraw_lnurl(
1671        &self,
1672        req: WithdrawLnurlRequest,
1673    ) -> anyhow::Result<Payment> {
1674        /// The amount of time to wait for the payment after making
1675        /// the LNURL callback.
1676        const TIMEOUT: Duration = Duration::from_secs(60);
1677
1678        // Get the withdraw request
1679        let withdraw_request = match (req.lnurl, req.withdraw_request) {
1680            (Some(s), None) => {
1681                let lnurl = Lnurl::parse(&s)
1682                    .context("Failed to parse LNURL from string")?;
1683
1684                self.lnurl_client
1685                    .get_withdraw_request(&lnurl)
1686                    .await
1687                    .context("Failed to resolve LNURL into withdraw request")?
1688            }
1689            (None, Some(withdraw_request)) => withdraw_request,
1690            _ =>
1691                return Err(anyhow!(
1692                    "Exactly one of `withdraw_request` or \
1693                     `lnurl` must be provided"
1694                )),
1695        };
1696
1697        // Create an invoice according to the withdraw request.
1698        // A `None` amount withdraws the maximum allowed.
1699        let amount = match req.amount {
1700            Some(amt) => {
1701                // Ensure amount is within bounds
1702                ensure!(
1703                    withdraw_request.min_withdrawable <= amt,
1704                    "Given amount ({amt} sats) shouldn't be lower than the \
1705                     receiver's requested minimum amount: \
1706                     {} sats",
1707                    withdraw_request.min_withdrawable
1708                );
1709                ensure!(
1710                    amt <= withdraw_request.max_withdrawable,
1711                    "Given amount ({amt} sats) shouldn't be higher than the \
1712                     receiver's requested maximum amount: \
1713                     {} sats",
1714                    withdraw_request.max_withdrawable
1715                );
1716                amt
1717            }
1718            None => withdraw_request.max_withdrawable,
1719        };
1720
1721        let invoice_req = CreateInvoiceRequest {
1722            expiration_secs: None,
1723            amount: Some(amount),
1724            description: Some(req.description.unwrap_or_else(|| {
1725                withdraw_request.default_description.to_owned()
1726            })),
1727            description_hash: None,
1728            personal_note: req.personal_note,
1729            partner_pk: None,
1730            partner_prop_fee: None,
1731            partner_base_fee: None,
1732        };
1733        let invoice_resp = self
1734            .create_invoice(invoice_req)
1735            .await
1736            .context("Failed to create invoice for withdrawal request")?;
1737
1738        // Make the LNURL callback with the invoice
1739        self.lnurl_client
1740            .resolve_withdraw_request(&withdraw_request, invoice_resp.invoice)
1741            .await
1742            .context("Failed to make LNURL withdraw callback")?;
1743
1744        // Wait for the payment
1745        self.wait_for_payment(invoice_resp.index, Some(TIMEOUT))
1746            .await
1747            .context("Couldn't receive withdrawal payment")
1748    }
1749
1750    /// Buy Bitcoin with Cash App.
1751    ///
1752    /// Given an amount of Bitcoin that the user wants to buy, returns a Cash
1753    /// App URL that you can redirect your user to complete the purchase.
1754    /// Cash App buys are instant and land directly into Lexe wallet.
1755    ///
1756    /// For the smoothest user experience, you should encourage your user to
1757    /// open this URL on a device where Cash App is already set up.
1758    #[instrument(skip_all, name = "(buy-with-cash-app)")]
1759    pub async fn buy_with_cash_app(
1760        &self,
1761        req: CashAppBuyRequest,
1762    ) -> anyhow::Result<CashAppBuyResponse> {
1763        /// Cash App accepts smaller amounts, but we enforce a minimum for a
1764        /// good user experience.
1765        // TODO(max): Consider lowering this once we have better support for
1766        // small balances
1767        const MINIMUM_BUY_SATS: u32 = 5_000;
1768        /// The minted invoice's expiration, in seconds.
1769        const EXPIRATION_SECS: u32 = 60 * 60 * 2; // 2 hours
1770
1771        // Cash App buys real Bitcoin, so they only make sense on mainnet.
1772        let network = self.user_config.env_config.wallet_env.network;
1773        ensure!(
1774            network == Network::Mainnet,
1775            "Cash App buys are only available on mainnet. \
1776             (Current network: {})",
1777            network.as_str(),
1778        );
1779
1780        let amount = req.amount;
1781        let min_buy_amount = Amount::from_sats_u32(MINIMUM_BUY_SATS);
1782        ensure!(
1783            amount >= min_buy_amount,
1784            "Cash App buy amount ({amount} sats) must be at least \
1785             {min_buy_amount} sats"
1786        );
1787
1788        // Create the invoice with our internal create_invoice API instead of
1789        // SDK create_invoice so we can label it with `PaymentKind::BuyCashApp`.
1790        let invoice_req = command::CreateInvoiceRequest {
1791            expiration_secs: EXPIRATION_SECS,
1792            amount: Some(amount),
1793            description: Some("Cash App Buy".to_owned()),
1794            description_hash: None,
1795            lud12_comment: None,
1796            personal_note: None,
1797            kind: PaymentKind::BuyCashApp,
1798            partner_pk: None,
1799            partner_prop_fee: None,
1800            partner_base_fee: None,
1801        };
1802        let resp = self
1803            .node_client
1804            .create_invoice(invoice_req)
1805            .await
1806            .context("Failed to create invoice")?;
1807
1808        let index = resp.created_index.context("Node is out of date")?;
1809        let invoice = resp.invoice;
1810        let redirect_url =
1811            format!("https://cash.app/launch/lightning/{invoice}");
1812
1813        Ok(CashAppBuyResponse {
1814            redirect_url,
1815            index,
1816        })
1817    }
1818
1819    /// Get the user's Human Bitcoin Address.
1820    ///
1821    /// The Human Bitcoin Address (BIP 353), e.g. `â‚¿username@lexe.app`, is a
1822    /// human-readable address which others can pay to send Bitcoin to this
1823    /// wallet. It also works as a Lightning Address (`username@lexe.app`) for
1824    /// senders which support LNURL but not BIP 353.
1825    #[instrument(skip_all, name = "(get-human-bitcoin-address)")]
1826    pub async fn get_human_bitcoin_address(
1827        &self,
1828    ) -> anyhow::Result<GetHumanBitcoinAddressResponse> {
1829        let resp = self
1830            .node_client
1831            .get_human_bitcoin_address()
1832            .await
1833            .context("Failed to get Human Bitcoin Address")?;
1834        Ok(GetHumanBitcoinAddressResponse::from(resp.hba))
1835    }
1836
1837    /// Claim or update the user's custom Human Bitcoin Address.
1838    ///
1839    /// Sets this wallet's Human Bitcoin Address to `â‚¿{username}@lexe.app`
1840    /// and its Lightning Address to `{username}@lexe.app`. Usernames must
1841    /// be 6 to 24 characters of lowercase alphanumerics and hyphens, and
1842    /// must not start with, end with, or contain consecutive hyphens.
1843    ///
1844    /// Claiming requires a total wallet balance of at least 10000 sats. Once
1845    /// claimed, the username can be changed for 24 hours, then is frozen
1846    /// for 90 days.
1847    #[instrument(skip_all, name = "(update-human-bitcoin-address)")]
1848    pub async fn update_human_bitcoin_address(
1849        &self,
1850        username: &str,
1851    ) -> anyhow::Result<GetHumanBitcoinAddressResponse> {
1852        let username = Username::parse(username).context("Invalid username")?;
1853        let resp = self
1854            .node_client
1855            .upsert_custom_human_bitcoin_address(UsernameStruct { username })
1856            .await
1857            .context("Failed to update Human Bitcoin Address")?;
1858        Ok(GetHumanBitcoinAddressResponse::from(resp.hba))
1859    }
1860
1861    /// Create a payer proof for a completed outbound offer payment.
1862    ///
1863    /// The returned proof (`lnp1...`) proves to any third party that the
1864    /// offer's invoice was paid.
1865    #[instrument(skip_all, name = "(create-payer-proof)")]
1866    pub async fn create_payer_proof(
1867        &self,
1868        req: CreatePayerProofRequest,
1869    ) -> anyhow::Result<CreatePayerProofResponse> {
1870        let req = command::CreatePayerProofRequest::try_from(req)?;
1871        let resp = self
1872            .node_client
1873            .create_payer_proof(req)
1874            .await
1875            .context("Failed to create payer proof")?;
1876        Ok(CreatePayerProofResponse { proof: resp.proof })
1877    }
1878
1879    // --- Payment information and management --- //
1880
1881    /// Sync payments from the user node to the local payments cache.
1882    ///
1883    /// Returns an error if local persistence is disabled for this wallet.
1884    #[instrument(skip_all, name = "(sync-payments)")]
1885    pub async fn sync_payments(&self) -> anyhow::Result<PaymentSyncSummary> {
1886        let db = self.require_db()?;
1887
1888        // Get a bearer token for the update check with the gateway
1889        let auth = self
1890            .node_client
1891            .get_gateway_proxy_token()
1892            .await
1893            .context("Could not get bearer token")?;
1894
1895        // This only wakes the node if there are actually updates to fetch.
1896        db.sync_payments(
1897            &self.gateway_client,
1898            &self.node_client,
1899            auth,
1900            constants::DEFAULT_PAYMENTS_BATCH_SIZE,
1901        )
1902        .await
1903    }
1904
1905    /// List payments from local storage with cursor-based pagination.
1906    ///
1907    /// Defaults to descending order (newest first) with a limit of 100.
1908    ///
1909    /// To continue paginating, set `after` to the `next_index` from the
1910    /// previous response. `after` is an *exclusive* index.
1911    ///
1912    /// If needed, use [`sync_payments`] to fetch the latest data from the
1913    /// node before calling this method.
1914    ///
1915    /// Returns an error if local persistence is disabled for this wallet.
1916    ///
1917    /// [`sync_payments`]: Self::sync_payments
1918    #[instrument(skip_all, name = "(list-payments)")]
1919    pub fn list_payments(
1920        &self,
1921        filter: &PaymentFilter,
1922        order: Option<Order>,
1923        limit: Option<usize>,
1924        after: Option<&PaymentCreatedIndex>,
1925    ) -> anyhow::Result<ListPaymentsResponse> {
1926        let order = order.unwrap_or(Order::Desc);
1927        let limit = limit.unwrap_or(DEFAULT_LIST_LIMIT);
1928        let (basics, next_index) = self
1929            .require_payments_db()?
1930            .list_payments(filter, order, limit, after);
1931        let payments = basics.into_iter().map(Payment::from).collect();
1932        Ok(ListPaymentsResponse {
1933            payments,
1934            next_index,
1935        })
1936    }
1937
1938    /// Clear all locally cached payment data for this wallet.
1939    ///
1940    /// Clears the local payment cache only. Remote data on the node is not
1941    /// affected. Call [`sync_payments`](Self::sync_payments) to re-populate.
1942    ///
1943    /// Returns an error if local persistence is disabled for this wallet.
1944    #[instrument(skip_all, name = "(clear-payments)")]
1945    pub fn clear_payments(&self) -> anyhow::Result<()> {
1946        self.require_payments_db()?
1947            .clear()
1948            .context("Failed to clear local payments")
1949    }
1950
1951    /// Wait for a payment to reach a terminal state (completed or failed)
1952    /// and return the payment information.
1953    ///
1954    /// Blocks until the payment finalizes or the timeout is reached.
1955    /// A `None` timeout waits indefinitely.
1956    #[instrument(skip_all, name = "(wait-for-payment)")]
1957    pub async fn wait_for_payment(
1958        &self,
1959        index: PaymentCreatedIndex,
1960        timeout: Option<Duration>,
1961    ) -> anyhow::Result<Payment> {
1962        self.wait_for_payment_by_id(index.id, timeout).await
1963    }
1964
1965    /// Like [`wait_for_payment`](Self::wait_for_payment), but takes the
1966    /// payment's id.
1967    #[instrument(skip_all, name = "(wait-for-payment-by-id)")]
1968    pub async fn wait_for_payment_by_id(
1969        &self,
1970        id: PaymentId,
1971        timeout: Option<Duration>,
1972    ) -> anyhow::Result<Payment> {
1973        helpers::with_timeout(timeout, "Payment did not complete", async {
1974            self.payments_bus()
1975                .await?
1976                .wait_for_payment_condition(self, id, |payment| {
1977                    payment.status.is_finalized()
1978                })
1979                .await
1980        })
1981        .await
1982    }
1983
1984    /// Wait for an update on a specific payment, and return its latest state.
1985    ///
1986    /// To wait until a payment reaches some state, use
1987    /// [`wait_for_payment_condition`](Self::wait_for_payment_condition).
1988    /// Concurrent waiters share one poll loop.
1989    #[instrument(skip_all, name = "(wait-for-payment-update)")]
1990    pub async fn wait_for_payment_update(
1991        &self,
1992        req: WaitForPaymentUpdateRequest,
1993    ) -> anyhow::Result<Payment> {
1994        let WaitForPaymentUpdateRequest { id, after, timeout } = req;
1995        helpers::with_timeout(timeout, "No payment update", async {
1996            self.payments_bus()
1997                .await?
1998                .wait_for_payment_condition(self, id, |payment| {
1999                    // `Some(_) > None`, so `after: None` matches the
2000                    // current state.
2001                    Some(payment.updated_index()) > after
2002                })
2003                .await
2004        })
2005        .await
2006    }
2007
2008    /// Wait until a payment satisfies `condition`, and return it.
2009    ///
2010    /// Intermediate states may be skipped. Concurrent waiters share one poll
2011    /// loop. A `None` timeout waits indefinitely.
2012    #[instrument(skip_all, name = "(wait-for-payment-condition)")]
2013    pub async fn wait_for_payment_condition(
2014        &self,
2015        id: PaymentId,
2016        timeout: Option<Duration>,
2017        condition: impl FnMut(&Payment) -> bool,
2018    ) -> anyhow::Result<Payment> {
2019        helpers::with_timeout(timeout, "Payment condition not met", async {
2020            self.payments_bus()
2021                .await?
2022                .wait_for_payment_condition(self, id, condition)
2023                .await
2024        })
2025        .await
2026    }
2027
2028    /// Waits until we observe a payment updated later than `start_index`, then
2029    /// returns the payment. Useful for tailing payment updates one-by-one.
2030    ///
2031    /// - Handling should be idempotent. The same payment may be returned
2032    ///   multiple times due to receiving repeated updates.
2033    /// - If your application fails to handle a payment update, resuming from
2034    ///   the [`start_index`](WaitForNextPaymentRequest::start_index) that
2035    ///   yielded the failed update will *eventually* yield the same payment.
2036    ///
2037    /// If persistence is enabled, this will sync the local database.
2038    #[instrument(skip_all, name = "(wait-for-next-payment)")]
2039    pub async fn wait_for_next_payment(
2040        &self,
2041        req: WaitForNextPaymentRequest,
2042    ) -> anyhow::Result<WaitForNextPaymentResponse> {
2043        helpers::with_timeout(req.timeout, "No payment update", async {
2044            let start_index = match req.start_index {
2045                Some(start_index) => Some(start_index),
2046                None => self.latest_payment_update().await?,
2047            };
2048
2049            self.payments_bus()
2050                .await?
2051                .wait_for_next_update(self, start_index)
2052                .await?;
2053
2054            // This syncs the local db, if any.
2055            let req = GetUpdatedPaymentsRequest {
2056                start_index,
2057                limit: Some(1),
2058            };
2059            let payment = self
2060                .get_updated_payments(req)
2061                .await?
2062                .payments
2063                .into_iter()
2064                .next()
2065                .context(
2066                    "Internal error: Expected a payment update but found none.",
2067                )?;
2068
2069            Ok(WaitForNextPaymentResponse {
2070                next_start_index: payment.updated_index(),
2071                payment,
2072            })
2073        })
2074        .await
2075    }
2076
2077    /// Get information about a payment by its index.
2078    #[instrument(skip_all, name = "(get-payment)")]
2079    pub async fn get_payment(
2080        &self,
2081        req: GetPaymentRequest,
2082    ) -> anyhow::Result<GetPaymentResponse> {
2083        let req = GetPaymentByIdRequest { id: req.index.id };
2084        self.get_payment_by_id(req).await
2085    }
2086
2087    /// Get information about a payment by its id.
2088    #[instrument(skip_all, name = "(get-payment-by-id)")]
2089    pub async fn get_payment_by_id(
2090        &self,
2091        req: GetPaymentByIdRequest,
2092    ) -> anyhow::Result<GetPaymentResponse> {
2093        let payment = match &self.store {
2094            WalletStore::Db(db) => {
2095                self.sync_payments().await?;
2096                db.payments_db()
2097                    .get_payment_by_id(&req.id)
2098                    .map(Payment::from)
2099            }
2100            WalletStore::Cache(cache) => cache
2101                .payments
2102                .write()
2103                .await
2104                .get_or_fetch(req.id, &self.node_client)
2105                .await?
2106                .cloned(),
2107        };
2108
2109        Ok(GetPaymentResponse { payment })
2110    }
2111
2112    /// Get a batch of payments in ascending `updated_at` order, starting from
2113    /// `start_index`, exclusive. If `None`, starts from the oldest-updated
2114    /// payment, inclusive.
2115    ///
2116    /// Useful for tailing / syncing payment updates as they occur and merging
2117    /// them into a local payments store.
2118    #[instrument(skip_all, name = "(get-updated-payments)")]
2119    pub async fn get_updated_payments(
2120        &self,
2121        req: GetUpdatedPaymentsRequest,
2122    ) -> anyhow::Result<GetUpdatedPaymentsResponse> {
2123        // Serve from the local db when we have one.
2124        if let Some(payments_db) = self.payments_db() {
2125            self.sync_payments().await?;
2126
2127            let limit = req.limit.unwrap_or(usize::MAX);
2128            let payments = payments_db
2129                .get_updated_payments(req.start_index, limit)
2130                .into_iter()
2131                .map(Payment::from)
2132                .collect::<Vec<_>>();
2133            let updated_index = payments.last().map(Payment::updated_index);
2134
2135            return Ok(GetUpdatedPaymentsResponse {
2136                payments,
2137                updated_index,
2138            });
2139        }
2140        // Otherwise, if there is no db...
2141
2142        // Ask the gateway if there are new updates, and short circuit if none.
2143        // This avoids needlessly waking up the node. (If the gateway query is
2144        // failing we expect the node query to fail too.)
2145        let latest_update = self.node_client.latest_payment_update().await?;
2146
2147        // Some > None
2148        if latest_update <= req.start_index {
2149            return Ok(GetUpdatedPaymentsResponse {
2150                payments: Vec::new(),
2151                updated_index: None,
2152            });
2153        }
2154
2155        // Enforce node batch limit.
2156        let max_limit = constants::MAX_PAYMENTS_BATCH_SIZE;
2157        let limit = match req.limit {
2158            Some(limit) => {
2159                let limit = u16::try_from(limit).unwrap_or(u16::MAX);
2160                ensure!(
2161                    limit <= max_limit,
2162                    "Max limit of {max_limit} exceeded"
2163                );
2164                limit
2165            }
2166            None => max_limit,
2167        };
2168        let req = GetUpdatedPayments {
2169            start_index: req.start_index,
2170            limit: Some(limit),
2171        };
2172        let resp = self
2173            .node_client
2174            .get_updated_payments(req)
2175            .await
2176            .context("Failed to get updated payments")?;
2177        let updated_index = resp.payments.last().map(|p| p.updated_index());
2178        let payments = resp.payments.into_iter().map(Payment::from).collect();
2179        Ok(GetUpdatedPaymentsResponse {
2180            payments,
2181            updated_index,
2182        })
2183    }
2184
2185    /// Update the personal note on an existing payment.
2186    /// The note is stored on the user node and is not visible to the
2187    /// counterparty.
2188    #[instrument(skip_all, name = "(update-personal-note)")]
2189    pub async fn update_personal_note(
2190        &self,
2191        req: UpdatePersonalNoteRequest,
2192    ) -> anyhow::Result<()> {
2193        let req = command::UpdatePersonalNote::try_from(req)?;
2194
2195        // Update remote store first
2196        self.node_client
2197            .update_personal_note(req)
2198            .await
2199            .context("Failed to update personal note on user node")?;
2200
2201        // Success. If persistence is enabled, sync the updated note into the
2202        // local payments store.
2203        if self.persistence_enabled() {
2204            self.sync_payments().await?;
2205        }
2206
2207        Ok(())
2208    }
2209
2210    /// Cancel an inbound invoice payment. Idempotent.
2211    #[instrument(skip_all, name = "(cancel-payment)")]
2212    pub async fn cancel_payment(
2213        &self,
2214        req: CancelPaymentRequest,
2215    ) -> anyhow::Result<()> {
2216        // Check locally-known payment state first, so the node is only woken
2217        // when there is actually something to cancel.
2218        let payment = self
2219            .get_payment(GetPaymentRequest { index: req.index })
2220            .await
2221            .context("Could not get payment")?
2222            .payment
2223            .context("Payment not found")?;
2224
2225        match payment.status {
2226            PaymentStatus::Pending => (),
2227            // Idempotency: canceling an already-canceled payment returns Ok.
2228            PaymentStatus::Failed
2229                if payment.status_msg.contains("canceled") =>
2230                return Ok(()),
2231            PaymentStatus::Completed | PaymentStatus::Failed => {
2232                let status_msg = &payment.status_msg;
2233                return Err(anyhow!("Payment already finalized: {status_msg}"));
2234            }
2235        }
2236
2237        // Keep this in sync with `PaymentsManager::cancel_payment`.
2238        let cancelable = matches!(
2239            (&payment.rail, payment.direction),
2240            (PaymentRail::Invoice, PaymentDirection::Inbound)
2241        );
2242        ensure!(cancelable, "Only inbound invoice payments can be canceled");
2243
2244        // Cancel on the user node
2245        let req = command::CancelPaymentRequest::from(req);
2246        self.node_client
2247            .cancel_payment(req)
2248            .await
2249            .context("Failed to cancel payment on user node")?;
2250
2251        // Success. If persistence is enabled, sync the updated payment status
2252        // into the local payments store.
2253        if self.persistence_enabled() {
2254            self.sync_payments().await?;
2255        }
2256
2257        Ok(())
2258    }
2259
2260    // --- Channel management --- //
2261
2262    /// List this node's Lightning channels.
2263    ///
2264    /// All of this node's Lightning channels are connected to the Lexe LSP.
2265    #[instrument(skip_all, name = "(list-channels)")]
2266    pub async fn list_channels(&self) -> anyhow::Result<ListChannelsResponse> {
2267        let resp = self
2268            .node_client
2269            .list_channels()
2270            .await
2271            .context("Failed to list channels")?;
2272        let channels = resp
2273            .channels
2274            .into_iter()
2275            .map(ChannelDetails::from)
2276            .collect();
2277
2278        Ok(ListChannelsResponse { channels })
2279    }
2280
2281    /// Open a Lightning channel from this node to Lexe's LSP.
2282    ///
2283    /// Returns the channel id of the newly opened channel.
2284    #[instrument(skip_all, name = "(open-channel)")]
2285    pub async fn open_channel(
2286        &self,
2287        req: OpenChannelRequest,
2288    ) -> anyhow::Result<OpenChannelResponse> {
2289        // Use the caller's idempotency key if provided; otherwise generate a
2290        // fresh one, which still guards against duplicate opens on retries of
2291        // the resulting request.
2292        let user_channel_id = req
2293            .user_channel_id
2294            .unwrap_or_else(|| UserChannelId::from_rng(&mut SysRng::new()));
2295        let cmd_req = command::OpenChannelRequest {
2296            user_channel_id,
2297            value: req.value,
2298        };
2299        let resp = self
2300            .node_client
2301            .open_channel(cmd_req)
2302            .await
2303            .context("Failed to open channel")?;
2304
2305        Ok(OpenChannelResponse {
2306            channel_id: resp.channel_id,
2307            user_channel_id,
2308        })
2309    }
2310
2311    /// Close a Lightning channel between this node and Lexe's LSP.
2312    #[instrument(skip_all, name = "(close-channel)")]
2313    pub async fn close_channel(
2314        &self,
2315        req: CloseChannelRequest,
2316    ) -> anyhow::Result<()> {
2317        self.node_client
2318            .close_channel(command::CloseChannelRequest::from(req))
2319            .await
2320            .context("Failed to close channel")?;
2321        Ok(())
2322    }
2323
2324    // --- Client credentials management --- //
2325
2326    /// Get info about the credentials associated with this `LexeWallet`.
2327    ///
2328    /// Includes granted scopes and permissions, expiration, etc.
2329    #[instrument(skip_all, name = "(client-info)")]
2330    pub async fn client_info(&self) -> anyhow::Result<GetClientInfoResponse> {
2331        let resp = self.node_client.client_info().await?;
2332        GetClientInfoResponse::try_from(resp)
2333    }
2334
2335    /// List the active clients for this node.
2336    ///
2337    /// Revoked and expired clients are not included.
2338    #[instrument(skip_all, name = "(list-clients)")]
2339    pub async fn list_clients(&self) -> anyhow::Result<ListClientsResponse> {
2340        let req = revocable_clients::models::ListRevocableClients {
2341            valid_only: true,
2342        };
2343        let clients = self
2344            .node_client
2345            .list_revocable_clients(req)
2346            .await?
2347            .clients
2348            .into_iter()
2349            .map(|(pk, rc)| ClientInfo::try_from(rc).map(|info| (pk, info)))
2350            .collect::<anyhow::Result<_>>()?;
2351
2352        Ok(ListClientsResponse { clients })
2353    }
2354
2355    /// Create new client credentials for this node.
2356    #[instrument(skip_all, name = "(create-client)")]
2357    pub async fn create_client(
2358        &self,
2359        req: CreateClientRequest,
2360    ) -> anyhow::Result<CreateClientResponse> {
2361        let req =
2362            revocable_clients::models::CreateRevocableClientRequest::try_from(
2363                req,
2364            )?;
2365        ensure!(
2366            !req.permissions.is_empty(),
2367            "Must grant at least one scope or permission"
2368        );
2369        let (client_with_budget, client_creds, effective_permissions) =
2370            self.node_client.create_client_credentials(req).await?;
2371        let budget = client_with_budget
2372            .budget
2373            .map(BudgetInfo::try_from)
2374            .transpose()?;
2375
2376        Ok(CreateClientResponse {
2377            client_pk: client_creds.client_pk,
2378            client_credentials: ClientCredentials::from_unstable(client_creds),
2379            created_at: client_with_budget.client.created_at,
2380            effective_permissions,
2381            budget,
2382        })
2383    }
2384
2385    /// Update a client's label, expiration, scopes, permissions, or budget.
2386    ///
2387    /// Omitted label, expiration, and budget fields are unchanged. If
2388    /// `new_scopes` or `new_permissions` is provided, together they replace
2389    /// the client's complete grant; an omitted set is treated as empty.
2390    #[instrument(skip_all, name = "(update-client)")]
2391    pub async fn update_client(
2392        &self,
2393        req: UpdateClientRequest,
2394    ) -> anyhow::Result<ClientInfoResponse> {
2395        if req.new_scopes.is_some() || req.new_permissions.is_some() {
2396            ensure!(
2397                req.new_scopes.as_ref().is_some_and(|x| !x.is_empty())
2398                    || req
2399                        .new_permissions
2400                        .as_ref()
2401                        .is_some_and(|x| !x.is_empty()),
2402                "Must grant at least one scope or permission",
2403            );
2404        }
2405        let req =
2406            revocable_clients::models::UpdateClientWithBudgetRequest::try_from(
2407                req,
2408            )?;
2409        let client =
2410            self.node_client.update_revocable_client(req).await?.client;
2411        Ok(ClientInfoResponse {
2412            client: ClientInfo::try_from(client)?,
2413        })
2414    }
2415
2416    /// Permanently revoke a client, making its credentials invalid for
2417    /// authentication. This cannot be undone.
2418    #[instrument(skip_all, name = "(revoke-client)")]
2419    pub async fn revoke_client(
2420        &self,
2421        req: RevokeClientRequest,
2422    ) -> anyhow::Result<ClientInfoResponse> {
2423        let req = revocable_clients::models::UpdateClientRequest {
2424            pubkey: req.client_pk,
2425            is_revoked: Some(true),
2426            label: None,
2427            expires_at: None,
2428            permissions: None,
2429        };
2430        let req =
2431            revocable_clients::models::UpdateClientWithBudgetRequest::from(req);
2432        let client =
2433            self.node_client.update_revocable_client(req).await?.client;
2434        Ok(ClientInfoResponse {
2435            client: ClientInfo::try_from(client)?,
2436        })
2437    }
2438}
2439
2440impl WalletUpdatesApi for LexeWallet {
2441    async fn get_updated_payments(
2442        &self,
2443        req: GetUpdatedPaymentsRequest,
2444    ) -> anyhow::Result<GetUpdatedPaymentsResponse> {
2445        LexeWallet::get_updated_payments(self, req).await
2446    }
2447
2448    async fn get_payment_by_id(
2449        &self,
2450        req: GetPaymentByIdRequest,
2451    ) -> anyhow::Result<GetPaymentResponse> {
2452        LexeWallet::get_payment_by_id(self, req).await
2453    }
2454}
2455
2456mod payment_cache {
2457    use std::collections::hash_map::Entry;
2458
2459    use super::*;
2460
2461    /// A nonexhaustive in-memory cache of payments.
2462    pub struct PaymentCache {
2463        payments: HashMap<PaymentId, Option<Payment>>,
2464
2465        /// Entries in the payment cache are up to date as of the invalidation
2466        /// key's index. If the node's updates are ahead of this index, then
2467        /// assume the cached entries are stale.
2468        invalidation_key: Option<PaymentUpdatedIndex>,
2469    }
2470
2471    impl PaymentCache {
2472        pub fn new() -> Self {
2473            Self {
2474                payments: HashMap::new(),
2475                invalidation_key: None,
2476            }
2477        }
2478
2479        /// Get the payment, fetching it from the node if not cached. Clears
2480        /// the cache first if the node has newer updates.
2481        pub async fn get_or_fetch(
2482            &mut self,
2483            payment_id: PaymentId,
2484            node_client: &NodeClient,
2485        ) -> anyhow::Result<Option<&Payment>> {
2486            let latest_update = node_client.latest_payment_update().await?;
2487
2488            // No payments at all, so there is nothing to look up or cache.
2489            if latest_update.is_none() {
2490                return Ok(None);
2491            }
2492
2493            // Update the cache invalidation key if needed.
2494            match latest_update.cmp(&self.invalidation_key) {
2495                Ordering::Greater => {
2496                    // Case: cache is stale
2497                    // TODO(nicole): add `get_payment_batch` API that lets
2498                    // us update all cached payments; add eviction policy
2499                    self.payments.clear();
2500                    self.invalidation_key = latest_update;
2501                }
2502                // Case: cache is up-to-date
2503                Ordering::Equal => (),
2504                Ordering::Less =>
2505                    return Err(anyhow!(
2506                        "Lexe err: Payments cache became malformed. \
2507                         Node's latest_update is {latest_update:?} but \
2508                         cache's invalidation key is {:?}. Please report.",
2509                        self.invalidation_key
2510                    )),
2511            }
2512
2513            // Fall back to the node if the payment isn't cached yet.
2514            let payment = match self.payments.entry(payment_id) {
2515                Entry::Occupied(entry) => entry.into_mut(),
2516                Entry::Vacant(entry) => {
2517                    let req = PaymentIdStruct { id: payment_id };
2518                    let payment = node_client
2519                        .get_payment_by_id(req)
2520                        .await?
2521                        .maybe_payment
2522                        .map(Payment::from);
2523                    entry.insert(payment)
2524                }
2525            };
2526
2527            Ok(payment.as_ref())
2528        }
2529    }
2530}
2531
2532mod helpers {
2533    use super::*;
2534
2535    /// Await `fut`, or fail with "{what} within {timeout}s timeout" once the
2536    /// timeout (if any) elapses.
2537    pub(super) async fn with_timeout<T>(
2538        timeout: Option<Duration>,
2539        what: &str,
2540        fut: impl Future<Output = anyhow::Result<T>>,
2541    ) -> anyhow::Result<T> {
2542        let Some(timeout) = timeout else {
2543            return fut.await;
2544        };
2545        let timeout_secs = timeout.as_secs();
2546        tokio::time::timeout(timeout, fut)
2547            .await
2548            .map_err(|_| anyhow!("{what} within {timeout_secs}s timeout"))?
2549    }
2550}