131caff7a0d107f94afebf36ce672b24808832d3
[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 chain::package;
32 use util::logger::Logger;
33 use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter};
34 use util::byte_utils;
35
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         latest_height: u32,
171
172         pub(super) secp_ctx: Secp256k1<secp256k1::All>,
173 }
174
175 const SERIALIZATION_VERSION: u8 = 1;
176 const MIN_SERIALIZATION_VERSION: u8 = 1;
177
178 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
179         pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
180                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
181
182                 self.destination_script.write(writer)?;
183                 self.holder_commitment.write(writer)?;
184                 self.holder_htlc_sigs.write(writer)?;
185                 self.prev_holder_commitment.write(writer)?;
186                 self.prev_holder_htlc_sigs.write(writer)?;
187
188                 self.channel_transaction_parameters.write(writer)?;
189
190                 let mut key_data = VecWriter(Vec::new());
191                 self.signer.write(&mut key_data)?;
192                 assert!(key_data.0.len() < core::usize::MAX);
193                 assert!(key_data.0.len() < core::u32::MAX as usize);
194                 (key_data.0.len() as u32).write(writer)?;
195                 writer.write_all(&key_data.0[..])?;
196
197                 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
198                 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
199                         ancestor_claim_txid.write(writer)?;
200                         request.write(writer)?;
201                 }
202
203                 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
204                 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
205                         outp.write(writer)?;
206                         claim_and_height.0.write(writer)?;
207                         claim_and_height.1.write(writer)?;
208                 }
209
210                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
211                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
212                         entry.txid.write(writer)?;
213                         writer.write_all(&byte_utils::be32_to_array(entry.height))?;
214                         match entry.event {
215                                 OnchainEvent::Claim { ref claim_request } => {
216                                         writer.write_all(&[0; 1])?;
217                                         claim_request.write(writer)?;
218                                 },
219                                 OnchainEvent::ContentiousOutpoint { ref package } => {
220                                         writer.write_all(&[1; 1])?;
221                                         package.write(writer)?;
222                                 }
223                         }
224                 }
225                 self.latest_height.write(writer)?;
226
227                 write_tlv_fields!(writer, {}, {});
228                 Ok(())
229         }
230 }
231
232 impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
233         fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
234                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
235
236                 let destination_script = Readable::read(reader)?;
237
238                 let holder_commitment = Readable::read(reader)?;
239                 let holder_htlc_sigs = Readable::read(reader)?;
240                 let prev_holder_commitment = Readable::read(reader)?;
241                 let prev_holder_htlc_sigs = Readable::read(reader)?;
242
243                 let channel_parameters = Readable::read(reader)?;
244
245                 let keys_len: u32 = Readable::read(reader)?;
246                 let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
247                 while keys_data.len() != keys_len as usize {
248                         // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
249                         let mut data = [0; 1024];
250                         let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
251                         reader.read_exact(read_slice)?;
252                         keys_data.extend_from_slice(read_slice);
253                 }
254                 let signer = keys_manager.read_chan_signer(&keys_data)?;
255
256                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
257                 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
258                 for _ in 0..pending_claim_requests_len {
259                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
260                 }
261
262                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
263                 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
264                 for _ in 0..claimable_outpoints_len {
265                         let outpoint = Readable::read(reader)?;
266                         let ancestor_claim_txid = Readable::read(reader)?;
267                         let height = Readable::read(reader)?;
268                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
269                 }
270                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
271                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
272                 for _ in 0..waiting_threshold_conf_len {
273                         let txid = Readable::read(reader)?;
274                         let height = Readable::read(reader)?;
275                         let event = match <u8 as Readable>::read(reader)? {
276                                 0 => {
277                                         let claim_request = Readable::read(reader)?;
278                                         OnchainEvent::Claim {
279                                                 claim_request
280                                         }
281                                 },
282                                 1 => {
283                                         let package = Readable::read(reader)?;
284                                         OnchainEvent::ContentiousOutpoint {
285                                                 package
286                                         }
287                                 }
288                                 _ => return Err(DecodeError::InvalidValue),
289                         };
290                         onchain_events_awaiting_threshold_conf.push(OnchainEventEntry { txid, height, event });
291                 }
292                 let latest_height = Readable::read(reader)?;
293
294                 read_tlv_fields!(reader, {}, {});
295
296                 let mut secp_ctx = Secp256k1::new();
297                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
298
299                 Ok(OnchainTxHandler {
300                         destination_script,
301                         holder_commitment,
302                         holder_htlc_sigs,
303                         prev_holder_commitment,
304                         prev_holder_htlc_sigs,
305                         signer,
306                         channel_transaction_parameters: channel_parameters,
307                         claimable_outpoints,
308                         pending_claim_requests,
309                         onchain_events_awaiting_threshold_conf,
310                         latest_height,
311                         secp_ctx,
312                 })
313         }
314 }
315
316 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
317         pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
318                 OnchainTxHandler {
319                         destination_script,
320                         holder_commitment,
321                         holder_htlc_sigs: None,
322                         prev_holder_commitment: None,
323                         prev_holder_htlc_sigs: None,
324                         signer,
325                         channel_transaction_parameters: channel_parameters,
326                         pending_claim_requests: HashMap::new(),
327                         claimable_outpoints: HashMap::new(),
328                         onchain_events_awaiting_threshold_conf: Vec::new(),
329                         latest_height: 0,
330
331                         secp_ctx,
332                 }
333         }
334
335         /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
336         /// output detection, we generate a first version of a claim tx and associate to it a height timer. A height timer is an absolute block
337         /// height than once reached we should generate a new bumped "version" of the claim tx to be sure than we safely claim outputs before
338         /// than our counterparty can do it too. If timelock expires soon, height timer is going to be scale down in consequence to increase
339         /// frequency of the bump and so increase our bets of success.
340         fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
341                 if timelock_expiration <= current_height + 3 {
342                         return current_height + 1
343                 } else if timelock_expiration - current_height <= 15 {
344                         return current_height + 3
345                 }
346                 current_height + 15
347         }
348
349         /// 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
350         /// (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.
351         /// Panics if there are signing errors, because signing operations in reaction to on-chain events
352         /// are not expected to fail, and if they do, we may lose funds.
353         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)>
354                 where F::Target: FeeEstimator,
355                                         L::Target: Logger,
356         {
357                 if cached_request.outpoints().len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
358
359                 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
360                 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
361                 let new_timer = Some(Self::get_height_timer(height, cached_request.timelock()));
362                 let amt = cached_request.package_amount();
363                 if cached_request.is_malleable() {
364                         let predicted_weight = cached_request.package_weight(&self.destination_script);
365                         if let Some((output_value, new_feerate)) = package::compute_output_value(predicted_weight, amt, cached_request.feerate(), fee_estimator, logger) {
366                                 assert!(new_feerate != 0);
367
368                                 let transaction = cached_request.finalize_package(self, output_value, self.destination_script.clone(), logger).unwrap();
369                                 log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
370                                 assert!(predicted_weight >= transaction.get_weight());
371                                 return Some((new_timer, new_feerate, transaction))
372                         }
373                 } else {
374                         // Note: Currently, amounts of holder outputs spending witnesses aren't used
375                         // as we can't malleate spending package to increase their feerate. This
376                         // should change with the remaining anchor output patchset.
377                         debug_assert!(amt == 0);
378                         if let Some(transaction) = cached_request.finalize_package(self, amt, self.destination_script.clone(), logger) {
379                                 return Some((None, 0, transaction));
380                         }
381                 }
382                 None
383         }
384
385         /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
386         /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
387         /// Formerly this was named `block_connected`, but it is now also used for claiming an HTLC output
388         /// if we receive a preimage after force-close.
389         pub(crate) fn update_claims_view<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], requests: Vec<PackageTemplate>, latest_height: Option<u32>, broadcaster: &B, fee_estimator: &F, logger: &L)
390                 where B::Target: BroadcasterInterface,
391                       F::Target: FeeEstimator,
392                                         L::Target: Logger,
393         {
394                 let height = match latest_height {
395                         Some(h) => h,
396                         None => self.latest_height,
397                 };
398                 log_trace!(logger, "Updating claims view at height {} with {} matched transactions and {} claim requests", height, txn_matched.len(), requests.len());
399                 let mut preprocessed_requests = Vec::with_capacity(requests.len());
400                 let mut aggregated_request = None;
401
402                 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
403                 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
404                 for req in requests {
405                         // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
406                         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 {
407                                 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), height + CLTV_SHARED_CLAIM_BUFFER);
408                                 if req.timelock() <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
409                                         // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
410                                         preprocessed_requests.push(req);
411                                 } else if aggregated_request.is_none() {
412                                         aggregated_request = Some(req);
413                                 } else {
414                                         aggregated_request.as_mut().unwrap().merge_package(req);
415                                 }
416                         }
417                 }
418                 if let Some(req) = aggregated_request {
419                         preprocessed_requests.push(req);
420                 }
421
422                 // Generate claim transactions and track them to bump if necessary at
423                 // height timer expiration (i.e in how many blocks we're going to take action).
424                 for mut req in preprocessed_requests {
425                         if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(height, &req, &*fee_estimator, &*logger) {
426                                 req.set_timer(new_timer);
427                                 req.set_feerate(new_feerate);
428                                 let txid = tx.txid();
429                                 for k in req.outpoints() {
430                                         log_trace!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
431                                         self.claimable_outpoints.insert(k.clone(), (txid, height));
432                                 }
433                                 self.pending_claim_requests.insert(txid, req);
434                                 log_trace!(logger, "Broadcasting onchain {}", log_tx!(tx));
435                                 broadcaster.broadcast_transaction(&tx);
436                         }
437                 }
438
439                 let mut bump_candidates = HashMap::new();
440                 for tx in txn_matched {
441                         // Scan all input to verify is one of the outpoint spent is of interest for us
442                         let mut claimed_outputs_material = Vec::new();
443                         for inp in &tx.input {
444                                 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
445                                         // If outpoint has claim request pending on it...
446                                         if let Some(request) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
447                                                 //... we need to verify equality between transaction outpoints and claim request
448                                                 // outpoints to know if transaction is the original claim or a bumped one issued
449                                                 // by us.
450                                                 let mut set_equality = true;
451                                                 if request.outpoints().len() != tx.input.len() {
452                                                         set_equality = false;
453                                                 } else {
454                                                         for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
455                                                                 if **claim_inp != tx_inp.previous_output {
456                                                                         set_equality = false;
457                                                                 }
458                                                         }
459                                                 }
460
461                                                 macro_rules! clean_claim_request_after_safety_delay {
462                                                         () => {
463                                                                 let entry = OnchainEventEntry {
464                                                                         txid: tx.txid(),
465                                                                         height,
466                                                                         event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
467                                                                 };
468                                                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
469                                                                         self.onchain_events_awaiting_threshold_conf.push(entry);
470                                                                 }
471                                                         }
472                                                 }
473
474                                                 // If this is our transaction (or our counterparty spent all the outputs
475                                                 // before we could anyway with same inputs order than us), wait for
476                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
477                                                 if set_equality {
478                                                         clean_claim_request_after_safety_delay!();
479                                                 } else { // If false, generate new claim request with update outpoint set
480                                                         let mut at_least_one_drop = false;
481                                                         for input in tx.input.iter() {
482                                                                 if let Some(package) = request.split_package(&input.previous_output) {
483                                                                         claimed_outputs_material.push(package);
484                                                                         at_least_one_drop = true;
485                                                                 }
486                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
487                                                                 if request.outpoints().is_empty() {
488                                                                         clean_claim_request_after_safety_delay!();
489                                                                 }
490                                                         }
491                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
492                                                         if at_least_one_drop {
493                                                                 bump_candidates.insert(first_claim_txid_height.0.clone(), request.clone());
494                                                         }
495                                                 }
496                                                 break; //No need to iterate further, either tx is our or their
497                                         } else {
498                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
499                                         }
500                                 }
501                         }
502                         for package in claimed_outputs_material.drain(..) {
503                                 let entry = OnchainEventEntry {
504                                         txid: tx.txid(),
505                                         height,
506                                         event: OnchainEvent::ContentiousOutpoint { package },
507                                 };
508                                 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
509                                         self.onchain_events_awaiting_threshold_conf.push(entry);
510                                 }
511                         }
512                 }
513
514                 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
515                 let onchain_events_awaiting_threshold_conf =
516                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
517                 for entry in onchain_events_awaiting_threshold_conf {
518                         if entry.has_reached_confirmation_threshold(height) {
519                                 match entry.event {
520                                         OnchainEvent::Claim { claim_request } => {
521                                                 // We may remove a whole set of claim outpoints here, as these one may have
522                                                 // been aggregated in a single tx and claimed so atomically
523                                                 if let Some(request) = self.pending_claim_requests.remove(&claim_request) {
524                                                         for outpoint in request.outpoints() {
525                                                                 self.claimable_outpoints.remove(&outpoint);
526                                                         }
527                                                 }
528                                         },
529                                         OnchainEvent::ContentiousOutpoint { package } => {
530                                                 self.claimable_outpoints.remove(&package.outpoints()[0]);
531                                         }
532                                 }
533                         } else {
534                                 self.onchain_events_awaiting_threshold_conf.push(entry);
535                         }
536                 }
537
538                 // Check if any pending claim request must be rescheduled
539                 for (first_claim_txid, ref request) in self.pending_claim_requests.iter() {
540                         if let Some(h) = request.timer() {
541                                 if height >= h {
542                                         bump_candidates.insert(*first_claim_txid, (*request).clone());
543                                 }
544                         }
545                 }
546
547                 // Build, bump and rebroadcast tx accordingly
548                 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
549                 for (first_claim_txid, request) in bump_candidates.iter() {
550                         if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &request, &*fee_estimator, &*logger) {
551                                 log_trace!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
552                                 broadcaster.broadcast_transaction(&bump_tx);
553                                 if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
554                                         request.set_timer(new_timer);
555                                         request.set_feerate(new_feerate);
556                                 }
557                         }
558                 }
559         }
560
561         pub(crate) fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
562                 &mut self,
563                 txid: &Txid,
564                 broadcaster: B,
565                 fee_estimator: F,
566                 logger: L,
567         ) where
568                 B::Target: BroadcasterInterface,
569                 F::Target: FeeEstimator,
570                 L::Target: Logger,
571         {
572                 let mut height = None;
573                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
574                         if entry.txid == *txid {
575                                 height = Some(entry.height);
576                                 break;
577                         }
578                 }
579
580                 if let Some(height) = height {
581                         self.block_disconnected(height, broadcaster, fee_estimator, logger);
582                 }
583         }
584
585         pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L)
586                 where B::Target: BroadcasterInterface,
587                       F::Target: FeeEstimator,
588                                         L::Target: Logger,
589         {
590                 let mut bump_candidates = HashMap::new();
591                 let onchain_events_awaiting_threshold_conf =
592                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
593                 for entry in onchain_events_awaiting_threshold_conf {
594                         if entry.height >= height {
595                                 //- our claim tx on a commitment tx output
596                                 //- resurect outpoint back in its claimable set and regenerate tx
597                                 match entry.event {
598                                         OnchainEvent::ContentiousOutpoint { package } => {
599                                                 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&package.outpoints()[0]) {
600                                                         if let Some(request) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
601                                                                 request.merge_package(package);
602                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
603                                                                 // resurrected only one bump claim tx is going to be broadcast
604                                                                 bump_candidates.insert(ancestor_claimable_txid.clone(), request.clone());
605                                                         }
606                                                 }
607                                         },
608                                         _ => {},
609                                 }
610                         } else {
611                                 self.onchain_events_awaiting_threshold_conf.push(entry);
612                         }
613                 }
614                 for (_, request) in bump_candidates.iter_mut() {
615                         if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &request, &&*fee_estimator, &&*logger) {
616                                 request.set_timer(new_timer);
617                                 request.set_feerate(new_feerate);
618                                 log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
619                                 broadcaster.broadcast_transaction(&bump_tx);
620                         }
621                 }
622                 for (ancestor_claim_txid, request) in bump_candidates.drain() {
623                         self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
624                 }
625                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
626                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
627                 let mut remove_request = Vec::new();
628                 self.claimable_outpoints.retain(|_, ref v|
629                         if v.1 >= height {
630                         remove_request.push(v.0.clone());
631                         false
632                         } else { true });
633                 for req in remove_request {
634                         self.pending_claim_requests.remove(&req);
635                 }
636         }
637
638         pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
639                 let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
640                         .iter()
641                         .map(|entry| entry.txid)
642                         .collect();
643                 txids.sort_unstable();
644                 txids.dedup();
645                 txids
646         }
647
648         pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
649                 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
650                 self.holder_htlc_sigs = None;
651         }
652
653         // Normally holder HTLCs are signed at the same time as the holder commitment tx.  However,
654         // in some configurations, the holder commitment tx has been signed and broadcast by a
655         // ChannelMonitor replica, so we handle that case here.
656         fn sign_latest_holder_htlcs(&mut self) {
657                 if self.holder_htlc_sigs.is_none() {
658                         let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
659                         self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
660                 }
661         }
662
663         // Normally only the latest commitment tx and HTLCs need to be signed.  However, in some
664         // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
665         // broadcast the previous one before we sync with it.  We handle that case here.
666         fn sign_prev_holder_htlcs(&mut self) {
667                 if self.prev_holder_htlc_sigs.is_none() {
668                         if let Some(ref holder_commitment) = self.prev_holder_commitment {
669                                 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
670                                 self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
671                         }
672                 }
673         }
674
675         fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
676                 let mut ret = Vec::new();
677                 for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
678                         let tx_idx = htlc.transaction_output_index.unwrap();
679                         if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
680                         ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
681                 }
682                 ret
683         }
684
685         //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
686         // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
687         // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
688         // to monitor before.
689         pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
690                 let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
691                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
692                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
693         }
694
695         #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
696         pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
697                 let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
698                 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
699                 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
700         }
701
702         pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
703                 let mut htlc_tx = None;
704                 let commitment_txid = self.holder_commitment.trust().txid();
705                 // Check if the HTLC spends from the current holder commitment
706                 if commitment_txid == outp.txid {
707                         self.sign_latest_holder_htlcs();
708                         if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
709                                 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
710                                 let trusted_tx = self.holder_commitment.trust();
711                                 let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
712                                 htlc_tx = Some(trusted_tx
713                                         .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
714                         }
715                 }
716                 // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
717                 if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
718                         let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
719                         if commitment_txid == outp.txid {
720                                 self.sign_prev_holder_htlcs();
721                                 if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
722                                         let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
723                                         let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
724                                         let trusted_tx = holder_commitment.trust();
725                                         let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
726                                         htlc_tx = Some(trusted_tx
727                                                 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
728                                 }
729                         }
730                 }
731                 htlc_tx
732         }
733
734         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
735         pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
736                 let latest_had_sigs = self.holder_htlc_sigs.is_some();
737                 let prev_had_sigs = self.prev_holder_htlc_sigs.is_some();
738                 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
739                 if !latest_had_sigs {
740                         self.holder_htlc_sigs = None;
741                 }
742                 if !prev_had_sigs {
743                         self.prev_holder_htlc_sigs = None;
744                 }
745                 ret
746         }
747 }