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