1use std::time::Duration;
27
28use bitcoin::secp256k1;
29use fedimint_api_client::api::FederationError;
30use fedimint_client_module::OperationLookupError;
31use fedimint_client_module::module::OutPointRange;
32use fedimint_client_module::transaction::{
33 ClientInput, ClientInputBundle, ClientOutput, ClientOutputBundle, TransactionBuilder,
34};
35use fedimint_core::core::{Account, OperationId};
36use fedimint_core::module::{Amounts, CommonModuleInit};
37use fedimint_core::task::sleep;
38use fedimint_core::util::FmtCompact as _;
39use fedimint_core::{Amount, OutPoint};
40use fedimint_lnv2_common::contracts::{OutgoingContract, PaymentImage};
41use fedimint_lnv2_common::{
42 LightningCommonInit, LightningInput, LightningInputV0, LightningOutput, LightningOutputV0,
43 OutgoingWitness, tweak,
44};
45use fedimint_logging::LOG_CLIENT_MODULE_LNV2;
46use secp256k1::schnorr::Signature;
47use secp256k1::{Keypair, PublicKey, SecretKey, ecdh};
48use serde::{Deserialize, Serialize};
49use serde_json::Value;
50use thiserror::Error;
51use tracing::debug;
52
53use crate::api::LightningFederationApi;
54use crate::{LightningClientModule, LightningOperationMeta};
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct CreateHtlcOperationMeta {
60 pub funding_outpoint: OutPoint,
64 pub contract: OutgoingContract,
65 pub change_outpoint_range: OutPointRange,
66 pub custom_meta: Value,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct SpendHtlcOperationMeta {
75 pub htlc_outpoint: OutPoint,
77 pub contract: OutgoingContract,
78 pub change_outpoint_range: OutPointRange,
79 pub custom_meta: Value,
80}
81
82#[derive(Error, Debug, Clone, Eq, PartialEq)]
85pub enum HtlcError {
86 #[error("The amount must be greater than zero")]
87 InvalidAmount,
88 #[error("The expiration delta must be greater than zero and must not overflow the block count")]
89 InvalidExpirationDelta,
90 #[error("Failed to request the consensus block count")]
91 FailedToRequestBlockCount(String),
92 #[error("The federation has not yet reached consensus on a block count")]
93 NoBlockCountConsensus,
94 #[error("Failed to submit the transaction")]
95 FailedToSubmitTransaction(String),
96 #[error("The keypair does not match the contract's claim public key")]
97 ClaimKeyMismatch,
98 #[error("The preimage does not match the contract's payment image")]
99 InvalidPreimage,
100 #[error("The contract's refund key is not derived from our static module key")]
101 RefundKeyMismatch,
102 #[error("A different contract is funded at this outpoint")]
103 ContractMismatch,
104 #[error("No unresolved contract is funded at this outpoint")]
105 ContractNotFound,
106 #[error("The contract has already expired")]
107 Expired,
108 #[error("The contract only expires in {0} more blocks")]
109 NotExpired(u64),
110 #[error("The forfeit signature is invalid for this contract")]
111 InvalidForfeitSignature,
112 #[error("The federation returned an invalid preimage")]
113 InvalidPreimageReturned,
114 #[error("Failed to query the federation")]
115 FederationApiError(String),
116 #[error("No operation with this id exists")]
117 UnknownOperation,
118 #[error("The operation is not a direct HTLC operation")]
119 NotAnHtlcOperation,
120 #[error("The transaction was rejected: {0}")]
121 TransactionRejected(String),
122 #[error("Failed to mint the ecash: {0}")]
123 FailedToMintEcash(String),
124}
125
126#[derive(Clone)]
131struct HtlcSpend {
132 outpoint: OutPoint,
133 contract: OutgoingContract,
134 witness: OutgoingWitness,
135 keypair: Keypair,
136 custom_meta: Value,
137 account: Account,
139}
140
141fn is_transient(error: &FederationError) -> bool {
144 error.get_general_error().is_none()
145 && error
146 .get_peer_errors()
147 .all(|(_, peer_error)| !peer_error.is_unusual())
148}
149
150impl HtlcSpend {
151 fn operation_id(&self) -> OperationId {
155 let action = match self.witness {
156 OutgoingWitness::Claim(..) => "lnv2-htlc-claim",
157 OutgoingWitness::Refund => "lnv2-htlc-refund",
158 OutgoingWitness::Cancel(..) => "lnv2-htlc-cancel",
159 };
160
161 OperationId::from_encodable(&(action, self.outpoint))
162 }
163
164 fn operation_meta(&self, change_outpoint_range: OutPointRange) -> LightningOperationMeta {
166 let meta = SpendHtlcOperationMeta {
167 htlc_outpoint: self.outpoint,
168 contract: self.contract.clone(),
169 change_outpoint_range,
170 custom_meta: self.custom_meta.clone(),
171 };
172
173 match self.witness {
174 OutgoingWitness::Claim(..) => LightningOperationMeta::ClaimHtlc(meta),
175 OutgoingWitness::Refund => LightningOperationMeta::RefundHtlc(meta),
176 OutgoingWitness::Cancel(..) => LightningOperationMeta::CancelHtlc(meta),
177 }
178 }
179}
180
181impl LightningClientModule {
182 pub async fn create_htlc(
202 &self,
203 account: Account,
204 amount: Amount,
205 payment_image: PaymentImage,
206 claim_pk: PublicKey,
207 expiration_delta: u64,
208 custom_meta: Value,
209 ) -> Result<(OperationId, OutPoint, OutgoingContract), HtlcError> {
210 if amount == Amount::ZERO {
211 return Err(HtlcError::InvalidAmount);
212 }
213
214 if expiration_delta == 0 {
215 return Err(HtlcError::InvalidExpirationDelta);
216 }
217
218 let expiration = self
219 .consensus_block_count()
220 .await?
221 .checked_add(expiration_delta)
222 .ok_or(HtlcError::InvalidExpirationDelta)?;
223
224 let (ephemeral_tweak, ephemeral_pk) =
225 tweak::generate(self.keys(account).keypair.public_key());
226
227 let refund_keypair = SecretKey::from_slice(&ephemeral_tweak)
228 .expect("32 bytes, within curve order")
229 .keypair(secp256k1::SECP256K1);
230
231 let contract = OutgoingContract {
232 payment_image,
233 amount,
234 expiration,
235 claim_pk,
236 refund_pk: refund_keypair.public_key(),
237 ephemeral_pk,
238 };
239
240 let operation_id = OperationId::from_encodable(&("lnv2-htlc-create", contract.clone()));
241
242 let client_output = ClientOutput::<LightningOutput> {
243 output: LightningOutput::V0(LightningOutputV0::Outgoing(contract.clone())),
244 amounts: Amounts::new_bitcoin(contract.amount),
245 };
246
247 let client_outputs = self
248 .client_ctx
249 .make_client_outputs(ClientOutputBundle::new_no_sm(vec![client_output]));
250
251 let transaction = TransactionBuilder::new(account).with_outputs(client_outputs);
252
253 let contract_clone = contract.clone();
254
255 let change_range = self
256 .client_ctx
257 .finalize_and_submit_transaction(
258 operation_id,
259 LightningCommonInit::KIND.as_str(),
260 move |change_outpoint_range: OutPointRange| {
261 LightningOperationMeta::CreateHtlc(CreateHtlcOperationMeta {
262 funding_outpoint: OutPoint {
265 txid: change_outpoint_range.txid,
266 out_idx: 0,
267 },
268 contract: contract_clone.clone(),
269 change_outpoint_range,
270 custom_meta: custom_meta.clone(),
271 })
272 },
273 transaction,
274 )
275 .await
276 .map_err(|e| HtlcError::FailedToSubmitTransaction(e.to_string()))?;
277
278 let funding_outpoint = OutPoint {
279 txid: change_range.txid,
280 out_idx: 0,
281 };
282
283 Ok((operation_id, funding_outpoint, contract))
284 }
285
286 pub async fn claim_htlc(
301 &self,
302 account: Account,
303 outpoint: OutPoint,
304 contract: OutgoingContract,
305 claim_keypair: Keypair,
306 preimage: [u8; 32],
307 custom_meta: Value,
308 ) -> Result<OperationId, HtlcError> {
309 if claim_keypair.public_key() != contract.claim_pk {
310 return Err(HtlcError::ClaimKeyMismatch);
311 }
312
313 if !contract.verify_preimage(&preimage) {
314 return Err(HtlcError::InvalidPreimage);
315 }
316
317 let spend = HtlcSpend {
318 outpoint,
319 contract,
320 witness: OutgoingWitness::Claim(preimage),
321 keypair: claim_keypair,
322 custom_meta,
323 account,
324 };
325
326 if let Some(operation_id) = self.existing_htlc_spend(&spend).await? {
327 return Ok(operation_id);
328 }
329
330 self.consensus_block_count().await?;
331
332 if self
333 .funded_contract_expiration(outpoint, &spend.contract)
334 .await?
335 == 0
336 {
337 return Err(HtlcError::Expired);
338 }
339
340 self.spend_htlc(spend).await
341 }
342
343 pub async fn refund_htlc(
347 &self,
348 outpoint: OutPoint,
349 contract: OutgoingContract,
350 custom_meta: Value,
351 ) -> Result<OperationId, HtlcError> {
352 let (account, refund_keypair) = self
353 .recover_htlc_refund_keypair(&contract)
354 .ok_or(HtlcError::RefundKeyMismatch)?;
355
356 let spend = HtlcSpend {
357 outpoint,
358 contract,
359 witness: OutgoingWitness::Refund,
360 keypair: refund_keypair,
361 custom_meta,
362 account,
363 };
364
365 if let Some(operation_id) = self.existing_htlc_spend(&spend).await? {
366 return Ok(operation_id);
367 }
368
369 let remaining_blocks = self
370 .funded_contract_expiration(outpoint, &spend.contract)
371 .await?;
372
373 if 0 < remaining_blocks {
374 return Err(HtlcError::NotExpired(remaining_blocks));
375 }
376
377 self.spend_htlc(spend).await
378 }
379
380 pub async fn cancel_htlc(
386 &self,
387 outpoint: OutPoint,
388 contract: OutgoingContract,
389 forfeit_signature: Signature,
390 custom_meta: Value,
391 ) -> Result<OperationId, HtlcError> {
392 if !contract.verify_forfeit_signature(&forfeit_signature) {
393 return Err(HtlcError::InvalidForfeitSignature);
394 }
395
396 let (account, refund_keypair) = self
397 .recover_htlc_refund_keypair(&contract)
398 .ok_or(HtlcError::RefundKeyMismatch)?;
399
400 let spend = HtlcSpend {
401 outpoint,
402 contract,
403 witness: OutgoingWitness::Cancel(forfeit_signature),
404 keypair: refund_keypair,
405 custom_meta,
406 account,
407 };
408
409 if let Some(operation_id) = self.existing_htlc_spend(&spend).await? {
410 return Ok(operation_id);
411 }
412
413 self.funded_contract_expiration(outpoint, &spend.contract)
414 .await?;
415
416 self.spend_htlc(spend).await
417 }
418
419 pub async fn consensus_block_count(&self) -> Result<u64, HtlcError> {
431 let consensus_block_count = self
432 .module_api
433 .consensus_block_count()
434 .await
435 .map_err(|e| HtlcError::FailedToRequestBlockCount(e.to_string()))?;
436
437 if consensus_block_count == 0 {
438 return Err(HtlcError::NoBlockCountConsensus);
439 }
440
441 Ok(consensus_block_count)
442 }
443
444 pub fn create_htlc_forfeit_signature(
450 contract: &OutgoingContract,
451 claim_keypair: &Keypair,
452 ) -> Result<Signature, HtlcError> {
453 if claim_keypair.public_key() != contract.claim_pk {
454 return Err(HtlcError::ClaimKeyMismatch);
455 }
456
457 Ok(claim_keypair.sign_schnorr(contract.forfeit_message()))
458 }
459
460 pub async fn await_htlc_funded(
476 &self,
477 outpoint: OutPoint,
478 contract: &OutgoingContract,
479 ) -> Result<u64, HtlcError> {
480 self.consensus_block_count().await?;
481
482 loop {
483 match self.module_api.outgoing_contract_expiration(outpoint).await {
484 Ok(Some((contract_id, remaining_blocks))) => {
485 if contract_id != contract.contract_id() {
486 return Err(HtlcError::ContractMismatch);
487 }
488
489 return Ok(remaining_blocks);
490 }
491 Ok(None) => {}
492 Err(error) if is_transient(&error) => {
493 debug!(
494 target: LOG_CLIENT_MODULE_LNV2,
495 err = %error.fmt_compact(),
496 "Failed to query the direct HTLC funding, retrying"
497 );
498 }
499 Err(error) => return Err(HtlcError::FederationApiError(error.to_string())),
500 }
501
502 sleep(Duration::from_secs(1)).await;
503 }
504 }
505
506 pub async fn await_htlc_resolution(
511 &self,
512 outpoint: OutPoint,
513 contract: &OutgoingContract,
514 ) -> Result<Option<[u8; 32]>, HtlcError> {
515 match self
516 .module_api
517 .await_preimage(outpoint, contract.expiration)
518 .await
519 {
520 Some(preimage) => {
521 if contract.verify_preimage(&preimage) {
522 Ok(Some(preimage))
523 } else {
524 Err(HtlcError::InvalidPreimageReturned)
525 }
526 }
527 None => Ok(None),
528 }
529 }
530
531 pub async fn await_htlc_operation_settled(
534 &self,
535 operation_id: OperationId,
536 ) -> Result<(), HtlcError> {
537 let operation = self
538 .client_ctx
539 .get_operation(operation_id)
540 .await
541 .map_err(|_| HtlcError::UnknownOperation)?;
542
543 if operation.operation_module_kind() != LightningCommonInit::KIND.as_str() {
544 return Err(HtlcError::NotAnHtlcOperation);
545 }
546
547 let change_outpoint_range = match operation.meta::<LightningOperationMeta>() {
548 LightningOperationMeta::CreateHtlc(meta) => meta.change_outpoint_range,
549 LightningOperationMeta::ClaimHtlc(meta)
550 | LightningOperationMeta::RefundHtlc(meta)
551 | LightningOperationMeta::CancelHtlc(meta) => meta.change_outpoint_range,
552 LightningOperationMeta::Send(..)
553 | LightningOperationMeta::Receive(..)
554 | LightningOperationMeta::LnurlReceive(..) => {
555 return Err(HtlcError::NotAnHtlcOperation);
556 }
557 };
558
559 self.client_ctx
560 .transaction_updates(operation_id)
561 .await
562 .await_tx_accepted(change_outpoint_range.txid)
563 .await
564 .map_err(HtlcError::TransactionRejected)?;
565
566 self.client_ctx
567 .await_primary_module_outputs(operation_id, change_outpoint_range.into_iter().collect())
568 .await
569 .map_err(|e| HtlcError::FailedToMintEcash(e.to_string()))?;
570
571 Ok(())
572 }
573
574 async fn existing_htlc_spend(
584 &self,
585 spend: &HtlcSpend,
586 ) -> Result<Option<OperationId>, HtlcError> {
587 let operation_id = spend.operation_id();
588
589 let operation = match self.client_ctx.get_operation(operation_id).await {
590 Ok(operation) => operation,
591 Err(OperationLookupError::NotFound(..)) => return Ok(None),
592 Err(..) => return Err(HtlcError::NotAnHtlcOperation),
593 };
594
595 let contract = match operation.meta::<LightningOperationMeta>() {
596 LightningOperationMeta::ClaimHtlc(meta)
597 | LightningOperationMeta::RefundHtlc(meta)
598 | LightningOperationMeta::CancelHtlc(meta) => meta.contract,
599 LightningOperationMeta::CreateHtlc(..)
600 | LightningOperationMeta::Send(..)
601 | LightningOperationMeta::Receive(..)
602 | LightningOperationMeta::LnurlReceive(..) => {
603 return Err(HtlcError::NotAnHtlcOperation);
604 }
605 };
606
607 if contract != spend.contract {
608 return Err(HtlcError::ContractMismatch);
609 }
610
611 Ok(Some(operation_id))
612 }
613
614 async fn spend_htlc(&self, spend: HtlcSpend) -> Result<OperationId, HtlcError> {
619 let operation_id = spend.operation_id();
620
621 let client_input = ClientInput::<LightningInput> {
622 input: LightningInput::V0(LightningInputV0::Outgoing(
623 spend.outpoint,
624 spend.witness.clone(),
625 )),
626 amounts: Amounts::new_bitcoin(spend.contract.amount),
627 keys: vec![spend.keypair],
628 };
629
630 let client_inputs = self
631 .client_ctx
632 .make_client_inputs(ClientInputBundle::new_no_sm(vec![client_input]));
633
634 let transaction = TransactionBuilder::new(spend.account).with_inputs(client_inputs);
635
636 self.client_ctx
637 .finalize_and_submit_transaction(
638 operation_id,
639 LightningCommonInit::KIND.as_str(),
640 move |change_outpoint_range: OutPointRange| {
641 spend.operation_meta(change_outpoint_range)
642 },
643 transaction,
644 )
645 .await
646 .map_err(|e| HtlcError::FailedToSubmitTransaction(e.to_string()))?;
647
648 Ok(operation_id)
649 }
650
651 async fn funded_contract_expiration(
661 &self,
662 outpoint: OutPoint,
663 contract: &OutgoingContract,
664 ) -> Result<u64, HtlcError> {
665 let (contract_id, remaining_blocks) = self
666 .module_api
667 .outgoing_contract_expiration(outpoint)
668 .await
669 .map_err(|e| HtlcError::FederationApiError(e.to_string()))?
670 .ok_or(HtlcError::ContractNotFound)?;
671
672 if contract_id != contract.contract_id() {
673 return Err(HtlcError::ContractMismatch);
674 }
675
676 Ok(remaining_blocks)
677 }
678
679 fn recover_htlc_refund_keypair(
685 &self,
686 contract: &OutgoingContract,
687 ) -> Option<(Account, Keypair)> {
688 Account::ALL.into_iter().find_map(|account| {
689 let ephemeral_tweak = ecdh::SharedSecret::new(
690 &contract.ephemeral_pk,
691 &self.keys(account).keypair.secret_key(),
692 );
693
694 let refund_keypair = SecretKey::from_slice(&ephemeral_tweak.secret_bytes())
695 .expect("32 bytes, within curve order")
696 .keypair(secp256k1::SECP256K1);
697
698 (refund_keypair.public_key() == contract.refund_pk).then_some((account, refund_keypair))
699 })
700 }
701}