1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::must_use_candidate)]
6
7mod api;
8#[cfg(feature = "cli")]
9mod cli;
10mod db;
11pub mod events;
12mod receive_sm;
13mod send_sm;
14
15use std::collections::{BTreeMap, BTreeSet};
16use std::sync::Arc;
17
18use async_stream::stream;
19use bitcoin::hashes::{Hash, sha256};
20use bitcoin::secp256k1;
21use db::{DbKeyPrefix, GatewayKey, IncomingContractStreamIndexKey};
22use fedimint_api_client::api::{DynModuleApi, ServerError};
23use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
24use fedimint_client_module::module::recovery::NoModuleBackup;
25use fedimint_client_module::module::{ClientContext, ClientModule, OutPointRange};
26use fedimint_client_module::oplog::UpdateStreamOrOutcome;
27use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
28use fedimint_client_module::transaction::{
29 ClientOutput, ClientOutputBundle, ClientOutputSM, TransactionBuilder,
30};
31use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
32use fedimint_core::config::FederationId;
33use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
34use fedimint_core::db::{DatabaseTransaction, IDatabaseTransactionOpsCoreTyped};
35use fedimint_core::encoding::{Decodable, Encodable};
36use fedimint_core::module::{
37 Amounts, ApiAuth, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
38};
39use fedimint_core::secp256k1::SECP256K1;
40use fedimint_core::task::TaskGroup;
41use fedimint_core::time::duration_since_epoch;
42use fedimint_core::util::SafeUrl;
43use fedimint_core::{Amount, apply, async_trait_maybe_send};
44use fedimint_derive_secret::{ChildId, DerivableSecret};
45use fedimint_lnv2_common::config::LightningClientConfig;
46use fedimint_lnv2_common::contracts::{IncomingContract, OutgoingContract, PaymentImage};
47use fedimint_lnv2_common::gateway_api::{
48 GatewayConnection, PaymentFee, RealGatewayConnection, RoutingInfo,
49};
50use fedimint_lnv2_common::{
51 Bolt11InvoiceDescription, GatewayApi, KIND, LightningCommonInit, LightningInvoice,
52 LightningModuleTypes, LightningOutput, LightningOutputV0, lnurl, tweak,
53};
54use futures::StreamExt;
55use lightning_invoice::{Bolt11Invoice, Currency};
56use secp256k1::{Keypair, PublicKey, Scalar, SecretKey, ecdh};
57use serde::{Deserialize, Serialize};
58use serde_json::Value;
59use strum::IntoEnumIterator as _;
60use thiserror::Error;
61use tpe::{AggregateDecryptionKey, derive_agg_dk};
62use tracing::warn;
63
64use crate::api::LightningFederationApi;
65use crate::events::SendPaymentEvent;
66use crate::receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
67use crate::send_sm::{SendSMCommon, SendSMState, SendStateMachine};
68
69const EXPIRATION_DELTA_LIMIT: u64 = 1440;
72
73const CONTRACT_CONFIRMATION_BUFFER: u64 = 12;
75
76#[allow(clippy::large_enum_variant)]
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub enum LightningOperationMeta {
79 Send(SendOperationMeta),
80 Receive(ReceiveOperationMeta),
81 LnurlReceive(LnurlReceiveOperationMeta),
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct SendOperationMeta {
86 pub change_outpoint_range: OutPointRange,
87 pub gateway: SafeUrl,
88 pub contract: OutgoingContract,
89 pub invoice: LightningInvoice,
90 pub custom_meta: Value,
91}
92
93impl SendOperationMeta {
94 pub fn gateway_fee(&self) -> Amount {
96 match &self.invoice {
97 LightningInvoice::Bolt11(invoice) => self.contract.amount.saturating_sub(
98 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount")),
99 ),
100 }
101 }
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct ReceiveOperationMeta {
106 pub gateway: SafeUrl,
107 pub contract: IncomingContract,
108 pub invoice: LightningInvoice,
109 pub custom_meta: Value,
110}
111
112impl ReceiveOperationMeta {
113 pub fn gateway_fee(&self) -> Amount {
115 match &self.invoice {
116 LightningInvoice::Bolt11(invoice) => {
117 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount"))
118 .saturating_sub(self.contract.commitment.amount)
119 }
120 }
121 }
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct LnurlReceiveOperationMeta {
126 pub contract: IncomingContract,
127 pub custom_meta: Value,
128}
129
130#[cfg_attr(doc, aquamarine::aquamarine)]
131#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
149pub enum SendOperationState {
150 Funding,
152 Funded,
154 Success([u8; 32]),
156 Refunding,
158 Refunded,
160 Failure,
162}
163
164#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
166pub enum FinalSendOperationState {
167 Success,
169 Refunded,
171 Failure,
173}
174
175pub type SendResult = Result<OperationId, SendPaymentError>;
176
177#[cfg_attr(doc, aquamarine::aquamarine)]
178#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
190pub enum ReceiveOperationState {
191 Pending,
193 Expired,
195 Claiming,
197 Claimed,
199 Failure,
201}
202
203#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
205pub enum FinalReceiveOperationState {
206 Expired,
208 Claimed,
210 Failure,
212}
213
214pub type ReceiveResult = Result<(Bolt11Invoice, OperationId), ReceiveError>;
215
216#[derive(Clone)]
217pub struct LightningClientInit {
218 pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
219 pub custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
220}
221
222impl std::fmt::Debug for LightningClientInit {
223 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224 f.debug_struct("LightningClientInit")
225 .field("gateway_conn", &self.gateway_conn)
226 .field("custom_meta_fn", &"<function>")
227 .finish()
228 }
229}
230
231impl Default for LightningClientInit {
232 fn default() -> Self {
233 LightningClientInit {
234 gateway_conn: None,
235 custom_meta_fn: Arc::new(|| Value::Null),
236 }
237 }
238}
239
240impl ModuleInit for LightningClientInit {
241 type Common = LightningCommonInit;
242
243 async fn dump_database(
244 &self,
245 _dbtx: &mut DatabaseTransaction<'_>,
246 _prefix_names: Vec<String>,
247 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
248 Box::new(BTreeMap::new().into_iter())
249 }
250}
251
252#[apply(async_trait_maybe_send!)]
253impl ClientModuleInit for LightningClientInit {
254 type Module = LightningClientModule;
255
256 fn supported_api_versions(&self) -> MultiApiVersion {
257 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
258 .expect("no version conflicts")
259 }
260
261 async fn init(&self, args: &ClientModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
262 let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
263 gateway_conn
264 } else {
265 let api = GatewayApi::new(None, args.connector_registry.clone());
266 Arc::new(RealGatewayConnection { api })
267 };
268 Ok(LightningClientModule::new(
269 *args.federation_id(),
270 args.cfg().clone(),
271 args.notifier().clone(),
272 args.context(),
273 args.module_api().clone(),
274 args.module_root_secret(),
275 gateway_conn,
276 self.custom_meta_fn.clone(),
277 args.admin_auth().cloned(),
278 args.task_group(),
279 ))
280 }
281
282 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
283 Some(
284 DbKeyPrefix::iter()
285 .map(|p| p as u8)
286 .chain(
287 DbKeyPrefix::ExternalReservedStart as u8
288 ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
289 )
290 .collect(),
291 )
292 }
293}
294
295#[derive(Debug, Clone)]
296pub struct LightningClientContext {
297 federation_id: FederationId,
298 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
299 pub(crate) client_ctx: ClientContext<LightningClientModule>,
300}
301
302impl Context for LightningClientContext {
303 const KIND: Option<ModuleKind> = Some(KIND);
304}
305
306#[derive(Debug, Clone)]
307pub struct LightningClientModule {
308 federation_id: FederationId,
309 cfg: LightningClientConfig,
310 notifier: ModuleNotifier<LightningClientStateMachines>,
311 client_ctx: ClientContext<Self>,
312 module_api: DynModuleApi,
313 keypair: Keypair,
314 lnurl_keypair: Keypair,
315 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
316 #[allow(unused)] admin_auth: Option<ApiAuth>,
318}
319
320#[apply(async_trait_maybe_send!)]
321impl ClientModule for LightningClientModule {
322 type Init = LightningClientInit;
323 type Common = LightningModuleTypes;
324 type Backup = NoModuleBackup;
325 type ModuleStateMachineContext = LightningClientContext;
326 type States = LightningClientStateMachines;
327
328 fn context(&self) -> Self::ModuleStateMachineContext {
329 LightningClientContext {
330 federation_id: self.federation_id,
331 gateway_conn: self.gateway_conn.clone(),
332 client_ctx: self.client_ctx.clone(),
333 }
334 }
335
336 fn input_fee(
337 &self,
338 amounts: &Amounts,
339 _input: &<Self::Common as ModuleCommon>::Input,
340 ) -> Option<Amounts> {
341 Some(Amounts::new_bitcoin(
342 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
343 ))
344 }
345
346 fn output_fee(
347 &self,
348 amounts: &Amounts,
349 _output: &<Self::Common as ModuleCommon>::Output,
350 ) -> Option<Amounts> {
351 Some(Amounts::new_bitcoin(
352 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
353 ))
354 }
355
356 #[cfg(feature = "cli")]
357 async fn handle_cli_command(
358 &self,
359 args: &[std::ffi::OsString],
360 ) -> anyhow::Result<serde_json::Value> {
361 cli::handle_cli_command(self, args).await
362 }
363}
364
365impl LightningClientModule {
366 #[allow(clippy::too_many_arguments)]
367 fn new(
368 federation_id: FederationId,
369 cfg: LightningClientConfig,
370 notifier: ModuleNotifier<LightningClientStateMachines>,
371 client_ctx: ClientContext<Self>,
372 module_api: DynModuleApi,
373 module_root_secret: &DerivableSecret,
374 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
375 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
376 admin_auth: Option<ApiAuth>,
377 task_group: &TaskGroup,
378 ) -> Self {
379 let module = Self {
380 federation_id,
381 cfg,
382 notifier,
383 client_ctx,
384 module_api,
385 keypair: module_root_secret
386 .child_key(ChildId(0))
387 .to_secp_key(SECP256K1),
388 lnurl_keypair: module_root_secret
389 .child_key(ChildId(1))
390 .to_secp_key(SECP256K1),
391 gateway_conn,
392 admin_auth,
393 };
394
395 module.spawn_receive_lnurl_task(custom_meta_fn, task_group);
396
397 module.spawn_gateway_map_update_task(task_group);
398
399 module
400 }
401
402 fn spawn_gateway_map_update_task(&self, task_group: &TaskGroup) {
403 let module = self.clone();
404
405 task_group.spawn_cancellable("gateway_map_update_task", async move {
406 module.update_gateway_map().await;
407 });
408 }
409
410 async fn update_gateway_map(&self) {
411 if let Ok(gateways) = self.module_api.gateways().await {
418 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
419
420 for gateway in gateways {
421 if let Ok(Some(routing_info)) = self
422 .gateway_conn
423 .routing_info(gateway.clone(), &self.federation_id)
424 .await
425 {
426 dbtx.insert_entry(&GatewayKey(routing_info.lightning_public_key), &gateway)
427 .await;
428 }
429 }
430
431 if let Err(e) = dbtx.commit_tx_result().await {
432 warn!("Failed to commit the updated gateway mapping to the database: {e}");
433 }
434 }
435 }
436
437 pub async fn select_gateway(
438 &self,
439 invoice: Option<Bolt11Invoice>,
440 ) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
441 let gateways = self
442 .module_api
443 .gateways()
444 .await
445 .map_err(|e| SelectGatewayError::FederationError(e.to_string()))?;
446
447 if gateways.is_empty() {
448 return Err(SelectGatewayError::NoVettedGateways);
449 }
450
451 if let Some(invoice) = invoice
452 && let Some(gateway) = self
453 .client_ctx
454 .module_db()
455 .begin_transaction_nc()
456 .await
457 .get_value(&GatewayKey(invoice.recover_payee_pub_key()))
458 .await
459 .filter(|gateway| gateways.contains(gateway))
460 && let Ok(Some(routing_info)) = self.routing_info(&gateway).await
461 {
462 return Ok((gateway, routing_info));
463 }
464
465 for gateway in gateways {
466 if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
467 return Ok((gateway, routing_info));
468 }
469 }
470
471 Err(SelectGatewayError::FailedToFetchRoutingInfo)
472 }
473
474 async fn routing_info(&self, gateway: &SafeUrl) -> Result<Option<RoutingInfo>, ServerError> {
475 self.gateway_conn
476 .routing_info(gateway.clone(), &self.federation_id)
477 .await
478 }
479
480 #[allow(clippy::too_many_lines)]
497 pub async fn send(
498 &self,
499 invoice: Bolt11Invoice,
500 gateway: Option<SafeUrl>,
501 custom_meta: Value,
502 ) -> Result<OperationId, SendPaymentError> {
503 let amount = invoice
504 .amount_milli_satoshis()
505 .ok_or(SendPaymentError::InvoiceMissingAmount)?;
506
507 if invoice.is_expired() {
508 return Err(SendPaymentError::InvoiceExpired);
509 }
510
511 if self.cfg.network != invoice.currency().into() {
512 return Err(SendPaymentError::WrongCurrency {
513 invoice_currency: invoice.currency(),
514 federation_currency: self.cfg.network.into(),
515 });
516 }
517
518 let operation_id = self.get_next_operation_id(&invoice).await?;
519
520 let (ephemeral_tweak, ephemeral_pk) = tweak::generate(self.keypair.public_key());
521
522 let refund_keypair = SecretKey::from_slice(&ephemeral_tweak)
523 .expect("32 bytes, within curve order")
524 .keypair(secp256k1::SECP256K1);
525
526 let (gateway_api, routing_info) = match gateway {
527 Some(gateway_api) => (
528 gateway_api.clone(),
529 self.routing_info(&gateway_api)
530 .await
531 .map_err(|e| SendPaymentError::GatewayConnectionError(e.to_string()))?
532 .ok_or(SendPaymentError::UnknownFederation)?,
533 ),
534 None => self
535 .select_gateway(Some(invoice.clone()))
536 .await
537 .map_err(SendPaymentError::FailedToSelectGateway)?,
538 };
539
540 let (send_fee, expiration_delta) = routing_info.send_parameters(&invoice);
541
542 if !send_fee.le(&PaymentFee::SEND_FEE_LIMIT) {
543 return Err(SendPaymentError::PaymentFeeExceedsLimit);
544 }
545
546 if EXPIRATION_DELTA_LIMIT < expiration_delta {
547 return Err(SendPaymentError::ExpirationDeltaExceedsLimit);
548 }
549
550 let consensus_block_count = self
551 .module_api
552 .consensus_block_count()
553 .await
554 .map_err(|e| SendPaymentError::FederationError(e.to_string()))?;
555
556 let contract = OutgoingContract {
557 payment_image: PaymentImage::Hash(*invoice.payment_hash()),
558 amount: send_fee.add_to(amount),
559 expiration: consensus_block_count + expiration_delta + CONTRACT_CONFIRMATION_BUFFER,
560 claim_pk: routing_info.module_public_key,
561 refund_pk: refund_keypair.public_key(),
562 ephemeral_pk,
563 };
564
565 let contract_clone = contract.clone();
566 let gateway_api_clone = gateway_api.clone();
567 let invoice_clone = invoice.clone();
568
569 let client_output = ClientOutput::<LightningOutput> {
570 output: LightningOutput::V0(LightningOutputV0::Outgoing(contract.clone())),
571 amounts: Amounts::new_bitcoin(contract.amount),
572 };
573
574 let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
575 state_machines: Arc::new(move |range: OutPointRange| {
576 vec![LightningClientStateMachines::Send(SendStateMachine {
577 common: SendSMCommon {
578 operation_id,
579 outpoint: range.into_iter().next().unwrap(),
580 contract: contract_clone.clone(),
581 gateway_api: Some(gateway_api_clone.clone()),
582 invoice: Some(LightningInvoice::Bolt11(invoice_clone.clone())),
583 refund_keypair,
584 },
585 state: SendSMState::Funding,
586 })]
587 }),
588 };
589
590 let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
591 vec![client_output],
592 vec![client_output_sm],
593 ));
594
595 let transaction = TransactionBuilder::new().with_outputs(client_output);
596
597 self.client_ctx
598 .finalize_and_submit_transaction(
599 operation_id,
600 LightningCommonInit::KIND.as_str(),
601 move |change_outpoint_range| {
602 LightningOperationMeta::Send(SendOperationMeta {
603 change_outpoint_range,
604 gateway: gateway_api.clone(),
605 contract: contract.clone(),
606 invoice: LightningInvoice::Bolt11(invoice.clone()),
607 custom_meta: custom_meta.clone(),
608 })
609 },
610 transaction,
611 )
612 .await
613 .map_err(|e| SendPaymentError::FinalizationError(e.to_string()))?;
614
615 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
616
617 self.client_ctx
618 .log_event(
619 &mut dbtx,
620 SendPaymentEvent {
621 operation_id,
622 amount: send_fee.add_to(amount),
623 fee: Some(send_fee.fee(amount)),
624 },
625 )
626 .await;
627
628 dbtx.commit_tx().await;
629
630 Ok(operation_id)
631 }
632
633 async fn get_next_operation_id(
634 &self,
635 invoice: &Bolt11Invoice,
636 ) -> Result<OperationId, SendPaymentError> {
637 for payment_attempt in 0..u64::MAX {
638 let operation_id = OperationId::from_encodable(&(invoice.clone(), payment_attempt));
639
640 if !self.client_ctx.operation_exists(operation_id).await {
641 return Ok(operation_id);
642 }
643
644 if self.client_ctx.has_active_states(operation_id).await {
645 return Err(SendPaymentError::PendingPreviousPayment(operation_id));
646 }
647
648 let mut stream = self
649 .subscribe_send_operation_state_updates(operation_id)
650 .await
651 .expect("operation_id exists")
652 .into_stream();
653
654 while let Some(state) = stream.next().await {
657 if let SendOperationState::Success(_) = state {
658 return Err(SendPaymentError::SuccessfulPreviousPayment(operation_id));
659 }
660 }
661 }
662
663 panic!("We could not find an unused operation id for sending a lightning payment");
664 }
665
666 pub async fn subscribe_send_operation_state_updates(
668 &self,
669 operation_id: OperationId,
670 ) -> anyhow::Result<UpdateStreamOrOutcome<SendOperationState>> {
671 let operation = self.client_ctx.get_operation(operation_id).await?;
672 let mut stream = self.notifier.subscribe(operation_id).await;
673 let client_ctx = self.client_ctx.clone();
674 let module_api = self.module_api.clone();
675
676 Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
677 stream! {
678 loop {
679 if let Some(LightningClientStateMachines::Send(state)) = stream.next().await {
680 match state.state {
681 SendSMState::Funding => yield SendOperationState::Funding,
682 SendSMState::Funded => yield SendOperationState::Funded,
683 SendSMState::Success(preimage) => {
684 assert!(state.common.contract.verify_preimage(&preimage));
686
687 yield SendOperationState::Success(preimage);
688 return;
689 },
690 SendSMState::Refunding(out_points) => {
691 yield SendOperationState::Refunding;
692
693 if client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await.is_ok() {
694 yield SendOperationState::Refunded;
695 return;
696 }
697
698 if let Some(preimage) = module_api.await_preimage(
702 state.common.outpoint,
703 0
704 ).await
705 && state.common.contract.verify_preimage(&preimage) {
706 yield SendOperationState::Success(preimage);
707 return;
708 }
709
710 yield SendOperationState::Failure;
711 return;
712 },
713 SendSMState::Rejected(..) => {
714 yield SendOperationState::Failure;
715 return;
716 },
717 }
718 }
719 }
720 }
721 }))
722 }
723
724 pub async fn await_final_send_operation_state(
726 &self,
727 operation_id: OperationId,
728 ) -> anyhow::Result<FinalSendOperationState> {
729 let state = self
730 .subscribe_send_operation_state_updates(operation_id)
731 .await?
732 .into_stream()
733 .filter_map(|state| {
734 futures::future::ready(match state {
735 SendOperationState::Success(_) => Some(FinalSendOperationState::Success),
736 SendOperationState::Refunded => Some(FinalSendOperationState::Refunded),
737 SendOperationState::Failure => Some(FinalSendOperationState::Failure),
738 _ => None,
739 })
740 })
741 .next()
742 .await
743 .expect("Stream contains one final state");
744
745 Ok(state)
746 }
747
748 pub async fn receive(
760 &self,
761 amount: Amount,
762 expiry_secs: u32,
763 description: Bolt11InvoiceDescription,
764 gateway: Option<SafeUrl>,
765 custom_meta: Value,
766 ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
767 let (gateway, contract, invoice) = self
768 .create_contract_and_fetch_invoice(
769 self.keypair.public_key(),
770 amount,
771 expiry_secs,
772 description,
773 gateway,
774 )
775 .await?;
776
777 let operation_id = self
778 .receive_incoming_contract(
779 self.keypair.secret_key(),
780 contract.clone(),
781 LightningOperationMeta::Receive(ReceiveOperationMeta {
782 gateway,
783 contract,
784 invoice: LightningInvoice::Bolt11(invoice.clone()),
785 custom_meta,
786 }),
787 )
788 .await
789 .expect("The contract has been generated with our public key");
790
791 Ok((invoice, operation_id))
792 }
793
794 async fn create_contract_and_fetch_invoice(
798 &self,
799 recipient_static_pk: PublicKey,
800 amount: Amount,
801 expiry_secs: u32,
802 description: Bolt11InvoiceDescription,
803 gateway: Option<SafeUrl>,
804 ) -> Result<(SafeUrl, IncomingContract, Bolt11Invoice), ReceiveError> {
805 let (ephemeral_tweak, ephemeral_pk) = tweak::generate(recipient_static_pk);
806
807 let encryption_seed = ephemeral_tweak
808 .consensus_hash::<sha256::Hash>()
809 .to_byte_array();
810
811 let preimage = encryption_seed
812 .consensus_hash::<sha256::Hash>()
813 .to_byte_array();
814
815 let (gateway, routing_info) = match gateway {
816 Some(gateway) => (
817 gateway.clone(),
818 self.routing_info(&gateway)
819 .await
820 .map_err(|e| ReceiveError::GatewayConnectionError(e.to_string()))?
821 .ok_or(ReceiveError::UnknownFederation)?,
822 ),
823 None => self
824 .select_gateway(None)
825 .await
826 .map_err(ReceiveError::FailedToSelectGateway)?,
827 };
828
829 if !routing_info.receive_fee.le(&PaymentFee::RECEIVE_FEE_LIMIT) {
830 return Err(ReceiveError::PaymentFeeExceedsLimit);
831 }
832
833 let contract_amount = routing_info.receive_fee.subtract_from(amount.msats);
834
835 if contract_amount < Amount::from_sats(5) {
838 return Err(ReceiveError::DustAmount);
839 }
840
841 let expiration = duration_since_epoch()
842 .as_secs()
843 .saturating_add(u64::from(expiry_secs));
844
845 let claim_pk = recipient_static_pk
846 .mul_tweak(
847 secp256k1::SECP256K1,
848 &Scalar::from_be_bytes(ephemeral_tweak).expect("Within curve order"),
849 )
850 .expect("Tweak is valid");
851
852 let contract = IncomingContract::new(
853 self.cfg.tpe_agg_pk,
854 encryption_seed,
855 preimage,
856 PaymentImage::Hash(preimage.consensus_hash()),
857 contract_amount,
858 expiration,
859 claim_pk,
860 routing_info.module_public_key,
861 ephemeral_pk,
862 );
863
864 let invoice = self
865 .gateway_conn
866 .bolt11_invoice(
867 gateway.clone(),
868 self.federation_id,
869 contract.clone(),
870 amount,
871 description,
872 expiry_secs,
873 )
874 .await
875 .map_err(|e| ReceiveError::GatewayConnectionError(e.to_string()))?;
876
877 if invoice.payment_hash() != &preimage.consensus_hash() {
878 return Err(ReceiveError::InvalidInvoicePaymentHash);
879 }
880
881 if invoice.amount_milli_satoshis() != Some(amount.msats) {
882 return Err(ReceiveError::InvalidInvoiceAmount);
883 }
884
885 Ok((gateway, contract, invoice))
886 }
887
888 async fn receive_incoming_contract(
891 &self,
892 sk: SecretKey,
893 contract: IncomingContract,
894 operation_meta: LightningOperationMeta,
895 ) -> Option<OperationId> {
896 let operation_id = OperationId::from_encodable(&contract.clone());
897
898 let (claim_keypair, agg_decryption_key) = self.recover_contract_keys(sk, &contract)?;
899
900 let receive_sm = LightningClientStateMachines::Receive(ReceiveStateMachine {
901 common: ReceiveSMCommon {
902 operation_id,
903 contract: contract.clone(),
904 claim_keypair,
905 agg_decryption_key,
906 },
907 state: ReceiveSMState::Pending,
908 });
909
910 self.client_ctx
913 .manual_operation_start(
914 operation_id,
915 LightningCommonInit::KIND.as_str(),
916 operation_meta,
917 vec![self.client_ctx.make_dyn_state(receive_sm)],
918 )
919 .await
920 .ok();
921
922 Some(operation_id)
923 }
924
925 fn recover_contract_keys(
926 &self,
927 sk: SecretKey,
928 contract: &IncomingContract,
929 ) -> Option<(Keypair, AggregateDecryptionKey)> {
930 let tweak = ecdh::SharedSecret::new(&contract.commitment.ephemeral_pk, &sk);
931
932 let encryption_seed = tweak
933 .secret_bytes()
934 .consensus_hash::<sha256::Hash>()
935 .to_byte_array();
936
937 let claim_keypair = sk
938 .mul_tweak(&Scalar::from_be_bytes(tweak.secret_bytes()).expect("Within curve order"))
939 .expect("Tweak is valid")
940 .keypair(secp256k1::SECP256K1);
941
942 if claim_keypair.public_key() != contract.commitment.claim_pk {
943 return None; }
945
946 let agg_decryption_key = derive_agg_dk(&self.cfg.tpe_agg_pk, &encryption_seed);
947
948 if !contract.verify_agg_decryption_key(&self.cfg.tpe_agg_pk, &agg_decryption_key) {
949 return None; }
951
952 contract.decrypt_preimage(&agg_decryption_key)?;
953
954 Some((claim_keypair, agg_decryption_key))
955 }
956
957 pub async fn subscribe_receive_operation_state_updates(
959 &self,
960 operation_id: OperationId,
961 ) -> anyhow::Result<UpdateStreamOrOutcome<ReceiveOperationState>> {
962 let operation = self.client_ctx.get_operation(operation_id).await?;
963 let mut stream = self.notifier.subscribe(operation_id).await;
964 let client_ctx = self.client_ctx.clone();
965
966 Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
967 stream! {
968 loop {
969 if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
970 match state.state {
971 ReceiveSMState::Pending => yield ReceiveOperationState::Pending,
972 ReceiveSMState::Claiming(out_points) => {
973 yield ReceiveOperationState::Claiming;
974
975 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
976 yield ReceiveOperationState::Claimed;
977 } else {
978 yield ReceiveOperationState::Failure;
979 }
980 return;
981 },
982 ReceiveSMState::Expired => {
983 yield ReceiveOperationState::Expired;
984 return;
985 }
986 }
987 }
988 }
989 }
990 }))
991 }
992
993 pub async fn await_final_receive_operation_state(
995 &self,
996 operation_id: OperationId,
997 ) -> anyhow::Result<FinalReceiveOperationState> {
998 let state = self
999 .subscribe_receive_operation_state_updates(operation_id)
1000 .await?
1001 .into_stream()
1002 .filter_map(|state| {
1003 futures::future::ready(match state {
1004 ReceiveOperationState::Expired => Some(FinalReceiveOperationState::Expired),
1005 ReceiveOperationState::Claimed => Some(FinalReceiveOperationState::Claimed),
1006 ReceiveOperationState::Failure => Some(FinalReceiveOperationState::Failure),
1007 _ => None,
1008 })
1009 })
1010 .next()
1011 .await
1012 .expect("Stream contains one final state");
1013
1014 Ok(state)
1015 }
1016
1017 pub async fn generate_lnurl(
1020 &self,
1021 recurringd: SafeUrl,
1022 gateway: Option<SafeUrl>,
1023 ) -> Result<String, RegisterLnurlError> {
1024 let gateways = if let Some(gateway) = gateway {
1025 vec![gateway]
1026 } else {
1027 let gateways = self
1028 .module_api
1029 .gateways()
1030 .await
1031 .map_err(|e| RegisterLnurlError::FederationError(e.to_string()))?;
1032
1033 if gateways.is_empty() {
1034 return Err(RegisterLnurlError::NoVettedGateways);
1035 }
1036
1037 gateways
1038 };
1039
1040 let lnurl = lnurl::generate_lnurl(
1041 recurringd,
1042 self.federation_id,
1043 self.lnurl_keypair.public_key(),
1044 self.cfg.tpe_agg_pk,
1045 gateways,
1046 )
1047 .await
1048 .map_err(|e| RegisterLnurlError::RegistrationError(e.to_string()))?;
1049
1050 Ok(lnurl)
1051 }
1052
1053 fn spawn_receive_lnurl_task(
1054 &self,
1055 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
1056 task_group: &TaskGroup,
1057 ) {
1058 let module = self.clone();
1059
1060 task_group.spawn_cancellable("receive_lnurl_task", async move {
1061 loop {
1062 module.receive_lnurl(custom_meta_fn()).await;
1063 }
1064 });
1065 }
1066
1067 async fn receive_lnurl(&self, custom_meta: Value) {
1068 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1069
1070 let stream_index = dbtx
1071 .get_value(&IncomingContractStreamIndexKey)
1072 .await
1073 .unwrap_or(0);
1074
1075 let (contracts, next_index) = self
1076 .module_api
1077 .await_incoming_contracts(stream_index, 128)
1078 .await;
1079
1080 for contract in &contracts {
1081 if let Some(operation_id) = self
1082 .receive_incoming_contract(
1083 self.lnurl_keypair.secret_key(),
1084 contract.clone(),
1085 LightningOperationMeta::LnurlReceive(LnurlReceiveOperationMeta {
1086 contract: contract.clone(),
1087 custom_meta: custom_meta.clone(),
1088 }),
1089 )
1090 .await
1091 {
1092 self.await_final_receive_operation_state(operation_id)
1093 .await
1094 .ok();
1095 }
1096 }
1097
1098 dbtx.insert_entry(&IncomingContractStreamIndexKey, &next_index)
1099 .await;
1100
1101 dbtx.commit_tx().await;
1102 }
1103}
1104
1105#[derive(Error, Debug, Clone, Eq, PartialEq)]
1106pub enum SelectGatewayError {
1107 #[error("Federation returned an error: {0}")]
1108 FederationError(String),
1109 #[error("The federation has no vetted gateways")]
1110 NoVettedGateways,
1111 #[error("All vetted gateways failed to respond on request of the routing info")]
1112 FailedToFetchRoutingInfo,
1113}
1114
1115#[derive(Error, Debug, Clone, Eq, PartialEq)]
1116pub enum SendPaymentError {
1117 #[error("The invoice has not amount")]
1118 InvoiceMissingAmount,
1119 #[error("The invoice has expired")]
1120 InvoiceExpired,
1121 #[error("A previous payment for the same invoice is still pending: {}", .0.fmt_full())]
1122 PendingPreviousPayment(OperationId),
1123 #[error("A previous payment for the same invoice was successful: {}", .0.fmt_full())]
1124 SuccessfulPreviousPayment(OperationId),
1125 #[error("Failed to select gateway: {0}")]
1126 FailedToSelectGateway(SelectGatewayError),
1127 #[error("Gateway connection error: {0}")]
1128 GatewayConnectionError(String),
1129 #[error("The gateway does not support our federation")]
1130 UnknownFederation,
1131 #[error("The gateways fee of exceeds the limit")]
1132 PaymentFeeExceedsLimit,
1133 #[error("The gateways expiration delta of exceeds the limit")]
1134 ExpirationDeltaExceedsLimit,
1135 #[error("Federation returned an error: {0}")]
1136 FederationError(String),
1137 #[error("We failed to finalize the funding transaction")]
1138 FinalizationError(String),
1139 #[error(
1140 "The invoice was for the wrong currency. Invoice currency={invoice_currency} Federation Currency={federation_currency}"
1141 )]
1142 WrongCurrency {
1143 invoice_currency: Currency,
1144 federation_currency: Currency,
1145 },
1146}
1147
1148#[derive(Error, Debug, Clone, Eq, PartialEq)]
1149pub enum ReceiveError {
1150 #[error("Failed to select gateway: {0}")]
1151 FailedToSelectGateway(SelectGatewayError),
1152 #[error("Gateway connection error: {0}")]
1153 GatewayConnectionError(String),
1154 #[error("The gateway does not support our federation")]
1155 UnknownFederation,
1156 #[error("The gateways fee exceeds the limit")]
1157 PaymentFeeExceedsLimit,
1158 #[error("The total fees required to complete this payment exceed its amount")]
1159 DustAmount,
1160 #[error("The invoice's payment hash is incorrect")]
1161 InvalidInvoicePaymentHash,
1162 #[error("The invoice's amount is incorrect")]
1163 InvalidInvoiceAmount,
1164}
1165
1166#[derive(Error, Debug, Clone, Eq, PartialEq)]
1167pub enum RegisterLnurlError {
1168 #[error("The federation has no vetted gateways")]
1169 NoVettedGateways,
1170 #[error("Federation returned an error: {0}")]
1171 FederationError(String),
1172 #[error("Failed to register lnurl: {0}")]
1173 RegistrationError(String),
1174}
1175
1176#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1177pub enum LightningClientStateMachines {
1178 Send(SendStateMachine),
1179 Receive(ReceiveStateMachine),
1180}
1181
1182impl IntoDynInstance for LightningClientStateMachines {
1183 type DynType = DynState;
1184
1185 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1186 DynState::from_typed(instance_id, self)
1187 }
1188}
1189
1190impl State for LightningClientStateMachines {
1191 type ModuleContext = LightningClientContext;
1192
1193 fn transitions(
1194 &self,
1195 context: &Self::ModuleContext,
1196 global_context: &DynGlobalClientContext,
1197 ) -> Vec<StateTransition<Self>> {
1198 match self {
1199 LightningClientStateMachines::Send(state) => {
1200 sm_enum_variant_translation!(
1201 state.transitions(context, global_context),
1202 LightningClientStateMachines::Send
1203 )
1204 }
1205 LightningClientStateMachines::Receive(state) => {
1206 sm_enum_variant_translation!(
1207 state.transitions(context, global_context),
1208 LightningClientStateMachines::Receive
1209 )
1210 }
1211 }
1212 }
1213
1214 fn operation_id(&self) -> OperationId {
1215 match self {
1216 LightningClientStateMachines::Send(state) => state.operation_id(),
1217 LightningClientStateMachines::Receive(state) => state.operation_id(),
1218 }
1219 }
1220}