Merge pull request #2966 from G8XSU/2647-distribute
[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::amount::Amount;
16 use bitcoin::blockdata::locktime::absolute::LockTime;
17 use bitcoin::blockdata::transaction::Transaction;
18 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
19 use bitcoin::blockdata::script::{Script, ScriptBuf};
20 use bitcoin::hashes::{Hash, HashEngine};
21 use bitcoin::hashes::sha256::Hash as Sha256;
22 use bitcoin::hash_types::{Txid, BlockHash};
23 use bitcoin::secp256k1::PublicKey;
24 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
25 use bitcoin::secp256k1;
26
27 use crate::chain::chaininterface::compute_feerate_sat_per_1000_weight;
28 use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, ChannelSigner, EntropySource, SignerProvider, ecdsa::EcdsaChannelSigner};
29 use crate::ln::msgs::DecodeError;
30 use crate::ln::types::PaymentPreimage;
31 use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction};
32 use crate::chain::ClaimId;
33 use crate::chain::chaininterface::{ConfirmationTarget, FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
34 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
35 use crate::chain::package::{PackageSolvingData, PackageTemplate};
36 use crate::chain::transaction::MaybeSignedTransaction;
37 use crate::util::logger::Logger;
38 use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, UpgradableRequired, Writer, Writeable};
39
40 use crate::io;
41 use crate::prelude::*;
42 use alloc::collections::BTreeMap;
43 use core::cmp;
44 use core::ops::Deref;
45 use core::mem::replace;
46 use core::mem::swap;
47 use crate::ln::features::ChannelTypeFeatures;
48
49 const MAX_ALLOC_SIZE: usize = 64*1024;
50
51 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
52 /// transaction causing it.
53 ///
54 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
55 #[derive(Clone, PartialEq, Eq)]
56 struct OnchainEventEntry {
57         txid: Txid,
58         height: u32,
59         block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
60         event: OnchainEvent,
61 }
62
63 impl OnchainEventEntry {
64         fn confirmation_threshold(&self) -> u32 {
65                 self.height + ANTI_REORG_DELAY - 1
66         }
67
68         fn has_reached_confirmation_threshold(&self, height: u32) -> bool {
69                 height >= self.confirmation_threshold()
70         }
71 }
72
73 /// Events for claims the [`OnchainTxHandler`] has generated. Once the events are considered safe
74 /// from a chain reorg, the [`OnchainTxHandler`] will act accordingly.
75 #[derive(Clone, PartialEq, Eq)]
76 enum OnchainEvent {
77         /// A pending request has been claimed by a transaction spending the exact same set of outpoints
78         /// as the request. This claim can either be ours or from the counterparty. Once the claiming
79         /// transaction has met [`ANTI_REORG_DELAY`] confirmations, we consider it final and remove the
80         /// pending request.
81         Claim {
82                 claim_id: ClaimId,
83         },
84         /// The counterparty has claimed an outpoint from one of our pending requests through a
85         /// different transaction than ours. If our transaction was attempting to claim multiple
86         /// outputs, we need to drop the outpoint claimed by the counterparty and regenerate a new claim
87         /// transaction for ourselves. We keep tracking, separately, the outpoint claimed by the
88         /// counterparty up to [`ANTI_REORG_DELAY`] confirmations to ensure we attempt to re-claim it
89         /// if the counterparty's claim is reorged from the chain.
90         ContentiousOutpoint {
91                 package: PackageTemplate,
92         }
93 }
94
95 impl Writeable for OnchainEventEntry {
96         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
97                 write_tlv_fields!(writer, {
98                         (0, self.txid, required),
99                         (1, self.block_hash, option),
100                         (2, self.height, required),
101                         (4, self.event, required),
102                 });
103                 Ok(())
104         }
105 }
106
107 impl MaybeReadable for OnchainEventEntry {
108         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
109                 let mut txid = Txid::all_zeros();
110                 let mut height = 0;
111                 let mut block_hash = None;
112                 let mut event = UpgradableRequired(None);
113                 read_tlv_fields!(reader, {
114                         (0, txid, required),
115                         (1, block_hash, option),
116                         (2, height, required),
117                         (4, event, upgradable_required),
118                 });
119                 Ok(Some(Self { txid, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
120         }
121 }
122
123 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
124         (0, Claim) => {
125                 (0, claim_id, required),
126         },
127         (1, ContentiousOutpoint) => {
128                 (0, package, required),
129         },
130 );
131
132 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
133         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
134                 match Readable::read(reader)? {
135                         0u8 => Ok(None),
136                         1u8 => {
137                                 let vlen: u64 = Readable::read(reader)?;
138                                 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<Option<(usize, Signature)>>()));
139                                 for _ in 0..vlen {
140                                         ret.push(match Readable::read(reader)? {
141                                                 0u8 => None,
142                                                 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
143                                                 _ => return Err(DecodeError::InvalidValue)
144                                         });
145                                 }
146                                 Ok(Some(ret))
147                         },
148                         _ => Err(DecodeError::InvalidValue),
149                 }
150         }
151 }
152
153 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
154         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
155                 match self {
156                         &Some(ref vec) => {
157                                 1u8.write(writer)?;
158                                 (vec.len() as u64).write(writer)?;
159                                 for opt in vec.iter() {
160                                         match opt {
161                                                 &Some((ref idx, ref sig)) => {
162                                                         1u8.write(writer)?;
163                                                         (*idx as u64).write(writer)?;
164                                                         sig.write(writer)?;
165                                                 },
166                                                 &None => 0u8.write(writer)?,
167                                         }
168                                 }
169                         },
170                         &None => 0u8.write(writer)?,
171                 }
172                 Ok(())
173         }
174 }
175
176 /// The claim commonly referred to as the pre-signed second-stage HTLC transaction.
177 #[derive(Clone, PartialEq, Eq)]
178 pub(crate) struct ExternalHTLCClaim {
179         pub(crate) commitment_txid: Txid,
180         pub(crate) per_commitment_number: u64,
181         pub(crate) htlc: HTLCOutputInCommitment,
182         pub(crate) preimage: Option<PaymentPreimage>,
183         pub(crate) counterparty_sig: Signature,
184         pub(crate) per_commitment_point: PublicKey,
185 }
186
187 // Represents the different types of claims for which events are yielded externally to satisfy said
188 // claims.
189 #[derive(Clone, PartialEq, Eq)]
190 pub(crate) enum ClaimEvent {
191         /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
192         /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
193         BumpCommitment {
194                 package_target_feerate_sat_per_1000_weight: u32,
195                 commitment_tx: Transaction,
196                 anchor_output_idx: u32,
197         },
198         /// Event yielded to signal that the commitment transaction has confirmed and its HTLCs must be
199         /// resolved by broadcasting a transaction with sufficient fee to claim them.
200         BumpHTLC {
201                 target_feerate_sat_per_1000_weight: u32,
202                 htlcs: Vec<ExternalHTLCClaim>,
203                 tx_lock_time: LockTime,
204         },
205 }
206
207 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
208 /// control) onchain.
209 pub(crate) enum OnchainClaim {
210         /// A finalized transaction pending confirmation spending the output to claim.
211         Tx(MaybeSignedTransaction),
212         /// An event yielded externally to signal additional inputs must be added to a transaction
213         /// pending confirmation spending the output to claim.
214         Event(ClaimEvent),
215 }
216
217 /// Represents the different feerate strategies a pending request can use when generating a claim.
218 pub(crate) enum FeerateStrategy {
219         /// We must reuse the most recently used feerate, if any.
220         RetryPrevious,
221         /// We must pick the highest between the most recently used and the current feerate estimate.
222         HighestOfPreviousOrNew,
223         /// We must force a bump of the most recently used feerate, either by using the current feerate
224         /// estimate if it's higher, or manually bumping.
225         ForceBump,
226 }
227
228 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
229 /// do RBF bumping if possible.
230 #[derive(Clone)]
231 pub struct OnchainTxHandler<ChannelSigner: EcdsaChannelSigner> {
232         channel_value_satoshis: u64,
233         channel_keys_id: [u8; 32],
234         destination_script: ScriptBuf,
235         holder_commitment: HolderCommitmentTransaction,
236         prev_holder_commitment: Option<HolderCommitmentTransaction>,
237
238         pub(super) signer: ChannelSigner,
239         pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
240
241         // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
242         // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
243         // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
244         // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
245         // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
246         // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
247         // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
248         // we need to regenerate new claim request with reduced set of still-claimable outpoints.
249         // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
250         // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
251         // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
252         #[cfg(test)] // Used in functional_test to verify sanitization
253         pub(crate) pending_claim_requests: HashMap<ClaimId, PackageTemplate>,
254         #[cfg(not(test))]
255         pending_claim_requests: HashMap<ClaimId, PackageTemplate>,
256
257         // Used to track external events that need to be forwarded to the `ChainMonitor`. This `Vec`
258         // essentially acts as an insertion-ordered `HashMap` â€“ there should only ever be one occurrence
259         // of a `ClaimId`, which tracks its latest `ClaimEvent`, i.e., if a pending claim exists, and
260         // a new block has been connected, resulting in a new claim, the previous will be replaced with
261         // the new.
262         //
263         // These external events may be generated in the following cases:
264         //      - A channel has been force closed by broadcasting the holder's latest commitment transaction
265         //      - A block being connected/disconnected
266         //      - Learning the preimage for an HTLC we can claim onchain
267         pending_claim_events: Vec<(ClaimId, ClaimEvent)>,
268
269         // Used to link outpoints claimed in a connected block to a pending claim request. The keys
270         // represent the outpoints that our `ChannelMonitor` has detected we have keys/scripts to
271         // claim. The values track the pending claim request identifier and the initial confirmation
272         // block height, and are immutable until the outpoint has enough confirmations to meet our
273         // [`ANTI_REORG_DELAY`]. The initial confirmation block height is used to remove the entry if
274         // the block gets disconnected.
275         #[cfg(test)] // Used in functional_test to verify sanitization
276         pub claimable_outpoints: HashMap<BitcoinOutPoint, (ClaimId, u32)>,
277         #[cfg(not(test))]
278         claimable_outpoints: HashMap<BitcoinOutPoint, (ClaimId, u32)>,
279
280         locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
281
282         onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
283
284         pub(super) secp_ctx: Secp256k1<secp256k1::All>,
285 }
286
287 impl<ChannelSigner: EcdsaChannelSigner> PartialEq for OnchainTxHandler<ChannelSigner> {
288         fn eq(&self, other: &Self) -> bool {
289                 // `signer`, `secp_ctx`, and `pending_claim_events` are excluded on purpose.
290                 self.channel_value_satoshis == other.channel_value_satoshis &&
291                         self.channel_keys_id == other.channel_keys_id &&
292                         self.destination_script == other.destination_script &&
293                         self.holder_commitment == other.holder_commitment &&
294                         self.prev_holder_commitment == other.prev_holder_commitment &&
295                         self.channel_transaction_parameters == other.channel_transaction_parameters &&
296                         self.pending_claim_requests == other.pending_claim_requests &&
297                         self.claimable_outpoints == other.claimable_outpoints &&
298                         self.locktimed_packages == other.locktimed_packages &&
299                         self.onchain_events_awaiting_threshold_conf == other.onchain_events_awaiting_threshold_conf
300         }
301 }
302
303 const SERIALIZATION_VERSION: u8 = 1;
304 const MIN_SERIALIZATION_VERSION: u8 = 1;
305
306 impl<ChannelSigner: EcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
307         pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
308                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
309
310                 self.destination_script.write(writer)?;
311                 self.holder_commitment.write(writer)?;
312                 None::<Option<Vec<Option<(usize, Signature)>>>>.write(writer)?; // holder_htlc_sigs
313                 self.prev_holder_commitment.write(writer)?;
314                 None::<Option<Vec<Option<(usize, Signature)>>>>.write(writer)?; // prev_holder_htlc_sigs
315
316                 self.channel_transaction_parameters.write(writer)?;
317
318                 // Write a zero-length signer. The data is no longer deserialized as of version 0.0.113 and
319                 // downgrades before version 0.0.113 are no longer supported as of version 0.0.119.
320                 0u32.write(writer)?;
321
322                 writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?;
323                 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
324                         ancestor_claim_txid.write(writer)?;
325                         request.write(writer)?;
326                 }
327
328                 writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?;
329                 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
330                         outp.write(writer)?;
331                         claim_and_height.0.write(writer)?;
332                         claim_and_height.1.write(writer)?;
333                 }
334
335                 writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?;
336                 for (ref locktime, ref packages) in self.locktimed_packages.iter() {
337                         locktime.write(writer)?;
338                         writer.write_all(&(packages.len() as u64).to_be_bytes())?;
339                         for ref package in packages.iter() {
340                                 package.write(writer)?;
341                         }
342                 }
343
344                 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
345                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
346                         entry.write(writer)?;
347                 }
348
349                 write_tlv_fields!(writer, {});
350                 Ok(())
351         }
352 }
353
354 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP, u64, [u8; 32])> for OnchainTxHandler<SP::EcdsaSigner> {
355         fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP, u64, [u8; 32])) -> Result<Self, DecodeError> {
356                 let entropy_source = args.0;
357                 let signer_provider = args.1;
358                 let channel_value_satoshis = args.2;
359                 let channel_keys_id = args.3;
360
361                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
362
363                 let destination_script = Readable::read(reader)?;
364
365                 let holder_commitment = Readable::read(reader)?;
366                 let _holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>> = Readable::read(reader)?;
367                 let prev_holder_commitment = Readable::read(reader)?;
368                 let _prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>> = Readable::read(reader)?;
369
370                 let channel_parameters = Readable::read(reader)?;
371
372                 // Read the serialized signer bytes, but don't deserialize them, as we'll obtain our signer
373                 // by re-deriving the private key material.
374                 let keys_len: u32 = Readable::read(reader)?;
375                 let mut bytes_read = 0;
376                 while bytes_read != keys_len as usize {
377                         // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
378                         let mut data = [0; 1024];
379                         let bytes_to_read = cmp::min(1024, keys_len as usize - bytes_read);
380                         let read_slice = &mut data[0..bytes_to_read];
381                         reader.read_exact(read_slice)?;
382                         bytes_read += bytes_to_read;
383                 }
384
385                 let mut signer = signer_provider.derive_channel_signer(channel_value_satoshis, channel_keys_id);
386                 signer.provide_channel_parameters(&channel_parameters);
387
388                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
389                 let mut pending_claim_requests = hash_map_with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
390                 for _ in 0..pending_claim_requests_len {
391                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
392                 }
393
394                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
395                 let mut claimable_outpoints = hash_map_with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
396                 for _ in 0..claimable_outpoints_len {
397                         let outpoint = Readable::read(reader)?;
398                         let ancestor_claim_txid = Readable::read(reader)?;
399                         let height = Readable::read(reader)?;
400                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
401                 }
402
403                 let locktimed_packages_len: u64 = Readable::read(reader)?;
404                 let mut locktimed_packages = BTreeMap::new();
405                 for _ in 0..locktimed_packages_len {
406                         let locktime = Readable::read(reader)?;
407                         let packages_len: u64 = Readable::read(reader)?;
408                         let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
409                         for _ in 0..packages_len {
410                                 packages.push(Readable::read(reader)?);
411                         }
412                         locktimed_packages.insert(locktime, packages);
413                 }
414
415                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
416                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
417                 for _ in 0..waiting_threshold_conf_len {
418                         if let Some(val) = MaybeReadable::read(reader)? {
419                                 onchain_events_awaiting_threshold_conf.push(val);
420                         }
421                 }
422
423                 read_tlv_fields!(reader, {});
424
425                 let mut secp_ctx = Secp256k1::new();
426                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
427
428                 Ok(OnchainTxHandler {
429                         channel_value_satoshis,
430                         channel_keys_id,
431                         destination_script,
432                         holder_commitment,
433                         prev_holder_commitment,
434                         signer,
435                         channel_transaction_parameters: channel_parameters,
436                         claimable_outpoints,
437                         locktimed_packages,
438                         pending_claim_requests,
439                         onchain_events_awaiting_threshold_conf,
440                         pending_claim_events: Vec::new(),
441                         secp_ctx,
442                 })
443         }
444 }
445
446 impl<ChannelSigner: EcdsaChannelSigner> OnchainTxHandler<ChannelSigner> {
447         pub(crate) fn new(
448                 channel_value_satoshis: u64, channel_keys_id: [u8; 32], destination_script: ScriptBuf,
449                 signer: ChannelSigner, channel_parameters: ChannelTransactionParameters,
450                 holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>
451         ) -> Self {
452                 OnchainTxHandler {
453                         channel_value_satoshis,
454                         channel_keys_id,
455                         destination_script,
456                         holder_commitment,
457                         prev_holder_commitment: None,
458                         signer,
459                         channel_transaction_parameters: channel_parameters,
460                         pending_claim_requests: new_hash_map(),
461                         claimable_outpoints: new_hash_map(),
462                         locktimed_packages: BTreeMap::new(),
463                         onchain_events_awaiting_threshold_conf: Vec::new(),
464                         pending_claim_events: Vec::new(),
465                         secp_ctx,
466                 }
467         }
468
469         pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
470                 self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
471         }
472
473         pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
474                 self.holder_commitment.to_broadcaster_value_sat()
475         }
476
477         pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<(ClaimId, ClaimEvent)> {
478                 let mut events = Vec::new();
479                 swap(&mut events, &mut self.pending_claim_events);
480                 events
481         }
482
483         /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
484         /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
485         /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
486         /// invoking this every 30 seconds, or lower if running in an environment with spotty
487         /// connections, like on mobile.
488         pub(super) fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Logger>(
489                 &mut self, current_height: u32, feerate_strategy: FeerateStrategy, broadcaster: &B,
490                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
491         )
492         where
493                 B::Target: BroadcasterInterface,
494                 F::Target: FeeEstimator,
495         {
496                 let mut bump_requests = Vec::with_capacity(self.pending_claim_requests.len());
497                 for (claim_id, request) in self.pending_claim_requests.iter() {
498                         let inputs = request.outpoints();
499                         log_info!(logger, "Triggering rebroadcast/fee-bump for request with inputs {:?}", inputs);
500                         bump_requests.push((*claim_id, request.clone()));
501                 }
502                 for (claim_id, request) in bump_requests {
503                         self.generate_claim(current_height, &request, &feerate_strategy, fee_estimator, logger)
504                                 .map(|(_, new_feerate, claim)| {
505                                         let mut bumped_feerate = false;
506                                         if let Some(mut_request) = self.pending_claim_requests.get_mut(&claim_id) {
507                                                 bumped_feerate = request.previous_feerate() > new_feerate;
508                                                 mut_request.set_feerate(new_feerate);
509                                         }
510                                         match claim {
511                                                 OnchainClaim::Tx(tx) => {
512                                                         if tx.is_fully_signed() {
513                                                                 let log_start = if bumped_feerate { "Broadcasting RBF-bumped" } else { "Rebroadcasting" };
514                                                                 log_info!(logger, "{} onchain {}", log_start, log_tx!(tx.0));
515                                                                 broadcaster.broadcast_transactions(&[&tx.0]);
516                                                         } else {
517                                                                 log_info!(logger, "Waiting for signature of unsigned onchain transaction {}", tx.0.txid());
518                                                         }
519                                                 },
520                                                 OnchainClaim::Event(event) => {
521                                                         let log_start = if bumped_feerate { "Yielding fee-bumped" } else { "Replaying" };
522                                                         log_info!(logger, "{} onchain event to spend inputs {:?}", log_start,
523                                                                 request.outpoints());
524                                                         #[cfg(debug_assertions)] {
525                                                                 debug_assert!(request.requires_external_funding());
526                                                                 let num_existing = self.pending_claim_events.iter()
527                                                                         .filter(|entry| entry.0 == claim_id).count();
528                                                                 assert!(num_existing == 0 || num_existing == 1);
529                                                         }
530                                                         self.pending_claim_events.retain(|event| event.0 != claim_id);
531                                                         self.pending_claim_events.push((claim_id, event));
532                                                 }
533                                         }
534                                 });
535                 }
536         }
537
538         /// Returns true if we are currently tracking any pending claim requests that are not fully 
539         /// confirmed yet.
540         pub(super) fn has_pending_claims(&self) -> bool
541         {
542                 self.pending_claim_requests.len() != 0
543         }
544
545         /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
546         /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
547         /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
548         /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
549         /// Child-Pay-For-Parent.
550         ///
551         /// Panics if there are signing errors, because signing operations in reaction to on-chain
552         /// events are not expected to fail, and if they do, we may lose funds.
553         fn generate_claim<F: Deref, L: Logger>(
554                 &mut self, cur_height: u32, cached_request: &PackageTemplate, feerate_strategy: &FeerateStrategy,
555                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
556         ) -> Option<(u32, u64, OnchainClaim)>
557         where F::Target: FeeEstimator,
558         {
559                 let request_outpoints = cached_request.outpoints();
560                 if request_outpoints.is_empty() {
561                         // Don't prune pending claiming request yet, we may have to resurrect HTLCs. Untractable
562                         // packages cannot be aggregated and will never be split, so we cannot end up with an
563                         // empty claim.
564                         debug_assert!(cached_request.is_malleable());
565                         return None;
566                 }
567                 // If we've seen transaction inclusion in the chain for all outpoints in our request, we
568                 // don't need to continue generating more claims. We'll keep tracking the request to fully
569                 // remove it once it reaches the confirmation threshold, or to generate a new claim if the
570                 // transaction is reorged out.
571                 let mut all_inputs_have_confirmed_spend = true;
572                 for outpoint in request_outpoints.iter() {
573                         if let Some((request_claim_id, _)) = self.claimable_outpoints.get(*outpoint) {
574                                 // We check for outpoint spends within claims individually rather than as a set
575                                 // since requests can have outpoints split off.
576                                 if !self.onchain_events_awaiting_threshold_conf.iter()
577                                         .any(|event_entry| if let OnchainEvent::Claim { claim_id } = event_entry.event {
578                                                 *request_claim_id == claim_id
579                                         } else {
580                                                 // The onchain event is not a claim, keep seeking until we find one.
581                                                 false
582                                         })
583                                 {
584                                         // Either we had no `OnchainEvent::Claim`, or we did but none matched the
585                                         // outpoint's registered spend.
586                                         all_inputs_have_confirmed_spend = false;
587                                 }
588                         } else {
589                                 // The request's outpoint spend does not exist yet.
590                                 all_inputs_have_confirmed_spend = false;
591                         }
592                 }
593                 if all_inputs_have_confirmed_spend {
594                         return None;
595                 }
596
597                 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
598                 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
599                 let new_timer = cached_request.get_height_timer(cur_height);
600                 if cached_request.is_malleable() {
601                         if cached_request.requires_external_funding() {
602                                 let target_feerate_sat_per_1000_weight = cached_request.compute_package_feerate(
603                                         fee_estimator, ConfirmationTarget::OnChainSweep, feerate_strategy,
604                                 );
605                                 if let Some(htlcs) = cached_request.construct_malleable_package_with_external_funding(self) {
606                                         return Some((
607                                                 new_timer,
608                                                 target_feerate_sat_per_1000_weight as u64,
609                                                 OnchainClaim::Event(ClaimEvent::BumpHTLC {
610                                                         target_feerate_sat_per_1000_weight,
611                                                         htlcs,
612                                                         tx_lock_time: LockTime::from_consensus(cached_request.package_locktime(cur_height)),
613                                                 }),
614                                         ));
615                                 } else {
616                                         return None;
617                                 }
618                         }
619
620                         let predicted_weight = cached_request.package_weight(&self.destination_script);
621                         if let Some((output_value, new_feerate)) = cached_request.compute_package_output(
622                                 predicted_weight, self.destination_script.dust_value().to_sat(),
623                                 feerate_strategy, fee_estimator, logger,
624                         ) {
625                                 assert!(new_feerate != 0);
626
627                                 let transaction = cached_request.maybe_finalize_malleable_package(
628                                         cur_height, self, Amount::from_sat(output_value), self.destination_script.clone(), logger
629                                 ).unwrap();
630                                 assert!(predicted_weight >= transaction.0.weight().to_wu());
631                                 return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
632                         }
633                 } else {
634                         // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
635                         // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
636                         // which require external funding.
637                         let mut inputs = cached_request.inputs();
638                         debug_assert_eq!(inputs.len(), 1);
639                         let tx = match cached_request.maybe_finalize_untractable_package(self, logger) {
640                                 Some(tx) => tx,
641                                 None => return None,
642                         };
643                         if !cached_request.requires_external_funding() {
644                                 return Some((new_timer, 0, OnchainClaim::Tx(tx)));
645                         }
646                         return inputs.find_map(|input| match input {
647                                 // Commitment inputs with anchors support are the only untractable inputs supported
648                                 // thus far that require external funding.
649                                 PackageSolvingData::HolderFundingOutput(output) => {
650                                         debug_assert_eq!(tx.0.txid(), self.holder_commitment.trust().txid(),
651                                                 "Holder commitment transaction mismatch");
652
653                                         let conf_target = ConfirmationTarget::OnChainSweep;
654                                         let package_target_feerate_sat_per_1000_weight = cached_request
655                                                 .compute_package_feerate(fee_estimator, conf_target, feerate_strategy);
656                                         if let Some(input_amount_sat) = output.funding_amount {
657                                                 let fee_sat = input_amount_sat - tx.0.output.iter().map(|output| output.value.to_sat()).sum::<u64>();
658                                                 let commitment_tx_feerate_sat_per_1000_weight =
659                                                         compute_feerate_sat_per_1000_weight(fee_sat, tx.0.weight().to_wu());
660                                                 if commitment_tx_feerate_sat_per_1000_weight >= package_target_feerate_sat_per_1000_weight {
661                                                         log_debug!(logger, "Pre-signed commitment {} already has feerate {} sat/kW above required {} sat/kW",
662                                                                 tx.0.txid(), commitment_tx_feerate_sat_per_1000_weight,
663                                                                 package_target_feerate_sat_per_1000_weight);
664                                                         return Some((new_timer, 0, OnchainClaim::Tx(tx.clone())));
665                                                 }
666                                         }
667
668                                         // We'll locate an anchor output we can spend within the commitment transaction.
669                                         let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
670                                         match chan_utils::get_anchor_output(&tx.0, funding_pubkey) {
671                                                 // An anchor output was found, so we should yield a funding event externally.
672                                                 Some((idx, _)) => {
673                                                         // TODO: Use a lower confirmation target when both our and the
674                                                         // counterparty's latest commitment don't have any HTLCs present.
675                                                         Some((
676                                                                 new_timer,
677                                                                 package_target_feerate_sat_per_1000_weight as u64,
678                                                                 OnchainClaim::Event(ClaimEvent::BumpCommitment {
679                                                                         package_target_feerate_sat_per_1000_weight,
680                                                                         commitment_tx: tx.0.clone(),
681                                                                         anchor_output_idx: idx,
682                                                                 }),
683                                                         ))
684                                                 },
685                                                 // An anchor output was not found. There's nothing we can do other than
686                                                 // attempt to broadcast the transaction with its current fee rate and hope
687                                                 // it confirms. This is essentially the same behavior as a commitment
688                                                 // transaction without anchor outputs.
689                                                 None => Some((new_timer, 0, OnchainClaim::Tx(tx.clone()))),
690                                         }
691                                 },
692                                 _ => {
693                                         debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
694                                         None
695                                 },
696                         })
697                 }
698                 None
699         }
700
701         pub fn abandon_claim(&mut self, outpoint: &BitcoinOutPoint) {
702                 let claim_id = self.claimable_outpoints.get(outpoint).map(|(claim_id, _)| *claim_id)
703                         .or_else(|| {
704                                 self.pending_claim_requests.iter()
705                                         .find(|(_, claim)| claim.outpoints().iter().any(|claim_outpoint| *claim_outpoint == outpoint))
706                                         .map(|(claim_id, _)| *claim_id)
707                         });
708                 if let Some(claim_id) = claim_id {
709                         if let Some(claim) = self.pending_claim_requests.remove(&claim_id) {
710                                 for outpoint in claim.outpoints() {
711                                         self.claimable_outpoints.remove(outpoint);
712                                 }
713                         }
714                 } else {
715                         self.locktimed_packages.values_mut().for_each(|claims|
716                                 claims.retain(|claim| !claim.outpoints().iter().any(|claim_outpoint| *claim_outpoint == outpoint)));
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_matched_txn` this used to be named
723         /// `block_connected`, but it is now also used for claiming an HTLC output if we receive a
724         /// preimage after force-close.
725         ///
726         /// `conf_height` represents the height at which the request was generated. This
727         /// does not need to equal the current blockchain tip height, which should be provided via
728         /// `cur_height`, however it must never be higher than `cur_height`.
729         pub(super) fn update_claims_view_from_requests<B: Deref, F: Deref, L: Logger>(
730                 &mut self, requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32,
731                 broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
732         ) where
733                 B::Target: BroadcasterInterface,
734                 F::Target: FeeEstimator,
735         {
736                 if !requests.is_empty() {
737                         log_debug!(logger, "Updating claims view at height {} with {} claim requests", cur_height, requests.len());
738                 }
739
740                 let mut preprocessed_requests = Vec::with_capacity(requests.len());
741                 let mut aggregated_request = None;
742
743                 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
744                 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
745                 for req in requests {
746                         // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
747                         if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
748                                 log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
749                         } else {
750                                 let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
751                                         .find(|locked_package| locked_package.outpoints() == req.outpoints());
752                                 if let Some(package) = timelocked_equivalent_package {
753                                         log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
754                                                 req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
755                                         continue;
756                                 }
757
758                                 let package_locktime = req.package_locktime(cur_height);
759                                 if package_locktime > cur_height + 1 {
760                                         log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
761                                         for outpoint in req.outpoints() {
762                                                 log_info!(logger, "  Outpoint {}", outpoint);
763                                         }
764                                         self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
765                                         continue;
766                                 }
767
768                                 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
769                                 if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
770                                         // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
771                                         preprocessed_requests.push(req);
772                                 } else if aggregated_request.is_none() {
773                                         aggregated_request = Some(req);
774                                 } else {
775                                         aggregated_request.as_mut().unwrap().merge_package(req);
776                                 }
777                         }
778                 }
779                 if let Some(req) = aggregated_request {
780                         preprocessed_requests.push(req);
781                 }
782
783                 // Claim everything up to and including `cur_height`
784                 let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 1));
785                 if !self.locktimed_packages.is_empty() {
786                         log_debug!(logger,
787                                 "Updating claims view at height {} with {} locked packages available for claim",
788                                 cur_height,
789                                 self.locktimed_packages.len());
790                 }
791                 for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
792                         log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
793                         preprocessed_requests.append(&mut entry);
794                 }
795                 self.locktimed_packages = remaining_locked_packages;
796
797                 // Generate claim transactions and track them to bump if necessary at
798                 // height timer expiration (i.e in how many blocks we're going to take action).
799                 for mut req in preprocessed_requests {
800                         if let Some((new_timer, new_feerate, claim)) = self.generate_claim(
801                                 cur_height, &req, &FeerateStrategy::ForceBump, &*fee_estimator, &*logger,
802                         ) {
803                                 req.set_timer(new_timer);
804                                 req.set_feerate(new_feerate);
805                                 // Once a pending claim has an id assigned, it remains fixed until the claim is
806                                 // satisfied, regardless of whether the claim switches between different variants of
807                                 // `OnchainClaim`.
808                                 let claim_id = match claim {
809                                         OnchainClaim::Tx(tx) => {
810                                                 if tx.is_fully_signed() {
811                                                         log_info!(logger, "Broadcasting onchain {}", log_tx!(tx.0));
812                                                         broadcaster.broadcast_transactions(&[&tx.0]);
813                                                 } else {
814                                                         log_info!(logger, "Waiting for signature of unsigned onchain transaction {}", tx.0.txid());
815                                                 }
816                                                 ClaimId(tx.0.txid().to_byte_array())
817                                         },
818                                         OnchainClaim::Event(claim_event) => {
819                                                 log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
820                                                 let claim_id = match claim_event {
821                                                         ClaimEvent::BumpCommitment { ref commitment_tx, .. } =>
822                                                                 // For commitment claims, we can just use their txid as it should
823                                                                 // already be unique.
824                                                                 ClaimId(commitment_tx.txid().to_byte_array()),
825                                                         ClaimEvent::BumpHTLC { ref htlcs, .. } => {
826                                                                 // For HTLC claims, commit to the entire set of HTLC outputs to
827                                                                 // claim, which will always be unique per request. Once a claim ID
828                                                                 // is generated, it is assigned and remains unchanged, even if the
829                                                                 // underlying set of HTLCs changes.
830                                                                 let mut engine = Sha256::engine();
831                                                                 for htlc in htlcs {
832                                                                         engine.input(&htlc.commitment_txid.to_byte_array());
833                                                                         engine.input(&htlc.htlc.transaction_output_index.unwrap().to_be_bytes());
834                                                                 }
835                                                                 ClaimId(Sha256::from_engine(engine).to_byte_array())
836                                                         },
837                                                 };
838                                                 debug_assert!(self.pending_claim_requests.get(&claim_id).is_none());
839                                                 debug_assert_eq!(self.pending_claim_events.iter().filter(|entry| entry.0 == claim_id).count(), 0);
840                                                 self.pending_claim_events.push((claim_id, claim_event));
841                                                 claim_id
842                                         },
843                                 };
844                                 // Because fuzzing can cause hash collisions, we can end up with conflicting claim
845                                 // ids here, so we only assert when not fuzzing.
846                                 debug_assert!(cfg!(fuzzing) || self.pending_claim_requests.get(&claim_id).is_none());
847                                 for k in req.outpoints() {
848                                         log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
849                                         self.claimable_outpoints.insert(k.clone(), (claim_id, conf_height));
850                                 }
851                                 self.pending_claim_requests.insert(claim_id, req);
852                         }
853                 }
854         }
855
856         /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
857         /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
858         /// Together with `update_claims_view_from_requests` this used to be named `block_connected`,
859         /// but it is now also used for claiming an HTLC output if we receive a preimage after force-close.
860         ///
861         /// `conf_height` represents the height at which the transactions in `txn_matched` were
862         /// confirmed. This does not need to equal the current blockchain tip height, which should be
863         /// provided via `cur_height`, however it must never be higher than `cur_height`.
864         pub(super) fn update_claims_view_from_matched_txn<B: Deref, F: Deref, L: Logger>(
865                 &mut self, txn_matched: &[&Transaction], conf_height: u32, conf_hash: BlockHash,
866                 cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
867         ) where
868                 B::Target: BroadcasterInterface,
869                 F::Target: FeeEstimator,
870         {
871                 let mut have_logged_intro = false;
872                 let mut maybe_log_intro = || {
873                         if !have_logged_intro {
874                                 log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {}", cur_height, txn_matched.len(), conf_height);
875                                 have_logged_intro = true;
876                         }
877                 };
878                 let mut bump_candidates = new_hash_map();
879                 if !txn_matched.is_empty() { maybe_log_intro(); }
880                 for tx in txn_matched {
881                         // Scan all input to verify is one of the outpoint spent is of interest for us
882                         let mut claimed_outputs_material = Vec::new();
883                         for inp in &tx.input {
884                                 if let Some((claim_id, _)) = self.claimable_outpoints.get(&inp.previous_output) {
885                                         // If outpoint has claim request pending on it...
886                                         if let Some(request) = self.pending_claim_requests.get_mut(claim_id) {
887                                                 //... we need to verify equality between transaction outpoints and claim request
888                                                 // outpoints to know if transaction is the original claim or a bumped one issued
889                                                 // by us.
890                                                 let mut are_sets_equal = true;
891                                                 let mut tx_inputs = tx.input.iter().map(|input| &input.previous_output).collect::<Vec<_>>();
892                                                 tx_inputs.sort_unstable();
893                                                 for request_input in request.outpoints() {
894                                                         if tx_inputs.binary_search(&request_input).is_err() {
895                                                                 are_sets_equal = false;
896                                                                 break;
897                                                         }
898                                                 }
899
900                                                 macro_rules! clean_claim_request_after_safety_delay {
901                                                         () => {
902                                                                 let entry = OnchainEventEntry {
903                                                                         txid: tx.txid(),
904                                                                         height: conf_height,
905                                                                         block_hash: Some(conf_hash),
906                                                                         event: OnchainEvent::Claim { claim_id: *claim_id }
907                                                                 };
908                                                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
909                                                                         self.onchain_events_awaiting_threshold_conf.push(entry);
910                                                                 }
911                                                         }
912                                                 }
913
914                                                 // If this is our transaction (or our counterparty spent all the outputs
915                                                 // before we could anyway with same inputs order than us), wait for
916                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
917                                                 if are_sets_equal {
918                                                         clean_claim_request_after_safety_delay!();
919                                                 } else { // If false, generate new claim request with update outpoint set
920                                                         let mut at_least_one_drop = false;
921                                                         for input in tx.input.iter() {
922                                                                 if let Some(package) = request.split_package(&input.previous_output) {
923                                                                         claimed_outputs_material.push(package);
924                                                                         at_least_one_drop = true;
925                                                                 }
926                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
927                                                                 if request.outpoints().is_empty() {
928                                                                         clean_claim_request_after_safety_delay!();
929                                                                 }
930                                                         }
931                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
932                                                         if at_least_one_drop {
933                                                                 bump_candidates.insert(*claim_id, request.clone());
934                                                                 // If we have any pending claim events for the request being updated
935                                                                 // that have yet to be consumed, we'll remove them since they will
936                                                                 // end up producing an invalid transaction by double spending
937                                                                 // input(s) that already have a confirmed spend. If such spend is
938                                                                 // reorged out of the chain, then we'll attempt to re-spend the
939                                                                 // inputs once we see it.
940                                                                 #[cfg(debug_assertions)] {
941                                                                         let existing = self.pending_claim_events.iter()
942                                                                                 .filter(|entry| entry.0 == *claim_id).count();
943                                                                         assert!(existing == 0 || existing == 1);
944                                                                 }
945                                                                 self.pending_claim_events.retain(|entry| entry.0 != *claim_id);
946                                                         }
947                                                 }
948                                                 break; //No need to iterate further, either tx is our or their
949                                         } else {
950                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
951                                         }
952                                 }
953                         }
954                         for package in claimed_outputs_material.drain(..) {
955                                 let entry = OnchainEventEntry {
956                                         txid: tx.txid(),
957                                         height: conf_height,
958                                         block_hash: Some(conf_hash),
959                                         event: OnchainEvent::ContentiousOutpoint { package },
960                                 };
961                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
962                                         self.onchain_events_awaiting_threshold_conf.push(entry);
963                                 }
964                         }
965                 }
966
967                 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
968                 let onchain_events_awaiting_threshold_conf =
969                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
970                 for entry in onchain_events_awaiting_threshold_conf {
971                         if entry.has_reached_confirmation_threshold(cur_height) {
972                                 maybe_log_intro();
973                                 match entry.event {
974                                         OnchainEvent::Claim { claim_id } => {
975                                                 // We may remove a whole set of claim outpoints here, as these one may have
976                                                 // been aggregated in a single tx and claimed so atomically
977                                                 if let Some(request) = self.pending_claim_requests.remove(&claim_id) {
978                                                         for outpoint in request.outpoints() {
979                                                                 log_debug!(logger, "Removing claim tracking for {} due to maturation of claim package {}.",
980                                                                         outpoint, log_bytes!(claim_id.0));
981                                                                 self.claimable_outpoints.remove(outpoint);
982                                                         }
983                                                         #[cfg(debug_assertions)] {
984                                                                 let num_existing = self.pending_claim_events.iter()
985                                                                         .filter(|entry| entry.0 == claim_id).count();
986                                                                 assert!(num_existing == 0 || num_existing == 1);
987                                                         }
988                                                         self.pending_claim_events.retain(|(id, _)| *id != claim_id);
989                                                 }
990                                         },
991                                         OnchainEvent::ContentiousOutpoint { package } => {
992                                                 log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
993                                                 log_debug!(logger, " {:?}", package.outpoints());
994                                                 self.claimable_outpoints.remove(package.outpoints()[0]);
995                                         }
996                                 }
997                         } else {
998                                 self.onchain_events_awaiting_threshold_conf.push(entry);
999                         }
1000                 }
1001
1002                 // Check if any pending claim request must be rescheduled
1003                 for (claim_id, request) in self.pending_claim_requests.iter() {
1004                         if cur_height >= request.timer() {
1005                                 bump_candidates.insert(*claim_id, request.clone());
1006                         }
1007                 }
1008
1009                 // Build, bump and rebroadcast tx accordingly
1010                 if !bump_candidates.is_empty() {
1011                         maybe_log_intro();
1012                         log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
1013                 }
1014
1015                 for (claim_id, request) in bump_candidates.iter() {
1016                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(
1017                                 cur_height, &request, &FeerateStrategy::ForceBump, &*fee_estimator, &*logger,
1018                         ) {
1019                                 match bump_claim {
1020                                         OnchainClaim::Tx(bump_tx) => {
1021                                                 if bump_tx.is_fully_signed() {
1022                                                         log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx.0));
1023                                                         broadcaster.broadcast_transactions(&[&bump_tx.0]);
1024                                                 } else {
1025                                                         log_info!(logger, "Waiting for signature of RBF-bumped unsigned onchain transaction {}",
1026                                                                 bump_tx.0.txid());
1027                                                 }
1028                                         },
1029                                         OnchainClaim::Event(claim_event) => {
1030                                                 log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
1031                                                 #[cfg(debug_assertions)] {
1032                                                         let num_existing = self.pending_claim_events.iter().
1033                                                                 filter(|entry| entry.0 == *claim_id).count();
1034                                                         assert!(num_existing == 0 || num_existing == 1);
1035                                                 }
1036                                                 self.pending_claim_events.retain(|event| event.0 != *claim_id);
1037                                                 self.pending_claim_events.push((*claim_id, claim_event));
1038                                         },
1039                                 }
1040                                 if let Some(request) = self.pending_claim_requests.get_mut(claim_id) {
1041                                         request.set_timer(new_timer);
1042                                         request.set_feerate(new_feerate);
1043                                 }
1044                         }
1045                 }
1046         }
1047
1048         pub(super) fn transaction_unconfirmed<B: Deref, F: Deref, L: Logger>(
1049                 &mut self,
1050                 txid: &Txid,
1051                 broadcaster: B,
1052                 fee_estimator: &LowerBoundedFeeEstimator<F>,
1053                 logger: &L,
1054         ) where
1055                 B::Target: BroadcasterInterface,
1056                 F::Target: FeeEstimator,
1057         {
1058                 let mut height = None;
1059                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
1060                         if entry.txid == *txid {
1061                                 height = Some(entry.height);
1062                                 break;
1063                         }
1064                 }
1065
1066                 if let Some(height) = height {
1067                         self.block_disconnected(height, broadcaster, fee_estimator, logger);
1068                 }
1069         }
1070
1071         pub(super) fn block_disconnected<B: Deref, F: Deref, L: Logger>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
1072                 where B::Target: BroadcasterInterface,
1073                         F::Target: FeeEstimator,
1074         {
1075                 let mut bump_candidates = new_hash_map();
1076                 let onchain_events_awaiting_threshold_conf =
1077                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
1078                 for entry in onchain_events_awaiting_threshold_conf {
1079                         if entry.height >= height {
1080                                 //- our claim tx on a commitment tx output
1081                                 //- resurect outpoint back in its claimable set and regenerate tx
1082                                 match entry.event {
1083                                         OnchainEvent::ContentiousOutpoint { package } => {
1084                                                 if let Some(pending_claim) = self.claimable_outpoints.get(package.outpoints()[0]) {
1085                                                         if let Some(request) = self.pending_claim_requests.get_mut(&pending_claim.0) {
1086                                                                 request.merge_package(package);
1087                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
1088                                                                 // resurrected only one bump claim tx is going to be broadcast
1089                                                                 bump_candidates.insert(pending_claim.clone(), request.clone());
1090                                                         }
1091                                                 }
1092                                         },
1093                                         _ => {},
1094                                 }
1095                         } else {
1096                                 self.onchain_events_awaiting_threshold_conf.push(entry);
1097                         }
1098                 }
1099                 for ((_claim_id, _), ref mut request) in bump_candidates.iter_mut() {
1100                         // `height` is the height being disconnected, so our `current_height` is 1 lower.
1101                         let current_height = height - 1;
1102                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(
1103                                 current_height, &request, &FeerateStrategy::ForceBump, fee_estimator, logger
1104                         ) {
1105                                 request.set_timer(new_timer);
1106                                 request.set_feerate(new_feerate);
1107                                 match bump_claim {
1108                                         OnchainClaim::Tx(bump_tx) => {
1109                                                 if bump_tx.is_fully_signed() {
1110                                                         log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx.0));
1111                                                         broadcaster.broadcast_transactions(&[&bump_tx.0]);
1112                                                 } else {
1113                                                         log_info!(logger, "Waiting for signature of unsigned onchain transaction {}", bump_tx.0.txid());
1114                                                 }
1115                                         },
1116                                         OnchainClaim::Event(claim_event) => {
1117                                                 log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
1118                                                 #[cfg(debug_assertions)] {
1119                                                         let num_existing = self.pending_claim_events.iter()
1120                                                                 .filter(|entry| entry.0 == *_claim_id).count();
1121                                                         assert!(num_existing == 0 || num_existing == 1);
1122                                                 }
1123                                                 self.pending_claim_events.retain(|event| event.0 != *_claim_id);
1124                                                 self.pending_claim_events.push((*_claim_id, claim_event));
1125                                         },
1126                                 }
1127                         }
1128                 }
1129                 for (ancestor_claim_txid, request) in bump_candidates.drain() {
1130                         self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
1131                 }
1132                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
1133                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
1134                 let mut remove_request = Vec::new();
1135                 self.claimable_outpoints.retain(|_, ref v|
1136                         if v.1 >= height {
1137                         remove_request.push(v.0.clone());
1138                         false
1139                         } else { true });
1140                 for req in remove_request {
1141                         self.pending_claim_requests.remove(&req);
1142                 }
1143         }
1144
1145         pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
1146                 self.claimable_outpoints.get(outpoint).is_some()
1147         }
1148
1149         pub(crate) fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
1150                 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = self.onchain_events_awaiting_threshold_conf
1151                         .iter()
1152                         .map(|entry| (entry.txid, entry.height, entry.block_hash))
1153                         .collect();
1154                 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
1155                 txids.dedup_by_key(|(txid, _, _)| *txid);
1156                 txids
1157         }
1158
1159         pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
1160                 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
1161         }
1162
1163         pub(crate) fn get_unsigned_holder_commitment_tx(&self) -> &Transaction {
1164                 &self.holder_commitment.trust().built_transaction().transaction
1165         }
1166
1167         pub(crate) fn get_maybe_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> MaybeSignedTransaction {
1168                 let tx = self.signer.sign_holder_commitment(&self.holder_commitment, &self.secp_ctx)
1169                         .map(|sig| self.holder_commitment.add_holder_sig(funding_redeemscript, sig))
1170                         .unwrap_or_else(|_| self.get_unsigned_holder_commitment_tx().clone());
1171                 MaybeSignedTransaction(tx)
1172         }
1173
1174         #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
1175         pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
1176                 let sig = self.signer.unsafe_sign_holder_commitment(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
1177                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
1178         }
1179
1180         pub(crate) fn get_maybe_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<MaybeSignedTransaction> {
1181                 let get_signed_htlc_tx = |holder_commitment: &HolderCommitmentTransaction| {
1182                         let trusted_tx = holder_commitment.trust();
1183                         if trusted_tx.txid() != outp.txid {
1184                                 return None;
1185                         }
1186                         let (htlc_idx, htlc) = trusted_tx.htlcs().iter().enumerate()
1187                                 .find(|(_, htlc)| htlc.transaction_output_index.unwrap() == outp.vout)
1188                                 .unwrap();
1189                         let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
1190                         let mut htlc_tx = trusted_tx.build_unsigned_htlc_tx(
1191                                 &self.channel_transaction_parameters.as_holder_broadcastable(), htlc_idx, preimage,
1192                         );
1193
1194                         let htlc_descriptor = HTLCDescriptor {
1195                                 channel_derivation_parameters: ChannelDerivationParameters {
1196                                         value_satoshis: self.channel_value_satoshis,
1197                                         keys_id: self.channel_keys_id,
1198                                         transaction_parameters: self.channel_transaction_parameters.clone(),
1199                                 },
1200                                 commitment_txid: trusted_tx.txid(),
1201                                 per_commitment_number: trusted_tx.commitment_number(),
1202                                 per_commitment_point: trusted_tx.per_commitment_point(),
1203                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
1204                                 htlc: htlc.clone(),
1205                                 preimage: preimage.clone(),
1206                                 counterparty_sig: counterparty_htlc_sig.clone(),
1207                         };
1208                         if let Ok(htlc_sig) = self.signer.sign_holder_htlc_transaction(&htlc_tx, 0, &htlc_descriptor, &self.secp_ctx) {
1209                                 htlc_tx.input[0].witness = trusted_tx.build_htlc_input_witness(
1210                                         htlc_idx, &counterparty_htlc_sig, &htlc_sig, preimage,
1211                                 );
1212                         }
1213                         Some(MaybeSignedTransaction(htlc_tx))
1214                 };
1215
1216                 // Check if the HTLC spends from the current holder commitment first, or the previous.
1217                 get_signed_htlc_tx(&self.holder_commitment)
1218                         .or_else(|| self.prev_holder_commitment.as_ref().and_then(|prev_holder_commitment| get_signed_htlc_tx(prev_holder_commitment)))
1219         }
1220
1221         pub(crate) fn generate_external_htlc_claim(
1222                 &self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>
1223         ) -> Option<ExternalHTLCClaim> {
1224                 let find_htlc = |holder_commitment: &HolderCommitmentTransaction| -> Option<ExternalHTLCClaim> {
1225                         let trusted_tx = holder_commitment.trust();
1226                         if outp.txid != trusted_tx.txid() {
1227                                 return None;
1228                         }
1229                         trusted_tx.htlcs().iter().enumerate()
1230                                 .find(|(_, htlc)| if let Some(output_index) = htlc.transaction_output_index {
1231                                         output_index == outp.vout
1232                                 } else {
1233                                         false
1234                                 })
1235                                 .map(|(htlc_idx, htlc)| {
1236                                         let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
1237                                         ExternalHTLCClaim {
1238                                                 commitment_txid: trusted_tx.txid(),
1239                                                 per_commitment_number: trusted_tx.commitment_number(),
1240                                                 htlc: htlc.clone(),
1241                                                 preimage: *preimage,
1242                                                 counterparty_sig: counterparty_htlc_sig,
1243                                                 per_commitment_point: trusted_tx.per_commitment_point(),
1244                                         }
1245                                 })
1246                 };
1247                 // Check if the HTLC spends from the current holder commitment or the previous one otherwise.
1248                 find_htlc(&self.holder_commitment)
1249                         .or_else(|| self.prev_holder_commitment.as_ref().map(|c| find_htlc(c)).flatten())
1250         }
1251
1252         pub(crate) fn channel_type_features(&self) -> &ChannelTypeFeatures {
1253                 &self.channel_transaction_parameters.channel_type_features
1254         }
1255 }