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