c8874b7ac597baa9702d5f8e3dc1d5857815cfcd
[rust-lightning] / lightning / src / chain / onchaintx.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The logic to build claims and bump in-flight transactions until confirmations.
11 //!
12 //! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
13 //! building, tracking, bumping and notifications functions.
14
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
18
19 use bitcoin::hash_types::Txid;
20
21 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
22 use bitcoin::secp256k1;
23
24 use ln::msgs::DecodeError;
25 use ln::PaymentPreimage;
26 #[cfg(anchors)]
27 use ln::chan_utils;
28 use ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
29 #[cfg(anchors)]
30 use chain::chaininterface::ConfirmationTarget;
31 use chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
32 use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
33 use chain::keysinterface::{Sign, KeysInterface};
34 #[cfg(anchors)]
35 use chain::package::PackageSolvingData;
36 use chain::package::PackageTemplate;
37 use util::logger::Logger;
38 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
39 use util::byte_utils;
40
41 use io;
42 use prelude::*;
43 use alloc::collections::BTreeMap;
44 use core::cmp;
45 use core::ops::Deref;
46 use core::mem::replace;
47 use bitcoin::hashes::Hash;
48
49 const MAX_ALLOC_SIZE: usize = 64*1024;
50
51 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
52 /// transaction causing it.
53 ///
54 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
55 #[derive(PartialEq, Eq)]
56 struct OnchainEventEntry {
57         txid: Txid,
58         height: u32,
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 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
73 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
74 #[derive(PartialEq, Eq)]
75 enum OnchainEvent {
76         /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
77         /// bump-txn candidate buffer.
78         Claim {
79                 claim_request: Txid,
80         },
81         /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a counterparty party tx.
82         /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
83         /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
84         ContentiousOutpoint {
85                 package: PackageTemplate,
86         }
87 }
88
89 impl Writeable for OnchainEventEntry {
90         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
91                 write_tlv_fields!(writer, {
92                         (0, self.txid, required),
93                         (2, self.height, required),
94                         (4, self.event, required),
95                 });
96                 Ok(())
97         }
98 }
99
100 impl MaybeReadable for OnchainEventEntry {
101         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
102                 let mut txid = Txid::all_zeros();
103                 let mut height = 0;
104                 let mut event = None;
105                 read_tlv_fields!(reader, {
106                         (0, txid, required),
107                         (2, height, required),
108                         (4, event, ignorable),
109                 });
110                 if let Some(ev) = event {
111                         Ok(Some(Self { txid, height, event: ev }))
112                 } else {
113                         Ok(None)
114                 }
115         }
116 }
117
118 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
119         (0, Claim) => {
120                 (0, claim_request, required),
121         },
122         (1, ContentiousOutpoint) => {
123                 (0, package, required),
124         },
125 );
126
127 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
128         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
129                 match Readable::read(reader)? {
130                         0u8 => Ok(None),
131                         1u8 => {
132                                 let vlen: u64 = Readable::read(reader)?;
133                                 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<Option<(usize, Signature)>>()));
134                                 for _ in 0..vlen {
135                                         ret.push(match Readable::read(reader)? {
136                                                 0u8 => None,
137                                                 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
138                                                 _ => return Err(DecodeError::InvalidValue)
139                                         });
140                                 }
141                                 Ok(Some(ret))
142                         },
143                         _ => Err(DecodeError::InvalidValue),
144                 }
145         }
146 }
147
148 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
149         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
150                 match self {
151                         &Some(ref vec) => {
152                                 1u8.write(writer)?;
153                                 (vec.len() as u64).write(writer)?;
154                                 for opt in vec.iter() {
155                                         match opt {
156                                                 &Some((ref idx, ref sig)) => {
157                                                         1u8.write(writer)?;
158                                                         (*idx as u64).write(writer)?;
159                                                         sig.write(writer)?;
160                                                 },
161                                                 &None => 0u8.write(writer)?,
162                                         }
163                                 }
164                         },
165                         &None => 0u8.write(writer)?,
166                 }
167                 Ok(())
168         }
169 }
170
171 // Represents the different types of claims for which events are yielded externally to satisfy said
172 // claims.
173 #[cfg(anchors)]
174 pub(crate) enum ClaimEvent {
175         /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
176         /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
177         BumpCommitment {
178                 package_target_feerate_sat_per_1000_weight: u32,
179                 commitment_tx: Transaction,
180                 anchor_output_idx: u32,
181         },
182 }
183
184 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
185 /// control) onchain.
186 pub(crate) enum OnchainClaim {
187         /// A finalized transaction pending confirmation spending the output to claim.
188         Tx(Transaction),
189         #[cfg(anchors)]
190         /// An event yielded externally to signal additional inputs must be added to a transaction
191         /// pending confirmation spending the output to claim.
192         Event(ClaimEvent),
193 }
194
195 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
196 /// do RBF bumping if possible.
197 pub struct OnchainTxHandler<ChannelSigner: Sign> {
198         destination_script: Script,
199         holder_commitment: HolderCommitmentTransaction,
200         // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
201         // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
202         // the set of HTLCs in the HolderCommitmentTransaction.
203         holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
204         prev_holder_commitment: Option<HolderCommitmentTransaction>,
205         prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
206
207         pub(super) signer: ChannelSigner,
208         pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
209
210         // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
211         // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
212         // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
213         // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
214         // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
215         // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
216         // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
217         // we need to regenerate new claim request with reduced set of still-claimable outpoints.
218         // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
219         // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
220         // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
221         #[cfg(test)] // Used in functional_test to verify sanitization
222         pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
223         #[cfg(not(test))]
224         pending_claim_requests: HashMap<Txid, PackageTemplate>,
225         #[cfg(anchors)]
226         pending_claim_events: HashMap<Txid, ClaimEvent>,
227
228         // Used to link outpoints claimed in a connected block to a pending claim request.
229         // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
230         // Value is (pending claim request identifier, confirmation_block), identifier
231         // is txid of the initial claiming transaction and is immutable until outpoint is
232         // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
233         // block with output gets disconnected.
234         #[cfg(test)] // Used in functional_test to verify sanitization
235         pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
236         #[cfg(not(test))]
237         claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
238
239         locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
240
241         onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
242
243         pub(super) secp_ctx: Secp256k1<secp256k1::All>,
244 }
245
246 const SERIALIZATION_VERSION: u8 = 1;
247 const MIN_SERIALIZATION_VERSION: u8 = 1;
248
249 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
250         pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
251                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
252
253                 self.destination_script.write(writer)?;
254                 self.holder_commitment.write(writer)?;
255                 self.holder_htlc_sigs.write(writer)?;
256                 self.prev_holder_commitment.write(writer)?;
257                 self.prev_holder_htlc_sigs.write(writer)?;
258
259                 self.channel_transaction_parameters.write(writer)?;
260
261                 let mut key_data = VecWriter(Vec::new());
262                 self.signer.write(&mut key_data)?;
263                 assert!(key_data.0.len() < core::usize::MAX);
264                 assert!(key_data.0.len() < core::u32::MAX as usize);
265                 (key_data.0.len() as u32).write(writer)?;
266                 writer.write_all(&key_data.0[..])?;
267
268                 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
269                 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
270                         ancestor_claim_txid.write(writer)?;
271                         request.write(writer)?;
272                 }
273
274                 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
275                 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
276                         outp.write(writer)?;
277                         claim_and_height.0.write(writer)?;
278                         claim_and_height.1.write(writer)?;
279                 }
280
281                 writer.write_all(&byte_utils::be64_to_array(self.locktimed_packages.len() as u64))?;
282                 for (ref locktime, ref packages) in self.locktimed_packages.iter() {
283                         locktime.write(writer)?;
284                         writer.write_all(&byte_utils::be64_to_array(packages.len() as u64))?;
285                         for ref package in packages.iter() {
286                                 package.write(writer)?;
287                         }
288                 }
289
290                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
291                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
292                         entry.write(writer)?;
293                 }
294
295                 write_tlv_fields!(writer, {});
296                 Ok(())
297         }
298 }
299
300 impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
301         fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
302                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
303
304                 let destination_script = Readable::read(reader)?;
305
306                 let holder_commitment = Readable::read(reader)?;
307                 let holder_htlc_sigs = Readable::read(reader)?;
308                 let prev_holder_commitment = Readable::read(reader)?;
309                 let prev_holder_htlc_sigs = Readable::read(reader)?;
310
311                 let channel_parameters = Readable::read(reader)?;
312
313                 let keys_len: u32 = Readable::read(reader)?;
314                 let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
315                 while keys_data.len() != keys_len as usize {
316                         // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
317                         let mut data = [0; 1024];
318                         let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
319                         reader.read_exact(read_slice)?;
320                         keys_data.extend_from_slice(read_slice);
321                 }
322                 let signer = keys_manager.read_chan_signer(&keys_data)?;
323
324                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
325                 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
326                 for _ in 0..pending_claim_requests_len {
327                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
328                 }
329
330                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
331                 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
332                 for _ in 0..claimable_outpoints_len {
333                         let outpoint = Readable::read(reader)?;
334                         let ancestor_claim_txid = Readable::read(reader)?;
335                         let height = Readable::read(reader)?;
336                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
337                 }
338
339                 let locktimed_packages_len: u64 = Readable::read(reader)?;
340                 let mut locktimed_packages = BTreeMap::new();
341                 for _ in 0..locktimed_packages_len {
342                         let locktime = Readable::read(reader)?;
343                         let packages_len: u64 = Readable::read(reader)?;
344                         let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
345                         for _ in 0..packages_len {
346                                 packages.push(Readable::read(reader)?);
347                         }
348                         locktimed_packages.insert(locktime, packages);
349                 }
350
351                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
352                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
353                 for _ in 0..waiting_threshold_conf_len {
354                         if let Some(val) = MaybeReadable::read(reader)? {
355                                 onchain_events_awaiting_threshold_conf.push(val);
356                         }
357                 }
358
359                 read_tlv_fields!(reader, {});
360
361                 let mut secp_ctx = Secp256k1::new();
362                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
363
364                 Ok(OnchainTxHandler {
365                         destination_script,
366                         holder_commitment,
367                         holder_htlc_sigs,
368                         prev_holder_commitment,
369                         prev_holder_htlc_sigs,
370                         signer,
371                         channel_transaction_parameters: channel_parameters,
372                         claimable_outpoints,
373                         locktimed_packages,
374                         pending_claim_requests,
375                         onchain_events_awaiting_threshold_conf,
376                         #[cfg(anchors)]
377                         pending_claim_events: HashMap::new(),
378                         secp_ctx,
379                 })
380         }
381 }
382
383 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
384         pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
385                 OnchainTxHandler {
386                         destination_script,
387                         holder_commitment,
388                         holder_htlc_sigs: None,
389                         prev_holder_commitment: None,
390                         prev_holder_htlc_sigs: None,
391                         signer,
392                         channel_transaction_parameters: channel_parameters,
393                         pending_claim_requests: HashMap::new(),
394                         claimable_outpoints: HashMap::new(),
395                         locktimed_packages: BTreeMap::new(),
396                         onchain_events_awaiting_threshold_conf: Vec::new(),
397                         #[cfg(anchors)]
398                         pending_claim_events: HashMap::new(),
399
400                         secp_ctx,
401                 }
402         }
403
404         pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
405                 self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
406         }
407
408         pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
409                 self.holder_commitment.to_broadcaster_value_sat()
410         }
411
412         /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
413         /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
414         /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
415         /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
416         /// Child-Pay-For-Parent.
417         ///
418         /// Panics if there are signing errors, because signing operations in reaction to on-chain
419         /// events are not expected to fail, and if they do, we may lose funds.
420         fn generate_claim<F: Deref, L: Deref>(&mut self, cur_height: u32, cached_request: &PackageTemplate, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L) -> Option<(Option<u32>, u64, OnchainClaim)>
421                 where F::Target: FeeEstimator,
422                                         L::Target: Logger,
423         {
424                 if cached_request.outpoints().len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
425
426                 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
427                 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
428                 let new_timer = Some(cached_request.get_height_timer(cur_height));
429                 if cached_request.is_malleable() {
430                         let predicted_weight = cached_request.package_weight(&self.destination_script);
431                         if let Some((output_value, new_feerate)) =
432                                         cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger) {
433                                 assert!(new_feerate != 0);
434
435                                 let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
436                                 log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
437                                 assert!(predicted_weight >= transaction.weight());
438                                 return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
439                         }
440                 } else {
441                         // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
442                         // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
443                         // which require external funding.
444                         #[cfg(not(anchors))]
445                         let inputs = cached_request.inputs();
446                         #[cfg(anchors)]
447                         let mut inputs = cached_request.inputs();
448                         debug_assert_eq!(inputs.len(), 1);
449                         let tx = match cached_request.finalize_untractable_package(self, logger) {
450                                 Some(tx) => tx,
451                                 None => return None,
452                         };
453                         if !cached_request.requires_external_funding() {
454                                 return Some((None, 0, OnchainClaim::Tx(tx)));
455                         }
456                         #[cfg(anchors)]
457                         return inputs.find_map(|input| match input {
458                                 // Commitment inputs with anchors support are the only untractable inputs supported
459                                 // thus far that require external funding.
460                                 PackageSolvingData::HolderFundingOutput(..) => {
461                                         debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
462                                                 "Holder commitment transaction mismatch");
463                                         // We'll locate an anchor output we can spend within the commitment transaction.
464                                         let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
465                                         match chan_utils::get_anchor_output(&tx, funding_pubkey) {
466                                                 // An anchor output was found, so we should yield a funding event externally.
467                                                 Some((idx, _)) => {
468                                                         // TODO: Use a lower confirmation target when both our and the
469                                                         // counterparty's latest commitment don't have any HTLCs present.
470                                                         let conf_target = ConfirmationTarget::HighPriority;
471                                                         let package_target_feerate_sat_per_1000_weight = cached_request
472                                                                 .compute_package_feerate(fee_estimator, conf_target);
473                                                         Some((
474                                                                 new_timer,
475                                                                 package_target_feerate_sat_per_1000_weight as u64,
476                                                                 OnchainClaim::Event(ClaimEvent::BumpCommitment {
477                                                                         package_target_feerate_sat_per_1000_weight,
478                                                                         commitment_tx: tx.clone(),
479                                                                         anchor_output_idx: idx,
480                                                                 }),
481                                                         ))
482                                                 },
483                                                 // An anchor output was not found. There's nothing we can do other than
484                                                 // attempt to broadcast the transaction with its current fee rate and hope
485                                                 // it confirms. This is essentially the same behavior as a commitment
486                                                 // transaction without anchor outputs.
487                                                 None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
488                                         }
489                                 },
490                                 _ => {
491                                         debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
492                                         None
493                                 },
494                         });
495                 }
496                 None
497         }
498
499         /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
500         /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
501         /// Formerly this was named `block_connected`, but it is now also used for claiming an HTLC output
502         /// if we receive a preimage after force-close.
503         /// `conf_height` represents the height at which the transactions in `txn_matched` were
504         /// confirmed. This does not need to equal the current blockchain tip height, which should be
505         /// provided via `cur_height`, however it must never be higher than `cur_height`.
506         pub(crate) fn update_claims_view<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
507                 where B::Target: BroadcasterInterface,
508                       F::Target: FeeEstimator,
509                                         L::Target: Logger,
510         {
511                 log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {} and {} claim requests", cur_height, txn_matched.len(), conf_height, requests.len());
512                 let mut preprocessed_requests = Vec::with_capacity(requests.len());
513                 let mut aggregated_request = None;
514
515                 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
516                 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
517                 for req in requests {
518                         // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
519                         if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
520                                 log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
521                         } else {
522                                 let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
523                                         .find(|locked_package| locked_package.outpoints() == req.outpoints());
524                                 if let Some(package) = timelocked_equivalent_package {
525                                         log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
526                                                 req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
527                                         continue;
528                                 }
529
530                                 if req.package_timelock() > cur_height + 1 {
531                                         log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
532                                         for outpoint in req.outpoints() {
533                                                 log_info!(logger, "  Outpoint {}", outpoint);
534                                         }
535                                         self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
536                                         continue;
537                                 }
538
539                                 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
540                                 if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
541                                         // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
542                                         preprocessed_requests.push(req);
543                                 } else if aggregated_request.is_none() {
544                                         aggregated_request = Some(req);
545                                 } else {
546                                         aggregated_request.as_mut().unwrap().merge_package(req);
547                                 }
548                         }
549                 }
550                 if let Some(req) = aggregated_request {
551                         preprocessed_requests.push(req);
552                 }
553
554                 // Claim everything up to and including cur_height + 1
555                 let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2));
556                 for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
557                         log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
558                         preprocessed_requests.append(&mut entry);
559                 }
560                 self.locktimed_packages = remaining_locked_packages;
561
562                 // Generate claim transactions and track them to bump if necessary at
563                 // height timer expiration (i.e in how many blocks we're going to take action).
564                 for mut req in preprocessed_requests {
565                         if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
566                                 req.set_timer(new_timer);
567                                 req.set_feerate(new_feerate);
568                                 let txid = match claim {
569                                         OnchainClaim::Tx(tx) => {
570                                                 log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
571                                                 broadcaster.broadcast_transaction(&tx);
572                                                 tx.txid()
573                                         },
574                                         #[cfg(anchors)]
575                                         OnchainClaim::Event(claim_event) => {
576                                                 log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
577                                                 let txid = match claim_event {
578                                                         ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
579                                                 };
580                                                 self.pending_claim_events.insert(txid, claim_event);
581                                                 txid
582                                         },
583                                 };
584                                 for k in req.outpoints() {
585                                         log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
586                                         self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
587                                 }
588                                 self.pending_claim_requests.insert(txid, req);
589                         }
590                 }
591
592                 let mut bump_candidates = HashMap::new();
593                 for tx in txn_matched {
594                         // Scan all input to verify is one of the outpoint spent is of interest for us
595                         let mut claimed_outputs_material = Vec::new();
596                         for inp in &tx.input {
597                                 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
598                                         // If outpoint has claim request pending on it...
599                                         if let Some(request) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
600                                                 //... we need to verify equality between transaction outpoints and claim request
601                                                 // outpoints to know if transaction is the original claim or a bumped one issued
602                                                 // by us.
603                                                 let mut set_equality = true;
604                                                 if request.outpoints().len() != tx.input.len() {
605                                                         set_equality = false;
606                                                 } else {
607                                                         for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
608                                                                 if **claim_inp != tx_inp.previous_output {
609                                                                         set_equality = false;
610                                                                 }
611                                                         }
612                                                 }
613
614                                                 macro_rules! clean_claim_request_after_safety_delay {
615                                                         () => {
616                                                                 let entry = OnchainEventEntry {
617                                                                         txid: tx.txid(),
618                                                                         height: conf_height,
619                                                                         event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
620                                                                 };
621                                                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
622                                                                         self.onchain_events_awaiting_threshold_conf.push(entry);
623                                                                 }
624                                                         }
625                                                 }
626
627                                                 // If this is our transaction (or our counterparty spent all the outputs
628                                                 // before we could anyway with same inputs order than us), wait for
629                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
630                                                 if set_equality {
631                                                         clean_claim_request_after_safety_delay!();
632                                                 } else { // If false, generate new claim request with update outpoint set
633                                                         let mut at_least_one_drop = false;
634                                                         for input in tx.input.iter() {
635                                                                 if let Some(package) = request.split_package(&input.previous_output) {
636                                                                         claimed_outputs_material.push(package);
637                                                                         at_least_one_drop = true;
638                                                                 }
639                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
640                                                                 if request.outpoints().is_empty() {
641                                                                         clean_claim_request_after_safety_delay!();
642                                                                 }
643                                                         }
644                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
645                                                         if at_least_one_drop {
646                                                                 bump_candidates.insert(first_claim_txid_height.0.clone(), request.clone());
647                                                         }
648                                                 }
649                                                 break; //No need to iterate further, either tx is our or their
650                                         } else {
651                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
652                                         }
653                                 }
654                         }
655                         for package in claimed_outputs_material.drain(..) {
656                                 let entry = OnchainEventEntry {
657                                         txid: tx.txid(),
658                                         height: conf_height,
659                                         event: OnchainEvent::ContentiousOutpoint { package },
660                                 };
661                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
662                                         self.onchain_events_awaiting_threshold_conf.push(entry);
663                                 }
664                         }
665                 }
666
667                 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
668                 let onchain_events_awaiting_threshold_conf =
669                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
670                 for entry in onchain_events_awaiting_threshold_conf {
671                         if entry.has_reached_confirmation_threshold(cur_height) {
672                                 match entry.event {
673                                         OnchainEvent::Claim { claim_request } => {
674                                                 // We may remove a whole set of claim outpoints here, as these one may have
675                                                 // been aggregated in a single tx and claimed so atomically
676                                                 if let Some(request) = self.pending_claim_requests.remove(&claim_request) {
677                                                         for outpoint in request.outpoints() {
678                                                                 log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
679                                                                 self.claimable_outpoints.remove(&outpoint);
680                                                                 #[cfg(anchors)]
681                                                                 self.pending_claim_events.remove(&claim_request);
682                                                         }
683                                                 }
684                                         },
685                                         OnchainEvent::ContentiousOutpoint { package } => {
686                                                 log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
687                                                 log_debug!(logger, " {:?}", package.outpoints());
688                                                 self.claimable_outpoints.remove(&package.outpoints()[0]);
689                                         }
690                                 }
691                         } else {
692                                 self.onchain_events_awaiting_threshold_conf.push(entry);
693                         }
694                 }
695
696                 // Check if any pending claim request must be rescheduled
697                 for (first_claim_txid, ref request) in self.pending_claim_requests.iter() {
698                         if let Some(h) = request.timer() {
699                                 if cur_height >= h {
700                                         bump_candidates.insert(*first_claim_txid, (*request).clone());
701                                 }
702                         }
703                 }
704
705                 // Build, bump and rebroadcast tx accordingly
706                 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
707                 for (first_claim_txid, request) in bump_candidates.iter() {
708                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(cur_height, &request, &*fee_estimator, &*logger) {
709                                 match bump_claim {
710                                         OnchainClaim::Tx(bump_tx) => {
711                                                 log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
712                                                 broadcaster.broadcast_transaction(&bump_tx);
713                                         },
714                                         #[cfg(anchors)]
715                                         OnchainClaim::Event(claim_event) => {
716                                                 log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
717                                                 self.pending_claim_events.insert(*first_claim_txid, claim_event);
718                                         },
719                                 }
720                                 if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
721                                         request.set_timer(new_timer);
722                                         request.set_feerate(new_feerate);
723                                 }
724                         }
725                 }
726         }
727
728         pub(crate) fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
729                 &mut self,
730                 txid: &Txid,
731                 broadcaster: B,
732                 fee_estimator: &LowerBoundedFeeEstimator<F>,
733                 logger: L,
734         ) where
735                 B::Target: BroadcasterInterface,
736                 F::Target: FeeEstimator,
737                 L::Target: Logger,
738         {
739                 let mut height = None;
740                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
741                         if entry.txid == *txid {
742                                 height = Some(entry.height);
743                                 break;
744                         }
745                 }
746
747                 if let Some(height) = height {
748                         self.block_disconnected(height, broadcaster, fee_estimator, logger);
749                 }
750         }
751
752         pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L)
753                 where B::Target: BroadcasterInterface,
754                       F::Target: FeeEstimator,
755                                         L::Target: Logger,
756         {
757                 let mut bump_candidates = HashMap::new();
758                 let onchain_events_awaiting_threshold_conf =
759                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
760                 for entry in onchain_events_awaiting_threshold_conf {
761                         if entry.height >= height {
762                                 //- our claim tx on a commitment tx output
763                                 //- resurect outpoint back in its claimable set and regenerate tx
764                                 match entry.event {
765                                         OnchainEvent::ContentiousOutpoint { package } => {
766                                                 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&package.outpoints()[0]) {
767                                                         if let Some(request) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
768                                                                 request.merge_package(package);
769                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
770                                                                 // resurrected only one bump claim tx is going to be broadcast
771                                                                 bump_candidates.insert(ancestor_claimable_txid.clone(), request.clone());
772                                                         }
773                                                 }
774                                         },
775                                         _ => {},
776                                 }
777                         } else {
778                                 self.onchain_events_awaiting_threshold_conf.push(entry);
779                         }
780                 }
781                 for (_first_claim_txid_height, request) in bump_candidates.iter_mut() {
782                         if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
783                                 request.set_timer(new_timer);
784                                 request.set_feerate(new_feerate);
785                                 match bump_claim {
786                                         OnchainClaim::Tx(bump_tx) => {
787                                                 log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
788                                                 broadcaster.broadcast_transaction(&bump_tx);
789                                         },
790                                         #[cfg(anchors)]
791                                         OnchainClaim::Event(claim_event) => {
792                                                 log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
793                                                 self.pending_claim_events.insert(_first_claim_txid_height.0, claim_event);
794                                         },
795                                 }
796                         }
797                 }
798                 for (ancestor_claim_txid, request) in bump_candidates.drain() {
799                         self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
800                 }
801                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
802                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
803                 let mut remove_request = Vec::new();
804                 self.claimable_outpoints.retain(|_, ref v|
805                         if v.1 >= height {
806                         remove_request.push(v.0.clone());
807                         false
808                         } else { true });
809                 for req in remove_request {
810                         self.pending_claim_requests.remove(&req);
811                 }
812         }
813
814         pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
815                 self.claimable_outpoints.get(outpoint).is_some()
816         }
817
818         pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
819                 let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
820                         .iter()
821                         .map(|entry| entry.txid)
822                         .collect();
823                 txids.sort_unstable();
824                 txids.dedup();
825                 txids
826         }
827
828         pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
829                 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
830                 self.holder_htlc_sigs = None;
831         }
832
833         // Normally holder HTLCs are signed at the same time as the holder commitment tx.  However,
834         // in some configurations, the holder commitment tx has been signed and broadcast by a
835         // ChannelMonitor replica, so we handle that case here.
836         fn sign_latest_holder_htlcs(&mut self) {
837                 if self.holder_htlc_sigs.is_none() {
838                         let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
839                         self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
840                 }
841         }
842
843         // Normally only the latest commitment tx and HTLCs need to be signed.  However, in some
844         // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
845         // broadcast the previous one before we sync with it.  We handle that case here.
846         fn sign_prev_holder_htlcs(&mut self) {
847                 if self.prev_holder_htlc_sigs.is_none() {
848                         if let Some(ref holder_commitment) = self.prev_holder_commitment {
849                                 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
850                                 self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
851                         }
852                 }
853         }
854
855         fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
856                 let mut ret = Vec::new();
857                 for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
858                         let tx_idx = htlc.transaction_output_index.unwrap();
859                         if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
860                         ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
861                 }
862                 ret
863         }
864
865         //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
866         // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
867         // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
868         // to monitor before.
869         pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
870                 let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
871                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
872                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
873         }
874
875         #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
876         pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
877                 let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
878                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
879                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
880         }
881
882         pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
883                 let mut htlc_tx = None;
884                 let commitment_txid = self.holder_commitment.trust().txid();
885                 // Check if the HTLC spends from the current holder commitment
886                 if commitment_txid == outp.txid {
887                         self.sign_latest_holder_htlcs();
888                         if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
889                                 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
890                                 let trusted_tx = self.holder_commitment.trust();
891                                 let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
892                                 htlc_tx = Some(trusted_tx
893                                         .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
894                         }
895                 }
896                 // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
897                 if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
898                         let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
899                         if commitment_txid == outp.txid {
900                                 self.sign_prev_holder_htlcs();
901                                 if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
902                                         let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
903                                         let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
904                                         let trusted_tx = holder_commitment.trust();
905                                         let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
906                                         htlc_tx = Some(trusted_tx
907                                                 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
908                                 }
909                         }
910                 }
911                 htlc_tx
912         }
913
914         pub(crate) fn opt_anchors(&self) -> bool {
915                 self.channel_transaction_parameters.opt_anchors.is_some()
916         }
917
918         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
919         pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
920                 let latest_had_sigs = self.holder_htlc_sigs.is_some();
921                 let prev_had_sigs = self.prev_holder_htlc_sigs.is_some();
922                 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
923                 if !latest_had_sigs {
924                         self.holder_htlc_sigs = None;
925                 }
926                 if !prev_had_sigs {
927                         self.prev_holder_htlc_sigs = None;
928                 }
929                 ret
930         }
931 }