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