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