1use std::path::{Path, PathBuf};
2use std::{ffi, iter};
3
4use bitcoin::hashes::sha256;
5use bitcoin::secp256k1;
6use clap::{Parser, Subcommand};
7use fedimint_api_client::api::FederationError;
8use fedimint_client_module::error::OperationLookupError;
9use fedimint_core::core::{Account, OperationId};
10use fedimint_core::util::SafeUrl;
11use fedimint_core::{Amount, OutPoint, PeerId, TransactionId, hex};
12use fedimint_lnv2_common::contracts::{OutgoingContract, PaymentImage};
13use lightning_invoice::Bolt11Invoice;
14use secp256k1::schnorr::Signature;
15use secp256k1::{Keypair, PublicKey, SecretKey};
16use serde::Serialize;
17use serde_json::Value;
18
19use crate::api::LightningFederationApi;
20use crate::{
21 Bolt11InvoiceDescription, GenerateLnurlError, LightningClientModule, ListGatewaysError,
22 ReceiveError, SelectGatewayError, SendPaymentError,
23};
24
25#[cfg(test)]
26mod tests;
27
28#[derive(Parser, Serialize)]
29enum Opts {
30 Send {
33 invoice: Bolt11Invoice,
34 #[arg(long)]
35 gateway: Option<SafeUrl>,
36 #[arg(long, default_value_t = Account::Primary)]
37 account: Account,
38 },
39 AwaitSend { operation_id: OperationId },
41 Receive {
45 amount: Amount,
46 #[arg(long)]
47 gateway: Option<SafeUrl>,
48 #[arg(long, default_value_t = Account::Primary)]
49 account: Account,
50 },
51 AwaitReceive { operation_id: OperationId },
53 #[command(subcommand)]
55 Lnurl(LnurlOpts),
56 #[command(subcommand)]
58 Gateways(GatewaysOpts),
59 #[command(subcommand)]
62 Htlc(HtlcOpts),
63}
64
65#[derive(Clone, Subcommand, Serialize)]
66enum HtlcOpts {
67 Create {
70 amount: Amount,
71 claim_pk: PublicKey,
72 expiration_delta: u64,
73 #[arg(long)]
74 payment_hash: Option<sha256::Hash>,
75 #[arg(long)]
76 payment_point: Option<PublicKey>,
77 #[arg(long, default_value_t = Account::Primary)]
78 account: Account,
79 },
80 NewClaimKeypair {
84 #[arg(long)]
87 secret_key_file: PathBuf,
88 },
89 AwaitFunded {
92 funding_txid: TransactionId,
93 #[arg(long, default_value_t = 0)]
94 out_idx: u64,
95 contract: String,
96 },
97 Claim {
99 funding_txid: TransactionId,
100 #[arg(long, default_value_t = 0)]
101 out_idx: u64,
102 contract: String,
103 #[arg(long)]
105 claim_sk_file: PathBuf,
106 #[arg(long)]
108 preimage_file: PathBuf,
109 #[arg(long, default_value_t = Account::Primary)]
110 account: Account,
111 },
112 Forfeit {
115 contract: String,
116 #[arg(long)]
118 claim_sk_file: PathBuf,
119 },
120 Cancel {
123 funding_txid: TransactionId,
124 #[arg(long, default_value_t = 0)]
125 out_idx: u64,
126 contract: String,
127 forfeit_signature: Signature,
128 },
129 Refund {
131 funding_txid: TransactionId,
132 #[arg(long, default_value_t = 0)]
133 out_idx: u64,
134 contract: String,
135 },
136 AwaitResolution {
139 funding_txid: TransactionId,
140 #[arg(long, default_value_t = 0)]
141 out_idx: u64,
142 contract: String,
143 },
144 AwaitSettled { operation_id: OperationId },
147}
148
149#[derive(Clone, Subcommand, Serialize)]
150enum LnurlOpts {
151 Generate {
153 recurringd: SafeUrl,
154 #[arg(long)]
155 gateway: Option<SafeUrl>,
156 #[arg(long, default_value_t = Account::Primary)]
157 account: Account,
158 },
159}
160
161#[derive(Clone, Subcommand, Serialize)]
162enum GatewaysOpts {
163 Map,
167 Select {
169 #[arg(long)]
170 invoice: Option<Bolt11Invoice>,
171 },
172 List {
174 #[arg(long)]
175 peer: Option<PeerId>,
176 },
177 Add { gateway: SafeUrl },
179 Remove { gateway: SafeUrl },
181}
182
183pub(crate) async fn handle_cli_command(
184 lightning: &LightningClientModule,
185 args: &[ffi::OsString],
186) -> Result<serde_json::Value, CliCommandError> {
187 let opts = Opts::parse_from(iter::once(&ffi::OsString::from("lnv2")).chain(args.iter()));
188
189 let value = match opts {
190 Opts::Send {
191 gateway,
192 invoice,
193 account,
194 } => json(
195 lightning
196 .send(account, invoice, gateway, Value::Null)
197 .await?,
198 ),
199 Opts::AwaitSend { operation_id } => json(
200 lightning
201 .await_final_send_operation_state(operation_id)
202 .await?,
203 ),
204 Opts::Receive {
205 amount,
206 gateway,
207 account,
208 } => json(
209 lightning
210 .receive(
211 account,
212 amount,
213 3600,
214 Bolt11InvoiceDescription::Direct(String::new()),
215 gateway,
216 Value::Null,
217 )
218 .await?,
219 ),
220 Opts::AwaitReceive { operation_id } => json(
221 lightning
222 .await_final_receive_operation_state(operation_id)
223 .await?,
224 ),
225 Opts::Lnurl(lnurl_opts) => match lnurl_opts {
226 LnurlOpts::Generate {
227 recurringd,
228 gateway,
229 account,
230 } => json(
231 lightning
232 .generate_lnurl(account, recurringd, gateway)
233 .await?,
234 ),
235 },
236 Opts::Gateways(gateway_opts) => match gateway_opts {
237 #[allow(clippy::unit_arg)]
238 GatewaysOpts::Map => json(lightning.update_gateway_map().await),
239 GatewaysOpts::Select { invoice } => json(lightning.select_gateway(invoice).await?.0),
240 GatewaysOpts::List { peer } => json(lightning.list_gateways(peer).await?),
241 GatewaysOpts::Add { gateway } => {
242 let auth = lightning
243 .admin_auth
244 .clone()
245 .ok_or(CliCommandError::AdminAuthNotSet)?;
246
247 json(lightning.module_api.add_gateway(auth, gateway).await?)
248 }
249 GatewaysOpts::Remove { gateway } => {
250 let auth = lightning
251 .admin_auth
252 .clone()
253 .ok_or(CliCommandError::AdminAuthNotSet)?;
254
255 json(lightning.module_api.remove_gateway(auth, gateway).await?)
256 }
257 },
258 Opts::Htlc(htlc_opts) => handle_htlc_command(lightning, htlc_opts).await?,
259 };
260
261 Ok(value)
262}
263
264#[allow(clippy::too_many_lines)]
265async fn handle_htlc_command(
266 lightning: &LightningClientModule,
267 htlc_opts: HtlcOpts,
268) -> Result<Value, CliCommandError> {
269 let value = match htlc_opts {
270 HtlcOpts::Create {
271 amount,
272 claim_pk,
273 expiration_delta,
274 payment_hash,
275 payment_point,
276 account,
277 } => {
278 let payment_image = match (payment_hash, payment_point) {
279 (Some(hash), None) => PaymentImage::Hash(hash),
280 (None, Some(point)) => PaymentImage::Point(point),
281 _ => return Err(CliCommandError::InvalidPaymentImage),
282 };
283
284 let (operation_id, outpoint, contract) = lightning
285 .create_htlc(
286 account,
287 amount,
288 payment_image,
289 claim_pk,
290 expiration_delta,
291 Value::Null,
292 )
293 .await?;
294
295 json(serde_json::json!({
296 "operation_id": operation_id,
297 "outpoint": outpoint,
298 "contract": contract,
299 }))
300 }
301 HtlcOpts::NewClaimKeypair { secret_key_file } => {
302 let keypair = Keypair::new(secp256k1::SECP256K1, &mut rand::thread_rng());
303
304 write_secret_key_file(&secret_key_file, &keypair.secret_key())?;
305
306 json(serde_json::json!({
307 "public_key": keypair.public_key(),
308 }))
309 }
310 HtlcOpts::AwaitFunded {
311 funding_txid,
312 out_idx,
313 contract,
314 } => json(
315 lightning
316 .await_htlc_funded(outpoint(funding_txid, out_idx), &parse_contract(&contract)?)
317 .await?,
318 ),
319 HtlcOpts::Claim {
320 funding_txid,
321 out_idx,
322 contract,
323 claim_sk_file,
324 preimage_file,
325 account,
326 } => {
327 let contract = parse_contract(&contract)?;
328
329 ensure_single_stdin(&claim_sk_file, &preimage_file)?;
330
331 let claim_sk = read_claim_sk(&claim_sk_file)?;
332 let preimage = read_preimage(&preimage_file)?;
333
334 json(
335 lightning
336 .claim_htlc(
337 account,
338 outpoint(funding_txid, out_idx),
339 contract,
340 claim_sk.keypair(secp256k1::SECP256K1),
341 preimage,
342 Value::Null,
343 )
344 .await?,
345 )
346 }
347 HtlcOpts::Forfeit {
348 contract,
349 claim_sk_file,
350 } => {
351 let contract = parse_contract(&contract)?;
352 let claim_sk = read_claim_sk(&claim_sk_file)?;
353
354 json(LightningClientModule::create_htlc_forfeit_signature(
355 &contract,
356 &claim_sk.keypair(secp256k1::SECP256K1),
357 )?)
358 }
359 HtlcOpts::Cancel {
360 funding_txid,
361 out_idx,
362 contract,
363 forfeit_signature,
364 } => json(
365 lightning
366 .cancel_htlc(
367 outpoint(funding_txid, out_idx),
368 parse_contract(&contract)?,
369 forfeit_signature,
370 Value::Null,
371 )
372 .await?,
373 ),
374 HtlcOpts::Refund {
375 funding_txid,
376 out_idx,
377 contract,
378 } => json(
379 lightning
380 .refund_htlc(
381 outpoint(funding_txid, out_idx),
382 parse_contract(&contract)?,
383 Value::Null,
384 )
385 .await?,
386 ),
387 HtlcOpts::AwaitResolution {
388 funding_txid,
389 out_idx,
390 contract,
391 } => json(
392 lightning
393 .await_htlc_resolution(outpoint(funding_txid, out_idx), &parse_contract(&contract)?)
394 .await?
395 .map(hex::encode),
396 ),
397 HtlcOpts::AwaitSettled { operation_id } => {
398 lightning.await_htlc_operation_settled(operation_id).await?;
399
400 json("settled")
401 }
402 };
403
404 Ok(value)
405}
406
407fn outpoint(txid: TransactionId, out_idx: u64) -> OutPoint {
408 OutPoint { txid, out_idx }
409}
410
411fn parse_contract(contract: &str) -> Result<OutgoingContract, CliCommandError> {
412 serde_json::from_str(contract).map_err(CliCommandError::InvalidContract)
413}
414
415const MAX_SECRET_HEX_BYTES: usize = 66;
417
418fn read_claim_sk(path: &Path) -> Result<SecretKey, CliCommandError> {
419 let claim_sk = read_secret_hex(path)?;
420
421 claim_sk
423 .parse()
424 .map_err(|_| CliCommandError::InvalidClaimSecretKey)
425}
426
427fn read_preimage(path: &Path) -> Result<[u8; 32], CliCommandError> {
428 let preimage = read_secret_hex(path)?;
429
430 <[u8; 32]>::try_from(hex::decode(preimage).map_err(|_| CliCommandError::InvalidPreimageHex)?)
431 .map_err(|_| CliCommandError::InvalidPreimageLength)
432}
433
434fn ensure_single_stdin(first: &Path, second: &Path) -> Result<(), CliCommandError> {
435 #[cfg(not(target_family = "wasm"))]
436 fedimint_core::util::ensure_single_stdin([first, second])?;
437
438 #[cfg(target_family = "wasm")]
439 let _ = (first, second);
440
441 Ok(())
442}
443
444fn read_secret_hex(path: &Path) -> Result<String, CliCommandError> {
445 #[cfg(not(target_family = "wasm"))]
446 {
447 Ok(fedimint_core::util::read_secret_file(
448 path,
449 MAX_SECRET_HEX_BYTES,
450 )?)
451 }
452
453 #[cfg(target_family = "wasm")]
454 {
455 let _ = path;
456
457 Err(CliCommandError::UnsupportedSecretInput)
458 }
459}
460
461fn write_secret_key_file(path: &Path, secret_key: &SecretKey) -> Result<(), CliCommandError> {
463 #[cfg(not(target_family = "wasm"))]
464 {
465 use std::io::Write as _;
466
467 let mut options = std::fs::OpenOptions::new();
468
469 options.write(true).create_new(true);
470
471 #[cfg(unix)]
472 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
473
474 let mut file = options
475 .open(path)
476 .map_err(CliCommandError::SecretKeyFileCreate)?;
477
478 writeln!(file, "{}", secret_key.display_secret())
479 .and_then(|()| file.sync_all())
480 .map_err(|_| CliCommandError::SecretKeyFileWrite)
481 }
482
483 #[cfg(target_family = "wasm")]
484 {
485 let _ = (path, secret_key);
486
487 Err(CliCommandError::UnsupportedSecretInput)
488 }
489}
490
491fn json<T: Serialize>(value: T) -> Value {
492 serde_json::to_value(value).expect("JSON serialization failed")
493}
494
495#[derive(Debug, thiserror::Error)]
497pub(crate) enum CliCommandError {
498 #[error(transparent)]
500 Htlc(#[from] crate::htlc::HtlcError),
501
502 #[error("Specify exactly one of --payment-hash and --payment-point")]
504 InvalidPaymentImage,
505
506 #[error("Failed to parse the contract JSON: {0}")]
508 InvalidContract(#[source] serde_json::Error),
509
510 #[cfg(not(target_family = "wasm"))]
512 #[error(transparent)]
513 SecretInput(#[from] fedimint_core::util::SecretInputError),
514
515 #[cfg(target_family = "wasm")]
517 #[error("Secret input files are not supported on this platform")]
518 UnsupportedSecretInput,
519
520 #[error("Could not create the secret key file: {0}")]
522 SecretKeyFileCreate(#[source] std::io::Error),
523
524 #[error("Could not write the secret key file")]
526 SecretKeyFileWrite,
527
528 #[error("The claim secret key is not a valid hex secret key")]
530 InvalidClaimSecretKey,
531
532 #[error("The preimage is not valid hex")]
534 InvalidPreimageHex,
535
536 #[error("The preimage must be exactly 32 bytes")]
538 InvalidPreimageLength,
539
540 #[error(transparent)]
542 Send(#[from] SendPaymentError),
543
544 #[error(transparent)]
546 OperationLookup(#[from] OperationLookupError),
547
548 #[error(transparent)]
550 Receive(#[from] ReceiveError),
551
552 #[error(transparent)]
554 GenerateLnurl(#[from] GenerateLnurlError),
555
556 #[error(transparent)]
558 SelectGateway(#[from] SelectGatewayError),
559
560 #[error(transparent)]
562 ListGateways(#[from] ListGatewaysError),
563
564 #[error(transparent)]
566 Federation(#[from] FederationError),
567
568 #[error("Admin auth not set")]
571 AdminAuthNotSet,
572}