1use std::collections::BTreeMap;
2use std::time::UNIX_EPOCH;
3use std::{ffi, iter};
4
5use clap::{Parser, Subcommand};
6use fedimint_api_client::api::FederationError;
7use fedimint_client_module::error::{ModuleLookupError, OperationLookupError};
8use fedimint_core::Amount;
9use fedimint_core::core::{Account, OperationId};
10use fedimint_core::secp256k1::PublicKey;
11use fedimint_core::util::SafeUrl;
12use futures::StreamExt;
13use lightning_invoice::{Bolt11InvoiceDescription, CreationError, Description};
14use serde::{Deserialize, Serialize};
15use serde_json::json;
16use tracing::{debug, info};
17
18use crate::receive::LightningReceiveError;
19use crate::recurring::api::RecurringdApiError;
20use crate::recurring::{PaymentCodeRootKey, RecurringPaymentProtocol};
21use crate::{
22 CreateBolt11InvoiceError, GatewaySelectionError, LightningOperationMeta,
23 LightningOperationMetaVariant, LnReceiveState, LnSubscribeError, OutgoingLightningPayment,
24 PayBolt11InvoiceError, PaymentInfoError, SpendableAmountError,
25};
26
27#[derive(Parser, Serialize)]
28enum Opts {
29 Invoice {
31 amount: Amount,
32 #[clap(long, default_value = "")]
33 description: String,
34 #[clap(long)]
35 expiry_time: Option<u64>,
36 #[clap(long)]
37 gateway_id: Option<PublicKey>,
38 #[clap(long, default_value = "false")]
39 force_internal: bool,
40 },
41 Pay {
43 payment_info: String,
45 #[clap(long, conflicts_with = "all")]
47 amount: Option<Amount>,
48 #[clap(long, default_value = "false")]
53 all: bool,
54 #[clap(long)]
56 lnurl_comment: Option<String>,
57 #[clap(long)]
58 gateway_id: Option<PublicKey>,
59 #[clap(long, default_value = "false")]
60 force_internal: bool,
61 },
62 AwaitInvoice {
64 operation_id: OperationId,
66 },
67 AwaitPay {
69 operation_id: OperationId,
71 },
72 ListGateways {
74 #[clap(long, default_value = "false")]
76 no_update: bool,
77 },
78 #[clap(subcommand)]
80 Lnurl(LnurlCommands),
81}
82
83#[derive(Subcommand, Serialize)]
84enum LnurlCommands {
85 Register {
87 server_url: SafeUrl,
89 #[clap(long)]
91 meta: Option<String>,
92 #[clap(long, default_value = "Fedimint LNURL Pay")]
94 description: String,
95 },
96 List,
98 Invoices { payment_code_idx: u64 },
100 InvoiceDetails { operation_id: OperationId },
102 AwaitInvoicePaid {
104 operation_id: OperationId,
106 },
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub struct LnInvoiceResponse {
112 pub operation_id: OperationId,
113 pub invoice: String,
114}
115
116pub(crate) async fn handle_cli_command(
117 module: &super::LightningClientModule,
118 args: &[ffi::OsString],
119) -> Result<serde_json::Value, CliCommandError> {
120 let opts = Opts::parse_from(iter::once(&ffi::OsString::from("meta")).chain(args.iter()));
121
122 Ok(match opts {
123 Opts::Invoice {
124 amount,
125 description,
126 expiry_time,
127 gateway_id,
128 force_internal,
129 } => {
130 let ln_gateway = module.get_gateway(gateway_id, force_internal).await?;
131
132 let desc = Description::new(description)?;
133 let (operation_id, invoice, _) = module
134 .create_bolt11_invoice(
135 amount,
136 Bolt11InvoiceDescription::Direct(desc),
137 expiry_time,
138 (),
139 ln_gateway,
140 )
141 .await?;
142 serde_json::to_value(LnInvoiceResponse {
143 operation_id,
144 invoice: invoice.to_string(),
145 })
146 .expect("Can't fail")
147 }
148 Opts::Pay {
149 payment_info,
150 amount,
151 all,
152 lnurl_comment,
153 gateway_id,
154 force_internal,
155 } => {
156 let ln_gateway = module.get_gateway(gateway_id, force_internal).await?;
159
160 let payment_info = crate::PaymentInfo::parse(&payment_info).await?;
161
162 let amount = if all {
163 let crate::PaymentInfo::Lnurl(pay_response) = &payment_info else {
164 return Err(CliCommandError::AllRequiresLnurl);
165 };
166
167 let gateway = ln_gateway
168 .clone()
169 .ok_or(CliCommandError::AllRequiresGateway)?;
170 let balance = module
171 .client_ctx
172 .get_balance_for_btc(Account::Primary)
173 .await?;
174 let spendable = module.spendable_amount(balance, Some(gateway)).await?;
175
176 let max_sendable = Amount::from_msats(pay_response.max_sendable);
179 let min_sendable = Amount::from_msats(pay_response.min_sendable);
180 let capped = spendable.min(max_sendable);
181 if capped < min_sendable {
182 return Err(CliCommandError::BelowMinSendable {
183 capped,
184 min_sendable,
185 });
186 }
187 if capped < spendable {
188 info!(
189 "Balance supports sending {spendable}, but the recipient's LNURL maxSendable caps the payment at {capped}"
190 );
191 } else {
192 info!("Spending entire balance, requesting invoice for {capped}");
193 }
194 Some(capped)
195 } else {
196 amount
197 };
198
199 let bolt11 = payment_info.get_invoice(amount, lnurl_comment).await?;
200 info!("Paying invoice: {bolt11}");
201
202 let OutgoingLightningPayment {
203 payment_type,
204 contract_id: _,
205 fee,
206 } = module.pay_bolt11_invoice(ln_gateway, bolt11, ()).await?;
207 let operation_id = payment_type.operation_id();
208 info!(
209 "Gateway fee: {fee}, payment operation id: {}",
210 operation_id.fmt_short()
211 );
212 let outcome = module.await_outgoing_payment(operation_id).await?;
213 serde_json::to_value(outcome).expect("cant fail")
214 }
215 Opts::AwaitInvoice { operation_id } => {
216 let mut updates = module
217 .subscribe_ln_receive(operation_id)
218 .await?
219 .into_stream();
220 while let Some(update) = updates.next().await {
221 debug!(?update, "Await invoice state update");
222 match update {
223 LnReceiveState::Claimed => {
224 return Ok(json!({
225 "status": "paid"
226 }));
227 }
228 LnReceiveState::Canceled { reason } => {
229 return Err(reason.into());
230 }
231 _ => {}
232 }
233 }
234 unreachable!("Stream should not end without an outcome");
235 }
236 Opts::AwaitPay { operation_id } => {
237 let outcome = module.await_outgoing_payment(operation_id).await?;
238 serde_json::to_value(outcome).expect("serialization can't fail")
239 }
240 Opts::ListGateways { no_update } => {
241 if !no_update {
242 module.update_gateway_cache().await?;
243 }
244 let gateways = module.list_gateways().await;
245 if gateways.is_empty() {
246 return Ok(
247 serde_json::to_value(Vec::<String>::new()).expect("serialization can't fail")
248 );
249 }
250 json!(&gateways)
251 }
252 Opts::Lnurl(LnurlCommands::Register {
253 server_url,
254 meta,
255 description,
256 }) => {
257 let meta = meta.unwrap_or_else(|| {
258 serde_json::to_string(&json!([["text/plain", description]]))
259 .expect("serialization can't fail")
260 });
261 let recurring_payment_code = module
262 .register_recurring_payment_code(RecurringPaymentProtocol::LNURL, server_url, &meta)
263 .await?;
264 json!({
265 "lnurl": recurring_payment_code.code,
266 })
267 }
268 Opts::Lnurl(LnurlCommands::List) => {
269 let codes: BTreeMap<u64, serde_json::Value> = module
270 .list_recurring_payment_codes()
271 .await
272 .into_iter()
273 .map(|(idx, code)| {
274 let root_public_key = PaymentCodeRootKey(code.root_keypair.public_key());
275 let recurring_payment_code_id = root_public_key.to_payment_code_id();
276 let creation_timestamp = code
277 .creation_time
278 .duration_since(UNIX_EPOCH)
279 .expect("Time went backwards")
280 .as_secs();
281 let code_json = json!({
282 "lnurl": code.code,
283 "creation_timestamp": creation_timestamp,
285 "root_public_key": root_public_key,
286 "recurring_payment_code_id": recurring_payment_code_id,
287 "recurringd_api": code.recurringd_api,
288 "last_derivation_index": code.last_derivation_index,
289 });
290 (idx, code_json)
291 })
292 .collect();
293
294 json!({
295 "codes": codes,
296 })
297 }
298 Opts::Lnurl(LnurlCommands::Invoices { payment_code_idx }) => {
299 let invoices = module
301 .list_recurring_payment_code_invoices(payment_code_idx)
302 .await
303 .ok_or(CliCommandError::UnknownPaymentCodeIndex)?
304 .into_iter()
305 .map(|(idx, operation_id)| {
306 let invoice = json!({
307 "operation_id": operation_id,
308 });
309 (idx, invoice)
310 })
311 .collect::<BTreeMap<_, _>>();
312 json!({
313 "invoices": invoices,
314 })
315 }
316 Opts::Lnurl(LnurlCommands::InvoiceDetails { operation_id }) => {
317 let LightningOperationMetaVariant::RecurringPaymentReceive(operation_meta) = module
318 .client_ctx
319 .get_operation(operation_id)
320 .await?
321 .meta::<LightningOperationMeta>()
322 .variant
323 else {
324 return Err(CliCommandError::NotRecurringReceive);
325 };
326
327 json!({
328 "payment_code_id": operation_meta.payment_code_id,
329 "invoice": operation_meta.invoice,
330 "amount_msat": operation_meta.invoice.amount_milli_satoshis(),
331 })
332 }
333 Opts::Lnurl(LnurlCommands::AwaitInvoicePaid { operation_id }) => {
334 let LightningOperationMetaVariant::RecurringPaymentReceive(operation_meta) = module
335 .client_ctx
336 .get_operation(operation_id)
337 .await?
338 .meta::<LightningOperationMeta>()
339 .variant
340 else {
341 return Err(CliCommandError::NotRecurringReceive);
342 };
343 let mut stream = module
344 .subscribe_ln_recurring_receive(operation_id)
345 .await?
346 .into_stream();
347 while let Some(update) = stream.next().await {
348 debug!(?update, "Await invoice state update");
349 match update {
350 LnReceiveState::Claimed => {
351 let amount_msat = operation_meta.invoice.amount_milli_satoshis();
352 return Ok(json!({
353 "payment_code_id": operation_meta.payment_code_id,
354 "invoice": operation_meta.invoice,
355 "amount_msat": amount_msat,
356 }));
357 }
358 LnReceiveState::Canceled { reason } => {
359 return Err(reason.into());
360 }
361 _ => {}
362 }
363 }
364 unreachable!("Stream should not end without an outcome");
365 }
366 })
367}
368
369#[derive(Debug, thiserror::Error)]
371pub(crate) enum CliCommandError {
372 #[error(transparent)]
374 GatewaySelection(#[from] GatewaySelectionError),
375
376 #[error(transparent)]
378 InvoiceDescription(#[from] CreationError),
379
380 #[error(transparent)]
382 CreateInvoice(#[from] CreateBolt11InvoiceError),
383
384 #[error(transparent)]
387 PaymentInfo(#[from] PaymentInfoError),
388
389 #[error("--all is only valid for LNURL/Lightning Address payments, not fixed-amount invoices")]
391 AllRequiresLnurl,
392
393 #[error("--all requires a gateway to price the payment; internal payments are not supported")]
395 AllRequiresGateway,
396
397 #[error(transparent)]
399 Balance(#[from] ModuleLookupError),
400
401 #[error(transparent)]
403 SpendableAmount(#[from] SpendableAmountError),
404
405 #[error(
407 "--all can send at most {capped}, but the recipient requires at least \
408 {min_sendable} (LNURL minSendable)"
409 )]
410 BelowMinSendable {
411 capped: Amount,
412 min_sendable: Amount,
413 },
414
415 #[error(transparent)]
417 Pay(#[from] PayBolt11InvoiceError),
418
419 #[error(transparent)]
421 Subscribe(#[from] LnSubscribeError),
422
423 #[error(transparent)]
425 Receive(#[from] LightningReceiveError),
426
427 #[error(transparent)]
429 Federation(#[from] FederationError),
430
431 #[error(transparent)]
433 RecurringdApi(#[from] RecurringdApiError),
434
435 #[error("Unknown payment code index")]
437 UnknownPaymentCodeIndex,
438
439 #[error(transparent)]
441 OperationLookup(#[from] OperationLookupError),
442
443 #[error("Operation is not a recurring lightning receive")]
445 NotRecurringReceive,
446}