1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The logic to build claims and bump in-flight transactions until confirmations.
12 //! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
13 //! building, tracking, bumping and notifications functions.
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
19 use bitcoin::hash_types::{Txid, BlockHash};
21 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
22 use bitcoin::secp256k1;
24 use crate::chain::keysinterface::{ChannelSigner, EntropySource, SignerProvider};
25 use crate::ln::msgs::DecodeError;
26 use crate::ln::PaymentPreimage;
28 use crate::ln::chan_utils::{self, HTLCOutputInCommitment};
29 use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
31 use crate::chain::chaininterface::ConfirmationTarget;
32 use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
33 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
34 use crate::chain::keysinterface::WriteableEcdsaChannelSigner;
36 use crate::chain::package::PackageSolvingData;
37 use crate::chain::package::PackageTemplate;
38 use crate::util::logger::Logger;
39 use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, UpgradableRequired, Writer, Writeable, VecWriter};
42 use crate::prelude::*;
43 use alloc::collections::BTreeMap;
46 use core::mem::replace;
49 use bitcoin::hashes::Hash;
51 const MAX_ALLOC_SIZE: usize = 64*1024;
53 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
54 /// transaction causing it.
56 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
57 #[derive(PartialEq, Eq)]
58 struct OnchainEventEntry {
61 block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
65 impl OnchainEventEntry {
66 fn confirmation_threshold(&self) -> u32 {
67 self.height + ANTI_REORG_DELAY - 1
70 fn has_reached_confirmation_threshold(&self, height: u32) -> bool {
71 height >= self.confirmation_threshold()
75 /// Events for claims the [`OnchainTxHandler`] has generated. Once the events are considered safe
76 /// from a chain reorg, the [`OnchainTxHandler`] will act accordingly.
77 #[derive(PartialEq, Eq)]
79 /// A pending request has been claimed by a transaction spending the exact same set of outpoints
80 /// as the request. This claim can either be ours or from the counterparty. Once the claiming
81 /// transaction has met [`ANTI_REORG_DELAY`] confirmations, we consider it final and remove the
84 package_id: PackageID,
86 /// The counterparty has claimed an outpoint from one of our pending requests through a
87 /// different transaction than ours. If our transaction was attempting to claim multiple
88 /// outputs, we need to drop the outpoint claimed by the counterparty and regenerate a new claim
89 /// transaction for ourselves. We keep tracking, separately, the outpoint claimed by the
90 /// counterparty up to [`ANTI_REORG_DELAY`] confirmations to ensure we attempt to re-claim it
91 /// if the counterparty's claim is reorged from the chain.
93 package: PackageTemplate,
97 impl Writeable for OnchainEventEntry {
98 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
99 write_tlv_fields!(writer, {
100 (0, self.txid, required),
101 (1, self.block_hash, option),
102 (2, self.height, required),
103 (4, self.event, required),
109 impl MaybeReadable for OnchainEventEntry {
110 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
111 let mut txid = Txid::all_zeros();
113 let mut block_hash = None;
114 let mut event = UpgradableRequired(None);
115 read_tlv_fields!(reader, {
117 (1, block_hash, option),
118 (2, height, required),
119 (4, event, upgradable_required),
121 Ok(Some(Self { txid, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
125 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
127 (0, package_id, required),
129 (1, ContentiousOutpoint) => {
130 (0, package, required),
134 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
135 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
136 match Readable::read(reader)? {
139 let vlen: u64 = Readable::read(reader)?;
140 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<Option<(usize, Signature)>>()));
142 ret.push(match Readable::read(reader)? {
144 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
145 _ => return Err(DecodeError::InvalidValue)
150 _ => Err(DecodeError::InvalidValue),
155 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
156 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
160 (vec.len() as u64).write(writer)?;
161 for opt in vec.iter() {
163 &Some((ref idx, ref sig)) => {
165 (*idx as u64).write(writer)?;
168 &None => 0u8.write(writer)?,
172 &None => 0u8.write(writer)?,
179 /// The claim commonly referred to as the pre-signed second-stage HTLC transaction.
180 pub(crate) struct ExternalHTLCClaim {
181 pub(crate) commitment_txid: Txid,
182 pub(crate) per_commitment_number: u64,
183 pub(crate) htlc: HTLCOutputInCommitment,
184 pub(crate) preimage: Option<PaymentPreimage>,
185 pub(crate) counterparty_sig: Signature,
188 // Represents the different types of claims for which events are yielded externally to satisfy said
191 pub(crate) enum ClaimEvent {
192 /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
193 /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
195 package_target_feerate_sat_per_1000_weight: u32,
196 commitment_tx: Transaction,
197 anchor_output_idx: u32,
199 /// Event yielded to signal that the commitment transaction has confirmed and its HTLCs must be
200 /// resolved by broadcasting a transaction with sufficient fee to claim them.
202 target_feerate_sat_per_1000_weight: u32,
203 htlcs: Vec<ExternalHTLCClaim>,
207 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
208 /// control) onchain.
209 pub(crate) enum OnchainClaim {
210 /// A finalized transaction pending confirmation spending the output to claim.
213 /// An event yielded externally to signal additional inputs must be added to a transaction
214 /// pending confirmation spending the output to claim.
218 /// An internal identifier to track pending package claims within the `OnchainTxHandler`.
219 type PackageID = [u8; 32];
221 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
222 /// do RBF bumping if possible.
223 pub struct OnchainTxHandler<ChannelSigner: WriteableEcdsaChannelSigner> {
224 destination_script: Script,
225 holder_commitment: HolderCommitmentTransaction,
226 // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
227 // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
228 // the set of HTLCs in the HolderCommitmentTransaction.
229 holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
230 prev_holder_commitment: Option<HolderCommitmentTransaction>,
231 prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
233 pub(super) signer: ChannelSigner,
234 pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
236 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
237 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
238 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
239 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
240 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
241 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
242 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
243 // we need to regenerate new claim request with reduced set of still-claimable outpoints.
244 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
245 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
246 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
247 #[cfg(test)] // Used in functional_test to verify sanitization
248 pub(crate) pending_claim_requests: HashMap<PackageID, PackageTemplate>,
250 pending_claim_requests: HashMap<PackageID, PackageTemplate>,
252 // Used to track external events that need to be forwarded to the `ChainMonitor`. This `Vec`
253 // essentially acts as an insertion-ordered `HashMap` – there should only ever be one occurrence
254 // of a `PackageID`, which tracks its latest `ClaimEvent`, i.e., if a pending claim exists, and
255 // a new block has been connected, resulting in a new claim, the previous will be replaced with
258 // These external events may be generated in the following cases:
259 // - A channel has been force closed by broadcasting the holder's latest commitment transaction
260 // - A block being connected/disconnected
261 // - Learning the preimage for an HTLC we can claim onchain
263 pending_claim_events: Vec<(PackageID, ClaimEvent)>,
265 // Used to link outpoints claimed in a connected block to a pending claim request. The keys
266 // represent the outpoints that our `ChannelMonitor` has detected we have keys/scripts to
267 // claim. The values track the pending claim request identifier and the initial confirmation
268 // block height, and are immutable until the outpoint has enough confirmations to meet our
269 // [`ANTI_REORG_DELAY`]. The initial confirmation block height is used to remove the entry if
270 // the block gets disconnected.
271 #[cfg(test)] // Used in functional_test to verify sanitization
272 pub claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
274 claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
276 locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
278 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
280 pub(super) secp_ctx: Secp256k1<secp256k1::All>,
283 impl<ChannelSigner: WriteableEcdsaChannelSigner> PartialEq for OnchainTxHandler<ChannelSigner> {
284 fn eq(&self, other: &Self) -> bool {
285 // `signer`, `secp_ctx`, and `pending_claim_events` are excluded on purpose.
286 self.destination_script == other.destination_script &&
287 self.holder_commitment == other.holder_commitment &&
288 self.holder_htlc_sigs == other.holder_htlc_sigs &&
289 self.prev_holder_commitment == other.prev_holder_commitment &&
290 self.prev_holder_htlc_sigs == other.prev_holder_htlc_sigs &&
291 self.channel_transaction_parameters == other.channel_transaction_parameters &&
292 self.pending_claim_requests == other.pending_claim_requests &&
293 self.claimable_outpoints == other.claimable_outpoints &&
294 self.locktimed_packages == other.locktimed_packages &&
295 self.onchain_events_awaiting_threshold_conf == other.onchain_events_awaiting_threshold_conf
299 const SERIALIZATION_VERSION: u8 = 1;
300 const MIN_SERIALIZATION_VERSION: u8 = 1;
302 impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
303 pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
304 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
306 self.destination_script.write(writer)?;
307 self.holder_commitment.write(writer)?;
308 self.holder_htlc_sigs.write(writer)?;
309 self.prev_holder_commitment.write(writer)?;
310 self.prev_holder_htlc_sigs.write(writer)?;
312 self.channel_transaction_parameters.write(writer)?;
314 let mut key_data = VecWriter(Vec::new());
315 self.signer.write(&mut key_data)?;
316 assert!(key_data.0.len() < core::usize::MAX);
317 assert!(key_data.0.len() < core::u32::MAX as usize);
318 (key_data.0.len() as u32).write(writer)?;
319 writer.write_all(&key_data.0[..])?;
321 writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?;
322 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
323 ancestor_claim_txid.write(writer)?;
324 request.write(writer)?;
327 writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?;
328 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
330 claim_and_height.0.write(writer)?;
331 claim_and_height.1.write(writer)?;
334 writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?;
335 for (ref locktime, ref packages) in self.locktimed_packages.iter() {
336 locktime.write(writer)?;
337 writer.write_all(&(packages.len() as u64).to_be_bytes())?;
338 for ref package in packages.iter() {
339 package.write(writer)?;
343 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
344 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
345 entry.write(writer)?;
348 write_tlv_fields!(writer, {});
353 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP, u64, [u8; 32])> for OnchainTxHandler<SP::Signer> {
354 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP, u64, [u8; 32])) -> Result<Self, DecodeError> {
355 let entropy_source = args.0;
356 let signer_provider = args.1;
357 let channel_value_satoshis = args.2;
358 let channel_keys_id = args.3;
360 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
362 let destination_script = Readable::read(reader)?;
364 let holder_commitment = Readable::read(reader)?;
365 let holder_htlc_sigs = Readable::read(reader)?;
366 let prev_holder_commitment = Readable::read(reader)?;
367 let prev_holder_htlc_sigs = Readable::read(reader)?;
369 let channel_parameters = Readable::read(reader)?;
371 // Read the serialized signer bytes, but don't deserialize them, as we'll obtain our signer
372 // by re-deriving the private key material.
373 let keys_len: u32 = Readable::read(reader)?;
374 let mut bytes_read = 0;
375 while bytes_read != keys_len as usize {
376 // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
377 let mut data = [0; 1024];
378 let bytes_to_read = cmp::min(1024, keys_len as usize - bytes_read);
379 let read_slice = &mut data[0..bytes_to_read];
380 reader.read_exact(read_slice)?;
381 bytes_read += bytes_to_read;
384 let mut signer = signer_provider.derive_channel_signer(channel_value_satoshis, channel_keys_id);
385 signer.provide_channel_parameters(&channel_parameters);
387 let pending_claim_requests_len: u64 = Readable::read(reader)?;
388 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
389 for _ in 0..pending_claim_requests_len {
390 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
393 let claimable_outpoints_len: u64 = Readable::read(reader)?;
394 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
395 for _ in 0..claimable_outpoints_len {
396 let outpoint = Readable::read(reader)?;
397 let ancestor_claim_txid = Readable::read(reader)?;
398 let height = Readable::read(reader)?;
399 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
402 let locktimed_packages_len: u64 = Readable::read(reader)?;
403 let mut locktimed_packages = BTreeMap::new();
404 for _ in 0..locktimed_packages_len {
405 let locktime = Readable::read(reader)?;
406 let packages_len: u64 = Readable::read(reader)?;
407 let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
408 for _ in 0..packages_len {
409 packages.push(Readable::read(reader)?);
411 locktimed_packages.insert(locktime, packages);
414 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
415 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
416 for _ in 0..waiting_threshold_conf_len {
417 if let Some(val) = MaybeReadable::read(reader)? {
418 onchain_events_awaiting_threshold_conf.push(val);
422 read_tlv_fields!(reader, {});
424 let mut secp_ctx = Secp256k1::new();
425 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
427 Ok(OnchainTxHandler {
431 prev_holder_commitment,
432 prev_holder_htlc_sigs,
434 channel_transaction_parameters: channel_parameters,
437 pending_claim_requests,
438 onchain_events_awaiting_threshold_conf,
440 pending_claim_events: Vec::new(),
446 impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
447 pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
451 holder_htlc_sigs: None,
452 prev_holder_commitment: None,
453 prev_holder_htlc_sigs: None,
455 channel_transaction_parameters: channel_parameters,
456 pending_claim_requests: HashMap::new(),
457 claimable_outpoints: HashMap::new(),
458 locktimed_packages: BTreeMap::new(),
459 onchain_events_awaiting_threshold_conf: Vec::new(),
461 pending_claim_events: Vec::new(),
466 pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
467 self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
470 pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
471 self.holder_commitment.to_broadcaster_value_sat()
475 pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<ClaimEvent> {
476 let mut events = Vec::new();
477 swap(&mut events, &mut self.pending_claim_events);
478 events.into_iter().map(|(_, event)| event).collect()
481 /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
482 /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
483 /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
484 /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
485 /// Child-Pay-For-Parent.
487 /// Panics if there are signing errors, because signing operations in reaction to on-chain
488 /// events are not expected to fail, and if they do, we may lose funds.
489 fn generate_claim<F: Deref, L: Deref>(&mut self, cur_height: u32, cached_request: &PackageTemplate, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L) -> Option<(Option<u32>, u64, OnchainClaim)>
490 where F::Target: FeeEstimator,
493 let request_outpoints = cached_request.outpoints();
494 if request_outpoints.is_empty() {
495 // Don't prune pending claiming request yet, we may have to resurrect HTLCs. Untractable
496 // packages cannot be aggregated and will never be split, so we cannot end up with an
498 debug_assert!(cached_request.is_malleable());
501 // If we've seen transaction inclusion in the chain for all outpoints in our request, we
502 // don't need to continue generating more claims. We'll keep tracking the request to fully
503 // remove it once it reaches the confirmation threshold, or to generate a new claim if the
504 // transaction is reorged out.
505 let mut all_inputs_have_confirmed_spend = true;
506 for outpoint in request_outpoints.iter() {
507 if let Some((request_package_id, _)) = self.claimable_outpoints.get(*outpoint) {
508 // We check for outpoint spends within claims individually rather than as a set
509 // since requests can have outpoints split off.
510 if !self.onchain_events_awaiting_threshold_conf.iter()
511 .any(|event_entry| if let OnchainEvent::Claim { package_id } = event_entry.event {
512 *request_package_id == package_id
514 // The onchain event is not a claim, keep seeking until we find one.
518 // Either we had no `OnchainEvent::Claim`, or we did but none matched the
519 // outpoint's registered spend.
520 all_inputs_have_confirmed_spend = false;
523 // The request's outpoint spend does not exist yet.
524 all_inputs_have_confirmed_spend = false;
527 if all_inputs_have_confirmed_spend {
531 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
532 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
533 let new_timer = Some(cached_request.get_height_timer(cur_height));
534 if cached_request.is_malleable() {
536 { // Attributes are not allowed on if expressions on our current MSRV of 1.41.
537 if cached_request.requires_external_funding() {
538 let target_feerate_sat_per_1000_weight = cached_request
539 .compute_package_feerate(fee_estimator, ConfirmationTarget::HighPriority);
540 if let Some(htlcs) = cached_request.construct_malleable_package_with_external_funding(self) {
543 target_feerate_sat_per_1000_weight as u64,
544 OnchainClaim::Event(ClaimEvent::BumpHTLC {
545 target_feerate_sat_per_1000_weight,
555 let predicted_weight = cached_request.package_weight(&self.destination_script);
556 if let Some((output_value, new_feerate)) = cached_request.compute_package_output(
557 predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger,
559 assert!(new_feerate != 0);
561 let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
562 log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
563 assert!(predicted_weight >= transaction.weight());
564 return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
567 // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
568 // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
569 // which require external funding.
571 let inputs = cached_request.inputs();
573 let mut inputs = cached_request.inputs();
574 debug_assert_eq!(inputs.len(), 1);
575 let tx = match cached_request.finalize_untractable_package(self, logger) {
579 if !cached_request.requires_external_funding() {
580 return Some((None, 0, OnchainClaim::Tx(tx)));
583 return inputs.find_map(|input| match input {
584 // Commitment inputs with anchors support are the only untractable inputs supported
585 // thus far that require external funding.
586 PackageSolvingData::HolderFundingOutput(..) => {
587 debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
588 "Holder commitment transaction mismatch");
589 // We'll locate an anchor output we can spend within the commitment transaction.
590 let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
591 match chan_utils::get_anchor_output(&tx, funding_pubkey) {
592 // An anchor output was found, so we should yield a funding event externally.
594 // TODO: Use a lower confirmation target when both our and the
595 // counterparty's latest commitment don't have any HTLCs present.
596 let conf_target = ConfirmationTarget::HighPriority;
597 let package_target_feerate_sat_per_1000_weight = cached_request
598 .compute_package_feerate(fee_estimator, conf_target);
601 package_target_feerate_sat_per_1000_weight as u64,
602 OnchainClaim::Event(ClaimEvent::BumpCommitment {
603 package_target_feerate_sat_per_1000_weight,
604 commitment_tx: tx.clone(),
605 anchor_output_idx: idx,
609 // An anchor output was not found. There's nothing we can do other than
610 // attempt to broadcast the transaction with its current fee rate and hope
611 // it confirms. This is essentially the same behavior as a commitment
612 // transaction without anchor outputs.
613 None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
617 debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
625 /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
626 /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
627 /// Together with `update_claims_view_from_matched_txn` this used to be named
628 /// `block_connected`, but it is now also used for claiming an HTLC output if we receive a
629 /// preimage after force-close.
631 /// `conf_height` represents the height at which the request was generated. This
632 /// does not need to equal the current blockchain tip height, which should be provided via
633 /// `cur_height`, however it must never be higher than `cur_height`.
634 pub(crate) fn update_claims_view_from_requests<B: Deref, F: Deref, L: Deref>(
635 &mut self, requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32,
636 broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
638 B::Target: BroadcasterInterface,
639 F::Target: FeeEstimator,
642 log_debug!(logger, "Updating claims view at height {} with {} claim requests", cur_height, requests.len());
643 let mut preprocessed_requests = Vec::with_capacity(requests.len());
644 let mut aggregated_request = None;
646 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
647 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
648 for req in requests {
649 // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
650 if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
651 log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
653 let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
654 .find(|locked_package| locked_package.outpoints() == req.outpoints());
655 if let Some(package) = timelocked_equivalent_package {
656 log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
657 req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
661 let package_locktime = req.package_locktime(cur_height);
662 if package_locktime > cur_height + 1 {
663 log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
664 for outpoint in req.outpoints() {
665 log_info!(logger, " Outpoint {}", outpoint);
667 self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
671 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
672 if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
673 // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
674 preprocessed_requests.push(req);
675 } else if aggregated_request.is_none() {
676 aggregated_request = Some(req);
678 aggregated_request.as_mut().unwrap().merge_package(req);
682 if let Some(req) = aggregated_request {
683 preprocessed_requests.push(req);
686 // Claim everything up to and including cur_height + 1
687 let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2));
688 for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
689 log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
690 preprocessed_requests.append(&mut entry);
692 self.locktimed_packages = remaining_locked_packages;
694 // Generate claim transactions and track them to bump if necessary at
695 // height timer expiration (i.e in how many blocks we're going to take action).
696 for mut req in preprocessed_requests {
697 if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
698 req.set_timer(new_timer);
699 req.set_feerate(new_feerate);
700 let package_id = match claim {
701 OnchainClaim::Tx(tx) => {
702 log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
703 broadcaster.broadcast_transaction(&tx);
704 tx.txid().into_inner()
707 OnchainClaim::Event(claim_event) => {
708 log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
709 let package_id = match claim_event {
710 ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid().into_inner(),
711 ClaimEvent::BumpHTLC { ref htlcs, .. } => {
712 // Use the same construction as a lightning channel id to generate
713 // the package id for this request based on the first HTLC. It
714 // doesn't matter what we use as long as it's unique per request.
715 let mut package_id = [0; 32];
716 package_id[..].copy_from_slice(&htlcs[0].commitment_txid[..]);
717 let htlc_output_index = htlcs[0].htlc.transaction_output_index.unwrap();
718 package_id[30] ^= ((htlc_output_index >> 8) & 0xff) as u8;
719 package_id[31] ^= ((htlc_output_index >> 0) & 0xff) as u8;
723 debug_assert_eq!(self.pending_claim_events.iter().filter(|entry| entry.0 == package_id).count(), 0);
724 self.pending_claim_events.push((package_id, claim_event));
728 for k in req.outpoints() {
729 log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
730 self.claimable_outpoints.insert(k.clone(), (package_id, conf_height));
732 self.pending_claim_requests.insert(package_id, req);
737 /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
738 /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
739 /// Together with `update_claims_view_from_requests` this used to be named `block_connected`,
740 /// but it is now also used for claiming an HTLC output if we receive a preimage after force-close.
742 /// `conf_height` represents the height at which the transactions in `txn_matched` were
743 /// confirmed. This does not need to equal the current blockchain tip height, which should be
744 /// provided via `cur_height`, however it must never be higher than `cur_height`.
745 pub(crate) fn update_claims_view_from_matched_txn<B: Deref, F: Deref, L: Deref>(
746 &mut self, txn_matched: &[&Transaction], conf_height: u32, conf_hash: BlockHash,
747 cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
749 B::Target: BroadcasterInterface,
750 F::Target: FeeEstimator,
753 log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {}", cur_height, txn_matched.len(), conf_height);
754 let mut bump_candidates = HashMap::new();
755 for tx in txn_matched {
756 // Scan all input to verify is one of the outpoint spent is of interest for us
757 let mut claimed_outputs_material = Vec::new();
758 for inp in &tx.input {
759 if let Some((package_id, _)) = self.claimable_outpoints.get(&inp.previous_output) {
760 // If outpoint has claim request pending on it...
761 if let Some(request) = self.pending_claim_requests.get_mut(package_id) {
762 //... we need to verify equality between transaction outpoints and claim request
763 // outpoints to know if transaction is the original claim or a bumped one issued
765 let mut are_sets_equal = true;
766 let mut tx_inputs = tx.input.iter().map(|input| &input.previous_output).collect::<Vec<_>>();
767 tx_inputs.sort_unstable();
768 for request_input in request.outpoints() {
769 if tx_inputs.binary_search(&request_input).is_err() {
770 are_sets_equal = false;
775 macro_rules! clean_claim_request_after_safety_delay {
777 let entry = OnchainEventEntry {
780 block_hash: Some(conf_hash),
781 event: OnchainEvent::Claim { package_id: *package_id }
783 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
784 self.onchain_events_awaiting_threshold_conf.push(entry);
789 // If this is our transaction (or our counterparty spent all the outputs
790 // before we could anyway with same inputs order than us), wait for
791 // ANTI_REORG_DELAY and clean the RBF tracking map.
793 clean_claim_request_after_safety_delay!();
794 } else { // If false, generate new claim request with update outpoint set
795 let mut at_least_one_drop = false;
796 for input in tx.input.iter() {
797 if let Some(package) = request.split_package(&input.previous_output) {
798 claimed_outputs_material.push(package);
799 at_least_one_drop = true;
801 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
802 if request.outpoints().is_empty() {
803 clean_claim_request_after_safety_delay!();
806 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
807 if at_least_one_drop {
808 bump_candidates.insert(*package_id, request.clone());
809 // If we have any pending claim events for the request being updated
810 // that have yet to be consumed, we'll remove them since they will
811 // end up producing an invalid transaction by double spending
812 // input(s) that already have a confirmed spend. If such spend is
813 // reorged out of the chain, then we'll attempt to re-spend the
814 // inputs once we see it.
816 #[cfg(debug_assertions)] {
817 let existing = self.pending_claim_events.iter()
818 .filter(|entry| entry.0 == *package_id).count();
819 assert!(existing == 0 || existing == 1);
821 self.pending_claim_events.retain(|entry| entry.0 != *package_id);
825 break; //No need to iterate further, either tx is our or their
827 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
831 for package in claimed_outputs_material.drain(..) {
832 let entry = OnchainEventEntry {
835 block_hash: Some(conf_hash),
836 event: OnchainEvent::ContentiousOutpoint { package },
838 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
839 self.onchain_events_awaiting_threshold_conf.push(entry);
844 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
845 let onchain_events_awaiting_threshold_conf =
846 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
847 for entry in onchain_events_awaiting_threshold_conf {
848 if entry.has_reached_confirmation_threshold(cur_height) {
850 OnchainEvent::Claim { package_id } => {
851 // We may remove a whole set of claim outpoints here, as these one may have
852 // been aggregated in a single tx and claimed so atomically
853 if let Some(request) = self.pending_claim_requests.remove(&package_id) {
854 for outpoint in request.outpoints() {
855 log_debug!(logger, "Removing claim tracking for {} due to maturation of claim package {}.",
856 outpoint, log_bytes!(package_id));
857 self.claimable_outpoints.remove(outpoint);
860 #[cfg(debug_assertions)] {
861 let num_existing = self.pending_claim_events.iter()
862 .filter(|entry| entry.0 == package_id).count();
863 assert!(num_existing == 0 || num_existing == 1);
865 self.pending_claim_events.retain(|(id, _)| *id != package_id);
869 OnchainEvent::ContentiousOutpoint { package } => {
870 log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
871 log_debug!(logger, " {:?}", package.outpoints());
872 self.claimable_outpoints.remove(package.outpoints()[0]);
876 self.onchain_events_awaiting_threshold_conf.push(entry);
880 // Check if any pending claim request must be rescheduled
881 for (package_id, request) in self.pending_claim_requests.iter() {
882 if let Some(h) = request.timer() {
884 bump_candidates.insert(*package_id, request.clone());
889 // Build, bump and rebroadcast tx accordingly
890 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
891 for (package_id, request) in bump_candidates.iter() {
892 if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(cur_height, &request, &*fee_estimator, &*logger) {
894 OnchainClaim::Tx(bump_tx) => {
895 log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
896 broadcaster.broadcast_transaction(&bump_tx);
899 OnchainClaim::Event(claim_event) => {
900 log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
901 #[cfg(debug_assertions)] {
902 let num_existing = self.pending_claim_events.iter().
903 filter(|entry| entry.0 == *package_id).count();
904 assert!(num_existing == 0 || num_existing == 1);
906 self.pending_claim_events.retain(|event| event.0 != *package_id);
907 self.pending_claim_events.push((*package_id, claim_event));
910 if let Some(request) = self.pending_claim_requests.get_mut(package_id) {
911 request.set_timer(new_timer);
912 request.set_feerate(new_feerate);
918 pub(crate) fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
922 fee_estimator: &LowerBoundedFeeEstimator<F>,
925 B::Target: BroadcasterInterface,
926 F::Target: FeeEstimator,
929 let mut height = None;
930 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
931 if entry.txid == *txid {
932 height = Some(entry.height);
937 if let Some(height) = height {
938 self.block_disconnected(height, broadcaster, fee_estimator, logger);
942 pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L)
943 where B::Target: BroadcasterInterface,
944 F::Target: FeeEstimator,
947 let mut bump_candidates = HashMap::new();
948 let onchain_events_awaiting_threshold_conf =
949 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
950 for entry in onchain_events_awaiting_threshold_conf {
951 if entry.height >= height {
952 //- our claim tx on a commitment tx output
953 //- resurect outpoint back in its claimable set and regenerate tx
955 OnchainEvent::ContentiousOutpoint { package } => {
956 if let Some(pending_claim) = self.claimable_outpoints.get(package.outpoints()[0]) {
957 if let Some(request) = self.pending_claim_requests.get_mut(&pending_claim.0) {
958 request.merge_package(package);
959 // Using a HashMap guarantee us than if we have multiple outpoints getting
960 // resurrected only one bump claim tx is going to be broadcast
961 bump_candidates.insert(pending_claim.clone(), request.clone());
968 self.onchain_events_awaiting_threshold_conf.push(entry);
971 for ((_package_id, _), ref mut request) in bump_candidates.iter_mut() {
972 if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
973 request.set_timer(new_timer);
974 request.set_feerate(new_feerate);
976 OnchainClaim::Tx(bump_tx) => {
977 log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
978 broadcaster.broadcast_transaction(&bump_tx);
981 OnchainClaim::Event(claim_event) => {
982 log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
983 #[cfg(debug_assertions)] {
984 let num_existing = self.pending_claim_events.iter()
985 .filter(|entry| entry.0 == *_package_id).count();
986 assert!(num_existing == 0 || num_existing == 1);
988 self.pending_claim_events.retain(|event| event.0 != *_package_id);
989 self.pending_claim_events.push((*_package_id, claim_event));
994 for (ancestor_claim_txid, request) in bump_candidates.drain() {
995 self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
997 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
998 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
999 let mut remove_request = Vec::new();
1000 self.claimable_outpoints.retain(|_, ref v|
1002 remove_request.push(v.0.clone());
1005 for req in remove_request {
1006 self.pending_claim_requests.remove(&req);
1010 pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
1011 self.claimable_outpoints.get(outpoint).is_some()
1014 pub(crate) fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
1015 let mut txids: Vec<(Txid, Option<BlockHash>)> = self.onchain_events_awaiting_threshold_conf
1017 .map(|entry| (entry.txid, entry.block_hash))
1019 txids.sort_unstable_by_key(|(txid, _)| *txid);
1024 pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
1025 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
1026 self.holder_htlc_sigs = None;
1029 // Normally holder HTLCs are signed at the same time as the holder commitment tx. However,
1030 // in some configurations, the holder commitment tx has been signed and broadcast by a
1031 // ChannelMonitor replica, so we handle that case here.
1032 fn sign_latest_holder_htlcs(&mut self) {
1033 if self.holder_htlc_sigs.is_none() {
1034 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
1035 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
1039 // Normally only the latest commitment tx and HTLCs need to be signed. However, in some
1040 // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
1041 // broadcast the previous one before we sync with it. We handle that case here.
1042 fn sign_prev_holder_htlcs(&mut self) {
1043 if self.prev_holder_htlc_sigs.is_none() {
1044 if let Some(ref holder_commitment) = self.prev_holder_commitment {
1045 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
1046 self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
1051 fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
1052 let mut ret = Vec::new();
1053 for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
1054 let tx_idx = htlc.transaction_output_index.unwrap();
1055 if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
1056 ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
1061 //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
1062 // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
1063 // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
1064 // to monitor before.
1065 pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
1066 let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
1067 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
1068 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
1071 #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
1072 pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
1073 let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
1074 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
1075 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
1078 pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
1079 let mut htlc_tx = None;
1080 let commitment_txid = self.holder_commitment.trust().txid();
1081 // Check if the HTLC spends from the current holder commitment
1082 if commitment_txid == outp.txid {
1083 self.sign_latest_holder_htlcs();
1084 if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
1085 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
1086 let trusted_tx = self.holder_commitment.trust();
1087 let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
1088 htlc_tx = Some(trusted_tx
1089 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
1092 // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
1093 if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
1094 let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
1095 if commitment_txid == outp.txid {
1096 self.sign_prev_holder_htlcs();
1097 if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
1098 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
1099 let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
1100 let trusted_tx = holder_commitment.trust();
1101 let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
1102 htlc_tx = Some(trusted_tx
1103 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
1111 pub(crate) fn generate_external_htlc_claim(
1112 &self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>
1113 ) -> Option<ExternalHTLCClaim> {
1114 let find_htlc = |holder_commitment: &HolderCommitmentTransaction| -> Option<ExternalHTLCClaim> {
1115 let trusted_tx = holder_commitment.trust();
1116 if outp.txid != trusted_tx.txid() {
1119 trusted_tx.htlcs().iter().enumerate()
1120 .find(|(_, htlc)| if let Some(output_index) = htlc.transaction_output_index {
1121 output_index == outp.vout
1125 .map(|(htlc_idx, htlc)| {
1126 let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
1128 commitment_txid: trusted_tx.txid(),
1129 per_commitment_number: trusted_tx.commitment_number(),
1131 preimage: *preimage,
1132 counterparty_sig: counterparty_htlc_sig,
1136 // Check if the HTLC spends from the current holder commitment or the previous one otherwise.
1137 find_htlc(&self.holder_commitment)
1138 .or_else(|| self.prev_holder_commitment.as_ref().map(|c| find_htlc(c)).flatten())
1141 pub(crate) fn opt_anchors(&self) -> bool {
1142 self.channel_transaction_parameters.opt_anchors.is_some()
1145 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1146 pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
1147 let latest_had_sigs = self.holder_htlc_sigs.is_some();
1148 let prev_had_sigs = self.prev_holder_htlc_sigs.is_some();
1149 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
1150 if !latest_had_sigs {
1151 self.holder_htlc_sigs = None;
1154 self.prev_holder_htlc_sigs = None;