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