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