8dcfea347040abf5a065217378ea2fcfbabc48c7
[rust-lightning] / lightning / src / chain / onchaintx.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! The logic to build claims and bump in-flight transactions until confirmations.
11 //!
12 //! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
13 //! building, tracking, bumping and notifications functions.
14
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
18
19 use bitcoin::hash_types::{Txid, BlockHash};
20
21 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
22 use bitcoin::secp256k1;
23
24 use crate::chain::keysinterface::BaseSign;
25 use crate::ln::msgs::DecodeError;
26 use crate::ln::PaymentPreimage;
27 #[cfg(anchors)]
28 use crate::ln::chan_utils;
29 use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
30 #[cfg(anchors)]
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::{Sign, KeysInterface};
35 #[cfg(anchors)]
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, Writer, Writeable, VecWriter};
40
41 use crate::io;
42 use crate::prelude::*;
43 use alloc::collections::BTreeMap;
44 use core::cmp;
45 use core::ops::Deref;
46 use core::mem::replace;
47 #[cfg(anchors)]
48 use core::mem::swap;
49 use bitcoin::hashes::Hash;
50
51 const MAX_ALLOC_SIZE: usize = 64*1024;
52
53 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
54 /// transaction causing it.
55 ///
56 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
57 #[derive(PartialEq, Eq)]
58 struct OnchainEventEntry {
59         txid: Txid,
60         height: u32,
61         block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
62         event: OnchainEvent,
63 }
64
65 impl OnchainEventEntry {
66         fn confirmation_threshold(&self) -> u32 {
67                 self.height + ANTI_REORG_DELAY - 1
68         }
69
70         fn has_reached_confirmation_threshold(&self, height: u32) -> bool {
71                 height >= self.confirmation_threshold()
72         }
73 }
74
75 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
76 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
77 #[derive(PartialEq, Eq)]
78 enum OnchainEvent {
79         /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
80         /// bump-txn candidate buffer.
81         Claim {
82                 claim_request: Txid,
83         },
84         /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a counterparty party tx.
85         /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
86         /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
87         ContentiousOutpoint {
88                 package: PackageTemplate,
89         }
90 }
91
92 impl Writeable for OnchainEventEntry {
93         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
94                 write_tlv_fields!(writer, {
95                         (0, self.txid, required),
96                         (1, self.block_hash, option),
97                         (2, self.height, required),
98                         (4, self.event, required),
99                 });
100                 Ok(())
101         }
102 }
103
104 impl MaybeReadable for OnchainEventEntry {
105         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
106                 let mut txid = Txid::all_zeros();
107                 let mut height = 0;
108                 let mut block_hash = None;
109                 let mut event = None;
110                 read_tlv_fields!(reader, {
111                         (0, txid, required),
112                         (1, block_hash, option),
113                         (2, height, required),
114                         (4, event, ignorable),
115                 });
116                 if let Some(ev) = event {
117                         Ok(Some(Self { txid, height, block_hash, event: ev }))
118                 } else {
119                         Ok(None)
120                 }
121         }
122 }
123
124 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
125         (0, Claim) => {
126                 (0, claim_request, required),
127         },
128         (1, ContentiousOutpoint) => {
129                 (0, package, required),
130         },
131 );
132
133 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
134         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
135                 match Readable::read(reader)? {
136                         0u8 => Ok(None),
137                         1u8 => {
138                                 let vlen: u64 = Readable::read(reader)?;
139                                 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<Option<(usize, Signature)>>()));
140                                 for _ in 0..vlen {
141                                         ret.push(match Readable::read(reader)? {
142                                                 0u8 => None,
143                                                 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
144                                                 _ => return Err(DecodeError::InvalidValue)
145                                         });
146                                 }
147                                 Ok(Some(ret))
148                         },
149                         _ => Err(DecodeError::InvalidValue),
150                 }
151         }
152 }
153
154 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
155         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
156                 match self {
157                         &Some(ref vec) => {
158                                 1u8.write(writer)?;
159                                 (vec.len() as u64).write(writer)?;
160                                 for opt in vec.iter() {
161                                         match opt {
162                                                 &Some((ref idx, ref sig)) => {
163                                                         1u8.write(writer)?;
164                                                         (*idx as u64).write(writer)?;
165                                                         sig.write(writer)?;
166                                                 },
167                                                 &None => 0u8.write(writer)?,
168                                         }
169                                 }
170                         },
171                         &None => 0u8.write(writer)?,
172                 }
173                 Ok(())
174         }
175 }
176
177 // Represents the different types of claims for which events are yielded externally to satisfy said
178 // claims.
179 #[cfg(anchors)]
180 pub(crate) enum ClaimEvent {
181         /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
182         /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
183         BumpCommitment {
184                 package_target_feerate_sat_per_1000_weight: u32,
185                 commitment_tx: Transaction,
186                 anchor_output_idx: u32,
187         },
188 }
189
190 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
191 /// control) onchain.
192 pub(crate) enum OnchainClaim {
193         /// A finalized transaction pending confirmation spending the output to claim.
194         Tx(Transaction),
195         #[cfg(anchors)]
196         /// An event yielded externally to signal additional inputs must be added to a transaction
197         /// pending confirmation spending the output to claim.
198         Event(ClaimEvent),
199 }
200
201 /// An internal identifier to track pending package claims within the `OnchainTxHandler`.
202 type PackageID = [u8; 32];
203
204 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
205 /// do RBF bumping if possible.
206 pub struct OnchainTxHandler<ChannelSigner: Sign> {
207         destination_script: Script,
208         holder_commitment: HolderCommitmentTransaction,
209         // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
210         // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
211         // the set of HTLCs in the HolderCommitmentTransaction.
212         holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
213         prev_holder_commitment: Option<HolderCommitmentTransaction>,
214         prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
215
216         pub(super) signer: ChannelSigner,
217         pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
218
219         // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
220         // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
221         // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
222         // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
223         // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
224         // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
225         // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
226         // we need to regenerate new claim request with reduced set of still-claimable outpoints.
227         // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
228         // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
229         // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
230         #[cfg(test)] // Used in functional_test to verify sanitization
231         pub(crate) pending_claim_requests: HashMap<PackageID, PackageTemplate>,
232         #[cfg(not(test))]
233         pending_claim_requests: HashMap<PackageID, PackageTemplate>,
234         #[cfg(anchors)]
235         pending_claim_events: HashMap<PackageID, ClaimEvent>,
236
237         // Used to link outpoints claimed in a connected block to a pending claim request.
238         // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
239         // Value is (pending claim request identifier, confirmation_block), identifier
240         // is txid of the initial claiming transaction and is immutable until outpoint is
241         // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
242         // block with output gets disconnected.
243         #[cfg(test)] // Used in functional_test to verify sanitization
244         pub claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
245         #[cfg(not(test))]
246         claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
247
248         locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
249
250         onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
251
252         pub(super) secp_ctx: Secp256k1<secp256k1::All>,
253 }
254
255 const SERIALIZATION_VERSION: u8 = 1;
256 const MIN_SERIALIZATION_VERSION: u8 = 1;
257
258 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
259         pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
260                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
261
262                 self.destination_script.write(writer)?;
263                 self.holder_commitment.write(writer)?;
264                 self.holder_htlc_sigs.write(writer)?;
265                 self.prev_holder_commitment.write(writer)?;
266                 self.prev_holder_htlc_sigs.write(writer)?;
267
268                 self.channel_transaction_parameters.write(writer)?;
269
270                 let mut key_data = VecWriter(Vec::new());
271                 self.signer.write(&mut key_data)?;
272                 assert!(key_data.0.len() < core::usize::MAX);
273                 assert!(key_data.0.len() < core::u32::MAX as usize);
274                 (key_data.0.len() as u32).write(writer)?;
275                 writer.write_all(&key_data.0[..])?;
276
277                 writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?;
278                 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
279                         ancestor_claim_txid.write(writer)?;
280                         request.write(writer)?;
281                 }
282
283                 writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?;
284                 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
285                         outp.write(writer)?;
286                         claim_and_height.0.write(writer)?;
287                         claim_and_height.1.write(writer)?;
288                 }
289
290                 writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?;
291                 for (ref locktime, ref packages) in self.locktimed_packages.iter() {
292                         locktime.write(writer)?;
293                         writer.write_all(&(packages.len() as u64).to_be_bytes())?;
294                         for ref package in packages.iter() {
295                                 package.write(writer)?;
296                         }
297                 }
298
299                 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
300                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
301                         entry.write(writer)?;
302                 }
303
304                 write_tlv_fields!(writer, {});
305                 Ok(())
306         }
307 }
308
309 impl<'a, K: KeysInterface> ReadableArgs<(&'a K, u64, [u8; 32])> for OnchainTxHandler<K::Signer> {
310         fn read<R: io::Read>(reader: &mut R, args: (&'a K, u64, [u8; 32])) -> Result<Self, DecodeError> {
311                 let keys_manager = args.0;
312                 let channel_value_satoshis = args.1;
313                 let channel_keys_id = args.2;
314
315                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
316
317                 let destination_script = Readable::read(reader)?;
318
319                 let holder_commitment = Readable::read(reader)?;
320                 let holder_htlc_sigs = Readable::read(reader)?;
321                 let prev_holder_commitment = Readable::read(reader)?;
322                 let prev_holder_htlc_sigs = Readable::read(reader)?;
323
324                 let channel_parameters = Readable::read(reader)?;
325
326                 // Read the serialized signer bytes, but don't deserialize them, as we'll obtain our signer
327                 // by re-deriving the private key material.
328                 let keys_len: u32 = Readable::read(reader)?;
329                 let mut bytes_read = 0;
330                 while bytes_read != keys_len as usize {
331                         // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
332                         let mut data = [0; 1024];
333                         let bytes_to_read = cmp::min(1024, keys_len as usize - bytes_read);
334                         let read_slice = &mut data[0..bytes_to_read];
335                         reader.read_exact(read_slice)?;
336                         bytes_read += bytes_to_read;
337                 }
338
339                 let mut signer = keys_manager.derive_channel_signer(channel_value_satoshis, channel_keys_id);
340                 signer.provide_channel_parameters(&channel_parameters);
341
342                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
343                 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
344                 for _ in 0..pending_claim_requests_len {
345                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
346                 }
347
348                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
349                 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
350                 for _ in 0..claimable_outpoints_len {
351                         let outpoint = Readable::read(reader)?;
352                         let ancestor_claim_txid = Readable::read(reader)?;
353                         let height = Readable::read(reader)?;
354                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
355                 }
356
357                 let locktimed_packages_len: u64 = Readable::read(reader)?;
358                 let mut locktimed_packages = BTreeMap::new();
359                 for _ in 0..locktimed_packages_len {
360                         let locktime = Readable::read(reader)?;
361                         let packages_len: u64 = Readable::read(reader)?;
362                         let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
363                         for _ in 0..packages_len {
364                                 packages.push(Readable::read(reader)?);
365                         }
366                         locktimed_packages.insert(locktime, packages);
367                 }
368
369                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
370                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
371                 for _ in 0..waiting_threshold_conf_len {
372                         if let Some(val) = MaybeReadable::read(reader)? {
373                                 onchain_events_awaiting_threshold_conf.push(val);
374                         }
375                 }
376
377                 read_tlv_fields!(reader, {});
378
379                 let mut secp_ctx = Secp256k1::new();
380                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
381
382                 Ok(OnchainTxHandler {
383                         destination_script,
384                         holder_commitment,
385                         holder_htlc_sigs,
386                         prev_holder_commitment,
387                         prev_holder_htlc_sigs,
388                         signer,
389                         channel_transaction_parameters: channel_parameters,
390                         claimable_outpoints,
391                         locktimed_packages,
392                         pending_claim_requests,
393                         onchain_events_awaiting_threshold_conf,
394                         #[cfg(anchors)]
395                         pending_claim_events: HashMap::new(),
396                         secp_ctx,
397                 })
398         }
399 }
400
401 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
402         pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
403                 OnchainTxHandler {
404                         destination_script,
405                         holder_commitment,
406                         holder_htlc_sigs: None,
407                         prev_holder_commitment: None,
408                         prev_holder_htlc_sigs: None,
409                         signer,
410                         channel_transaction_parameters: channel_parameters,
411                         pending_claim_requests: HashMap::new(),
412                         claimable_outpoints: HashMap::new(),
413                         locktimed_packages: BTreeMap::new(),
414                         onchain_events_awaiting_threshold_conf: Vec::new(),
415                         #[cfg(anchors)]
416                         pending_claim_events: HashMap::new(),
417
418                         secp_ctx,
419                 }
420         }
421
422         pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
423                 self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
424         }
425
426         pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
427                 self.holder_commitment.to_broadcaster_value_sat()
428         }
429
430         #[cfg(anchors)]
431         pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<ClaimEvent> {
432                 let mut ret = HashMap::new();
433                 swap(&mut ret, &mut self.pending_claim_events);
434                 ret.into_iter().map(|(_, event)| event).collect::<Vec<_>>()
435         }
436
437         /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
438         /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
439         /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
440         /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
441         /// Child-Pay-For-Parent.
442         ///
443         /// Panics if there are signing errors, because signing operations in reaction to on-chain
444         /// events are not expected to fail, and if they do, we may lose funds.
445         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)>
446                 where F::Target: FeeEstimator,
447                                         L::Target: Logger,
448         {
449                 let request_outpoints = cached_request.outpoints();
450                 if request_outpoints.is_empty() {
451                         // Don't prune pending claiming request yet, we may have to resurrect HTLCs. Untractable
452                         // packages cannot be aggregated and will never be split, so we cannot end up with an
453                         // empty claim.
454                         debug_assert!(cached_request.is_malleable());
455                         return None;
456                 }
457                 // If we've seen transaction inclusion in the chain for all outpoints in our request, we
458                 // don't need to continue generating more claims. We'll keep tracking the request to fully
459                 // remove it once it reaches the confirmation threshold, or to generate a new claim if the
460                 // transaction is reorged out.
461                 let mut all_inputs_have_confirmed_spend = true;
462                 for outpoint in &request_outpoints {
463                         if let Some(first_claim_txid_height) = self.claimable_outpoints.get(outpoint) {
464                                 // We check for outpoint spends within claims individually rather than as a set
465                                 // since requests can have outpoints split off.
466                                 if !self.onchain_events_awaiting_threshold_conf.iter()
467                                         .any(|event_entry| if let OnchainEvent::Claim { claim_request } = event_entry.event {
468                                                 first_claim_txid_height.0 == claim_request.into_inner()
469                                         } else {
470                                                 // The onchain event is not a claim, keep seeking until we find one.
471                                                 false
472                                         })
473                                 {
474                                         // Either we had no `OnchainEvent::Claim`, or we did but none matched the
475                                         // outpoint's registered spend.
476                                         all_inputs_have_confirmed_spend = false;
477                                 }
478                         } else {
479                                 // The request's outpoint spend does not exist yet.
480                                 all_inputs_have_confirmed_spend = false;
481                         }
482                 }
483                 if all_inputs_have_confirmed_spend {
484                         return None;
485                 }
486
487                 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
488                 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
489                 let new_timer = Some(cached_request.get_height_timer(cur_height));
490                 if cached_request.is_malleable() {
491                         let predicted_weight = cached_request.package_weight(&self.destination_script);
492                         if let Some((output_value, new_feerate)) =
493                                         cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger) {
494                                 assert!(new_feerate != 0);
495
496                                 let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
497                                 log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
498                                 assert!(predicted_weight >= transaction.weight());
499                                 return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
500                         }
501                 } else {
502                         // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
503                         // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
504                         // which require external funding.
505                         #[cfg(not(anchors))]
506                         let inputs = cached_request.inputs();
507                         #[cfg(anchors)]
508                         let mut inputs = cached_request.inputs();
509                         debug_assert_eq!(inputs.len(), 1);
510                         let tx = match cached_request.finalize_untractable_package(self, logger) {
511                                 Some(tx) => tx,
512                                 None => return None,
513                         };
514                         if !cached_request.requires_external_funding() {
515                                 return Some((None, 0, OnchainClaim::Tx(tx)));
516                         }
517                         #[cfg(anchors)]
518                         return inputs.find_map(|input| match input {
519                                 // Commitment inputs with anchors support are the only untractable inputs supported
520                                 // thus far that require external funding.
521                                 PackageSolvingData::HolderFundingOutput(..) => {
522                                         debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
523                                                 "Holder commitment transaction mismatch");
524                                         // We'll locate an anchor output we can spend within the commitment transaction.
525                                         let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
526                                         match chan_utils::get_anchor_output(&tx, funding_pubkey) {
527                                                 // An anchor output was found, so we should yield a funding event externally.
528                                                 Some((idx, _)) => {
529                                                         // TODO: Use a lower confirmation target when both our and the
530                                                         // counterparty's latest commitment don't have any HTLCs present.
531                                                         let conf_target = ConfirmationTarget::HighPriority;
532                                                         let package_target_feerate_sat_per_1000_weight = cached_request
533                                                                 .compute_package_feerate(fee_estimator, conf_target);
534                                                         Some((
535                                                                 new_timer,
536                                                                 package_target_feerate_sat_per_1000_weight as u64,
537                                                                 OnchainClaim::Event(ClaimEvent::BumpCommitment {
538                                                                         package_target_feerate_sat_per_1000_weight,
539                                                                         commitment_tx: tx.clone(),
540                                                                         anchor_output_idx: idx,
541                                                                 }),
542                                                         ))
543                                                 },
544                                                 // An anchor output was not found. There's nothing we can do other than
545                                                 // attempt to broadcast the transaction with its current fee rate and hope
546                                                 // it confirms. This is essentially the same behavior as a commitment
547                                                 // transaction without anchor outputs.
548                                                 None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
549                                         }
550                                 },
551                                 _ => {
552                                         debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
553                                         None
554                                 },
555                         });
556                 }
557                 None
558         }
559
560         /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
561         /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
562         /// Together with `update_claims_view_from_matched_txn` this used to be named
563         /// `block_connected`, but it is now also used for claiming an HTLC output if we receive a
564         /// preimage after force-close.
565         ///
566         /// `conf_height` represents the height at which the request was generated. This
567         /// does not need to equal the current blockchain tip height, which should be provided via
568         /// `cur_height`, however it must never be higher than `cur_height`.
569         pub(crate) fn update_claims_view_from_requests<B: Deref, F: Deref, L: Deref>(
570                 &mut self, requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32,
571                 broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
572         ) where
573                 B::Target: BroadcasterInterface,
574                 F::Target: FeeEstimator,
575                 L::Target: Logger,
576         {
577                 log_debug!(logger, "Updating claims view at height {} with {} claim requests", cur_height, requests.len());
578                 let mut preprocessed_requests = Vec::with_capacity(requests.len());
579                 let mut aggregated_request = None;
580
581                 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
582                 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
583                 for req in requests {
584                         // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
585                         if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
586                                 log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
587                         } else {
588                                 let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
589                                         .find(|locked_package| locked_package.outpoints() == req.outpoints());
590                                 if let Some(package) = timelocked_equivalent_package {
591                                         log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
592                                                 req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
593                                         continue;
594                                 }
595
596                                 if req.package_timelock() > cur_height + 1 {
597                                         log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
598                                         for outpoint in req.outpoints() {
599                                                 log_info!(logger, "  Outpoint {}", outpoint);
600                                         }
601                                         self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
602                                         continue;
603                                 }
604
605                                 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
606                                 if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
607                                         // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
608                                         preprocessed_requests.push(req);
609                                 } else if aggregated_request.is_none() {
610                                         aggregated_request = Some(req);
611                                 } else {
612                                         aggregated_request.as_mut().unwrap().merge_package(req);
613                                 }
614                         }
615                 }
616                 if let Some(req) = aggregated_request {
617                         preprocessed_requests.push(req);
618                 }
619
620                 // Claim everything up to and including cur_height + 1
621                 let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2));
622                 for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
623                         log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
624                         preprocessed_requests.append(&mut entry);
625                 }
626                 self.locktimed_packages = remaining_locked_packages;
627
628                 // Generate claim transactions and track them to bump if necessary at
629                 // height timer expiration (i.e in how many blocks we're going to take action).
630                 for mut req in preprocessed_requests {
631                         if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
632                                 req.set_timer(new_timer);
633                                 req.set_feerate(new_feerate);
634                                 let package_id = match claim {
635                                         OnchainClaim::Tx(tx) => {
636                                                 log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
637                                                 broadcaster.broadcast_transaction(&tx);
638                                                 tx.txid().into_inner()
639                                         },
640                                         #[cfg(anchors)]
641                                         OnchainClaim::Event(claim_event) => {
642                                                 log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
643                                                 let txid = match claim_event {
644                                                         ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
645                                                 };
646                                                 let package_id = txid.into_inner();
647                                                 self.pending_claim_events.insert(package_id, claim_event);
648                                                 package_id
649                                         },
650                                 };
651                                 for k in req.outpoints() {
652                                         log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
653                                         self.claimable_outpoints.insert(k.clone(), (package_id, conf_height));
654                                 }
655                                 self.pending_claim_requests.insert(package_id, req);
656                         }
657                 }
658         }
659
660         /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
661         /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
662         /// Together with `update_claims_view_from_requests` this used to be named `block_connected`,
663         /// but it is now also used for claiming an HTLC output if we receive a preimage after force-close.
664         ///
665         /// `conf_height` represents the height at which the transactions in `txn_matched` were
666         /// confirmed. This does not need to equal the current blockchain tip height, which should be
667         /// provided via `cur_height`, however it must never be higher than `cur_height`.
668         pub(crate) fn update_claims_view_from_matched_txn<B: Deref, F: Deref, L: Deref>(
669                 &mut self, txn_matched: &[&Transaction], conf_height: u32, conf_hash: BlockHash,
670                 cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
671         ) where
672                 B::Target: BroadcasterInterface,
673                 F::Target: FeeEstimator,
674                 L::Target: Logger,
675         {
676                 log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {}", cur_height, txn_matched.len(), conf_height);
677                 let mut bump_candidates = HashMap::new();
678                 for tx in txn_matched {
679                         // Scan all input to verify is one of the outpoint spent is of interest for us
680                         let mut claimed_outputs_material = Vec::new();
681                         for inp in &tx.input {
682                                 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
683                                         // If outpoint has claim request pending on it...
684                                         if let Some(request) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
685                                                 //... we need to verify equality between transaction outpoints and claim request
686                                                 // outpoints to know if transaction is the original claim or a bumped one issued
687                                                 // by us.
688                                                 let mut set_equality = true;
689                                                 if request.outpoints().len() != tx.input.len() {
690                                                         set_equality = false;
691                                                 } else {
692                                                         for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
693                                                                 if **claim_inp != tx_inp.previous_output {
694                                                                         set_equality = false;
695                                                                 }
696                                                         }
697                                                 }
698
699                                                 macro_rules! clean_claim_request_after_safety_delay {
700                                                         () => {
701                                                                 let entry = OnchainEventEntry {
702                                                                         txid: tx.txid(),
703                                                                         height: conf_height,
704                                                                         block_hash: Some(conf_hash),
705                                                                         event: OnchainEvent::Claim { claim_request: Txid::from_inner(first_claim_txid_height.0) }
706                                                                 };
707                                                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
708                                                                         self.onchain_events_awaiting_threshold_conf.push(entry);
709                                                                 }
710                                                         }
711                                                 }
712
713                                                 // If this is our transaction (or our counterparty spent all the outputs
714                                                 // before we could anyway with same inputs order than us), wait for
715                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
716                                                 if set_equality {
717                                                         clean_claim_request_after_safety_delay!();
718                                                 } else { // If false, generate new claim request with update outpoint set
719                                                         let mut at_least_one_drop = false;
720                                                         for input in tx.input.iter() {
721                                                                 if let Some(package) = request.split_package(&input.previous_output) {
722                                                                         claimed_outputs_material.push(package);
723                                                                         at_least_one_drop = true;
724                                                                 }
725                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
726                                                                 if request.outpoints().is_empty() {
727                                                                         clean_claim_request_after_safety_delay!();
728                                                                 }
729                                                         }
730                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
731                                                         if at_least_one_drop {
732                                                                 bump_candidates.insert(first_claim_txid_height.0.clone(), request.clone());
733                                                         }
734                                                 }
735                                                 break; //No need to iterate further, either tx is our or their
736                                         } else {
737                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
738                                         }
739                                 }
740                         }
741                         for package in claimed_outputs_material.drain(..) {
742                                 let entry = OnchainEventEntry {
743                                         txid: tx.txid(),
744                                         height: conf_height,
745                                         block_hash: Some(conf_hash),
746                                         event: OnchainEvent::ContentiousOutpoint { package },
747                                 };
748                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
749                                         self.onchain_events_awaiting_threshold_conf.push(entry);
750                                 }
751                         }
752                 }
753
754                 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
755                 let onchain_events_awaiting_threshold_conf =
756                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
757                 for entry in onchain_events_awaiting_threshold_conf {
758                         if entry.has_reached_confirmation_threshold(cur_height) {
759                                 match entry.event {
760                                         OnchainEvent::Claim { claim_request } => {
761                                                 let package_id = claim_request.into_inner();
762                                                 // We may remove a whole set of claim outpoints here, as these one may have
763                                                 // been aggregated in a single tx and claimed so atomically
764                                                 if let Some(request) = self.pending_claim_requests.remove(&package_id) {
765                                                         for outpoint in request.outpoints() {
766                                                                 log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
767                                                                 self.claimable_outpoints.remove(&outpoint);
768                                                                 #[cfg(anchors)]
769                                                                 self.pending_claim_events.remove(&package_id);
770                                                         }
771                                                 }
772                                         },
773                                         OnchainEvent::ContentiousOutpoint { package } => {
774                                                 log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
775                                                 log_debug!(logger, " {:?}", package.outpoints());
776                                                 self.claimable_outpoints.remove(&package.outpoints()[0]);
777                                         }
778                                 }
779                         } else {
780                                 self.onchain_events_awaiting_threshold_conf.push(entry);
781                         }
782                 }
783
784                 // Check if any pending claim request must be rescheduled
785                 for (first_claim_txid, ref request) in self.pending_claim_requests.iter() {
786                         if let Some(h) = request.timer() {
787                                 if cur_height >= h {
788                                         bump_candidates.insert(*first_claim_txid, (*request).clone());
789                                 }
790                         }
791                 }
792
793                 // Build, bump and rebroadcast tx accordingly
794                 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
795                 for (first_claim_txid, request) in bump_candidates.iter() {
796                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(cur_height, &request, &*fee_estimator, &*logger) {
797                                 match bump_claim {
798                                         OnchainClaim::Tx(bump_tx) => {
799                                                 log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
800                                                 broadcaster.broadcast_transaction(&bump_tx);
801                                         },
802                                         #[cfg(anchors)]
803                                         OnchainClaim::Event(claim_event) => {
804                                                 log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
805                                                 self.pending_claim_events.insert(*first_claim_txid, claim_event);
806                                         },
807                                 }
808                                 if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
809                                         request.set_timer(new_timer);
810                                         request.set_feerate(new_feerate);
811                                 }
812                         }
813                 }
814         }
815
816         pub(crate) fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
817                 &mut self,
818                 txid: &Txid,
819                 broadcaster: B,
820                 fee_estimator: &LowerBoundedFeeEstimator<F>,
821                 logger: L,
822         ) where
823                 B::Target: BroadcasterInterface,
824                 F::Target: FeeEstimator,
825                 L::Target: Logger,
826         {
827                 let mut height = None;
828                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
829                         if entry.txid == *txid {
830                                 height = Some(entry.height);
831                                 break;
832                         }
833                 }
834
835                 if let Some(height) = height {
836                         self.block_disconnected(height, broadcaster, fee_estimator, logger);
837                 }
838         }
839
840         pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L)
841                 where B::Target: BroadcasterInterface,
842                       F::Target: FeeEstimator,
843                                         L::Target: Logger,
844         {
845                 let mut bump_candidates = HashMap::new();
846                 let onchain_events_awaiting_threshold_conf =
847                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
848                 for entry in onchain_events_awaiting_threshold_conf {
849                         if entry.height >= height {
850                                 //- our claim tx on a commitment tx output
851                                 //- resurect outpoint back in its claimable set and regenerate tx
852                                 match entry.event {
853                                         OnchainEvent::ContentiousOutpoint { package } => {
854                                                 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&package.outpoints()[0]) {
855                                                         if let Some(request) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
856                                                                 request.merge_package(package);
857                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
858                                                                 // resurrected only one bump claim tx is going to be broadcast
859                                                                 bump_candidates.insert(ancestor_claimable_txid.clone(), request.clone());
860                                                         }
861                                                 }
862                                         },
863                                         _ => {},
864                                 }
865                         } else {
866                                 self.onchain_events_awaiting_threshold_conf.push(entry);
867                         }
868                 }
869                 for (_first_claim_txid_height, request) in bump_candidates.iter_mut() {
870                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
871                                 request.set_timer(new_timer);
872                                 request.set_feerate(new_feerate);
873                                 match bump_claim {
874                                         OnchainClaim::Tx(bump_tx) => {
875                                                 log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
876                                                 broadcaster.broadcast_transaction(&bump_tx);
877                                         },
878                                         #[cfg(anchors)]
879                                         OnchainClaim::Event(claim_event) => {
880                                                 log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
881                                                 self.pending_claim_events.insert(_first_claim_txid_height.0, claim_event);
882                                         },
883                                 }
884                         }
885                 }
886                 for (ancestor_claim_txid, request) in bump_candidates.drain() {
887                         self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
888                 }
889                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
890                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
891                 let mut remove_request = Vec::new();
892                 self.claimable_outpoints.retain(|_, ref v|
893                         if v.1 >= height {
894                         remove_request.push(v.0.clone());
895                         false
896                         } else { true });
897                 for req in remove_request {
898                         self.pending_claim_requests.remove(&req);
899                 }
900         }
901
902         pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
903                 self.claimable_outpoints.get(outpoint).is_some()
904         }
905
906         pub(crate) fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
907                 let mut txids: Vec<(Txid, Option<BlockHash>)> = self.onchain_events_awaiting_threshold_conf
908                         .iter()
909                         .map(|entry| (entry.txid, entry.block_hash))
910                         .collect();
911                 txids.sort_unstable_by_key(|(txid, _)| *txid);
912                 txids.dedup();
913                 txids
914         }
915
916         pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
917                 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
918                 self.holder_htlc_sigs = None;
919         }
920
921         // Normally holder HTLCs are signed at the same time as the holder commitment tx.  However,
922         // in some configurations, the holder commitment tx has been signed and broadcast by a
923         // ChannelMonitor replica, so we handle that case here.
924         fn sign_latest_holder_htlcs(&mut self) {
925                 if self.holder_htlc_sigs.is_none() {
926                         let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
927                         self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
928                 }
929         }
930
931         // Normally only the latest commitment tx and HTLCs need to be signed.  However, in some
932         // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
933         // broadcast the previous one before we sync with it.  We handle that case here.
934         fn sign_prev_holder_htlcs(&mut self) {
935                 if self.prev_holder_htlc_sigs.is_none() {
936                         if let Some(ref holder_commitment) = self.prev_holder_commitment {
937                                 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
938                                 self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
939                         }
940                 }
941         }
942
943         fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
944                 let mut ret = Vec::new();
945                 for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
946                         let tx_idx = htlc.transaction_output_index.unwrap();
947                         if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
948                         ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
949                 }
950                 ret
951         }
952
953         //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
954         // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
955         // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
956         // to monitor before.
957         pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
958                 let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
959                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
960                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
961         }
962
963         #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
964         pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
965                 let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
966                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
967                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
968         }
969
970         pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
971                 let mut htlc_tx = None;
972                 let commitment_txid = self.holder_commitment.trust().txid();
973                 // Check if the HTLC spends from the current holder commitment
974                 if commitment_txid == outp.txid {
975                         self.sign_latest_holder_htlcs();
976                         if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
977                                 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
978                                 let trusted_tx = self.holder_commitment.trust();
979                                 let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
980                                 htlc_tx = Some(trusted_tx
981                                         .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
982                         }
983                 }
984                 // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
985                 if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
986                         let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
987                         if commitment_txid == outp.txid {
988                                 self.sign_prev_holder_htlcs();
989                                 if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
990                                         let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
991                                         let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
992                                         let trusted_tx = holder_commitment.trust();
993                                         let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
994                                         htlc_tx = Some(trusted_tx
995                                                 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
996                                 }
997                         }
998                 }
999                 htlc_tx
1000         }
1001
1002         pub(crate) fn opt_anchors(&self) -> bool {
1003                 self.channel_transaction_parameters.opt_anchors.is_some()
1004         }
1005
1006         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1007         pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
1008                 let latest_had_sigs = self.holder_htlc_sigs.is_some();
1009                 let prev_had_sigs = self.prev_holder_htlc_sigs.is_some();
1010                 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
1011                 if !latest_had_sigs {
1012                         self.holder_htlc_sigs = None;
1013                 }
1014                 if !prev_had_sigs {
1015                         self.prev_holder_htlc_sigs = None;
1016                 }
1017                 ret
1018         }
1019 }