1pub mod api;
2
3use std::collections::BTreeMap;
4use std::fmt::{Display, Formatter};
5use std::future::pending;
6use std::str::FromStr;
7use std::sync::Arc;
8use std::time::{Duration, SystemTime};
9
10use api::{RecurringdApiError, RecurringdClient};
11use async_stream::stream;
12use bitcoin::hashes::sha256;
13use bitcoin::secp256k1::SECP256K1;
14use fedimint_client_module::OperationId;
15use fedimint_client_module::error::OperationAlreadyExistsError;
16use fedimint_client_module::module::ClientContext;
17use fedimint_client_module::oplog::UpdateStreamOrOutcome;
18use fedimint_core::BitcoinHash;
19use fedimint_core::config::FederationId;
20use fedimint_core::core::{Account, ModuleKind};
21use fedimint_core::db::{DatabaseError, IDatabaseTransactionOpsCoreTyped};
22use fedimint_core::encoding::{
23 Decodable, DecodeError, Encodable, decode_field_from_finite_reader,
24 decode_legacy_system_time_from_finite_reader, encode_legacy_system_time, with_decoding_context,
25};
26use fedimint_core::module::registry::ModuleDecoderRegistry;
27use fedimint_core::secp256k1::{Keypair, PublicKey};
28use fedimint_core::task::sleep;
29use fedimint_core::util::{BoxFuture, FmtCompact, SafeUrl};
30use fedimint_derive_secret::ChildId;
31use fedimint_eventlog::{Event, EventKind, EventPersistence};
32use futures::StreamExt;
33use futures::future::select_all;
34use lightning_invoice::Bolt11Invoice;
35use serde::{Deserialize, Serialize};
36use thiserror::Error;
37use tokio::select;
38use tokio::sync::Notify;
39use tracing::{debug, trace, warn};
40
41use crate::db::{RecurringPaymentCodeKey, RecurringPaymentCodeKeyPrefix};
42use crate::receive::LightningReceiveError;
43use crate::{
44 CreateBolt11InvoiceError, LightningClientModule, LightningClientStateMachines,
45 LightningOperationMeta, LightningOperationMetaVariant, LnReceiveState, LnSubscribeError,
46 tweak_user_key, tweak_user_secret_key,
47};
48
49const LOG_CLIENT_RECURRING: &str = "fm::client::ln::recurring";
50
51impl LightningClientModule {
52 pub async fn register_recurring_payment_code(
53 &self,
54 protocol: RecurringPaymentProtocol,
55 recurringd_api: SafeUrl,
56 meta: &str,
57 ) -> Result<RecurringPaymentCodeEntry, RecurringdApiError> {
58 self.client_ctx
59 .module_db()
60 .autocommit(
61 |dbtx, _| {
62 let recurringd_api_inner = recurringd_api.clone();
63 let new_recurring_payment_code = self.new_recurring_payment_code.clone();
64 Box::pin(async move {
65 let next_idx = dbtx
66 .find_by_prefix_sorted_descending(&RecurringPaymentCodeKeyPrefix)
67 .await
68 .map(|(k, _)| k.derivation_idx)
69 .next()
70 .await
71 .map_or(0, |last_idx| last_idx + 1);
72
73 let payment_code_root_key = self.get_payment_code_root_key(next_idx);
74
75 let recurringd_client =
76 RecurringdClient::new(&recurringd_api_inner.clone());
77 let register_response = recurringd_client
78 .register_recurring_payment_code(
79 self.client_ctx
80 .get_config()
81 .await
82 .global
83 .calculate_federation_id(),
84 protocol,
85 crate::recurring::PaymentCodeRootKey(
86 payment_code_root_key.public_key(),
87 ),
88 meta,
89 )
90 .await?;
91
92 debug!(
93 target: LOG_CLIENT_RECURRING,
94 ?register_response,
95 "Registered recurring payment code"
96 );
97
98 let payment_code_entry = RecurringPaymentCodeEntry {
99 protocol,
100 root_keypair: payment_code_root_key,
101 code: register_response.recurring_payment_code,
102 recurringd_api: recurringd_api_inner,
103 last_derivation_index: 0,
104 creation_time: fedimint_core::time::now(),
105 meta: meta.to_owned(),
106 };
107 dbtx.insert_new_entry(
108 &crate::db::RecurringPaymentCodeKey {
109 derivation_idx: next_idx,
110 },
111 &payment_code_entry,
112 )
113 .await;
114 dbtx.on_commit(move || new_recurring_payment_code.notify_waiters());
115
116 Ok(payment_code_entry)
117 })
118 },
119 None,
120 )
121 .await
122 .map_err(|e| match e {
123 fedimint_core::db::AutocommitError::ClosureError { error, .. } => error,
124 fedimint_core::db::AutocommitError::CommitFailed { last_error, .. } => {
125 panic!("Commit failed: {last_error}")
126 }
127 })
128 }
129
130 pub async fn get_recurring_payment_codes(&self) -> Vec<(u64, RecurringPaymentCodeEntry)> {
131 Self::get_recurring_payment_codes_static(self.client_ctx.module_db()).await
132 }
133
134 pub async fn get_recurring_payment_codes_static(
135 db: &fedimint_core::db::Database,
136 ) -> Vec<(u64, RecurringPaymentCodeEntry)> {
137 assert!(!db.is_global(), "Needs to run in module context");
138 db.begin_transaction_nc()
139 .await
140 .find_by_prefix(&RecurringPaymentCodeKeyPrefix)
141 .await
142 .map(|(idx, entry)| (idx.derivation_idx, entry))
143 .collect()
144 .await
145 }
146
147 fn get_payment_code_root_key(&self, payment_code_registration_idx: u64) -> Keypair {
148 self.recurring_payment_code_secret
149 .child_key(ChildId(payment_code_registration_idx))
150 .to_secp_key(&self.secp)
151 }
152
153 pub async fn scan_recurring_payment_code_invoices(
154 client: ClientContext<Self>,
155 new_code_registered: Arc<Notify>,
156 ) {
157 const QUERY_RETRY_DELAY: Duration = Duration::from_mins(1);
158
159 loop {
160 let new_code_registered_future = new_code_registered.notified();
164
165 let all_recurring_invoice_futures = Self::get_recurring_payment_codes_static(client.module_db())
167 .await
168 .into_iter()
169 .map(|(payment_code_idx, payment_code)| Box::pin(async move {
170 let client = RecurringdClient::new(&payment_code.recurringd_api.clone());
171 let invoice_index = payment_code.last_derivation_index + 1;
172
173 trace!(
174 target: LOG_CLIENT_RECURRING,
175 root_key=?payment_code.root_keypair.public_key(),
176 %invoice_index,
177 server=%payment_code.recurringd_api,
178 "Waiting for new invoice from recurringd"
179 );
180
181 match client.await_new_invoice(crate::recurring::PaymentCodeRootKey(payment_code.root_keypair.public_key()), invoice_index).await {
182 Ok(invoice) => {Ok((payment_code_idx, payment_code, invoice_index, invoice))}
183 Err(err) => {
184 debug!(
185 target: LOG_CLIENT_RECURRING,
186 err=%err.fmt_compact(),
187 root_key=?payment_code.root_keypair.public_key(),
188 invoice_index=%invoice_index,
189 server=%payment_code.recurringd_api,
190 "Failed querying recurring payment code invoice, will retry in {:?}",
191 QUERY_RETRY_DELAY,
192 );
193 sleep(QUERY_RETRY_DELAY).await;
194 Err(err)
195 }
196 }
197 }))
198 .collect::<Vec<_>>();
199
200 let await_any_invoice: BoxFuture<_> = if all_recurring_invoice_futures.is_empty() {
202 Box::pin(pending())
203 } else {
204 Box::pin(select_all(all_recurring_invoice_futures))
205 };
206
207 let (payment_code_idx, _payment_code, invoice_idx, invoice) = select! {
208 (ret, _, _) = await_any_invoice => match ret {
209 Ok(ret) => ret,
210 Err(_) => {
211 continue;
212 }
213 },
214 () = new_code_registered_future => {
215 continue;
216 }
217 };
218
219 Self::process_recurring_payment_code_invoice(
220 &client,
221 payment_code_idx,
222 invoice_idx,
223 invoice,
224 )
225 .await;
226
227 sleep(Duration::from_secs(1)).await;
229 }
230 }
231
232 async fn process_recurring_payment_code_invoice(
233 client: &ClientContext<Self>,
234 payment_code_idx: u64,
235 invoice_idx: u64,
236 invoice: lightning_invoice::Bolt11Invoice,
237 ) {
238 let mut dbtx = client.module_db().begin_transaction().await;
240 let old_payment_code_entry = dbtx
241 .get_value(&crate::db::RecurringPaymentCodeKey {
242 derivation_idx: payment_code_idx,
243 })
244 .await
245 .expect("We queried it, so it exists in our DB");
246
247 let new_payment_code_entry = RecurringPaymentCodeEntry {
248 last_derivation_index: invoice_idx,
249 ..old_payment_code_entry.clone()
250 };
251 dbtx.insert_entry(
252 &crate::db::RecurringPaymentCodeKey {
253 derivation_idx: payment_code_idx,
254 },
255 &new_payment_code_entry,
256 )
257 .await;
258
259 let mut dbtx_nc = dbtx.to_ref_nc();
263 if let Ok(operation_id) = Self::create_recurring_receive_operation(
264 client,
265 &mut dbtx_nc,
266 &old_payment_code_entry,
267 invoice_idx,
268 invoice,
269 )
270 .await
271 {
272 client
273 .log_event(
274 &mut dbtx_nc,
275 RecurringInvoiceCreatedEvent {
276 payment_code_idx,
277 invoice_idx,
278 operation_id,
279 },
280 )
281 .await;
282 } else {
283 debug_assert!(
284 false,
285 "Recurring invoice operation creation failed, this should never happen"
286 );
287 }
288 drop(dbtx_nc);
289
290 dbtx.commit_tx().await;
291 }
292
293 #[allow(clippy::pedantic)]
294 async fn create_recurring_receive_operation(
295 client: &ClientContext<Self>,
296 dbtx: &mut fedimint_core::db::DatabaseTransaction<'_>,
297 payment_code: &RecurringPaymentCodeEntry,
298 invoice_index: u64,
299 invoice: lightning_invoice::Bolt11Invoice,
300 ) -> Result<OperationId, OperationAlreadyExistsError> {
301 let invoice_key =
303 tweak_user_secret_key(SECP256K1, payment_code.root_keypair, invoice_index);
304
305 let operation_id = OperationId(*invoice.payment_hash().as_ref());
306 debug!(
307 target: LOG_CLIENT_RECURRING,
308 ?operation_id,
309 payment_code_key=?payment_code.root_keypair.public_key(),
310 invoice_index=%invoice_index,
311 "Creating recurring receive operation"
312 );
313 let ln_state =
314 LightningClientStateMachines::Receive(crate::receive::LightningReceiveStateMachine {
315 operation_id,
316 state: crate::receive::LightningReceiveStates::ConfirmedInvoice(
319 crate::receive::LightningReceiveConfirmedInvoice {
320 invoice: invoice.clone(),
321 receiving_key: crate::ReceivingKey::Personal(invoice_key),
322 },
323 ),
324 });
325
326 if let Err(e) = client
327 .manual_operation_start_dbtx(
328 dbtx,
329 operation_id,
330 Account::Primary,
331 "ln",
332 LightningOperationMeta {
333 variant: LightningOperationMetaVariant::RecurringPaymentReceive(
334 ReurringPaymentReceiveMeta {
335 payment_code_id: PaymentCodeRootKey(
336 payment_code.root_keypair.public_key(),
337 )
338 .to_payment_code_id(),
339 invoice,
340 },
341 ),
342 extra_meta: serde_json::Value::Null,
343 },
344 vec![client.make_dyn_state(ln_state)],
345 )
346 .await
347 {
348 warn!(
349 target: LOG_CLIENT_RECURRING,
350 ?operation_id,
351 payment_code_key=?payment_code.root_keypair.public_key(),
352 invoice_index=%invoice_index,
353 err = %e.fmt_compact(),
354 "Failed to create recurring receive operation"
355 );
356 Err(e)
357 } else {
358 Ok(operation_id)
359 }
360 }
361
362 pub async fn subscribe_ln_recurring_receive(
363 &self,
364 operation_id: OperationId,
365 ) -> Result<UpdateStreamOrOutcome<LnReceiveState>, LnSubscribeError> {
366 let operation = self.client_ctx.get_operation(operation_id).await?;
367 let LightningOperationMetaVariant::RecurringPaymentReceive(ReurringPaymentReceiveMeta {
368 invoice,
369 ..
370 }) = operation.meta::<LightningOperationMeta>().variant
371 else {
372 return Err(LnSubscribeError::NotARecurringReceive);
373 };
374
375 let client_ctx = self.client_ctx.clone();
376
377 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
378 LnReceiveState::Created
379 | LnReceiveState::WaitingForPayment { .. }
380 | LnReceiveState::Funded
381 | LnReceiveState::AwaitingFunds => false,
382 LnReceiveState::Canceled { .. } | LnReceiveState::Claimed => true,
383 }, move || {
384 stream! {
385 let self_ref = client_ctx.self_ref();
386
387 yield LnReceiveState::Created;
388 yield LnReceiveState::WaitingForPayment { invoice: invoice.to_string(), timeout: invoice.expiry_time() };
389
390 match self_ref.await_receive_success(operation_id).await {
391 Ok(()) => {
392 yield LnReceiveState::Funded;
393
394 if let Ok(out_points) = self_ref.await_claim_acceptance(operation_id).await {
395 yield LnReceiveState::AwaitingFunds;
396
397 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
398 yield LnReceiveState::Claimed;
399 return;
400 }
401 }
402
403 yield LnReceiveState::Canceled { reason: LightningReceiveError::Rejected };
404 }
405 Err(e) => {
406 yield LnReceiveState::Canceled { reason: e };
407 }
408 }
409 }
410 }))
411 }
412
413 pub async fn list_recurring_payment_codes(&self) -> BTreeMap<u64, RecurringPaymentCodeEntry> {
414 self.client_ctx
415 .module_db()
416 .begin_transaction_nc()
417 .await
418 .find_by_prefix(&RecurringPaymentCodeKeyPrefix)
419 .await
420 .map(|(idx, entry)| (idx.derivation_idx, entry))
421 .collect()
422 .await
423 }
424
425 pub async fn get_recurring_payment_code(
426 &self,
427 payment_code_idx: u64,
428 ) -> Option<RecurringPaymentCodeEntry> {
429 self.client_ctx
430 .module_db()
431 .begin_transaction_nc()
432 .await
433 .get_value(&RecurringPaymentCodeKey {
434 derivation_idx: payment_code_idx,
435 })
436 .await
437 }
438
439 pub async fn list_recurring_payment_code_invoices(
440 &self,
441 payment_code_idx: u64,
442 ) -> Option<BTreeMap<u64, OperationId>> {
443 let payment_code = self.get_recurring_payment_code(payment_code_idx).await?;
444
445 let operations = (1..=payment_code.last_derivation_index)
446 .map(|invoice_idx: u64| {
447 let invoice_key = tweak_user_key(
448 SECP256K1,
449 payment_code.root_keypair.public_key(),
450 invoice_idx,
451 );
452 let payment_hash =
453 sha256::Hash::hash(&sha256::Hash::hash(&invoice_key.serialize())[..]);
454 let operation_id = OperationId(*payment_hash.as_ref());
455
456 (invoice_idx, operation_id)
457 })
458 .collect();
459
460 Some(operations)
461 }
462}
463
464#[derive(
465 Debug,
466 Clone,
467 Copy,
468 PartialOrd,
469 Eq,
470 PartialEq,
471 Hash,
472 Encodable,
473 Decodable,
474 Serialize,
475 Deserialize,
476)]
477pub struct PaymentCodeRootKey(pub PublicKey);
478
479#[derive(
480 Debug,
481 Clone,
482 Copy,
483 PartialOrd,
484 Eq,
485 PartialEq,
486 Hash,
487 Encodable,
488 Decodable,
489 Serialize,
490 Deserialize,
491)]
492pub struct PaymentCodeId(sha256::Hash);
493
494impl PaymentCodeRootKey {
495 pub fn to_payment_code_id(&self) -> PaymentCodeId {
496 PaymentCodeId(sha256::Hash::hash(&self.0.serialize()))
497 }
498}
499
500impl Display for PaymentCodeId {
501 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
502 write!(f, "{}", self.0)
503 }
504}
505
506impl FromStr for PaymentCodeId {
507 type Err = bitcoin::hashes::hex::HexToArrayError;
508
509 fn from_str(s: &str) -> Result<Self, Self::Err> {
510 Ok(Self(sha256::Hash::from_str(s)?))
511 }
512}
513
514impl Display for PaymentCodeRootKey {
515 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
516 write!(f, "{}", self.0)
517 }
518}
519
520impl FromStr for PaymentCodeRootKey {
521 type Err = fedimint_core::secp256k1::Error;
522
523 fn from_str(s: &str) -> Result<Self, Self::Err> {
524 Ok(Self(PublicKey::from_str(s)?))
525 }
526}
527
528#[derive(
529 Debug,
530 Clone,
531 Copy,
532 Eq,
533 PartialEq,
534 PartialOrd,
535 Hash,
536 Encodable,
537 Decodable,
538 Serialize,
539 Deserialize,
540)]
541pub enum RecurringPaymentProtocol {
542 LNURL,
543 BOLT12,
544}
545
546#[derive(Debug, Clone, Serialize, Deserialize)]
547pub struct ReurringPaymentReceiveMeta {
548 pub payment_code_id: PaymentCodeId,
549 pub invoice: Bolt11Invoice,
550}
551
552#[derive(Debug, Error)]
553pub enum RecurringPaymentError {
554 #[error("Unsupported protocol: {0:?}")]
555 UnsupportedProtocol(RecurringPaymentProtocol),
556 #[error("Unknown federation ID: {0}")]
557 UnknownFederationId(FederationId),
558 #[error("Unknown payment code: {0:?}")]
559 UnknownPaymentCode(PaymentCodeId),
560 #[error("Unknown lightning receive operation: {0:?}")]
561 UnknownInvoice(OperationId),
562 #[error("No compatible lightning module found")]
563 NoLightningModuleFound,
564 #[error("No gateway found")]
565 NoGatewayFound,
566 #[error("Payment code already exists with different settings: {0:?}")]
567 PaymentCodeAlreadyExists(PaymentCodeRootKey),
568 #[error("Federation already registered: {0}")]
569 FederationAlreadyRegistered(FederationId),
570 #[error("Error joining federation")]
573 JoiningFederationFailed(#[source] Box<dyn std::error::Error + Send + Sync>),
574 #[error("Database error")]
576 Database(#[from] DatabaseError),
577 #[error("The invoice could not be created")]
579 InvoiceCreation(#[source] CreateBolt11InvoiceError),
580 #[error("The lightning receive could not be followed")]
582 Subscribe(#[source] LnSubscribeError),
583 #[error("BOLT11 invoice not confirmed")]
586 InvoiceNotConfirmed,
587}
588
589#[derive(Debug, Clone, Serialize)]
590pub struct RecurringPaymentCodeEntry {
591 pub protocol: RecurringPaymentProtocol,
592 pub root_keypair: Keypair,
593 pub code: String,
594 pub recurringd_api: SafeUrl,
595 pub last_derivation_index: u64,
596 pub creation_time: SystemTime,
597 pub meta: String,
598}
599
600impl Encodable for RecurringPaymentCodeEntry {
601 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
602 self.protocol.consensus_encode(writer)?;
603 self.root_keypair.consensus_encode(writer)?;
604 self.code.consensus_encode(writer)?;
605 self.recurringd_api.consensus_encode(writer)?;
606 self.last_derivation_index.consensus_encode(writer)?;
607 encode_legacy_system_time(&self.creation_time, writer)?;
608 self.meta.consensus_encode(writer)
609 }
610}
611
612impl Decodable for RecurringPaymentCodeEntry {
613 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
614 decoder: &mut D,
615 modules: &ModuleDecoderRegistry,
616 ) -> Result<Self, DecodeError> {
617 Ok(Self {
618 protocol: decode_field_from_finite_reader(
619 decoder,
620 modules,
621 "Decoding named block field: RecurringPaymentCodeEntry{ ... protocol ... }",
622 )?,
623 root_keypair: decode_field_from_finite_reader(
624 decoder,
625 modules,
626 "Decoding named block field: RecurringPaymentCodeEntry{ ... root_keypair ... }",
627 )?,
628 code: decode_field_from_finite_reader(
629 decoder,
630 modules,
631 "Decoding named block field: RecurringPaymentCodeEntry{ ... code ... }",
632 )?,
633 recurringd_api: decode_field_from_finite_reader(
634 decoder,
635 modules,
636 "Decoding named block field: RecurringPaymentCodeEntry{ ... recurringd_api ... }",
637 )?,
638 last_derivation_index: decode_field_from_finite_reader(
639 decoder,
640 modules,
641 "Decoding named block field: RecurringPaymentCodeEntry{ ... last_derivation_index ... }",
642 )?,
643 creation_time: with_decoding_context(
644 decode_legacy_system_time_from_finite_reader(decoder, modules),
645 "Decoding named block field: RecurringPaymentCodeEntry{ ... creation_time ... }",
646 )?,
647 meta: decode_field_from_finite_reader(
648 decoder,
649 modules,
650 "Decoding named block field: RecurringPaymentCodeEntry{ ... meta ... }",
651 )?,
652 })
653 }
654}
655
656#[derive(Debug, Clone, Serialize, Deserialize)]
664pub struct RecurringInvoiceCreatedEvent {
665 pub payment_code_idx: u64,
666 pub invoice_idx: u64,
667 pub operation_id: OperationId,
668}
669
670impl Event for RecurringInvoiceCreatedEvent {
671 const MODULE: Option<ModuleKind> = Some(fedimint_ln_common::KIND);
672 const KIND: EventKind = EventKind::from_static("recurring_invoice_created");
673 const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
674}
675
676#[cfg(test)]
677mod tests;