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
80const DEFAULT_LIST_LIMIT: usize = 100;
82
83pub struct LexeWallet {
85 user_config: WalletUserConfig,
86
87 store: WalletStore,
88 payments_bus: OnceCell<PaymentsBus>,
89
90 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
99enum WalletStore {
102 Db(Box<WalletDb<DiskFs>>),
105 Cache(Box<WalletCache>),
107}
108
109struct WalletCache {
111 payments: tokio::sync::RwLock<PaymentCache>,
112 address_synced_block_heights: Mutex<HashMap<bitcoin::Address, u32>>,
115}
116
117impl WalletStore {
118 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 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
159struct CachedUnusedAddress {
164 address: bitcoin::Address<bitcoin::address::NetworkUnchecked>,
165 latest_update: Option<PaymentUpdatedIndex>,
166}
167
168impl LexeWallet {
172 #[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 #[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 #[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 #[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 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 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 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 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 pub fn persistence_enabled(&self) -> bool {
453 matches!(self.store, WalletStore::Db(_))
454 }
455
456 #[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 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 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 pub fn user_config(&self) -> &WalletUserConfig {
498 &self.user_config
499 }
500
501 #[cfg(feature = "unstable")]
503 pub fn gateway_client(&self) -> &GatewayClient {
504 &self.gateway_client
505 }
506
507 #[cfg(feature = "unstable")]
509 pub fn node_client(&self) -> &NodeClient {
510 &self.node_client
511 }
512
513 #[cfg(feature = "unstable")]
515 pub fn bip353_client(&self) -> &Bip353Client {
516 &self.bip353_client
517 }
518
519 #[cfg(feature = "unstable")]
521 pub fn lnurl_client(&self) -> &LnurlClient {
522 &self.lnurl_client
523 }
524
525 #[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 #[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 #[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 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 self.gateway_client
610 .signup_v2(&signed_signup_req)
611 .await
612 .context("Failed to signup user")?;
613
614 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 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 #[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, None, None, )
652 .await
653 }
654
655 #[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 #[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 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 let token = self
695 .node_client
696 .get_gateway_proxy_token()
697 .await
698 .context("Could not get bearer token")?;
699
700 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 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 CredentialsRef::ClientCredentials(_) =>
748 return Err(anyhow!(
749 "Delegated provisioning is not implemented yet"
750 )),
751 }
752
753 Ok(())
754 }
755
756 #[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 #[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 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 #[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 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 let payment_uri = PaymentUri::parse(&payable)
1046 .context("Failed to parse payable string")?;
1047
1048 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 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 self.pay_inner(best_payment_method, amount, message, personal_note)
1081 .await
1082 .context(uri_err_context)
1083 }
1084
1085 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 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 #[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 #[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 #[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 #[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 #[instrument(skip_all, name = "(get-next-unused-address)")]
1335 pub async fn get_next_unused_address(
1336 &self,
1337 ) -> anyhow::Result<GetNextUnusedAddressResponse> {
1338 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 #[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 #[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 let payments = match &self.store {
1447 WalletStore::Db(db) => {
1448 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 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 #[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 #[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 #[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 let pay_request = match (req.lnurl, req.pay_request) {
1570 (Some(s), None) => {
1571 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 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 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 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 #[instrument(skip_all, name = "(withdraw-lnurl)")]
1670 pub async fn withdraw_lnurl(
1671 &self,
1672 req: WithdrawLnurlRequest,
1673 ) -> anyhow::Result<Payment> {
1674 const TIMEOUT: Duration = Duration::from_secs(60);
1677
1678 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 let amount = match req.amount {
1700 Some(amt) => {
1701 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 self.lnurl_client
1740 .resolve_withdraw_request(&withdraw_request, invoice_resp.invoice)
1741 .await
1742 .context("Failed to make LNURL withdraw callback")?;
1743
1744 self.wait_for_payment(invoice_resp.index, Some(TIMEOUT))
1746 .await
1747 .context("Couldn't receive withdrawal payment")
1748 }
1749
1750 #[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 const MINIMUM_BUY_SATS: u32 = 5_000;
1768 const EXPIRATION_SECS: u32 = 60 * 60 * 2; 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 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 #[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 #[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 #[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 #[instrument(skip_all, name = "(sync-payments)")]
1885 pub async fn sync_payments(&self) -> anyhow::Result<PaymentSyncSummary> {
1886 let db = self.require_db()?;
1887
1888 let auth = self
1890 .node_client
1891 .get_gateway_proxy_token()
1892 .await
1893 .context("Could not get bearer token")?;
1894
1895 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 #[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 #[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 #[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 #[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 #[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(payment.updated_index()) > after
2002 })
2003 .await
2004 })
2005 .await
2006 }
2007
2008 #[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 #[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 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 #[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 #[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 #[instrument(skip_all, name = "(get-updated-payments)")]
2119 pub async fn get_updated_payments(
2120 &self,
2121 req: GetUpdatedPaymentsRequest,
2122 ) -> anyhow::Result<GetUpdatedPaymentsResponse> {
2123 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 let latest_update = self.node_client.latest_payment_update().await?;
2146
2147 if latest_update <= req.start_index {
2149 return Ok(GetUpdatedPaymentsResponse {
2150 payments: Vec::new(),
2151 updated_index: None,
2152 });
2153 }
2154
2155 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 #[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 self.node_client
2197 .update_personal_note(req)
2198 .await
2199 .context("Failed to update personal note on user node")?;
2200
2201 if self.persistence_enabled() {
2204 self.sync_payments().await?;
2205 }
2206
2207 Ok(())
2208 }
2209
2210 #[instrument(skip_all, name = "(cancel-payment)")]
2212 pub async fn cancel_payment(
2213 &self,
2214 req: CancelPaymentRequest,
2215 ) -> anyhow::Result<()> {
2216 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 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 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 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 if self.persistence_enabled() {
2254 self.sync_payments().await?;
2255 }
2256
2257 Ok(())
2258 }
2259
2260 #[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 #[instrument(skip_all, name = "(open-channel)")]
2285 pub async fn open_channel(
2286 &self,
2287 req: OpenChannelRequest,
2288 ) -> anyhow::Result<OpenChannelResponse> {
2289 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 #[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 #[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 #[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 #[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 #[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 #[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 pub struct PaymentCache {
2463 payments: HashMap<PaymentId, Option<Payment>>,
2464
2465 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 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 if latest_update.is_none() {
2490 return Ok(None);
2491 }
2492
2493 match latest_update.cmp(&self.invalidation_key) {
2495 Ordering::Greater => {
2496 self.payments.clear();
2500 self.invalidation_key = latest_update;
2501 }
2502 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 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 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}