1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::module_name_repetitions)]
6#![allow(clippy::must_use_candidate)]
7#![allow(clippy::too_many_lines)]
8
9pub use fedimint_ln_common as common;
10
11pub mod api;
12#[cfg(feature = "cli")]
13pub mod cli;
14pub mod db;
15pub mod error;
16pub mod events;
17pub mod incoming;
18pub mod pay;
19pub mod receive;
20pub mod recurring;
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::iter::once;
25use std::str::FromStr;
26use std::sync::Arc;
27use std::time::Duration;
28
29use api::LnFederationApi;
30use async_stream::{stream, try_stream};
31use bitcoin::Network;
32use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256};
33use db::{
34 DbKeyPrefix, LightningGatewayKey, LightningGatewayKeyPrefix, PaymentResult, PaymentResultKey,
35 RecurringPaymentCodeKeyPrefix,
36};
37use fedimint_api_client::api::{DynModuleApi, FederationError, FederationResult, ServerError};
38use fedimint_client_module::db::{ClientModuleMigrationFn, migrate_state};
39use fedimint_client_module::error::{ClientModuleError, TransactionSubmitError};
40use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
41use fedimint_client_module::module::recovery::NoModuleBackup;
42use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
43use fedimint_client_module::oplog::UpdateStreamOrOutcome;
44use fedimint_client_module::sm::{DynState, ModuleNotifier, State, StateTransition};
45use fedimint_client_module::transaction::{
46 ClientInput, ClientInputBundle, ClientOutput, ClientOutputBundle, ClientOutputSM, FeeQuote,
47 FeeQuoteRequest, TransactionBuilder, max_affordable_send_amount,
48};
49use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
50use fedimint_core::bolt11::{currency_for_network, currency_matches_network};
51use fedimint_core::config::FederationId;
52use fedimint_core::core::{
53 Account, Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId,
54};
55use fedimint_core::db::{DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped};
56use fedimint_core::encoding::{Decodable, Encodable};
57use fedimint_core::module::{
58 Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
59};
60use fedimint_core::secp256k1::{
61 All, Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing, Verification,
62};
63use fedimint_core::task::{MaybeSend, MaybeSync, timeout};
64use fedimint_core::util::update_merge::UpdateMerge;
65use fedimint_core::util::{BoxStream, FmtCompact as _, backoff_util, retry};
66use fedimint_core::{
67 Amount, OutPoint, apply, async_trait_maybe_send, push_db_pair_items, runtime, secp256k1,
68};
69use fedimint_derive_secret::{ChildId, DerivableSecret};
70use fedimint_ln_common::client::GatewayApi;
71use fedimint_ln_common::config::{FeeToAmount, LightningClientConfig};
72use fedimint_ln_common::contracts::incoming::{IncomingContract, IncomingContractOffer};
73use fedimint_ln_common::contracts::outgoing::{
74 OutgoingContract, OutgoingContractAccount, OutgoingContractData,
75};
76use fedimint_ln_common::contracts::{
77 Contract, ContractId, DecryptedPreimage, EncryptedPreimage, IdentifiableContract, Preimage,
78 PreimageKey,
79};
80use fedimint_ln_common::gateway_endpoint_constants::{
81 GET_GATEWAY_ID_ENDPOINT, PAY_INVOICE_ENDPOINT,
82};
83use fedimint_ln_common::{
84 ContractOutput, KIND, LNV1_INCOMING_HTLC_ADVERTISED_EXPIRY_DELTA, LightningCommonInit,
85 LightningGateway, LightningGatewayAnnouncement, LightningGatewayRegistration, LightningInput,
86 LightningModuleTypes, LightningOutput, LightningOutputV0,
87};
88use fedimint_logging::LOG_CLIENT_MODULE_LN;
89use futures::{Future, StreamExt, TryStreamExt as _};
90use incoming::IncomingSmError;
91use itertools::Itertools;
92use lightning_invoice::{
93 Bolt11Invoice, CreationError, InvoiceBuilder, PaymentSecret, RouteHint, RouteHintHop,
94 RoutingFees,
95};
96use pay::PayInvoicePayload;
97use rand::rngs::OsRng;
98use rand::seq::IteratorRandom as _;
99use rand::{CryptoRng, Rng, RngCore};
100use reqwest::Method;
101use serde::{Deserialize, Serialize};
102use strum::IntoEnumIterator;
103use tokio::sync::Notify;
104use tracing::{debug, error, info, warn};
105
106use crate::db::PaymentResultPrefix;
107pub use crate::error::{
108 ClaimIncomingContractError, CreateBolt11InvoiceError, GatewaySelectionError, LnSubscribeError,
109 PayBolt11InvoiceError, PaymentInfoError, ReclaimLnReceiveError, SpendableAmountError,
110};
111use crate::incoming::{
112 FundingOfferState, IncomingSmCommon, IncomingSmStates, IncomingStateMachine,
113};
114use crate::pay::lightningpay::LightningPayStates;
115use crate::pay::{
116 GatewayPayError, LightningPayCommon, LightningPayCreatedOutgoingLnContract,
117 LightningPayStateMachine,
118};
119use crate::receive::{
120 LightningReceiveConfirmedInvoice, LightningReceiveError, LightningReceiveStateMachine,
121 LightningReceiveStates, LightningReceiveSubmittedOffer, get_incoming_contract,
122};
123use crate::recurring::RecurringPaymentCodeEntry;
124
125const OUTGOING_LN_CONTRACT_TIMELOCK: u64 = 500;
128
129const MAX_OUTGOING_CONTRACT_TIMELOCK_DELTA: u64 = 1440;
135
136const DEFAULT_INVOICE_EXPIRY_TIME: Duration = Duration::from_hours(24);
139
140#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Encodable, Decodable)]
141#[serde(rename_all = "snake_case")]
142pub enum PayType {
143 Internal(OperationId),
145 Lightning(OperationId),
147}
148
149impl PayType {
150 pub fn operation_id(&self) -> OperationId {
151 match self {
152 PayType::Internal(operation_id) | PayType::Lightning(operation_id) => *operation_id,
153 }
154 }
155
156 pub fn payment_type(&self) -> String {
157 match self {
158 PayType::Internal(_) => "internal",
159 PayType::Lightning(_) => "lightning",
160 }
161 .into()
162 }
163}
164
165#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, Encodable, Decodable)]
167pub enum ReceivingKey {
168 Personal(Keypair),
171 External(PublicKey),
174}
175
176impl ReceivingKey {
177 pub fn public_key(&self) -> PublicKey {
179 match self {
180 ReceivingKey::Personal(keypair) => keypair.public_key(),
181 ReceivingKey::External(public_key) => *public_key,
182 }
183 }
184}
185
186#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
187pub enum LightningPaymentOutcome {
188 Success { preimage: String },
189 Failure { error_message: String },
190}
191
192#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum InternalPayState {
197 Funding,
198 Preimage(Preimage),
199 RefundSuccess {
200 out_points: Vec<OutPoint>,
201 error: IncomingSmError,
202 },
203 RefundError {
204 error_message: String,
205 error: IncomingSmError,
206 },
207 FundingFailed {
208 error: IncomingSmError,
209 },
210 UnexpectedError(String),
211}
212
213#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
216#[serde(rename_all = "snake_case")]
217pub enum LnPayState {
218 Created,
219 Canceled,
220 Funded { block_height: u32 },
221 WaitingForRefund { error_reason: String },
222 AwaitingChange,
223 Success { preimage: String },
224 Refunded { gateway_error: GatewayPayError },
225 UnexpectedError { error_message: String },
226}
227
228#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
231#[serde(rename_all = "snake_case")]
232pub enum LnReceiveState {
233 Created,
234 WaitingForPayment { invoice: String, timeout: Duration },
235 Canceled { reason: LightningReceiveError },
236 Funded,
237 AwaitingFunds,
238 Claimed,
239}
240
241fn invoice_has_internal_payment_markers(
242 invoice: &Bolt11Invoice,
243 markers: (fedimint_core::secp256k1::PublicKey, u64),
244) -> bool {
245 invoice
248 .route_hints()
249 .first()
250 .and_then(|rh| rh.0.last())
251 .map(|hop| (hop.src_node_id, hop.short_channel_id))
252 == Some(markers)
253}
254
255fn invoice_routes_back_to_federation(
256 invoice: &Bolt11Invoice,
257 gateways: Vec<LightningGateway>,
258) -> bool {
259 gateways.into_iter().any(|gateway| {
260 invoice
261 .route_hints()
262 .first()
263 .and_then(|rh| rh.0.last())
264 .map(|hop| (hop.src_node_id, hop.short_channel_id))
265 == Some((gateway.node_pub_key, gateway.federation_index))
266 })
267}
268
269#[derive(Debug, Clone, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub struct LightningOperationMetaPay {
272 pub out_point: OutPoint,
273 pub invoice: Bolt11Invoice,
274 pub fee: Amount,
275 pub change: Vec<OutPoint>,
276 pub is_internal_payment: bool,
277 pub contract_id: ContractId,
278 pub gateway_id: Option<secp256k1::PublicKey>,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
282pub struct LightningOperationMeta {
283 pub variant: LightningOperationMetaVariant,
284 pub extra_meta: serde_json::Value,
285}
286
287pub use deprecated_variant_hack::LightningOperationMetaVariant;
288
289#[allow(deprecated)]
294mod deprecated_variant_hack;
295
296#[derive(Debug, Clone, Default)]
297pub struct LightningClientInit {
298 pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
299}
300
301impl ModuleInit for LightningClientInit {
302 type Common = LightningCommonInit;
303
304 async fn dump_database(
305 &self,
306 dbtx: &mut DatabaseTransaction<'_>,
307 prefix_names: Vec<String>,
308 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
309 let mut ln_client_items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> =
310 BTreeMap::new();
311 let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
312 prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
313 });
314
315 for table in filtered_prefixes {
316 #[allow(clippy::match_same_arms)]
317 match table {
318 DbKeyPrefix::ActiveGateway | DbKeyPrefix::MetaOverridesDeprecated => {
319 }
321 DbKeyPrefix::PaymentResult => {
322 push_db_pair_items!(
323 dbtx,
324 PaymentResultPrefix,
325 PaymentResultKey,
326 PaymentResult,
327 ln_client_items,
328 "Payment Result"
329 );
330 }
331 DbKeyPrefix::LightningGateway => {
332 push_db_pair_items!(
333 dbtx,
334 LightningGatewayKeyPrefix,
335 LightningGatewayKey,
336 LightningGatewayRegistration,
337 ln_client_items,
338 "Lightning Gateways"
339 );
340 }
341 DbKeyPrefix::RecurringPaymentKey => {
342 push_db_pair_items!(
343 dbtx,
344 RecurringPaymentCodeKeyPrefix,
345 RecurringPaymentCodeKey,
346 RecurringPaymentCodeEntry,
347 ln_client_items,
348 "Recurring Payment Code"
349 );
350 }
351 DbKeyPrefix::ExternalReservedStart
352 | DbKeyPrefix::CoreInternalReservedStart
353 | DbKeyPrefix::CoreInternalReservedEnd => {}
354 }
355 }
356
357 Box::new(ln_client_items.into_iter())
358 }
359}
360
361#[derive(Debug)]
362#[repr(u64)]
363pub enum LightningChildKeys {
364 RedeemKey = 0,
365 PreimageAuthentication = 1,
366 RecurringPaymentCodeSecret = 2,
367}
368
369#[apply(async_trait_maybe_send!)]
370impl ClientModuleInit for LightningClientInit {
371 type Module = LightningClientModule;
372
373 fn supported_api_versions(&self) -> MultiApiVersion {
374 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
375 .expect("no version conflicts")
376 }
377
378 async fn init(
379 &self,
380 args: &ClientModuleInitArgs<Self>,
381 ) -> Result<Self::Module, ClientModuleError> {
382 let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
383 gateway_conn
384 } else {
385 let api = GatewayApi::new(None, args.connector_registry.clone());
386 Arc::new(RealGatewayConnection { api })
387 };
388 Ok(LightningClientModule::new(args, gateway_conn))
389 }
390
391 fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
392 let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
393 migrations.insert(DatabaseVersion(0), |dbtx, _, _| {
394 Box::pin(async {
395 dbtx.remove_entry(&crate::db::ActiveGatewayKey).await;
396 Ok(None)
397 })
398 });
399
400 migrations.insert(DatabaseVersion(1), |_, active_states, inactive_states| {
401 Box::pin(async {
402 migrate_state(active_states, inactive_states, db::get_v1_migrated_state)
403 })
404 });
405
406 migrations.insert(DatabaseVersion(2), |_, active_states, inactive_states| {
407 Box::pin(async {
408 migrate_state(active_states, inactive_states, db::get_v2_migrated_state)
409 })
410 });
411
412 migrations.insert(DatabaseVersion(3), |_, active_states, inactive_states| {
413 Box::pin(async {
414 migrate_state(active_states, inactive_states, db::get_v3_migrated_state)
415 })
416 });
417
418 migrations
419 }
420
421 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
422 Some(
423 DbKeyPrefix::iter()
424 .map(|p| p as u8)
425 .chain(
426 DbKeyPrefix::ExternalReservedStart as u8
427 ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
428 )
429 .collect(),
430 )
431 }
432}
433
434#[derive(Debug)]
439pub struct LightningClientModule {
440 pub cfg: LightningClientConfig,
441 notifier: ModuleNotifier<LightningClientStateMachines>,
442 redeem_key: Keypair,
443 recurring_payment_code_secret: DerivableSecret,
444 secp: Secp256k1<All>,
445 module_api: DynModuleApi,
446 preimage_auth: Keypair,
447 client_ctx: ClientContext<Self>,
448 update_gateway_cache_merge: UpdateMerge,
449 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
450 new_recurring_payment_code: Arc<Notify>,
451}
452
453#[apply(async_trait_maybe_send!)]
454impl ClientModule for LightningClientModule {
455 type Init = LightningClientInit;
456 type Common = LightningModuleTypes;
457 type Backup = NoModuleBackup;
458 type ModuleStateMachineContext = LightningClientContext;
459 type States = LightningClientStateMachines;
460
461 fn context(&self) -> Self::ModuleStateMachineContext {
462 LightningClientContext {
463 ln_decoder: self.decoder(),
464 redeem_key: self.redeem_key,
465 gateway_conn: self.gateway_conn.clone(),
466 client_ctx: Some(self.client_ctx.clone()),
467 }
468 }
469
470 fn input_fee(
471 &self,
472 _amount: &Amounts,
473 _input: &<Self::Common as ModuleCommon>::Input,
474 ) -> Option<Amounts> {
475 Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_input))
476 }
477
478 fn output_fee(
479 &self,
480 _amount: &Amounts,
481 output: &<Self::Common as ModuleCommon>::Output,
482 ) -> Option<Amounts> {
483 match output.maybe_v0_ref()? {
484 LightningOutputV0::Contract(_) => {
485 Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_output))
486 }
487 LightningOutputV0::Offer(_) | LightningOutputV0::CancelOutgoing { .. } => {
488 Some(Amounts::ZERO)
489 }
490 }
491 }
492
493 #[cfg(feature = "cli")]
494 async fn handle_cli_command(
495 &self,
496 args: &[std::ffi::OsString],
497 ) -> Result<serde_json::Value, ClientModuleError> {
498 cli::handle_cli_command(self, args)
499 .await
500 .map_err(ClientModuleError::other)
501 }
502
503 async fn handle_rpc(
504 &self,
505 method: String,
506 payload: serde_json::Value,
507 ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
508 let stream: BoxStream<'_, Result<serde_json::Value, RpcError>> = Box::pin(try_stream! {
509 match method.as_str() {
510 "create_bolt11_invoice" => {
511 let req: CreateBolt11InvoiceRequest = serde_json::from_value(payload)?;
512 let (op, invoice, _) = self
513 .create_bolt11_invoice(
514 req.amount,
515 lightning_invoice::Bolt11InvoiceDescription::Direct(
516 lightning_invoice::Description::new(req.description)?,
517 ),
518 req.expiry_time,
519 req.extra_meta,
520 req.gateway,
521 )
522 .await?;
523 yield serde_json::json!({
524 "operation_id": op,
525 "invoice": invoice,
526 });
527 }
528 "pay_bolt11_invoice" => {
529 let req: PayBolt11InvoiceRequest = serde_json::from_value(payload)?;
530 let outgoing_payment = self
531 .pay_bolt11_invoice(req.maybe_gateway, req.invoice, req.extra_meta)
532 .await?;
533 yield serde_json::to_value(outgoing_payment)?;
534 }
535 "select_available_gateway" => {
536 let req: SelectAvailableGatewayRequest = serde_json::from_value(payload)?;
537 let gateway = self.select_available_gateway(req.maybe_gateway,req.maybe_invoice).await?;
538 yield serde_json::to_value(gateway)?;
539 }
540 "subscribe_ln_pay" => {
541 let req: SubscribeLnPayRequest = serde_json::from_value(payload)?;
542 for await state in self.subscribe_ln_pay(req.operation_id).await?.into_stream() {
543 yield serde_json::to_value(state)?;
544 }
545 }
546 "subscribe_internal_pay" => {
547 let req: SubscribeInternalPayRequest = serde_json::from_value(payload)?;
548 for await state in self.subscribe_internal_pay(req.operation_id).await?.into_stream() {
549 yield serde_json::to_value(state)?;
550 }
551 }
552 "subscribe_ln_receive" => {
553 let req: SubscribeLnReceiveRequest = serde_json::from_value(payload)?;
554 for await state in self.subscribe_ln_receive(req.operation_id).await?.into_stream()
555 {
556 yield serde_json::to_value(state)?;
557 }
558 }
559 "reclaim_ln_receive" => {
560 let req: ReclaimLnReceiveRequest = serde_json::from_value(payload)?;
561 let operation_id = self.reclaim_ln_receive(req.original_operation_id).await?;
562 yield serde_json::json!({
563 "operation_id": operation_id,
564 });
565 }
566 "create_bolt11_invoice_for_user_tweaked" => {
567 let req: CreateBolt11InvoiceForUserTweakedRequest = serde_json::from_value(payload)?;
568 let (op, invoice, _) = self
569 .create_bolt11_invoice_for_user_tweaked(
570 req.amount,
571 lightning_invoice::Bolt11InvoiceDescription::Direct(
572 lightning_invoice::Description::new(req.description)?,
573 ),
574 req.expiry_time,
575 req.user_key,
576 req.index,
577 req.extra_meta,
578 req.gateway,
579 )
580 .await?;
581 yield serde_json::json!({
582 "operation_id": op,
583 "invoice": invoice,
584 });
585 }
586 #[allow(deprecated)]
587 "scan_receive_for_user_tweaked" => {
588 let req: ScanReceiveForUserTweakedRequest = serde_json::from_value(payload)?;
589 let keypair = Keypair::from_secret_key(&self.secp, &req.user_key);
590 let operation_ids = self.scan_receive_for_user_tweaked(keypair, req.indices, req.extra_meta).await;
591 yield serde_json::to_value(operation_ids)?;
592 }
593 #[allow(deprecated)]
594 "subscribe_ln_claim" => {
595 let req: SubscribeLnClaimRequest = serde_json::from_value(payload)?;
596 for await state in self.subscribe_ln_claim(req.operation_id).await?.into_stream() {
597 yield serde_json::to_value(state)?;
598 }
599 }
600 "get_gateway" => {
601 let req: GetGatewayRequest = serde_json::from_value(payload)?;
602 let gateway = self.get_gateway(req.gateway_id, req.force_internal).await?;
603 yield serde_json::to_value(gateway)?;
604 }
605 "list_gateways" => {
606 let gateways = self.list_gateways().await;
607 yield serde_json::to_value(gateways)?;
608 }
609 "update_gateway_cache" => {
610 self.update_gateway_cache().await?;
611 yield serde_json::Value::Null;
612 }
613 "pay_lightning_address" => {
614 let req: PayLightningAddressRequest = serde_json::from_value(payload)?;
615 let invoice = get_invoice(&req.address, Some(Amount::from_msats(req.amount)), None).await?;
616 let gateway = self.get_gateway(None, false).await?;
617 let output = self.pay_bolt11_invoice(gateway, invoice, ()).await?;
618
619 yield serde_json::to_value(output)?;
620 }
621 _ => {
622 Err(RpcError::UnknownMethod { method: method.clone() })?;
623 unreachable!()
624 },
625 }
626 });
627 Box::pin(stream.map_err(ClientModuleError::other))
628 }
629}
630
631#[derive(Debug, thiserror::Error)]
633enum RpcError {
634 #[error(transparent)]
637 Json(#[from] serde_json::Error),
638
639 #[error(transparent)]
641 InvoiceDescription(#[from] lightning_invoice::CreationError),
642
643 #[error(transparent)]
645 CreateInvoice(#[from] CreateBolt11InvoiceError),
646
647 #[error(transparent)]
649 Pay(#[from] PayBolt11InvoiceError),
650
651 #[error(transparent)]
653 GatewaySelection(#[from] GatewaySelectionError),
654
655 #[error(transparent)]
657 Subscribe(#[from] LnSubscribeError),
658
659 #[error(transparent)]
661 Reclaim(#[from] ReclaimLnReceiveError),
662
663 #[error(transparent)]
665 Federation(#[from] FederationError),
666
667 #[error(transparent)]
669 PaymentInfo(#[from] PaymentInfoError),
670
671 #[error("Unknown method: {method}")]
673 UnknownMethod { method: String },
674}
675
676#[derive(Deserialize)]
677struct CreateBolt11InvoiceRequest {
678 amount: Amount,
679 description: String,
680 expiry_time: Option<u64>,
681 extra_meta: serde_json::Value,
682 gateway: Option<LightningGateway>,
683}
684
685#[derive(Deserialize)]
686struct PayBolt11InvoiceRequest {
687 maybe_gateway: Option<LightningGateway>,
688 invoice: Bolt11Invoice,
689 extra_meta: Option<serde_json::Value>,
690}
691
692#[derive(Deserialize)]
693struct SubscribeLnPayRequest {
694 operation_id: OperationId,
695}
696
697#[derive(Deserialize)]
698struct SubscribeInternalPayRequest {
699 operation_id: OperationId,
700}
701
702#[derive(Deserialize)]
703struct SubscribeLnReceiveRequest {
704 operation_id: OperationId,
705}
706
707#[derive(Deserialize)]
708struct ReclaimLnReceiveRequest {
709 original_operation_id: OperationId,
710}
711
712#[derive(Debug, Serialize, Deserialize)]
713pub struct SelectAvailableGatewayRequest {
714 maybe_gateway: Option<LightningGateway>,
715 maybe_invoice: Option<Bolt11Invoice>,
716}
717
718#[derive(Deserialize)]
719struct CreateBolt11InvoiceForUserTweakedRequest {
720 amount: Amount,
721 description: String,
722 expiry_time: Option<u64>,
723 user_key: PublicKey,
724 index: u64,
725 extra_meta: serde_json::Value,
726 gateway: Option<LightningGateway>,
727}
728
729#[derive(Deserialize)]
730struct ScanReceiveForUserTweakedRequest {
731 user_key: SecretKey,
732 indices: Vec<u64>,
733 extra_meta: serde_json::Value,
734}
735
736#[derive(Deserialize)]
737struct SubscribeLnClaimRequest {
738 operation_id: OperationId,
739}
740
741#[derive(Deserialize)]
742struct GetGatewayRequest {
743 gateway_id: Option<secp256k1::PublicKey>,
744 force_internal: bool,
745}
746
747#[derive(Deserialize)]
748struct PayLightningAddressRequest {
749 address: String,
750 amount: u64,
751}
752
753#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
754pub enum GatewayStatus {
755 OnlineVetted,
756 OnlineNonVetted,
757}
758
759impl LightningClientModule {
760 fn new(
761 args: &ClientModuleInitArgs<LightningClientInit>,
762 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
763 ) -> Self {
764 let secp = Secp256k1::new();
765
766 let new_recurring_payment_code = Arc::new(Notify::new());
767 args.spawn_cancellable(
768 "Recurring payment sync",
769 Self::scan_recurring_payment_code_invoices(
770 args.context(),
771 new_recurring_payment_code.clone(),
772 ),
773 );
774
775 Self {
776 cfg: args.cfg().clone(),
777 notifier: args.notifier().clone(),
778 redeem_key: args
779 .module_root_secret()
780 .child_key(ChildId(LightningChildKeys::RedeemKey as u64))
781 .to_secp_key(&secp),
782 recurring_payment_code_secret: args.module_root_secret().child_key(ChildId(
783 LightningChildKeys::RecurringPaymentCodeSecret as u64,
784 )),
785 module_api: args.module_api().clone(),
786 preimage_auth: args
787 .module_root_secret()
788 .child_key(ChildId(LightningChildKeys::PreimageAuthentication as u64))
789 .to_secp_key(&secp),
790 secp,
791 client_ctx: args.context(),
792 update_gateway_cache_merge: UpdateMerge::default(),
793 gateway_conn,
794 new_recurring_payment_code,
795 }
796 }
797
798 pub async fn get_prev_payment_result(
799 &self,
800 payment_hash: &sha256::Hash,
801 dbtx: &mut DatabaseTransaction<'_>,
802 ) -> PaymentResult {
803 let prev_result = dbtx
804 .get_value(&PaymentResultKey {
805 payment_hash: *payment_hash,
806 })
807 .await;
808 prev_result.unwrap_or(PaymentResult {
809 index: 0,
810 completed_payment: None,
811 })
812 }
813
814 fn get_payment_operation_id(payment_hash: &sha256::Hash, index: u16) -> OperationId {
815 let mut bytes = [0; 34];
818 bytes[0..32].copy_from_slice(&payment_hash.to_byte_array());
819 bytes[32..34].copy_from_slice(&index.to_le_bytes());
820 let hash: sha256::Hash = Hash::hash(&bytes);
821 OperationId(hash.to_byte_array())
822 }
823
824 fn get_preimage_authentication(&self, payment_hash: &sha256::Hash) -> sha256::Hash {
829 let mut bytes = [0; 64];
830 bytes[0..32].copy_from_slice(&payment_hash.to_byte_array());
831 bytes[32..64].copy_from_slice(&self.preimage_auth.secret_bytes());
832 Hash::hash(&bytes)
833 }
834
835 async fn create_outgoing_output<'a, 'b>(
839 &'a self,
840 operation_id: OperationId,
841 invoice: Bolt11Invoice,
842 gateway: LightningGateway,
843 fed_id: FederationId,
844 mut rng: impl RngCore + CryptoRng + 'a,
845 ) -> Result<
846 (
847 ClientOutput<LightningOutputV0>,
848 ClientOutputSM<LightningClientStateMachines>,
849 ContractId,
850 ),
851 PayBolt11InvoiceError,
852 > {
853 let invoice_currency = invoice.currency();
854 if !currency_matches_network(&invoice_currency, self.cfg.network.0) {
855 return Err(PayBolt11InvoiceError::WrongCurrency {
856 expected: currency_for_network(self.cfg.network.0),
857 found: invoice_currency,
858 });
859 }
860
861 let timelock_delta = invoice
862 .min_final_cltv_expiry_delta()
863 .saturating_add(OUTGOING_LN_CONTRACT_TIMELOCK - 1);
864 if MAX_OUTGOING_CONTRACT_TIMELOCK_DELTA < timelock_delta {
865 return Err(PayBolt11InvoiceError::TimelockDeltaTooLarge {
866 found: timelock_delta,
867 max: MAX_OUTGOING_CONTRACT_TIMELOCK_DELTA,
868 });
869 }
870
871 self.gateway_conn
874 .verify_gateway_availability(&gateway)
875 .await
876 .map_err(PayBolt11InvoiceError::GatewayUnavailable)?;
877
878 let consensus_count = self
879 .module_api
880 .fetch_consensus_block_count()
881 .await?
882 .ok_or(PayBolt11InvoiceError::NoConsensusBlockCount)?;
883
884 let absolute_timelock = consensus_count + timelock_delta;
887
888 let invoice_amount = Amount::from_msats(
890 invoice
891 .amount_milli_satoshis()
892 .ok_or(PayBolt11InvoiceError::MissingInvoiceAmount)?,
893 );
894
895 let gateway_fee = gateway.fees.to_amount(&invoice_amount);
896 let contract_amount = invoice_amount + gateway_fee;
897
898 let user_sk = Keypair::new(&self.secp, &mut rng);
899
900 let payment_hash = *invoice.payment_hash();
901 let preimage_auth = self.get_preimage_authentication(&payment_hash);
902 let contract = OutgoingContract {
903 hash: payment_hash,
904 gateway_key: gateway.gateway_redeem_key,
905 timelock: absolute_timelock as u32,
906 user_key: user_sk.public_key(),
907 cancelled: false,
908 };
909
910 let outgoing_payment = OutgoingContractData {
911 recovery_key: user_sk,
912 contract_account: OutgoingContractAccount {
913 amount: contract_amount,
914 contract: contract.clone(),
915 },
916 };
917
918 let contract_id = contract.contract_id();
919 let sm_gen = Arc::new(move |out_point_range: OutPointRange| {
920 vec![LightningClientStateMachines::LightningPay(
921 LightningPayStateMachine {
922 common: LightningPayCommon {
923 operation_id,
924 federation_id: fed_id,
925 contract: outgoing_payment.clone(),
926 gateway_fee,
927 preimage_auth,
928 invoice: invoice.clone(),
929 },
930 state: LightningPayStates::CreatedOutgoingLnContract(
931 LightningPayCreatedOutgoingLnContract {
932 funding_txid: out_point_range.txid(),
933 contract_id,
934 gateway: gateway.clone(),
935 },
936 ),
937 },
938 )]
939 });
940
941 let ln_output = LightningOutputV0::Contract(ContractOutput {
942 amount: contract_amount,
943 contract: Contract::Outgoing(contract),
944 });
945
946 Ok((
947 ClientOutput {
948 output: ln_output,
949 amounts: Amounts::new_bitcoin(contract_amount),
950 },
951 ClientOutputSM {
952 state_machines: sm_gen,
953 },
954 contract_id,
955 ))
956 }
957
958 async fn create_incoming_output(
962 &self,
963 operation_id: OperationId,
964 invoice: Bolt11Invoice,
965 ) -> Result<
966 (
967 ClientOutput<LightningOutputV0>,
968 ClientOutputSM<LightningClientStateMachines>,
969 ContractId,
970 ),
971 IncomingSmError,
972 > {
973 let payment_hash = *invoice.payment_hash();
974 let invoice_amount = Amount {
975 msats: invoice
976 .amount_milli_satoshis()
977 .ok_or(IncomingSmError::AmountError {
978 invoice: invoice.clone(),
979 })?,
980 };
981
982 let (incoming_output, amount, contract_id) = create_incoming_contract_output(
983 &self.module_api,
984 payment_hash,
985 invoice_amount,
986 &self.redeem_key,
987 )
988 .await?;
989
990 let client_output = ClientOutput::<LightningOutputV0> {
991 output: incoming_output,
992 amounts: Amounts::new_bitcoin(amount),
993 };
994
995 let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
996 state_machines: Arc::new(move |out_point_range| {
997 vec![LightningClientStateMachines::InternalPay(
998 IncomingStateMachine {
999 common: IncomingSmCommon {
1000 operation_id,
1001 contract_id,
1002 payment_hash,
1003 },
1004 state: IncomingSmStates::FundingOffer(FundingOfferState {
1005 txid: out_point_range.txid(),
1006 }),
1007 },
1008 )]
1009 }),
1010 };
1011
1012 Ok((client_output, client_output_sm, contract_id))
1013 }
1014
1015 async fn await_receive_success(
1016 &self,
1017 operation_id: OperationId,
1018 ) -> Result<(), LightningReceiveError> {
1019 let mut stream = self.notifier.subscribe(operation_id).await;
1020 loop {
1021 if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
1022 match state.state {
1023 LightningReceiveStates::Success(_) => return Ok(()),
1024 LightningReceiveStates::Canceled(e) => {
1025 return Err(e);
1026 }
1027 _ => {}
1028 }
1029 }
1030 }
1031 }
1032
1033 async fn await_claim_acceptance(
1034 &self,
1035 operation_id: OperationId,
1036 ) -> Result<Vec<OutPoint>, LightningReceiveError> {
1037 let mut stream = self.notifier.subscribe(operation_id).await;
1038 loop {
1039 if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
1040 match state.state {
1041 LightningReceiveStates::Success(out_points) => return Ok(out_points),
1042 LightningReceiveStates::Canceled(e) => {
1043 return Err(e);
1044 }
1045 _ => {}
1046 }
1047 }
1048 }
1049 }
1050
1051 #[allow(clippy::too_many_arguments)]
1052 #[allow(clippy::type_complexity)]
1053 fn create_lightning_receive_output<'a>(
1054 &'a self,
1055 amount: Amount,
1056 description: lightning_invoice::Bolt11InvoiceDescription,
1057 receiving_key: ReceivingKey,
1058 mut rng: impl RngCore + CryptoRng + 'a,
1059 expiry_time: Option<u64>,
1060 src_node_id: secp256k1::PublicKey,
1061 short_channel_id: u64,
1062 route_hints: &[fedimint_ln_common::route_hints::RouteHint],
1063 network: Network,
1064 ) -> Result<
1065 (
1066 OperationId,
1067 Bolt11Invoice,
1068 ClientOutputBundle<LightningOutput, LightningClientStateMachines>,
1069 [u8; 32],
1070 ),
1071 CreationError,
1072 > {
1073 let preimage_key: [u8; 33] = receiving_key.public_key().serialize();
1074 let preimage = sha256::Hash::hash(&preimage_key);
1075 let payment_hash = sha256::Hash::hash(&preimage.to_byte_array());
1076
1077 let (node_secret_key, node_public_key) = self.secp.generate_keypair(&mut rng);
1079
1080 let route_hint_last_hop = RouteHintHop {
1082 src_node_id,
1083 short_channel_id,
1084 fees: RoutingFees {
1085 base_msat: 0,
1086 proportional_millionths: 0,
1087 },
1088 cltv_expiry_delta: LNV1_INCOMING_HTLC_ADVERTISED_EXPIRY_DELTA,
1089 htlc_minimum_msat: None,
1090 htlc_maximum_msat: None,
1091 };
1092 let mut final_route_hints = vec![RouteHint(vec![route_hint_last_hop.clone()])];
1093 if !route_hints.is_empty() {
1094 let mut two_hop_route_hints: Vec<RouteHint> = route_hints
1095 .iter()
1096 .map(|rh| {
1097 RouteHint(
1098 rh.to_ldk_route_hint()
1099 .0
1100 .iter()
1101 .cloned()
1102 .chain(once(route_hint_last_hop.clone()))
1103 .collect(),
1104 )
1105 })
1106 .collect();
1107 final_route_hints.append(&mut two_hop_route_hints);
1108 }
1109
1110 let duration_since_epoch = fedimint_core::time::duration_since_epoch();
1111
1112 let mut invoice_builder = InvoiceBuilder::new(currency_for_network(network))
1113 .amount_milli_satoshis(amount.msats)
1114 .invoice_description(description)
1115 .payment_hash(payment_hash)
1116 .payment_secret(PaymentSecret(rng.r#gen()))
1117 .duration_since_epoch(duration_since_epoch)
1118 .min_final_cltv_expiry_delta(18)
1119 .payee_pub_key(node_public_key)
1120 .expiry_time(Duration::from_secs(
1121 expiry_time.unwrap_or(DEFAULT_INVOICE_EXPIRY_TIME.as_secs()),
1122 ));
1123
1124 for rh in final_route_hints {
1125 invoice_builder = invoice_builder.private_route(rh);
1126 }
1127
1128 let invoice = invoice_builder
1129 .build_signed(|msg| self.secp.sign_ecdsa_recoverable(msg, &node_secret_key))?;
1130
1131 let operation_id = OperationId(*invoice.payment_hash().as_ref());
1132
1133 let sm_invoice = invoice.clone();
1134 let sm_gen = Arc::new(move |out_point_range: OutPointRange| {
1135 vec![LightningClientStateMachines::Receive(
1136 LightningReceiveStateMachine {
1137 operation_id,
1138 state: LightningReceiveStates::SubmittedOffer(LightningReceiveSubmittedOffer {
1139 offer_txid: out_point_range.txid(),
1140 invoice: sm_invoice.clone(),
1141 receiving_key,
1142 }),
1143 },
1144 )]
1145 });
1146
1147 let ln_output = LightningOutput::new_v0_offer(IncomingContractOffer {
1148 amount,
1149 hash: payment_hash,
1150 encrypted_preimage: EncryptedPreimage::new(
1151 &PreimageKey(preimage_key),
1152 &self.cfg.threshold_pub_key,
1153 ),
1154 expiry_time,
1155 });
1156
1157 Ok((
1158 operation_id,
1159 invoice,
1160 ClientOutputBundle::new(
1161 vec![ClientOutput {
1162 output: ln_output,
1163 amounts: Amounts::ZERO,
1164 }],
1165 vec![ClientOutputSM {
1166 state_machines: sm_gen,
1167 }],
1168 ),
1169 *preimage.as_ref(),
1170 ))
1171 }
1172
1173 pub async fn select_available_gateway(
1174 &self,
1175 maybe_gateway: Option<LightningGateway>,
1176 maybe_invoice: Option<Bolt11Invoice>,
1177 ) -> Result<LightningGateway, GatewaySelectionError> {
1178 if let Some(gw) = maybe_gateway {
1179 let gw_id = gw.gateway_id;
1180 if self
1181 .gateway_conn
1182 .verify_gateway_availability(&gw)
1183 .await
1184 .is_ok()
1185 {
1186 return Ok(gw);
1187 }
1188 return Err(GatewaySelectionError::Offline { gateway_id: gw_id });
1189 }
1190
1191 let gateways: Vec<LightningGatewayAnnouncement> = self.list_gateways().await;
1192 if gateways.is_empty() {
1193 return Err(GatewaySelectionError::NoGatewaysRegistered);
1194 }
1195
1196 let gateways_with_status =
1197 futures::future::join_all(gateways.into_iter().map(|gw| async {
1198 let online = self
1199 .gateway_conn
1200 .verify_gateway_availability(&gw.info)
1201 .await
1202 .is_ok();
1203 (gw, online)
1204 }))
1205 .await;
1206
1207 let sorted_gateways: Vec<(LightningGatewayAnnouncement, GatewayStatus)> =
1208 gateways_with_status
1209 .into_iter()
1210 .filter_map(|(ann, online)| {
1211 if online {
1212 let status = if ann.vetted {
1213 GatewayStatus::OnlineVetted
1214 } else {
1215 GatewayStatus::OnlineNonVetted
1216 };
1217 Some((ann, status))
1218 } else {
1219 None
1220 }
1221 })
1222 .collect();
1223
1224 if sorted_gateways.is_empty() {
1225 return Err(GatewaySelectionError::NoneReachable);
1226 }
1227
1228 let amount_msat = maybe_invoice.and_then(|inv| inv.amount_milli_satoshis());
1229 let sorted_gateways = sorted_gateways
1230 .into_iter()
1231 .sorted_by_key(|(ann, status)| {
1232 let total_fee_msat: u64 =
1233 amount_msat.map_or(u64::from(ann.info.fees.base_msat), |amt| {
1234 u64::from(ann.info.fees.base_msat)
1235 + ((u128::from(amt)
1236 * u128::from(ann.info.fees.proportional_millionths))
1237 / 1_000_000) as u64
1238 });
1239 (status.clone(), total_fee_msat)
1240 })
1241 .collect::<Vec<_>>();
1242
1243 Ok(sorted_gateways[0].0.info.clone())
1244 }
1245
1246 pub async fn select_gateway(
1249 &self,
1250 gateway_id: &secp256k1::PublicKey,
1251 ) -> Option<LightningGateway> {
1252 let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1253 let gateways = dbtx
1254 .find_by_prefix(&LightningGatewayKeyPrefix)
1255 .await
1256 .map(|(_, gw)| gw.info)
1257 .collect::<Vec<_>>()
1258 .await;
1259 gateways.into_iter().find(|g| &g.gateway_id == gateway_id)
1260 }
1261
1262 fn gateway_registration_proof_is_valid(&self, gw: &LightningGatewayAnnouncement) -> bool {
1269 let valid = gw.registration_proof_is_valid(self.cfg.threshold_pub_key);
1270
1271 if !valid {
1272 warn!(
1273 target: LOG_CLIENT_MODULE_LN,
1274 gateway_id = %gw.info.gateway_id,
1275 "Discarding gateway announcement with an invalid registration proof"
1276 );
1277 }
1278
1279 valid
1280 }
1281
1282 pub async fn update_gateway_cache(&self) -> FederationResult<()> {
1287 self.update_gateway_cache_merge
1288 .merge(async {
1289 let mut gateways = self
1290 .module_api
1291 .fetch_gateways(self.cfg.threshold_pub_key)
1292 .await?;
1293
1294 gateways.retain(|gw| self.gateway_registration_proof_is_valid(gw));
1298
1299 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1300
1301 dbtx.remove_by_prefix(&LightningGatewayKeyPrefix).await;
1303
1304 for gw in &gateways {
1305 dbtx.insert_entry(
1306 &LightningGatewayKey(gw.info.gateway_id),
1307 &gw.clone().anchor(),
1308 )
1309 .await;
1310 }
1311
1312 dbtx.commit_tx().await;
1313
1314 Ok(())
1315 })
1316 .await
1317 }
1318
1319 pub async fn update_gateway_cache_continuously<Fut>(
1324 &self,
1325 gateways_filter: impl Fn(Vec<LightningGatewayAnnouncement>) -> Fut,
1326 ) -> !
1327 where
1328 Fut: Future<Output = Vec<LightningGatewayAnnouncement>>,
1329 {
1330 const ABOUT_TO_EXPIRE: Duration = Duration::from_secs(30);
1331 const EMPTY_GATEWAY_SLEEP: Duration = Duration::from_mins(10);
1332
1333 let mut first_time = true;
1334
1335 loop {
1336 let gateways = self.list_gateways().await;
1337 let sleep_time = gateways_filter(gateways)
1338 .await
1339 .into_iter()
1340 .map(|x| x.ttl.saturating_sub(ABOUT_TO_EXPIRE))
1341 .min()
1342 .unwrap_or(if first_time {
1343 Duration::ZERO
1345 } else {
1346 EMPTY_GATEWAY_SLEEP
1347 });
1348 runtime::sleep(sleep_time).await;
1349
1350 let _ = retry(
1352 "update_gateway_cache",
1353 backoff_util::background_backoff(),
1354 || self.update_gateway_cache(),
1355 )
1356 .await;
1357 first_time = false;
1358 }
1359 }
1360
1361 pub async fn list_gateways(&self) -> Vec<LightningGatewayAnnouncement> {
1363 let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1364 dbtx.find_by_prefix(&LightningGatewayKeyPrefix)
1365 .await
1366 .map(|(_, gw)| gw.unanchor())
1367 .collect::<Vec<_>>()
1368 .await
1369 }
1370
1371 pub async fn pay_bolt11_invoice<M: Serialize + MaybeSend + MaybeSync>(
1380 &self,
1381 maybe_gateway: Option<LightningGateway>,
1382 invoice: Bolt11Invoice,
1383 extra_meta: M,
1384 ) -> Result<OutgoingLightningPayment, PayBolt11InvoiceError> {
1385 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1386 let maybe_gateway_id = maybe_gateway.as_ref().map(|g| g.gateway_id);
1387 let prev_payment_result = self
1388 .get_prev_payment_result(invoice.payment_hash(), &mut dbtx.to_ref_nc())
1389 .await;
1390
1391 if let Some(completed_payment) = prev_payment_result.completed_payment {
1392 return Ok(completed_payment);
1393 }
1394
1395 let prev_operation_id = LightningClientModule::get_payment_operation_id(
1397 invoice.payment_hash(),
1398 prev_payment_result.index,
1399 );
1400 if self.client_ctx.has_active_states(prev_operation_id).await {
1401 return Err(
1402 PayBolt11InvoiceError::PreviousPaymentAttemptStillInProgress {
1403 operation_id: prev_operation_id,
1404 },
1405 );
1406 }
1407
1408 if let Some(expires_at) = invoice.expires_at()
1417 && expires_at.as_secs() <= fedimint_core::time::duration_since_epoch().as_secs()
1418 {
1419 return Err(PayBolt11InvoiceError::InvoiceExpired);
1420 }
1421
1422 let next_index = prev_payment_result.index + 1;
1423 let operation_id =
1424 LightningClientModule::get_payment_operation_id(invoice.payment_hash(), next_index);
1425
1426 let new_payment_result = PaymentResult {
1427 index: next_index,
1428 completed_payment: None,
1429 };
1430
1431 dbtx.insert_entry(
1432 &PaymentResultKey {
1433 payment_hash: *invoice.payment_hash(),
1434 },
1435 &new_payment_result,
1436 )
1437 .await;
1438
1439 let markers = self
1440 .client_ctx
1441 .get_internal_payment_markers()
1442 .map_err(PayBolt11InvoiceError::PaymentMarkers)?;
1443
1444 let mut is_internal_payment = invoice_has_internal_payment_markers(&invoice, markers);
1445 if !is_internal_payment {
1446 let gateways = dbtx
1447 .find_by_prefix(&LightningGatewayKeyPrefix)
1448 .await
1449 .map(|(_, gw)| gw.info)
1450 .collect::<Vec<_>>()
1451 .await;
1452 is_internal_payment = invoice_routes_back_to_federation(&invoice, gateways);
1453 }
1454
1455 let (pay_type, client_output, client_output_sm, contract_id) = if is_internal_payment {
1456 let (output, output_sm, contract_id) = self
1457 .create_incoming_output(operation_id, invoice.clone())
1458 .await
1459 .map_err(PayBolt11InvoiceError::InternalContract)?;
1460 (
1461 PayType::Internal(operation_id),
1462 output,
1463 output_sm,
1464 contract_id,
1465 )
1466 } else {
1467 let gateway = maybe_gateway.ok_or(PayBolt11InvoiceError::NoLnGatewayAvailable)?;
1468 let (output, output_sm, contract_id) = self
1469 .create_outgoing_output(
1470 operation_id,
1471 invoice.clone(),
1472 gateway,
1473 self.client_ctx
1474 .get_config()
1475 .await
1476 .global
1477 .calculate_federation_id(),
1478 rand::rngs::OsRng,
1479 )
1480 .await?;
1481 (
1482 PayType::Lightning(operation_id),
1483 output,
1484 output_sm,
1485 contract_id,
1486 )
1487 };
1488
1489 if let Ok(Some(contract)) = self.module_api.fetch_contract(contract_id).await
1491 && contract.amount.msats != 0
1492 {
1493 return Err(PayBolt11InvoiceError::FundedContractAlreadyExists { contract_id });
1494 }
1495
1496 let amount_msat = invoice
1497 .amount_milli_satoshis()
1498 .ok_or(PayBolt11InvoiceError::MissingInvoiceAmount)?;
1499
1500 let fee = match &client_output.output {
1503 LightningOutputV0::Contract(contract) => {
1504 let fee_msat = contract
1505 .amount
1506 .msats
1507 .checked_sub(amount_msat)
1508 .expect("Contract amount should be greater or equal than invoice amount");
1509 Amount::from_msats(fee_msat)
1510 }
1511 _ => unreachable!("User client will only create contract outputs on spend"),
1512 };
1513
1514 let output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
1515 vec![ClientOutput {
1516 output: LightningOutput::V0(client_output.output),
1517 amounts: client_output.amounts,
1518 }],
1519 vec![client_output_sm],
1520 ));
1521
1522 let tx = TransactionBuilder::new(Account::Primary).with_outputs(output);
1523 let extra_meta =
1524 serde_json::to_value(extra_meta).map_err(PayBolt11InvoiceError::ExtraMeta)?;
1525 let operation_meta_gen = move |change_range: OutPointRange| LightningOperationMeta {
1526 variant: LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1527 out_point: OutPoint {
1528 txid: change_range.txid(),
1529 out_idx: 0,
1530 },
1531 invoice: invoice.clone(),
1532 fee,
1533 change: change_range.into_iter().collect(),
1534 is_internal_payment,
1535 contract_id,
1536 gateway_id: maybe_gateway_id,
1537 }),
1538 extra_meta: extra_meta.clone(),
1539 };
1540
1541 dbtx.commit_tx_result().await?;
1544
1545 self.client_ctx
1546 .finalize_and_submit_transaction_with_events(
1547 operation_id,
1548 LightningCommonInit::KIND.as_str(),
1549 operation_meta_gen,
1550 tx,
1551 vec![self.client_ctx.make_event(events::SendPaymentEvent {
1552 operation_id,
1553 amount: Amount::from_msats(amount_msat),
1554 fee,
1555 })],
1556 )
1557 .await?;
1558
1559 Ok(OutgoingLightningPayment {
1560 payment_type: pay_type,
1561 contract_id,
1562 fee,
1563 })
1564 }
1565
1566 pub async fn get_ln_pay_details_for(
1567 &self,
1568 operation_id: OperationId,
1569 ) -> Result<LightningOperationMetaPay, LnSubscribeError> {
1570 let operation = self.client_ctx.get_operation(operation_id).await?;
1571 let LightningOperationMetaVariant::Pay(pay) =
1572 operation.meta::<LightningOperationMeta>().variant
1573 else {
1574 return Err(LnSubscribeError::NotAPayment);
1575 };
1576 Ok(pay)
1577 }
1578
1579 pub async fn subscribe_internal_pay(
1580 &self,
1581 operation_id: OperationId,
1582 ) -> Result<UpdateStreamOrOutcome<InternalPayState>, LnSubscribeError> {
1583 let operation = self.client_ctx.get_operation(operation_id).await?;
1584
1585 let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1586 out_point: _,
1587 invoice: _,
1588 change: _, is_internal_payment,
1590 ..
1591 }) = operation.meta::<LightningOperationMeta>().variant
1592 else {
1593 return Err(LnSubscribeError::NotAPayment);
1594 };
1595
1596 if !is_internal_payment {
1597 return Err(LnSubscribeError::NotInternalPayment);
1598 }
1599
1600 let mut stream = self.notifier.subscribe(operation_id).await;
1601 let client_ctx = self.client_ctx.clone();
1602
1603 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1604 InternalPayState::Funding => false,
1605 InternalPayState::Preimage(_)
1606 | InternalPayState::RefundSuccess { .. }
1607 | InternalPayState::RefundError { .. }
1608 | InternalPayState::FundingFailed { .. }
1609 | InternalPayState::UnexpectedError(_) => true,
1610 }, move || {
1611 stream! {
1612 yield InternalPayState::Funding;
1613
1614 let state = loop {
1615 match stream.next().await { Some(LightningClientStateMachines::InternalPay(state)) => {
1616 match state.state {
1617 IncomingSmStates::Preimage(preimage) => break InternalPayState::Preimage(preimage),
1618 IncomingSmStates::RefundSubmitted{ out_points, error } => {
1619 match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
1620 Ok(()) => break InternalPayState::RefundSuccess { out_points, error },
1621 Err(e) => break InternalPayState::RefundError{ error_message: e.fmt_compact().to_string(), error },
1622 }
1623 },
1624 IncomingSmStates::FundingFailed { error } => break InternalPayState::FundingFailed{ error },
1625 _ => {}
1626 }
1627 } _ => {
1628 break InternalPayState::UnexpectedError("Unexpected State! Expected an InternalPay state".to_string())
1629 }}
1630 };
1631 yield state;
1632 }
1633 }))
1634 }
1635
1636 pub async fn subscribe_ln_pay(
1639 &self,
1640 operation_id: OperationId,
1641 ) -> Result<UpdateStreamOrOutcome<LnPayState>, LnSubscribeError> {
1642 async fn get_next_pay_state(
1643 stream: &mut BoxStream<'_, LightningClientStateMachines>,
1644 ) -> Option<LightningPayStates> {
1645 match stream.next().await {
1646 Some(LightningClientStateMachines::LightningPay(state)) => Some(state.state),
1647 Some(event) => {
1648 error!(event = ?event, "Operation is not a lightning payment");
1650 debug_assert!(false, "Operation is not a lightning payment: {event:?}");
1651 None
1652 }
1653 None => None,
1654 }
1655 }
1656
1657 let operation = self.client_ctx.get_operation(operation_id).await?;
1658 let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1659 out_point: _,
1660 invoice: _,
1661 change,
1662 is_internal_payment,
1663 ..
1664 }) = operation.meta::<LightningOperationMeta>().variant
1665 else {
1666 return Err(LnSubscribeError::NotAPayment);
1667 };
1668
1669 if is_internal_payment {
1670 return Err(LnSubscribeError::NotExternalPayment);
1671 }
1672
1673 let client_ctx = self.client_ctx.clone();
1674
1675 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1676 LnPayState::Created
1677 | LnPayState::Funded { .. }
1678 | LnPayState::WaitingForRefund { .. }
1679 | LnPayState::AwaitingChange => false,
1680 LnPayState::Success { .. }
1681 | LnPayState::Canceled
1682 | LnPayState::Refunded { .. }
1683 | LnPayState::UnexpectedError { .. } => true,
1684 }, move || {
1685 stream! {
1686 let self_ref = client_ctx.self_ref();
1687
1688 let mut stream = self_ref.notifier.subscribe(operation_id).await;
1689 let state = get_next_pay_state(&mut stream).await;
1690 match state {
1691 Some(LightningPayStates::CreatedOutgoingLnContract(_)) => {
1692 yield LnPayState::Created;
1693 }
1694 Some(LightningPayStates::FundingRejected) => {
1695 yield LnPayState::Canceled;
1696 return;
1697 }
1698 Some(state) => {
1699 yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1700 return;
1701 }
1702 None => {
1703 error!("Unexpected end of lightning pay state machine");
1704 return;
1705 }
1706 }
1707
1708 let state = get_next_pay_state(&mut stream).await;
1709 match state {
1710 Some(LightningPayStates::Funded(funded)) => {
1711 yield LnPayState::Funded { block_height: funded.timelock }
1712 }
1713 Some(state) => {
1714 yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1715 return;
1716 }
1717 _ => {
1718 error!("Unexpected end of lightning pay state machine");
1719 return;
1720 }
1721 }
1722
1723 let state = get_next_pay_state(&mut stream).await;
1724 match state {
1725 Some(LightningPayStates::Success(preimage)) => {
1726 if change.is_empty() {
1727 yield LnPayState::Success { preimage };
1728 } else {
1729 yield LnPayState::AwaitingChange;
1730 match client_ctx.await_primary_module_outputs(operation_id, change.clone()).await {
1731 Ok(()) => {
1732 yield LnPayState::Success { preimage };
1733 }
1734 Err(e) => {
1735 yield LnPayState::UnexpectedError { error_message: format!("Error occurred while waiting for the change: {e:?}") };
1736 }
1737 }
1738 }
1739 }
1740 Some(LightningPayStates::Refund(refund)) => {
1741 yield LnPayState::WaitingForRefund {
1742 error_reason: refund.error_reason.clone(),
1743 };
1744
1745 match client_ctx.await_primary_module_outputs(operation_id, refund.out_points).await {
1746 Ok(()) => {
1747 let gateway_error = GatewayPayError::GatewayInternalError { error_code: Some(500), error_message: refund.error_reason };
1748 yield LnPayState::Refunded { gateway_error };
1749 }
1750 Err(e) => {
1751 yield LnPayState::UnexpectedError {
1752 error_message: format!("Error occurred trying to get refund. Refund was not successful: {e:?}"),
1753 };
1754 }
1755 }
1756 }
1757 Some(state) => {
1758 yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1759 }
1760 None => {
1761 error!("Unexpected end of lightning pay state machine");
1762 yield LnPayState::UnexpectedError { error_message: "Unexpected end of lightning pay state machine".to_string() };
1763 }
1764 }
1765 }
1766 }))
1767 }
1768
1769 #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1772 #[allow(deprecated)]
1773 pub async fn scan_receive_for_user_tweaked<M: Serialize + Send + Sync + Clone>(
1774 &self,
1775 key_pair: Keypair,
1776 indices: Vec<u64>,
1777 extra_meta: M,
1778 ) -> Vec<OperationId> {
1779 let mut claims = Vec::new();
1780 for i in indices {
1781 let key_pair_tweaked = tweak_user_secret_key(&self.secp, key_pair, i);
1782 match self
1783 .scan_receive_for_user(key_pair_tweaked, extra_meta.clone())
1784 .await
1785 {
1786 Ok(operation_id) => claims.push(operation_id),
1787 Err(err) => {
1788 error!(err = %err.fmt_compact(), %i, "Failed to scan tweaked key at index i");
1789 }
1790 }
1791 }
1792
1793 claims
1794 }
1795
1796 #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1799 #[allow(deprecated)]
1800 pub async fn scan_receive_for_user<M: Serialize + Send + Sync>(
1801 &self,
1802 key_pair: Keypair,
1803 extra_meta: M,
1804 ) -> Result<OperationId, ClaimIncomingContractError> {
1805 let preimage_key: [u8; 33] = key_pair.public_key().serialize();
1806 let preimage = sha256::Hash::hash(&preimage_key);
1807 let contract_id = ContractId::from_raw_hash(sha256::Hash::hash(&preimage.to_byte_array()));
1808 self.claim_funded_incoming_contract(key_pair, contract_id, extra_meta)
1809 .await
1810 }
1811
1812 #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1815 #[allow(deprecated)]
1816 pub async fn claim_funded_incoming_contract<M: Serialize + Send + Sync>(
1817 &self,
1818 key_pair: Keypair,
1819 contract_id: ContractId,
1820 extra_meta: M,
1821 ) -> Result<OperationId, ClaimIncomingContractError> {
1822 let incoming_contract_account = get_incoming_contract(self.module_api.clone(), contract_id)
1823 .await?
1824 .ok_or(ClaimIncomingContractError::ContractNotFound { contract_id })?;
1825
1826 let input = incoming_contract_account.claim();
1827 let client_input = ClientInput::<LightningInput> {
1828 input,
1829 amounts: Amounts::new_bitcoin(incoming_contract_account.amount),
1830 keys: vec![key_pair],
1831 };
1832
1833 let tx = TransactionBuilder::new(Account::Primary).with_inputs(
1834 self.client_ctx
1835 .make_client_inputs(ClientInputBundle::new_no_sm(vec![client_input])),
1836 );
1837 let extra_meta = serde_json::to_value(extra_meta).expect("extra_meta is serializable");
1838 let operation_meta_gen = move |change_range: OutPointRange| LightningOperationMeta {
1839 variant: LightningOperationMetaVariant::Claim {
1840 out_points: change_range.into_iter().collect(),
1841 },
1842 extra_meta: extra_meta.clone(),
1843 };
1844 let operation_id = OperationId::new_random();
1845 self.client_ctx
1846 .finalize_and_submit_transaction(
1847 operation_id,
1848 LightningCommonInit::KIND.as_str(),
1849 operation_meta_gen,
1850 tx,
1851 )
1852 .await?;
1853 Ok(operation_id)
1854 }
1855
1856 pub async fn receive_fee_quote(
1872 &self,
1873 amount: Amount,
1874 ) -> Result<FeeQuote, TransactionSubmitError> {
1875 self.client_ctx
1876 .fee_quote(
1877 OperationId::new_random(),
1878 FeeQuoteRequest {
1879 input_amount: Amounts::new_bitcoin(amount),
1880 output_amount: Amounts::ZERO,
1881 input_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.contract_input),
1882 output_fee: Amounts::ZERO,
1883 account: Account::Primary,
1884 },
1885 )
1886 .await
1887 }
1888
1889 pub async fn send_fee_quote(&self, amount: Amount) -> Result<FeeQuote, TransactionSubmitError> {
1904 self.client_ctx
1905 .fee_quote(
1906 OperationId::new_random(),
1907 FeeQuoteRequest {
1908 input_amount: Amounts::ZERO,
1909 output_amount: Amounts::new_bitcoin(amount),
1910 input_fee: Amounts::ZERO,
1911 output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.contract_output),
1912 account: Account::Primary,
1913 },
1914 )
1915 .await
1916 }
1917
1918 pub async fn spendable_amount(
1950 &self,
1951 balance: Amount,
1952 gateway: Option<LightningGateway>,
1953 ) -> Result<Amount, SpendableAmountError> {
1954 let gateway = match gateway {
1955 Some(gateway) => gateway,
1956 None => self
1957 .get_gateway(None, false)
1958 .await?
1959 .ok_or(SpendableAmountError::NoGatewayAvailable)?,
1960 };
1961
1962 max_affordable_send_amount(
1963 balance,
1964 Amount::from_msats(1),
1965 balance,
1966 |invoice_amount: Amount| invoice_amount + gateway.fees.to_amount(&invoice_amount),
1967 |contract_amount: Amount| self.send_fee_quote(contract_amount),
1968 )
1969 .await
1970 .map_err(SpendableAmountError::Quote)?
1971 .ok_or(SpendableAmountError::BalanceTooLow { balance })
1972 }
1973
1974 pub async fn create_bolt11_invoice<M: Serialize + Send + Sync>(
1975 &self,
1976 amount: Amount,
1977 description: lightning_invoice::Bolt11InvoiceDescription,
1978 expiry_time: Option<u64>,
1979 extra_meta: M,
1980 gateway: Option<LightningGateway>,
1981 ) -> Result<(OperationId, Bolt11Invoice, [u8; 32]), CreateBolt11InvoiceError> {
1982 let receiving_key =
1983 ReceivingKey::Personal(Keypair::new(&self.secp, &mut rand::rngs::OsRng));
1984 self.create_bolt11_invoice_internal(
1985 amount,
1986 description,
1987 expiry_time,
1988 receiving_key,
1989 extra_meta,
1990 gateway,
1991 )
1992 .await
1993 }
1994
1995 #[allow(clippy::too_many_arguments)]
1998 pub async fn create_bolt11_invoice_for_user_tweaked<M: Serialize + Send + Sync>(
1999 &self,
2000 amount: Amount,
2001 description: lightning_invoice::Bolt11InvoiceDescription,
2002 expiry_time: Option<u64>,
2003 user_key: PublicKey,
2004 index: u64,
2005 extra_meta: M,
2006 gateway: Option<LightningGateway>,
2007 ) -> Result<(OperationId, Bolt11Invoice, [u8; 32]), CreateBolt11InvoiceError> {
2008 let tweaked_key = tweak_user_key(&self.secp, user_key, index);
2009 self.create_bolt11_invoice_for_user(
2010 amount,
2011 description,
2012 expiry_time,
2013 tweaked_key,
2014 extra_meta,
2015 gateway,
2016 )
2017 .await
2018 }
2019
2020 pub async fn create_bolt11_invoice_for_user<M: Serialize + Send + Sync>(
2022 &self,
2023 amount: Amount,
2024 description: lightning_invoice::Bolt11InvoiceDescription,
2025 expiry_time: Option<u64>,
2026 user_key: PublicKey,
2027 extra_meta: M,
2028 gateway: Option<LightningGateway>,
2029 ) -> Result<(OperationId, Bolt11Invoice, [u8; 32]), CreateBolt11InvoiceError> {
2030 let receiving_key = ReceivingKey::External(user_key);
2031 self.create_bolt11_invoice_internal(
2032 amount,
2033 description,
2034 expiry_time,
2035 receiving_key,
2036 extra_meta,
2037 gateway,
2038 )
2039 .await
2040 }
2041
2042 async fn create_bolt11_invoice_internal<M: Serialize + Send + Sync>(
2044 &self,
2045 amount: Amount,
2046 description: lightning_invoice::Bolt11InvoiceDescription,
2047 expiry_time: Option<u64>,
2048 receiving_key: ReceivingKey,
2049 extra_meta: M,
2050 gateway: Option<LightningGateway>,
2051 ) -> Result<(OperationId, Bolt11Invoice, [u8; 32]), CreateBolt11InvoiceError> {
2052 let gateway_id = gateway.as_ref().map(|g| g.gateway_id);
2053 let (src_node_id, short_channel_id, route_hints) = if let Some(current_gateway) = gateway {
2054 (
2055 current_gateway.node_pub_key,
2056 current_gateway.federation_index,
2057 current_gateway.route_hints,
2058 )
2059 } else {
2060 let markers = self
2062 .client_ctx
2063 .get_internal_payment_markers()
2064 .map_err(CreateBolt11InvoiceError::PaymentMarkers)?;
2065 (markers.0, markers.1, vec![])
2066 };
2067
2068 debug!(target: LOG_CLIENT_MODULE_LN, ?gateway_id, %amount, "Selected LN gateway for invoice generation");
2069
2070 let (operation_id, invoice, output, preimage) = self
2071 .create_lightning_receive_output(
2072 amount,
2073 description,
2074 receiving_key,
2075 rand::rngs::OsRng,
2076 expiry_time,
2077 src_node_id,
2078 short_channel_id,
2079 &route_hints,
2080 self.cfg.network.0,
2081 )
2082 .map_err(CreateBolt11InvoiceError::InvoiceCreation)?;
2083
2084 let tx = TransactionBuilder::new(Account::Primary)
2085 .with_outputs(self.client_ctx.make_client_outputs(output));
2086 let extra_meta = serde_json::to_value(extra_meta).expect("extra_meta is serializable");
2087 let operation_meta_gen = {
2088 let invoice = invoice.clone();
2089 move |change_range: OutPointRange| LightningOperationMeta {
2090 variant: LightningOperationMetaVariant::Receive {
2091 out_point: OutPoint {
2092 txid: change_range.txid(),
2093 out_idx: 0,
2094 },
2095 invoice: invoice.clone(),
2096 gateway_id,
2097 },
2098 extra_meta: extra_meta.clone(),
2099 }
2100 };
2101 let change_range = self
2102 .client_ctx
2103 .finalize_and_submit_transaction(
2104 operation_id,
2105 LightningCommonInit::KIND.as_str(),
2106 operation_meta_gen,
2107 tx,
2108 )
2109 .await?;
2110
2111 debug!(target: LOG_CLIENT_MODULE_LN, txid = ?change_range.txid(), ?operation_id, "Waiting for LN invoice to be confirmed");
2112
2113 self.client_ctx
2116 .transaction_updates(operation_id)
2117 .await
2118 .await_tx_accepted(change_range.txid())
2119 .await
2120 .map_err(|reason| CreateBolt11InvoiceError::OfferRejected { reason })?;
2121
2122 debug!(target: LOG_CLIENT_MODULE_LN, %invoice, "Invoice confirmed");
2123
2124 Ok((operation_id, invoice, preimage))
2125 }
2126
2127 pub async fn reclaim_ln_receive(
2147 &self,
2148 original_operation_id: OperationId,
2149 ) -> Result<OperationId, ReclaimLnReceiveError> {
2150 let operation = self.client_ctx.get_operation(original_operation_id).await?;
2151 let LightningOperationMeta {
2152 variant,
2153 extra_meta,
2154 } = operation
2155 .try_meta::<LightningOperationMeta>()
2156 .map_err(ReclaimLnReceiveError::Meta)?;
2157
2158 let (invoice, gateway_id) = match variant {
2159 LightningOperationMetaVariant::Receive {
2160 invoice,
2161 gateway_id,
2162 ..
2163 } => (invoice, gateway_id),
2164 LightningOperationMetaVariant::RecurringPaymentReceive(meta) => (meta.invoice, None),
2165 _ => return Err(ReclaimLnReceiveError::NotReclaimable),
2166 };
2167
2168 let active_states = self
2169 .client_ctx
2170 .get_own_operation_active_states(original_operation_id)
2171 .await;
2172 if active_states
2173 .iter()
2174 .any(|(state, _)| matches!(state, LightningClientStateMachines::Receive(_)))
2175 {
2176 return Err(ReclaimLnReceiveError::StillActive);
2177 }
2178
2179 let inactive_states = self
2180 .client_ctx
2181 .get_own_operation_inactive_states(original_operation_id)
2182 .await;
2183
2184 let receiving_key = inactive_states
2185 .iter()
2186 .find_map(|(state, _)| Self::ln_receive_key_from_state(state))
2187 .ok_or(ReclaimLnReceiveError::ReceiveKeyUnavailable)?;
2188 let db = self.client_ctx.module_db();
2189 let mut dbtx = db.begin_transaction().await;
2190 let reclaim_operation_id = OperationId::new_random();
2191 let operation_meta = LightningOperationMeta {
2192 variant: LightningOperationMetaVariant::ReceiveReclaim {
2193 original_operation_id,
2194 invoice: invoice.clone(),
2195 gateway_id,
2196 },
2197 extra_meta,
2198 };
2199 let state = LightningClientStateMachines::Receive(LightningReceiveStateMachine {
2200 operation_id: reclaim_operation_id,
2201 state: LightningReceiveStates::ConfirmedInvoice(LightningReceiveConfirmedInvoice {
2202 invoice,
2203 receiving_key,
2204 }),
2205 });
2206
2207 self.client_ctx
2208 .manual_operation_start_dbtx(
2209 &mut dbtx.to_ref_nc(),
2210 reclaim_operation_id,
2211 Account::Primary,
2212 LightningCommonInit::KIND.as_str(),
2213 operation_meta,
2214 vec![self.client_ctx.make_dyn_state(state)],
2215 )
2216 .await?;
2217
2218 dbtx.commit_tx().await;
2219
2220 Ok(reclaim_operation_id)
2221 }
2222
2223 fn ln_receive_key_from_state(state: &LightningClientStateMachines) -> Option<ReceivingKey> {
2224 match state {
2225 LightningClientStateMachines::Receive(receive) => match &receive.state {
2226 LightningReceiveStates::SubmittedOffer(submitted_offer) => {
2227 Some(submitted_offer.receiving_key)
2228 }
2229 LightningReceiveStates::ConfirmedInvoice(confirmed_invoice) => {
2230 Some(confirmed_invoice.receiving_key)
2231 }
2232 LightningReceiveStates::Canceled(_)
2233 | LightningReceiveStates::Funded(_)
2234 | LightningReceiveStates::Success(_) => None,
2235 },
2236 LightningClientStateMachines::InternalPay(_)
2237 | LightningClientStateMachines::LightningPay(_) => None,
2238 }
2239 }
2240
2241 #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
2242 #[allow(deprecated)]
2243 pub async fn subscribe_ln_claim(
2244 &self,
2245 operation_id: OperationId,
2246 ) -> Result<UpdateStreamOrOutcome<LnReceiveState>, LnSubscribeError> {
2247 let operation = self.client_ctx.get_operation(operation_id).await?;
2248 let LightningOperationMetaVariant::Claim { out_points } =
2249 operation.meta::<LightningOperationMeta>().variant
2250 else {
2251 return Err(LnSubscribeError::NotAClaim);
2252 };
2253
2254 let client_ctx = self.client_ctx.clone();
2255
2256 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
2257 LnReceiveState::Created
2258 | LnReceiveState::WaitingForPayment { .. }
2259 | LnReceiveState::Funded
2260 | LnReceiveState::AwaitingFunds => false,
2261 LnReceiveState::Canceled { .. } | LnReceiveState::Claimed => true,
2262 }, move || {
2263 stream! {
2264 yield LnReceiveState::AwaitingFunds;
2265
2266 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
2267 yield LnReceiveState::Claimed;
2268 } else {
2269 yield LnReceiveState::Canceled { reason: LightningReceiveError::ClaimRejected }
2270 }
2271 }
2272 }))
2273 }
2274
2275 pub async fn subscribe_ln_receive(
2276 &self,
2277 operation_id: OperationId,
2278 ) -> Result<UpdateStreamOrOutcome<LnReceiveState>, LnSubscribeError> {
2279 let operation = self.client_ctx.get_operation(operation_id).await?;
2280 let (invoice, tx_accepted_future) = match operation.meta::<LightningOperationMeta>().variant
2281 {
2282 LightningOperationMetaVariant::Receive {
2283 out_point, invoice, ..
2284 } => {
2285 let tx_accepted_future = self
2286 .client_ctx
2287 .transaction_updates(operation_id)
2288 .await
2289 .await_tx_accepted(out_point.txid);
2290 (invoice, Some(tx_accepted_future))
2291 }
2292 LightningOperationMetaVariant::ReceiveReclaim { invoice, .. } => (invoice, None),
2293 _ => return Err(LnSubscribeError::NotAReceive),
2294 };
2295
2296 let client_ctx = self.client_ctx.clone();
2297
2298 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
2299 LnReceiveState::Created
2300 | LnReceiveState::WaitingForPayment { .. }
2301 | LnReceiveState::Funded
2302 | LnReceiveState::AwaitingFunds => false,
2303 LnReceiveState::Canceled { .. } | LnReceiveState::Claimed => true,
2304 }, move || {
2305 stream! {
2306
2307 let self_ref = client_ctx.self_ref();
2308
2309 yield LnReceiveState::Created;
2310
2311 let tx_rejected = match tx_accepted_future {
2312 Some(tx_accepted_future) => tx_accepted_future.await.is_err(),
2313 None => false,
2314 };
2315 if tx_rejected {
2316 yield LnReceiveState::Canceled { reason: LightningReceiveError::Rejected };
2317 return;
2318 }
2319 yield LnReceiveState::WaitingForPayment { invoice: invoice.to_string(), timeout: invoice.expiry_time() };
2320
2321 match self_ref.await_receive_success(operation_id).await {
2322 Ok(()) => {
2323
2324 yield LnReceiveState::Funded;
2325
2326 match self_ref.await_claim_acceptance(operation_id).await {
2327 Ok(out_points) => {
2328 yield LnReceiveState::AwaitingFunds;
2329
2330 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
2331 yield LnReceiveState::Claimed;
2332 return;
2333 }
2334
2335 yield LnReceiveState::Canceled { reason: LightningReceiveError::Rejected };
2339 }
2340 Err(e) => {
2341 yield LnReceiveState::Canceled { reason: e };
2342 }
2343 }
2344 }
2345 Err(e) => {
2346 yield LnReceiveState::Canceled { reason: e };
2347 }
2348 }
2349 }
2350 }))
2351 }
2352
2353 pub async fn get_gateway(
2357 &self,
2358 gateway_id: Option<secp256k1::PublicKey>,
2359 force_internal: bool,
2360 ) -> Result<Option<LightningGateway>, GatewaySelectionError> {
2361 match gateway_id {
2362 Some(gateway_id) => {
2363 if let Some(gw) = self.select_gateway(&gateway_id).await {
2364 Ok(Some(gw))
2365 } else {
2366 self.update_gateway_cache().await?;
2369 Ok(self.select_gateway(&gateway_id).await)
2370 }
2371 }
2372 None if !force_internal => {
2373 self.update_gateway_cache().await?;
2375 let gateways = self.list_gateways().await;
2376 let gw = gateways.into_iter().choose(&mut OsRng).map(|gw| gw.info);
2377 if let Some(gw) = gw {
2378 let gw_id = gw.gateway_id;
2379 info!(%gw_id, "Using random gateway");
2380 Ok(Some(gw))
2381 } else {
2382 Err(GatewaySelectionError::NoGatewaysRegistered)
2383 }
2384 }
2385 None => Ok(None),
2386 }
2387 }
2388
2389 pub async fn await_outgoing_payment(
2393 &self,
2394 operation_id: OperationId,
2395 ) -> Result<LightningPaymentOutcome, LnSubscribeError> {
2396 let operation = self.client_ctx.get_operation(operation_id).await?;
2397 let variant = operation.meta::<LightningOperationMeta>().variant;
2398 let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
2399 is_internal_payment,
2400 ..
2401 }) = variant
2402 else {
2403 return Err(LnSubscribeError::NotAPayment);
2404 };
2405
2406 let mut final_state = None;
2407
2408 if is_internal_payment {
2410 let updates = self.subscribe_internal_pay(operation_id).await?;
2411 let mut stream = updates.into_stream();
2412 while let Some(update) = stream.next().await {
2413 match update {
2414 InternalPayState::Preimage(preimage) => {
2415 final_state = Some(LightningPaymentOutcome::Success {
2416 preimage: preimage.0.consensus_encode_to_hex(),
2417 });
2418 }
2419 InternalPayState::RefundSuccess {
2420 out_points: _,
2421 error,
2422 } => {
2423 final_state = Some(LightningPaymentOutcome::Failure {
2424 error_message: format!("LNv1 internal payment was refunded: {error:?}"),
2425 });
2426 }
2427 InternalPayState::FundingFailed { error } => {
2428 final_state = Some(LightningPaymentOutcome::Failure {
2429 error_message: format!(
2430 "LNv1 internal payment funding failed: {error:?}"
2431 ),
2432 });
2433 }
2434 InternalPayState::RefundError {
2435 error_message,
2436 error,
2437 } => {
2438 final_state = Some(LightningPaymentOutcome::Failure {
2439 error_message: format!(
2440 "LNv1 refund failed: {error_message}: {error:?}"
2441 ),
2442 });
2443 }
2444 InternalPayState::UnexpectedError(error) => {
2445 final_state = Some(LightningPaymentOutcome::Failure {
2446 error_message: error,
2447 });
2448 }
2449 InternalPayState::Funding => {}
2450 }
2451 }
2452 } else {
2453 let updates = self.subscribe_ln_pay(operation_id).await?;
2454 let mut stream = updates.into_stream();
2455 while let Some(update) = stream.next().await {
2456 match update {
2457 LnPayState::Success { preimage } => {
2458 final_state = Some(LightningPaymentOutcome::Success { preimage });
2459 }
2460 LnPayState::Refunded { gateway_error } => {
2461 final_state = Some(LightningPaymentOutcome::Failure {
2462 error_message: format!(
2463 "LNv1 external payment was refunded: {gateway_error:?}"
2464 ),
2465 });
2466 }
2467 LnPayState::UnexpectedError { error_message } => {
2468 final_state = Some(LightningPaymentOutcome::Failure { error_message });
2469 }
2470 _ => {}
2471 }
2472 }
2473 }
2474
2475 final_state.ok_or(LnSubscribeError::NoFinalState)
2476 }
2477}
2478
2479#[derive(Debug, Clone, Serialize, Deserialize)]
2482#[serde(rename_all = "snake_case")]
2483pub struct PayInvoiceResponse {
2484 operation_id: OperationId,
2485 contract_id: ContractId,
2486 preimage: String,
2487}
2488
2489#[allow(clippy::large_enum_variant)]
2490#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
2491pub enum LightningClientStateMachines {
2492 InternalPay(IncomingStateMachine),
2493 LightningPay(LightningPayStateMachine),
2494 Receive(LightningReceiveStateMachine),
2495}
2496
2497impl IntoDynInstance for LightningClientStateMachines {
2498 type DynType = DynState;
2499
2500 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
2501 DynState::from_typed(instance_id, self)
2502 }
2503}
2504
2505impl State for LightningClientStateMachines {
2506 type ModuleContext = LightningClientContext;
2507
2508 fn transitions(
2509 &self,
2510 context: &Self::ModuleContext,
2511 global_context: &DynGlobalClientContext,
2512 ) -> Vec<StateTransition<Self>> {
2513 match self {
2514 LightningClientStateMachines::InternalPay(internal_pay_state) => {
2515 sm_enum_variant_translation!(
2516 internal_pay_state.transitions(context, global_context),
2517 LightningClientStateMachines::InternalPay
2518 )
2519 }
2520 LightningClientStateMachines::LightningPay(lightning_pay_state) => {
2521 sm_enum_variant_translation!(
2522 lightning_pay_state.transitions(context, global_context),
2523 LightningClientStateMachines::LightningPay
2524 )
2525 }
2526 LightningClientStateMachines::Receive(receive_state) => {
2527 sm_enum_variant_translation!(
2528 receive_state.transitions(context, global_context),
2529 LightningClientStateMachines::Receive
2530 )
2531 }
2532 }
2533 }
2534
2535 fn operation_id(&self) -> OperationId {
2536 match self {
2537 LightningClientStateMachines::InternalPay(internal_pay_state) => {
2538 internal_pay_state.operation_id()
2539 }
2540 LightningClientStateMachines::LightningPay(lightning_pay_state) => {
2541 lightning_pay_state.operation_id()
2542 }
2543 LightningClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
2544 }
2545 }
2546}
2547
2548async fn fetch_and_validate_offer(
2549 module_api: &DynModuleApi,
2550 payment_hash: sha256::Hash,
2551 amount_msat: Amount,
2552) -> Result<IncomingContractOffer, IncomingSmError> {
2553 let offer = timeout(Duration::from_secs(5), module_api.fetch_offer(payment_hash))
2554 .await
2555 .map_err(|_| IncomingSmError::TimeoutFetchingOffer { payment_hash })?
2556 .map_err(|e| IncomingSmError::FetchContractError {
2557 payment_hash,
2558 error_message: e.to_string(),
2559 })?;
2560
2561 if offer.amount > amount_msat {
2562 return Err(IncomingSmError::ViolatedFeePolicy {
2563 offer_amount: offer.amount,
2564 payment_amount: amount_msat,
2565 });
2566 }
2567 if offer.hash != payment_hash {
2568 return Err(IncomingSmError::InvalidOffer {
2569 offer_hash: offer.hash,
2570 payment_hash,
2571 });
2572 }
2573 Ok(offer)
2574}
2575
2576pub async fn create_incoming_contract_output(
2577 module_api: &DynModuleApi,
2578 payment_hash: sha256::Hash,
2579 amount_msat: Amount,
2580 redeem_key: &Keypair,
2581) -> Result<(LightningOutputV0, Amount, ContractId), IncomingSmError> {
2582 let offer = fetch_and_validate_offer(module_api, payment_hash, amount_msat).await?;
2583 let our_pub_key = secp256k1::PublicKey::from_keypair(redeem_key);
2584 let contract = IncomingContract {
2585 hash: offer.hash,
2586 encrypted_preimage: offer.encrypted_preimage.clone(),
2587 decrypted_preimage: DecryptedPreimage::Pending,
2588 gateway_key: our_pub_key,
2589 };
2590 let contract_id = contract.contract_id();
2591
2592 match module_api.fetch_contract(contract_id).await {
2598 Ok(None) => {}
2599 Ok(Some(_)) => {
2600 return Err(IncomingSmError::ContractAlreadyExists { payment_hash });
2601 }
2602 Err(error) => {
2603 return Err(IncomingSmError::FetchContractError {
2604 payment_hash,
2605 error_message: error.to_string(),
2606 });
2607 }
2608 }
2609
2610 let incoming_output = LightningOutputV0::Contract(ContractOutput {
2611 amount: offer.amount,
2612 contract: Contract::Incoming(contract),
2613 });
2614
2615 Ok((incoming_output, offer.amount, contract_id))
2616}
2617
2618#[derive(Debug, Encodable, Decodable, Serialize, Deserialize)]
2619pub struct OutgoingLightningPayment {
2620 pub payment_type: PayType,
2621 pub contract_id: ContractId,
2622 pub fee: Amount,
2623}
2624
2625async fn set_payment_result(
2626 dbtx: &mut DatabaseTransaction<'_>,
2627 payment_hash: sha256::Hash,
2628 payment_type: PayType,
2629 contract_id: ContractId,
2630 fee: Amount,
2631) {
2632 if let Some(mut payment_result) = dbtx.get_value(&PaymentResultKey { payment_hash }).await {
2633 payment_result.completed_payment = Some(OutgoingLightningPayment {
2634 payment_type,
2635 contract_id,
2636 fee,
2637 });
2638 dbtx.insert_entry(&PaymentResultKey { payment_hash }, &payment_result)
2639 .await;
2640 }
2641}
2642
2643pub fn tweak_user_key<Ctx: Verification + Signing>(
2646 secp: &Secp256k1<Ctx>,
2647 user_key: PublicKey,
2648 index: u64,
2649) -> PublicKey {
2650 let mut hasher = HmacEngine::<sha256::Hash>::new(&user_key.serialize()[..]);
2651 hasher.input(&index.to_be_bytes());
2652 let tweak = Hmac::from_engine(hasher).to_byte_array();
2653
2654 user_key
2655 .add_exp_tweak(secp, &Scalar::from_be_bytes(tweak).expect("can't fail"))
2656 .expect("tweak is always 32 bytes, other failure modes are negligible")
2657}
2658
2659fn tweak_user_secret_key<Ctx: Verification + Signing>(
2662 secp: &Secp256k1<Ctx>,
2663 key_pair: Keypair,
2664 index: u64,
2665) -> Keypair {
2666 let public_key = key_pair.public_key();
2667 let mut hasher = HmacEngine::<sha256::Hash>::new(&public_key.serialize()[..]);
2668 hasher.input(&index.to_be_bytes());
2669 let tweak = Hmac::from_engine(hasher).to_byte_array();
2670
2671 let secret_key = key_pair.secret_key();
2672 let sk_tweaked = secret_key
2673 .add_tweak(&Scalar::from_be_bytes(tweak).expect("Cant fail"))
2674 .expect("Cant fail");
2675 Keypair::from_secret_key(secp, &sk_tweaked)
2676}
2677
2678#[derive(Debug, Clone)]
2681pub enum PaymentInfo {
2682 Bolt11(Bolt11Invoice),
2683 Lnurl(lnurl::pay::PayResponse),
2684}
2685
2686impl PaymentInfo {
2687 pub async fn parse(info: &str) -> Result<Self, PaymentInfoError> {
2690 let info = info.trim();
2691 match lightning_invoice::Bolt11Invoice::from_str(info) {
2692 Ok(invoice) => {
2693 debug!("Parsed parameter as bolt11 invoice: {invoice}");
2694 Ok(Self::Bolt11(invoice))
2695 }
2696 Err(e) => {
2697 let lnurl = if info.to_lowercase().starts_with("lnurl") {
2698 lnurl::lnurl::LnUrl::from_str(info).map_err(PaymentInfoError::LnurlDecode)?
2699 } else if info.contains('@') {
2700 lnurl::lightning_address::LightningAddress::from_str(info)
2701 .map_err(PaymentInfoError::LnurlDecode)?
2702 .lnurl()
2703 } else {
2704 return Err(PaymentInfoError::NotAnInvoiceOrLnurl(e));
2705 };
2706 debug!("Parsed parameter as lnurl: {lnurl:?}");
2707 let async_client = lnurl::AsyncClient::from_client(reqwest::Client::new());
2708 let response = async_client
2709 .make_request(&lnurl.url)
2710 .await
2711 .map_err(PaymentInfoError::Lnurl)?;
2712 match response {
2713 lnurl::LnUrlResponse::LnUrlPayResponse(response) => Ok(Self::Lnurl(response)),
2714 _ => Err(PaymentInfoError::NotAPayRequest),
2715 }
2716 }
2717 }
2718 }
2719
2720 pub async fn get_invoice(
2723 self,
2724 amount: Option<Amount>,
2725 lnurl_comment: Option<String>,
2726 ) -> Result<Bolt11Invoice, PaymentInfoError> {
2727 match self {
2728 Self::Bolt11(invoice) => {
2729 match (invoice.amount_milli_satoshis(), amount) {
2730 (Some(_), Some(_)) => {
2731 return Err(PaymentInfoError::AmountInInvoiceAndCommandLine);
2732 }
2733 (None, _) => {
2734 return Err(PaymentInfoError::AmountMissingFromInvoice);
2735 }
2736 _ => {}
2737 }
2738 Ok(invoice)
2739 }
2740 Self::Lnurl(response) => {
2741 let amount = amount.ok_or(PaymentInfoError::AmountRequiredForLnurl)?;
2742 let async_client = lnurl::AsyncClient::from_client(reqwest::Client::new());
2743 let invoice = async_client
2744 .get_invoice(&response, amount.msats, None, lnurl_comment.as_deref())
2745 .await
2746 .map_err(PaymentInfoError::Lnurl)?;
2747 let invoice = Bolt11Invoice::from_str(invoice.invoice())
2748 .map_err(PaymentInfoError::InvoiceParse)?;
2749 let invoice_amount = invoice.amount_milli_satoshis();
2750 if invoice_amount != Some(amount.msats) {
2751 return Err(PaymentInfoError::AmountMismatch {
2752 requested: amount,
2753 generated: invoice_amount.map(Amount::from_msats),
2754 });
2755 }
2756 Ok(invoice)
2757 }
2758 }
2759 }
2760}
2761
2762pub async fn get_invoice(
2764 info: &str,
2765 amount: Option<Amount>,
2766 lnurl_comment: Option<String>,
2767) -> Result<Bolt11Invoice, PaymentInfoError> {
2768 PaymentInfo::parse(info)
2769 .await?
2770 .get_invoice(amount, lnurl_comment)
2771 .await
2772}
2773
2774#[derive(Debug, Clone)]
2775pub struct LightningClientContext {
2776 pub ln_decoder: Decoder,
2777 pub redeem_key: Keypair,
2778 pub gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
2779 pub client_ctx: Option<ClientContext<LightningClientModule>>,
2781}
2782
2783impl fedimint_client_module::sm::Context for LightningClientContext {
2784 const KIND: Option<ModuleKind> = Some(KIND);
2785}
2786
2787#[apply(async_trait_maybe_send!)]
2788pub trait GatewayConnection: std::fmt::Debug {
2789 async fn verify_gateway_availability(
2792 &self,
2793 gateway: &LightningGateway,
2794 ) -> Result<(), ServerError>;
2795
2796 async fn pay_invoice(
2798 &self,
2799 gateway: LightningGateway,
2800 payload: PayInvoicePayload,
2801 ) -> Result<String, GatewayPayError>;
2802}
2803
2804#[derive(Debug)]
2805pub struct RealGatewayConnection {
2806 pub api: GatewayApi,
2807}
2808
2809#[apply(async_trait_maybe_send!)]
2810impl GatewayConnection for RealGatewayConnection {
2811 async fn verify_gateway_availability(
2812 &self,
2813 gateway: &LightningGateway,
2814 ) -> Result<(), ServerError> {
2815 self.api
2816 .request::<PublicKey, serde_json::Value>(
2817 &gateway.api,
2818 Method::GET,
2819 GET_GATEWAY_ID_ENDPOINT,
2820 None,
2821 )
2822 .await?;
2823 Ok(())
2824 }
2825
2826 async fn pay_invoice(
2827 &self,
2828 gateway: LightningGateway,
2829 payload: PayInvoicePayload,
2830 ) -> Result<String, GatewayPayError> {
2831 self.api
2834 .request(
2835 &gateway.api,
2836 Method::POST,
2837 PAY_INVOICE_ENDPOINT,
2838 Some(payload),
2839 )
2840 .await
2841 .map_err(|e| GatewayPayError::GatewayInternalError {
2842 error_code: None,
2843 error_message: e.to_string(),
2844 })
2845 }
2846}
2847
2848#[derive(Debug)]
2849pub struct MockGatewayConnection;
2850
2851#[apply(async_trait_maybe_send!)]
2852impl GatewayConnection for MockGatewayConnection {
2853 async fn verify_gateway_availability(
2854 &self,
2855 _gateway: &LightningGateway,
2856 ) -> Result<(), ServerError> {
2857 Ok(())
2858 }
2859
2860 async fn pay_invoice(
2861 &self,
2862 _gateway: LightningGateway,
2863 _payload: PayInvoicePayload,
2864 ) -> Result<String, GatewayPayError> {
2865 Ok("01".repeat(32))
2869 }
2870}