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