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