Skip to main content

fedimint_lnv2_client/
htlc.rs

1//! # Direct HTLC API
2//!
3//! This module exposes the outgoing contract of the `LNv2` module as a plain
4//! HTLC between two clients of the same federation, without any Lightning
5//! gateway involvement. This enables atomic swaps with counterparties outside
6//! the federation's Lightning infrastructure, e.g. swaps with other chains or
7//! currencies.
8//!
9//! The funder locks ecash to the counterparty's claim key via
10//! [`LightningClientModule::create_htlc`]. The counterparty verifies the
11//! funding via [`LightningClientModule::await_htlc_funded`] and resolves the
12//! HTLC with the preimage via [`LightningClientModule::claim_htlc`], which
13//! reveals the preimage to the funder via
14//! [`LightningClientModule::await_htlc_resolution`]. A failed HTLC is either
15//! cancelled cooperatively before its expiration with the counterparty's
16//! forfeit signature via [`LightningClientModule::cancel_htlc`], or refunded
17//! unilaterally after its expiration via
18//! [`LightningClientModule::refund_htlc`].
19//!
20//! All coordination data - the contract, its funding outpoint and the forfeit
21//! signature - is exchanged between the two parties out of band; the CLI and
22//! the JSON representation of this data are documented in
23//! `docs/lightning_module_v2.md`. The contract expiration is measured in
24//! block count as tracked by the federation's consensus, not in unix time.
25
26use 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/// Metadata of an operation funding a direct HTLC via
57/// [`LightningClientModule::create_htlc`].
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct CreateHtlcOperationMeta {
60    /// The outpoint of the contract in the funding transaction; share this
61    /// together with `contract` with the counterparty so they can verify and
62    /// claim the HTLC.
63    pub funding_outpoint: OutPoint,
64    pub contract: OutgoingContract,
65    pub change_outpoint_range: OutPointRange,
66    pub custom_meta: Value,
67}
68
69/// Metadata of an operation spending a direct HTLC: a claim via
70/// [`LightningClientModule::claim_htlc`], a refund via
71/// [`LightningClientModule::refund_htlc`] or a cancellation via
72/// [`LightningClientModule::cancel_htlc`].
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct SpendHtlcOperationMeta {
75    /// The outpoint the contract was funded at.
76    pub htlc_outpoint: OutPoint,
77    pub contract: OutgoingContract,
78    pub change_outpoint_range: OutPointRange,
79    pub custom_meta: Value,
80}
81
82/// Errors of the direct HTLC operations; see
83/// [`LightningClientModule::create_htlc`].
84#[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/// The parameters of a transaction spending a direct HTLC; see
127/// [`LightningClientModule::spend_htlc`]. The witness is the action taken on
128/// the contract, from which the operation id and the operation meta of the
129/// spend are derived.
130#[derive(Clone)]
131struct HtlcSpend {
132    outpoint: OutPoint,
133    contract: OutgoingContract,
134    witness: OutgoingWitness,
135    keypair: Keypair,
136    custom_meta: Value,
137    /// The balance the spend is credited to.
138    account: Account,
139}
140
141/// Whether a federation error is caused by connection failures only, such that
142/// retrying the request may succeed.
143fn 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    /// The operation id of the spend, which is deterministic per action and
152    /// outpoint so that every action on a contract is recorded only once and
153    /// retrying it yields the recorded operation.
154    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    /// The operation meta of the spend for the given change outpoint range.
165    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    /// Fund a direct HTLC: an outgoing contract of `amount` locked to the
183    /// counterparty's `claim_pk`, without any gateway involvement. The
184    /// counterparty can claim the contract with the preimage of
185    /// `payment_image` via [`Self::claim_htlc`] until `expiration_delta`
186    /// blocks from now; afterwards we can reclaim it via
187    /// [`Self::refund_htlc`], or earlier via [`Self::cancel_htlc`] if the
188    /// counterparty provides a forfeit signature.
189    ///
190    /// Returns the contract and the outpoint it is funded at; share both with
191    /// the counterparty so they can verify the funding via
192    /// [`Self::await_htlc_funded`] and claim the contract. Await the
193    /// acceptance of the funding transaction via
194    /// [`Self::await_htlc_operation_settled`] and the counterparty's claim
195    /// via [`Self::await_htlc_resolution`], which yields the preimage.
196    ///
197    /// The contract's refund key is derived from our static module key via
198    /// the ephemeral key committed in the contract, so refunding and
199    /// cancelling only require the contract itself, not this operation's
200    /// local state.
201    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                        // The contract is the only output submitted before the
263                        // change, which is always appended after it.
264                        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    /// Claim a direct HTLC funded at `outpoint` with the preimage of its
287    /// payment image; the ecash is issued to our wallet. The claiming
288    /// transaction has to be signed by the contract's claim key, hence the
289    /// `claim_keypair`.
290    ///
291    /// Since the preimage becomes public with the claiming transaction the
292    /// caller has to ensure sufficient time until the contract's expiration
293    /// remains; this method only rejects contracts that have already expired.
294    /// Await the issuance of the ecash via
295    /// [`Self::await_htlc_operation_settled`].
296    ///
297    /// Retrying a claim, refund or cancellation that has already been
298    /// recorded returns the recorded operation, whether or not its
299    /// transaction has been accepted yet.
300    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    /// Refund a direct HTLC we created via [`Self::create_htlc`] after its
344    /// expiration; the ecash is issued back to our wallet. Await the issuance
345    /// via [`Self::await_htlc_operation_settled`].
346    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    /// Cancel a direct HTLC we created via [`Self::create_htlc`] before its
381    /// expiration using the counterparty's `forfeit_signature`, created via
382    /// [`Self::create_htlc_forfeit_signature`]; the ecash is issued back to
383    /// our wallet. Await the issuance via
384    /// [`Self::await_htlc_operation_settled`].
385    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    /// The federation's current consensus block count, against which direct
420    /// HTLC expirations are measured.
421    ///
422    /// Returns [`HtlcError::NoBlockCountConsensus`] while the federation has
423    /// not yet committed its first block count votes, during which the
424    /// reported count would be zero while the actual chain tip may already
425    /// be at a positive height; an expiration computed against the zero
426    /// count would be overtaken the moment the first votes are committed.
427    /// For the same reason [`Self::create_htlc`], [`Self::claim_htlc`] and
428    /// [`Self::await_htlc_funded`] refuse to operate until this method
429    /// succeeds.
430    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    /// Create a forfeit signature for a direct HTLC locked to our
445    /// `claim_keypair`, which allows its funder to reclaim the contract
446    /// before its expiration via [`Self::cancel_htlc`]. This is how the
447    /// claiming side fails an HTLC cooperatively; it is a pure offline
448    /// operation.
449    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    /// Wait until the given contract is funded at `outpoint` and return the
461    /// number of blocks remaining until its expiration. This is how the
462    /// claiming side verifies the funder's claim that the HTLC exists before
463    /// taking any action of its own, e.g. sending funds on another chain.
464    ///
465    /// This method polls the federation indefinitely, retrying connection
466    /// failures, so callers should enforce their own timeout; note that it
467    /// will also never resolve if the contract has already been claimed,
468    /// refunded or cancelled again. Any other federation error, e.g. one of a
469    /// federation that does not support direct HTLCs, is returned.
470    ///
471    /// Returns [`HtlcError::NoBlockCountConsensus`] while the federation has
472    /// not yet reached consensus on a block count, as the remaining blocks
473    /// would be measured against a count of zero and overstate the contract's
474    /// lifetime; see [`Self::consensus_block_count`].
475    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    /// Wait until the direct HTLC funded at `outpoint` is either claimed, in
507    /// which case the preimage is returned, or expired unclaimed, in which
508    /// case `None` is returned and the funder can safely refund the contract
509    /// via [`Self::refund_htlc`].
510    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    /// Wait until the transaction of a direct HTLC operation is accepted by
532    /// the federation and any ecash it issues has been minted.
533    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    /// Return the operation id of `spend` if it has already been recorded,
575    /// such that retrying a spend, e.g. after its caller was interrupted
576    /// while the transaction is in flight, yields the original operation.
577    /// Callers have to check this before they verify the contract against
578    /// the federation, since that check fails once the recorded spend has
579    /// resolved the contract. The retry's custom meta is ignored.
580    ///
581    /// Concurrent calls for the same spend may both miss the recorded
582    /// operation, in which case recording the second one fails.
583    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    /// Submit a transaction spending a direct HTLC and record it under a new
615    /// operation. Callers have to check for an existing operation via
616    /// [`Self::existing_htlc_spend`] and verify the contract against the
617    /// federation via [`Self::funded_contract_expiration`] first.
618    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    /// Verify that `contract` is the unresolved contract funded at `outpoint`
652    /// and return the number of blocks remaining until its expiration, which
653    /// is zero once it has expired.
654    ///
655    /// Every spend of a contract has to pass this check before it is
656    /// recorded, since spends are recorded under operation ids derived from
657    /// the outpoint alone: a spend recorded with a mismatched contract would
658    /// be rejected by the federation while making every later attempt with
659    /// the correct contract fail against the recorded operation.
660    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    /// Recover the refund keypair of a direct HTLC created by this client
680    /// from the contract's ephemeral key and the static module key of the
681    /// account that funded it, which is also the account the refund is
682    /// credited to. Each account's key is tried, since the contract does not
683    /// say which one it was created from.
684    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}