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