Remove BlockNotifier
[rust-lightning] / lightning / src / ln / channelmonitor.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 monitor for on-chain transactions and create the relevant claim responses lives
11 //! here.
12 //!
13 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
14 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15 //! be made in responding to certain messages, see [`chain::Watch`] for more.
16 //!
17 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20 //! security-domain-separated system design, you should consider having multiple paths for
21 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
22 //!
23 //! [`chain::Watch`]: ../../chain/trait.Watch.html
24
25 use bitcoin::blockdata::block::BlockHeader;
26 use bitcoin::blockdata::transaction::{TxOut,Transaction};
27 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
28 use bitcoin::blockdata::script::{Script, Builder};
29 use bitcoin::blockdata::opcodes;
30 use bitcoin::consensus::encode;
31
32 use bitcoin::hashes::Hash;
33 use bitcoin::hashes::sha256::Hash as Sha256;
34 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
35
36 use bitcoin::secp256k1::{Secp256k1,Signature};
37 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
38 use bitcoin::secp256k1;
39
40 use ln::msgs::DecodeError;
41 use ln::chan_utils;
42 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, HTLCType};
43 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
44 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
45 use chain;
46 use chain::chaininterface::{ChainListener, ChainWatchedUtil, BroadcasterInterface, FeeEstimator};
47 use chain::transaction::OutPoint;
48 use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
49 use util::logger::Logger;
50 use util::ser::{Readable, MaybeReadable, Writer, Writeable, U48};
51 use util::{byte_utils, events};
52 use util::events::Event;
53
54 use std::collections::{HashMap, HashSet, hash_map};
55 use std::sync::Mutex;
56 use std::{cmp, mem};
57 use std::ops::Deref;
58 use std::io::Error;
59
60 /// An update generated by the underlying Channel itself which contains some new information the
61 /// ChannelMonitor should be made aware of.
62 #[cfg_attr(test, derive(PartialEq))]
63 #[derive(Clone)]
64 #[must_use]
65 pub struct ChannelMonitorUpdate {
66         pub(super) updates: Vec<ChannelMonitorUpdateStep>,
67         /// The sequence number of this update. Updates *must* be replayed in-order according to this
68         /// sequence number (and updates may panic if they are not). The update_id values are strictly
69         /// increasing and increase by one for each new update.
70         ///
71         /// This sequence number is also used to track up to which points updates which returned
72         /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
73         /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
74         pub update_id: u64,
75 }
76
77 impl Writeable for ChannelMonitorUpdate {
78         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
79                 self.update_id.write(w)?;
80                 (self.updates.len() as u64).write(w)?;
81                 for update_step in self.updates.iter() {
82                         update_step.write(w)?;
83                 }
84                 Ok(())
85         }
86 }
87 impl Readable for ChannelMonitorUpdate {
88         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
89                 let update_id: u64 = Readable::read(r)?;
90                 let len: u64 = Readable::read(r)?;
91                 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
92                 for _ in 0..len {
93                         updates.push(Readable::read(r)?);
94                 }
95                 Ok(Self { update_id, updates })
96         }
97 }
98
99 /// An error enum representing a failure to persist a channel monitor update.
100 #[derive(Clone)]
101 pub enum ChannelMonitorUpdateErr {
102         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
103         /// our state failed, but is expected to succeed at some point in the future).
104         ///
105         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
106         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
107         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
108         /// restore the channel to an operational state.
109         ///
110         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
111         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
112         /// writing out the latest ChannelManager state.
113         ///
114         /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
115         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
116         /// to claim it on this channel) and those updates must be applied wherever they can be. At
117         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
118         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
119         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
120         /// been "frozen".
121         ///
122         /// Note that even if updates made after TemporaryFailure succeed you must still call
123         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
124         /// operation.
125         ///
126         /// Note that the update being processed here will not be replayed for you when you call
127         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
128         /// with the persisted ChannelMonitor on your own local disk prior to returning a
129         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
130         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
131         /// reload-time.
132         ///
133         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
134         /// remote location (with local copies persisted immediately), it is anticipated that all
135         /// updates will return TemporaryFailure until the remote copies could be updated.
136         TemporaryFailure,
137         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
138         /// different watchtower and cannot update with all watchtowers that were previously informed
139         /// of this channel).
140         ///
141         /// At reception of this error, ChannelManager will force-close the channel and return at
142         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
143         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
144         /// update must be rejected.
145         ///
146         /// This failure may also signal a failure to update the local persisted copy of one of
147         /// the channel monitor instance.
148         ///
149         /// Note that even when you fail a holder commitment transaction update, you must store the
150         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
151         /// broadcasts it (e.g distributed channel-monitor deployment)
152         ///
153         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
154         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
155         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
156         /// lagging behind on block processing.
157         PermanentFailure,
158 }
159
160 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
161 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
162 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
163 /// corrupted.
164 /// Contains a human-readable error message.
165 #[derive(Debug)]
166 pub struct MonitorUpdateError(pub &'static str);
167
168 /// An event to be processed by the ChannelManager.
169 #[derive(PartialEq)]
170 pub enum MonitorEvent {
171         /// A monitor event containing an HTLCUpdate.
172         HTLCEvent(HTLCUpdate),
173
174         /// A monitor event that the Channel's commitment transaction was broadcasted.
175         CommitmentTxBroadcasted(OutPoint),
176 }
177
178 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
179 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
180 /// preimage claim backward will lead to loss of funds.
181 ///
182 /// [`chain::Watch`]: ../../chain/trait.Watch.html
183 #[derive(Clone, PartialEq)]
184 pub struct HTLCUpdate {
185         pub(super) payment_hash: PaymentHash,
186         pub(super) payment_preimage: Option<PaymentPreimage>,
187         pub(super) source: HTLCSource
188 }
189 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
190
191 /// An implementation of a [`chain::Watch`] and ChainListener.
192 ///
193 /// May be used in conjunction with [`ChannelManager`] to monitor channels locally or used
194 /// independently to monitor channels remotely.
195 ///
196 /// [`chain::Watch`]: ../../chain/trait.Watch.html
197 /// [`ChannelManager`]: ../channelmanager/struct.ChannelManager.html
198 pub struct ChainMonitor<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref>
199         where T::Target: BroadcasterInterface,
200         F::Target: FeeEstimator,
201         L::Target: Logger,
202 {
203         /// The monitors
204         pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
205         watch_events: Mutex<WatchEventQueue>,
206         broadcaster: T,
207         logger: L,
208         fee_estimator: F
209 }
210
211 struct WatchEventQueue {
212         watched: ChainWatchedUtil,
213         events: Vec<chain::WatchEvent>,
214 }
215
216 impl WatchEventQueue {
217         fn new() -> Self {
218                 Self {
219                         watched: ChainWatchedUtil::new(),
220                         events: Vec::new(),
221                 }
222         }
223
224         fn watch_tx(&mut self, txid: &Txid, script_pubkey: &Script) {
225                 if self.watched.register_tx(txid, script_pubkey) {
226                         self.events.push(chain::WatchEvent::WatchTransaction {
227                                 txid: *txid,
228                                 script_pubkey: script_pubkey.clone()
229                         });
230                 }
231         }
232
233         fn watch_output(&mut self, outpoint: (&Txid, usize), script_pubkey: &Script) {
234                 let (txid, index) = outpoint;
235                 if self.watched.register_outpoint((*txid, index as u32), script_pubkey) {
236                         self.events.push(chain::WatchEvent::WatchOutput {
237                                 outpoint: OutPoint {
238                                         txid: *txid,
239                                         index: index as u16,
240                                 },
241                                 script_pubkey: script_pubkey.clone(),
242                         });
243                 }
244         }
245
246         fn dequeue_events(&mut self) -> Vec<chain::WatchEvent> {
247                 let mut pending_events = Vec::with_capacity(self.events.len());
248                 pending_events.append(&mut self.events);
249                 pending_events
250         }
251
252         fn filter_block<'a>(&self, txdata: &[(usize, &'a Transaction)]) -> Vec<(usize, &'a Transaction)> {
253                 let mut matched_txids = HashSet::new();
254                 txdata.iter().filter(|&&(_, tx)| {
255                         // A tx matches the filter if it either matches the filter directly (via does_match_tx)
256                         // or if it is a descendant of another matched transaction within the same block.
257                         let mut matched = self.watched.does_match_tx(tx);
258                         for input in tx.input.iter() {
259                                 if matched || matched_txids.contains(&input.previous_output.txid) {
260                                         matched = true;
261                                         break;
262                                 }
263                         }
264                         if matched {
265                                 matched_txids.insert(tx.txid());
266                         }
267                         matched
268                 }).map(|e| *e).collect()
269         }
270 }
271
272 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
273         ChainListener for ChainMonitor<ChanSigner, T, F, L>
274         where T::Target: BroadcasterInterface,
275               F::Target: FeeEstimator,
276               L::Target: Logger,
277 {
278         fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) {
279                 let mut watch_events = self.watch_events.lock().unwrap();
280                 let matched_txn = watch_events.filter_block(txdata);
281                 {
282                         let mut monitors = self.monitors.lock().unwrap();
283                         for monitor in monitors.values_mut() {
284                                 let txn_outputs = monitor.block_connected(header, &matched_txn, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
285
286                                 for (ref txid, ref outputs) in txn_outputs {
287                                         for (idx, output) in outputs.iter().enumerate() {
288                                                 watch_events.watch_output((txid, idx), &output.script_pubkey);
289                                         }
290                                 }
291                         }
292                 }
293         }
294
295         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
296                 let mut monitors = self.monitors.lock().unwrap();
297                 for monitor in monitors.values_mut() {
298                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
299                 }
300         }
301 }
302
303 impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, T, F, L>
304         where T::Target: BroadcasterInterface,
305               F::Target: FeeEstimator,
306               L::Target: Logger,
307 {
308         /// Creates a new object which can be used to monitor several channels given the chain
309         /// interface with which to register to receive notifications.
310         pub fn new(broadcaster: T, logger: L, feeest: F) -> Self {
311                 Self {
312                         monitors: Mutex::new(HashMap::new()),
313                         watch_events: Mutex::new(WatchEventQueue::new()),
314                         broadcaster,
315                         logger,
316                         fee_estimator: feeest,
317                 }
318         }
319
320         /// Adds the monitor that watches the channel referred to by the given outpoint.
321         fn add_monitor(&self, outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
322                 let mut watch_events = self.watch_events.lock().unwrap();
323                 let mut monitors = self.monitors.lock().unwrap();
324                 let entry = match monitors.entry(outpoint) {
325                         hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given outpoint is already present")),
326                         hash_map::Entry::Vacant(e) => e,
327                 };
328                 {
329                         let funding_txo = monitor.get_funding_txo();
330                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
331                         watch_events.watch_tx(&funding_txo.0.txid, &funding_txo.1);
332                         watch_events.watch_output((&funding_txo.0.txid, funding_txo.0.index as usize), &funding_txo.1);
333                         for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
334                                 for (idx, script) in outputs.iter().enumerate() {
335                                         watch_events.watch_output((txid, idx), script);
336                                 }
337                         }
338                 }
339                 entry.insert(monitor);
340                 Ok(())
341         }
342
343         /// Updates the monitor that watches the channel referred to by the given outpoint.
344         fn update_monitor(&self, outpoint: OutPoint, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
345                 let mut monitors = self.monitors.lock().unwrap();
346                 match monitors.get_mut(&outpoint) {
347                         Some(orig_monitor) => {
348                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
349                                 orig_monitor.update_monitor(update, &self.broadcaster, &self.logger)
350                         },
351                         None => Err(MonitorUpdateError("No such monitor registered"))
352                 }
353         }
354 }
355
356 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, T, F, L>
357         where T::Target: BroadcasterInterface,
358               F::Target: FeeEstimator,
359               L::Target: Logger,
360 {
361         type Keys = ChanSigner;
362
363         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
364                 match self.add_monitor(funding_txo, monitor) {
365                         Ok(_) => Ok(()),
366                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
367                 }
368         }
369
370         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
371                 match self.update_monitor(funding_txo, update) {
372                         Ok(_) => Ok(()),
373                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
374                 }
375         }
376
377         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
378                 let mut pending_monitor_events = Vec::new();
379                 for chan in self.monitors.lock().unwrap().values_mut() {
380                         pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
381                 }
382                 pending_monitor_events
383         }
384 }
385
386 impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<ChanSigner, T, F, L>
387         where T::Target: BroadcasterInterface,
388               F::Target: FeeEstimator,
389               L::Target: Logger,
390 {
391         fn get_and_clear_pending_events(&self) -> Vec<Event> {
392                 let mut pending_events = Vec::new();
393                 for chan in self.monitors.lock().unwrap().values_mut() {
394                         pending_events.append(&mut chan.get_and_clear_pending_events());
395                 }
396                 pending_events
397         }
398 }
399
400 impl<ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref> chain::WatchEventProvider for ChainMonitor<ChanSigner, T, F, L>
401         where T::Target: BroadcasterInterface,
402               F::Target: FeeEstimator,
403               L::Target: Logger,
404 {
405         fn release_pending_watch_events(&self) -> Vec<chain::WatchEvent> {
406                 self.watch_events.lock().unwrap().dequeue_events()
407         }
408 }
409
410 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
411 /// instead claiming it in its own individual transaction.
412 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
413 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
414 /// HTLC-Success transaction.
415 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
416 /// transaction confirmed (and we use it in a few more, equivalent, places).
417 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
418 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
419 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
420 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
421 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
422 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
423 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
424 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
425 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
426 /// accurate block height.
427 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
428 /// with at worst this delay, so we are not only using this value as a mercy for them but also
429 /// us as a safeguard to delay with enough time.
430 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
431 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
432 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
433 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
434 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
435 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
436 /// keeping bumping another claim tx to solve the outpoint.
437 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
438 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
439 /// refuse to accept a new HTLC.
440 ///
441 /// This is used for a few separate purposes:
442 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
443 ///    waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
444 ///    fail this HTLC,
445 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
446 ///    condition with the above), we will fail this HTLC without telling the user we received it,
447 /// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
448 ///    that HTLC expires within this many blocks, we will simply fail the HTLC instead.
449 ///
450 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
451 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
452 ///
453 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
454 /// in a race condition between the user connecting a block (which would fail it) and the user
455 /// providing us the preimage (which would claim it).
456 ///
457 /// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
458 /// end up force-closing the channel on us to claim it.
459 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
460
461 #[derive(Clone, PartialEq)]
462 struct HolderSignedTx {
463         /// txid of the transaction in tx, just used to make comparison faster
464         txid: Txid,
465         revocation_key: PublicKey,
466         a_htlc_key: PublicKey,
467         b_htlc_key: PublicKey,
468         delayed_payment_key: PublicKey,
469         per_commitment_point: PublicKey,
470         feerate_per_kw: u32,
471         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
472 }
473
474 /// We use this to track counterparty commitment transactions and htlcs outputs and
475 /// use it to generate any justice or 2nd-stage preimage/timeout transactions.
476 #[derive(PartialEq)]
477 struct CounterpartyCommitmentTransaction {
478         counterparty_delayed_payment_base_key: PublicKey,
479         counterparty_htlc_base_key: PublicKey,
480         on_counterparty_tx_csv: u16,
481         per_htlc: HashMap<Txid, Vec<HTLCOutputInCommitment>>
482 }
483
484 impl Writeable for CounterpartyCommitmentTransaction {
485         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
486                 self.counterparty_delayed_payment_base_key.write(w)?;
487                 self.counterparty_htlc_base_key.write(w)?;
488                 w.write_all(&byte_utils::be16_to_array(self.on_counterparty_tx_csv))?;
489                 w.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
490                 for (ref txid, ref htlcs) in self.per_htlc.iter() {
491                         w.write_all(&txid[..])?;
492                         w.write_all(&byte_utils::be64_to_array(htlcs.len() as u64))?;
493                         for &ref htlc in htlcs.iter() {
494                                 htlc.write(w)?;
495                         }
496                 }
497                 Ok(())
498         }
499 }
500 impl Readable for CounterpartyCommitmentTransaction {
501         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
502                 let counterparty_commitment_transaction = {
503                         let counterparty_delayed_payment_base_key = Readable::read(r)?;
504                         let counterparty_htlc_base_key = Readable::read(r)?;
505                         let on_counterparty_tx_csv: u16 = Readable::read(r)?;
506                         let per_htlc_len: u64 = Readable::read(r)?;
507                         let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64));
508                         for _  in 0..per_htlc_len {
509                                 let txid: Txid = Readable::read(r)?;
510                                 let htlcs_count: u64 = Readable::read(r)?;
511                                 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
512                                 for _ in 0..htlcs_count {
513                                         let htlc = Readable::read(r)?;
514                                         htlcs.push(htlc);
515                                 }
516                                 if let Some(_) = per_htlc.insert(txid, htlcs) {
517                                         return Err(DecodeError::InvalidValue);
518                                 }
519                         }
520                         CounterpartyCommitmentTransaction {
521                                 counterparty_delayed_payment_base_key,
522                                 counterparty_htlc_base_key,
523                                 on_counterparty_tx_csv,
524                                 per_htlc,
525                         }
526                 };
527                 Ok(counterparty_commitment_transaction)
528         }
529 }
530
531 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
532 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
533 /// a new bumped one in case of lenghty confirmation delay
534 #[derive(Clone, PartialEq)]
535 pub(crate) enum InputMaterial {
536         Revoked {
537                 per_commitment_point: PublicKey,
538                 counterparty_delayed_payment_base_key: PublicKey,
539                 counterparty_htlc_base_key: PublicKey,
540                 per_commitment_key: SecretKey,
541                 input_descriptor: InputDescriptors,
542                 amount: u64,
543                 htlc: Option<HTLCOutputInCommitment>,
544                 on_counterparty_tx_csv: u16,
545         },
546         CounterpartyHTLC {
547                 per_commitment_point: PublicKey,
548                 counterparty_delayed_payment_base_key: PublicKey,
549                 counterparty_htlc_base_key: PublicKey,
550                 preimage: Option<PaymentPreimage>,
551                 htlc: HTLCOutputInCommitment
552         },
553         HolderHTLC {
554                 preimage: Option<PaymentPreimage>,
555                 amount: u64,
556         },
557         Funding {
558                 funding_redeemscript: Script,
559         }
560 }
561
562 impl Writeable for InputMaterial  {
563         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
564                 match self {
565                         &InputMaterial::Revoked { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_counterparty_tx_csv} => {
566                                 writer.write_all(&[0; 1])?;
567                                 per_commitment_point.write(writer)?;
568                                 counterparty_delayed_payment_base_key.write(writer)?;
569                                 counterparty_htlc_base_key.write(writer)?;
570                                 writer.write_all(&per_commitment_key[..])?;
571                                 input_descriptor.write(writer)?;
572                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
573                                 htlc.write(writer)?;
574                                 on_counterparty_tx_csv.write(writer)?;
575                         },
576                         &InputMaterial::CounterpartyHTLC { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref preimage, ref htlc} => {
577                                 writer.write_all(&[1; 1])?;
578                                 per_commitment_point.write(writer)?;
579                                 counterparty_delayed_payment_base_key.write(writer)?;
580                                 counterparty_htlc_base_key.write(writer)?;
581                                 preimage.write(writer)?;
582                                 htlc.write(writer)?;
583                         },
584                         &InputMaterial::HolderHTLC { ref preimage, ref amount } => {
585                                 writer.write_all(&[2; 1])?;
586                                 preimage.write(writer)?;
587                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
588                         },
589                         &InputMaterial::Funding { ref funding_redeemscript } => {
590                                 writer.write_all(&[3; 1])?;
591                                 funding_redeemscript.write(writer)?;
592                         }
593                 }
594                 Ok(())
595         }
596 }
597
598 impl Readable for InputMaterial {
599         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
600                 let input_material = match <u8 as Readable>::read(reader)? {
601                         0 => {
602                                 let per_commitment_point = Readable::read(reader)?;
603                                 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
604                                 let counterparty_htlc_base_key = Readable::read(reader)?;
605                                 let per_commitment_key = Readable::read(reader)?;
606                                 let input_descriptor = Readable::read(reader)?;
607                                 let amount = Readable::read(reader)?;
608                                 let htlc = Readable::read(reader)?;
609                                 let on_counterparty_tx_csv = Readable::read(reader)?;
610                                 InputMaterial::Revoked {
611                                         per_commitment_point,
612                                         counterparty_delayed_payment_base_key,
613                                         counterparty_htlc_base_key,
614                                         per_commitment_key,
615                                         input_descriptor,
616                                         amount,
617                                         htlc,
618                                         on_counterparty_tx_csv
619                                 }
620                         },
621                         1 => {
622                                 let per_commitment_point = Readable::read(reader)?;
623                                 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
624                                 let counterparty_htlc_base_key = Readable::read(reader)?;
625                                 let preimage = Readable::read(reader)?;
626                                 let htlc = Readable::read(reader)?;
627                                 InputMaterial::CounterpartyHTLC {
628                                         per_commitment_point,
629                                         counterparty_delayed_payment_base_key,
630                                         counterparty_htlc_base_key,
631                                         preimage,
632                                         htlc
633                                 }
634                         },
635                         2 => {
636                                 let preimage = Readable::read(reader)?;
637                                 let amount = Readable::read(reader)?;
638                                 InputMaterial::HolderHTLC {
639                                         preimage,
640                                         amount,
641                                 }
642                         },
643                         3 => {
644                                 InputMaterial::Funding {
645                                         funding_redeemscript: Readable::read(reader)?,
646                                 }
647                         }
648                         _ => return Err(DecodeError::InvalidValue),
649                 };
650                 Ok(input_material)
651         }
652 }
653
654 /// ClaimRequest is a descriptor structure to communicate between detection
655 /// and reaction module. They are generated by ChannelMonitor while parsing
656 /// onchain txn leaked from a channel and handed over to OnchainTxHandler which
657 /// is responsible for opportunistic aggregation, selecting and enforcing
658 /// bumping logic, building and signing transactions.
659 pub(crate) struct ClaimRequest {
660         // Block height before which claiming is exclusive to one party,
661         // after reaching it, claiming may be contentious.
662         pub(crate) absolute_timelock: u32,
663         // Timeout tx must have nLocktime set which means aggregating multiple
664         // ones must take the higher nLocktime among them to satisfy all of them.
665         // Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
666         // of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
667         // Do simplify we mark them as non-aggregable.
668         pub(crate) aggregable: bool,
669         // Basic bitcoin outpoint (txid, vout)
670         pub(crate) outpoint: BitcoinOutPoint,
671         // Following outpoint type, set of data needed to generate transaction digest
672         // and satisfy witness program.
673         pub(crate) witness_data: InputMaterial
674 }
675
676 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
677 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
678 #[derive(Clone, PartialEq)]
679 enum OnchainEvent {
680         /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
681         /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
682         /// only win from it, so it's never an OnchainEvent
683         HTLCUpdate {
684                 htlc_update: (HTLCSource, PaymentHash),
685         },
686         MaturingOutput {
687                 descriptor: SpendableOutputDescriptor,
688         },
689 }
690
691 const SERIALIZATION_VERSION: u8 = 1;
692 const MIN_SERIALIZATION_VERSION: u8 = 1;
693
694 #[cfg_attr(test, derive(PartialEq))]
695 #[derive(Clone)]
696 pub(super) enum ChannelMonitorUpdateStep {
697         LatestHolderCommitmentTXInfo {
698                 commitment_tx: HolderCommitmentTransaction,
699                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
700         },
701         LatestCounterpartyCommitmentTXInfo {
702                 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
703                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
704                 commitment_number: u64,
705                 their_revocation_point: PublicKey,
706         },
707         PaymentPreimage {
708                 payment_preimage: PaymentPreimage,
709         },
710         CommitmentSecret {
711                 idx: u64,
712                 secret: [u8; 32],
713         },
714         /// Used to indicate that the no future updates will occur, and likely that the latest holder
715         /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
716         ChannelForceClosed {
717                 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
718                 /// think we've fallen behind!
719                 should_broadcast: bool,
720         },
721 }
722
723 impl Writeable for ChannelMonitorUpdateStep {
724         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
725                 match self {
726                         &ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { ref commitment_tx, ref htlc_outputs } => {
727                                 0u8.write(w)?;
728                                 commitment_tx.write(w)?;
729                                 (htlc_outputs.len() as u64).write(w)?;
730                                 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
731                                         output.write(w)?;
732                                         signature.write(w)?;
733                                         source.write(w)?;
734                                 }
735                         }
736                         &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
737                                 1u8.write(w)?;
738                                 unsigned_commitment_tx.write(w)?;
739                                 commitment_number.write(w)?;
740                                 their_revocation_point.write(w)?;
741                                 (htlc_outputs.len() as u64).write(w)?;
742                                 for &(ref output, ref source) in htlc_outputs.iter() {
743                                         output.write(w)?;
744                                         source.as_ref().map(|b| b.as_ref()).write(w)?;
745                                 }
746                         },
747                         &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
748                                 2u8.write(w)?;
749                                 payment_preimage.write(w)?;
750                         },
751                         &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
752                                 3u8.write(w)?;
753                                 idx.write(w)?;
754                                 secret.write(w)?;
755                         },
756                         &ChannelMonitorUpdateStep::ChannelForceClosed { ref should_broadcast } => {
757                                 4u8.write(w)?;
758                                 should_broadcast.write(w)?;
759                         },
760                 }
761                 Ok(())
762         }
763 }
764 impl Readable for ChannelMonitorUpdateStep {
765         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
766                 match Readable::read(r)? {
767                         0u8 => {
768                                 Ok(ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
769                                         commitment_tx: Readable::read(r)?,
770                                         htlc_outputs: {
771                                                 let len: u64 = Readable::read(r)?;
772                                                 let mut res = Vec::new();
773                                                 for _ in 0..len {
774                                                         res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
775                                                 }
776                                                 res
777                                         },
778                                 })
779                         },
780                         1u8 => {
781                                 Ok(ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
782                                         unsigned_commitment_tx: Readable::read(r)?,
783                                         commitment_number: Readable::read(r)?,
784                                         their_revocation_point: Readable::read(r)?,
785                                         htlc_outputs: {
786                                                 let len: u64 = Readable::read(r)?;
787                                                 let mut res = Vec::new();
788                                                 for _ in 0..len {
789                                                         res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
790                                                 }
791                                                 res
792                                         },
793                                 })
794                         },
795                         2u8 => {
796                                 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
797                                         payment_preimage: Readable::read(r)?,
798                                 })
799                         },
800                         3u8 => {
801                                 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
802                                         idx: Readable::read(r)?,
803                                         secret: Readable::read(r)?,
804                                 })
805                         },
806                         4u8 => {
807                                 Ok(ChannelMonitorUpdateStep::ChannelForceClosed {
808                                         should_broadcast: Readable::read(r)?
809                                 })
810                         },
811                         _ => Err(DecodeError::InvalidValue),
812                 }
813         }
814 }
815
816 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
817 /// on-chain transactions to ensure no loss of funds occurs.
818 ///
819 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
820 /// information and are actively monitoring the chain.
821 ///
822 /// Pending Events or updated HTLCs which have not yet been read out by
823 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
824 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
825 /// gotten are fully handled before re-serializing the new state.
826 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
827         latest_update_id: u64,
828         commitment_transaction_number_obscure_factor: u64,
829
830         destination_script: Script,
831         broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
832         counterparty_payment_script: Script,
833         shutdown_script: Script,
834
835         keys: ChanSigner,
836         funding_info: (OutPoint, Script),
837         current_counterparty_commitment_txid: Option<Txid>,
838         prev_counterparty_commitment_txid: Option<Txid>,
839
840         counterparty_tx_cache: CounterpartyCommitmentTransaction,
841         funding_redeemscript: Script,
842         channel_value_satoshis: u64,
843         // first is the idx of the first of the two revocation points
844         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
845
846         on_holder_tx_csv: u16,
847
848         commitment_secrets: CounterpartyCommitmentSecrets,
849         counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
850         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
851         /// Nor can we figure out their commitment numbers without the commitment transaction they are
852         /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
853         /// commitment transactions which we find on-chain, mapping them to the commitment number which
854         /// can be used to derive the revocation key and claim the transactions.
855         counterparty_commitment_txn_on_chain: HashMap<Txid, (u64, Vec<Script>)>,
856         /// Cache used to make pruning of payment_preimages faster.
857         /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
858         /// counterparty transactions (ie should remain pretty small).
859         /// Serialized to disk but should generally not be sent to Watchtowers.
860         counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
861
862         // We store two holder commitment transactions to avoid any race conditions where we may update
863         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
864         // various monitors for one channel being out of sync, and us broadcasting a holder
865         // transaction for which we have deleted claim information on some watchtowers.
866         prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
867         current_holder_commitment_tx: HolderSignedTx,
868
869         // Used just for ChannelManager to make sure it has the latest channel data during
870         // deserialization
871         current_counterparty_commitment_number: u64,
872         // Used just for ChannelManager to make sure it has the latest channel data during
873         // deserialization
874         current_holder_commitment_number: u64,
875
876         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
877
878         pending_monitor_events: Vec<MonitorEvent>,
879         pending_events: Vec<Event>,
880
881         // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
882         // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
883         // actions when we receive a block with given height. Actions depend on OnchainEvent type.
884         onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
885
886         // If we get serialized out and re-read, we need to make sure that the chain monitoring
887         // interface knows about the TXOs that we want to be notified of spends of. We could probably
888         // be smart and derive them from the above storage fields, but its much simpler and more
889         // Obviously Correct (tm) if we just keep track of them explicitly.
890         outputs_to_watch: HashMap<Txid, Vec<Script>>,
891
892         #[cfg(test)]
893         pub onchain_tx_handler: OnchainTxHandler<ChanSigner>,
894         #[cfg(not(test))]
895         onchain_tx_handler: OnchainTxHandler<ChanSigner>,
896
897         // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
898         // channel has been force-closed. After this is set, no further holder commitment transaction
899         // updates may occur, and we panic!() if one is provided.
900         lockdown_from_offchain: bool,
901
902         // Set once we've signed a holder commitment transaction and handed it over to our
903         // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
904         // may occur, and we fail any such monitor updates.
905         //
906         // In case of update rejection due to a locally already signed commitment transaction, we
907         // nevertheless store update content to track in case of concurrent broadcast by another
908         // remote monitor out-of-order with regards to the block view.
909         holder_tx_signed: bool,
910
911         // We simply modify last_block_hash in Channel's block_connected so that serialization is
912         // consistent but hopefully the users' copy handles block_connected in a consistent way.
913         // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
914         // their last_block_hash from its state and not based on updated copies that didn't run through
915         // the full block_connected).
916         last_block_hash: BlockHash,
917         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
918 }
919
920 #[cfg(any(test, feature = "fuzztarget"))]
921 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
922 /// underlying object
923 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
924         fn eq(&self, other: &Self) -> bool {
925                 if self.latest_update_id != other.latest_update_id ||
926                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
927                         self.destination_script != other.destination_script ||
928                         self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
929                         self.counterparty_payment_script != other.counterparty_payment_script ||
930                         self.keys.pubkeys() != other.keys.pubkeys() ||
931                         self.funding_info != other.funding_info ||
932                         self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
933                         self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
934                         self.counterparty_tx_cache != other.counterparty_tx_cache ||
935                         self.funding_redeemscript != other.funding_redeemscript ||
936                         self.channel_value_satoshis != other.channel_value_satoshis ||
937                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
938                         self.on_holder_tx_csv != other.on_holder_tx_csv ||
939                         self.commitment_secrets != other.commitment_secrets ||
940                         self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
941                         self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
942                         self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
943                         self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
944                         self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
945                         self.current_holder_commitment_number != other.current_holder_commitment_number ||
946                         self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
947                         self.payment_preimages != other.payment_preimages ||
948                         self.pending_monitor_events != other.pending_monitor_events ||
949                         self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
950                         self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
951                         self.outputs_to_watch != other.outputs_to_watch ||
952                         self.lockdown_from_offchain != other.lockdown_from_offchain ||
953                         self.holder_tx_signed != other.holder_tx_signed
954                 {
955                         false
956                 } else {
957                         true
958                 }
959         }
960 }
961
962 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
963         /// Writes this monitor into the given writer, suitable for writing to disk.
964         ///
965         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
966         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
967         /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
968         /// returned block hash and the the current chain and then reconnecting blocks to get to the
969         /// best chain) upon deserializing the object!
970         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
971                 //TODO: We still write out all the serialization here manually instead of using the fancy
972                 //serialization framework we have, we should migrate things over to it.
973                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
974                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
975
976                 self.latest_update_id.write(writer)?;
977
978                 // Set in initial Channel-object creation, so should always be set by now:
979                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
980
981                 self.destination_script.write(writer)?;
982                 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
983                         writer.write_all(&[0; 1])?;
984                         broadcasted_holder_revokable_script.0.write(writer)?;
985                         broadcasted_holder_revokable_script.1.write(writer)?;
986                         broadcasted_holder_revokable_script.2.write(writer)?;
987                 } else {
988                         writer.write_all(&[1; 1])?;
989                 }
990
991                 self.counterparty_payment_script.write(writer)?;
992                 self.shutdown_script.write(writer)?;
993
994                 self.keys.write(writer)?;
995                 writer.write_all(&self.funding_info.0.txid[..])?;
996                 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
997                 self.funding_info.1.write(writer)?;
998                 self.current_counterparty_commitment_txid.write(writer)?;
999                 self.prev_counterparty_commitment_txid.write(writer)?;
1000
1001                 self.counterparty_tx_cache.write(writer)?;
1002                 self.funding_redeemscript.write(writer)?;
1003                 self.channel_value_satoshis.write(writer)?;
1004
1005                 match self.their_cur_revocation_points {
1006                         Some((idx, pubkey, second_option)) => {
1007                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
1008                                 writer.write_all(&pubkey.serialize())?;
1009                                 match second_option {
1010                                         Some(second_pubkey) => {
1011                                                 writer.write_all(&second_pubkey.serialize())?;
1012                                         },
1013                                         None => {
1014                                                 writer.write_all(&[0; 33])?;
1015                                         },
1016                                 }
1017                         },
1018                         None => {
1019                                 writer.write_all(&byte_utils::be48_to_array(0))?;
1020                         },
1021                 }
1022
1023                 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
1024
1025                 self.commitment_secrets.write(writer)?;
1026
1027                 macro_rules! serialize_htlc_in_commitment {
1028                         ($htlc_output: expr) => {
1029                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1030                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1031                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1032                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1033                                 $htlc_output.transaction_output_index.write(writer)?;
1034                         }
1035                 }
1036
1037                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
1038                 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
1039                         writer.write_all(&txid[..])?;
1040                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1041                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1042                                 serialize_htlc_in_commitment!(htlc_output);
1043                                 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1044                         }
1045                 }
1046
1047                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
1048                 for (ref txid, &(commitment_number, ref txouts)) in self.counterparty_commitment_txn_on_chain.iter() {
1049                         writer.write_all(&txid[..])?;
1050                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1051                         (txouts.len() as u64).write(writer)?;
1052                         for script in txouts.iter() {
1053                                 script.write(writer)?;
1054                         }
1055                 }
1056
1057                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
1058                 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1059                         writer.write_all(&payment_hash.0[..])?;
1060                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1061                 }
1062
1063                 macro_rules! serialize_holder_tx {
1064                         ($holder_tx: expr) => {
1065                                 $holder_tx.txid.write(writer)?;
1066                                 writer.write_all(&$holder_tx.revocation_key.serialize())?;
1067                                 writer.write_all(&$holder_tx.a_htlc_key.serialize())?;
1068                                 writer.write_all(&$holder_tx.b_htlc_key.serialize())?;
1069                                 writer.write_all(&$holder_tx.delayed_payment_key.serialize())?;
1070                                 writer.write_all(&$holder_tx.per_commitment_point.serialize())?;
1071
1072                                 writer.write_all(&byte_utils::be32_to_array($holder_tx.feerate_per_kw))?;
1073                                 writer.write_all(&byte_utils::be64_to_array($holder_tx.htlc_outputs.len() as u64))?;
1074                                 for &(ref htlc_output, ref sig, ref htlc_source) in $holder_tx.htlc_outputs.iter() {
1075                                         serialize_htlc_in_commitment!(htlc_output);
1076                                         if let &Some(ref their_sig) = sig {
1077                                                 1u8.write(writer)?;
1078                                                 writer.write_all(&their_sig.serialize_compact())?;
1079                                         } else {
1080                                                 0u8.write(writer)?;
1081                                         }
1082                                         htlc_source.write(writer)?;
1083                                 }
1084                         }
1085                 }
1086
1087                 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1088                         writer.write_all(&[1; 1])?;
1089                         serialize_holder_tx!(prev_holder_tx);
1090                 } else {
1091                         writer.write_all(&[0; 1])?;
1092                 }
1093
1094                 serialize_holder_tx!(self.current_holder_commitment_tx);
1095
1096                 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1097                 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1098
1099                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1100                 for payment_preimage in self.payment_preimages.values() {
1101                         writer.write_all(&payment_preimage.0[..])?;
1102                 }
1103
1104                 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
1105                 for event in self.pending_monitor_events.iter() {
1106                         match event {
1107                                 MonitorEvent::HTLCEvent(upd) => {
1108                                         0u8.write(writer)?;
1109                                         upd.write(writer)?;
1110                                 },
1111                                 MonitorEvent::CommitmentTxBroadcasted(_) => 1u8.write(writer)?
1112                         }
1113                 }
1114
1115                 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
1116                 for event in self.pending_events.iter() {
1117                         event.write(writer)?;
1118                 }
1119
1120                 self.last_block_hash.write(writer)?;
1121
1122                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1123                 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1124                         writer.write_all(&byte_utils::be32_to_array(**target))?;
1125                         writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1126                         for ev in events.iter() {
1127                                 match *ev {
1128                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1129                                                 0u8.write(writer)?;
1130                                                 htlc_update.0.write(writer)?;
1131                                                 htlc_update.1.write(writer)?;
1132                                         },
1133                                         OnchainEvent::MaturingOutput { ref descriptor } => {
1134                                                 1u8.write(writer)?;
1135                                                 descriptor.write(writer)?;
1136                                         },
1137                                 }
1138                         }
1139                 }
1140
1141                 (self.outputs_to_watch.len() as u64).write(writer)?;
1142                 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1143                         txid.write(writer)?;
1144                         (output_scripts.len() as u64).write(writer)?;
1145                         for script in output_scripts.iter() {
1146                                 script.write(writer)?;
1147                         }
1148                 }
1149                 self.onchain_tx_handler.write(writer)?;
1150
1151                 self.lockdown_from_offchain.write(writer)?;
1152                 self.holder_tx_signed.write(writer)?;
1153
1154                 Ok(())
1155         }
1156 }
1157
1158 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1159         pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1160                         on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1161                         counterparty_htlc_base_key: &PublicKey, counterparty_delayed_payment_base_key: &PublicKey,
1162                         on_holder_tx_csv: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1163                         commitment_transaction_number_obscure_factor: u64,
1164                         initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<ChanSigner> {
1165
1166                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1167                 let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
1168                 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1169                 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1170                 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1171
1172                 let counterparty_tx_cache = CounterpartyCommitmentTransaction { counterparty_delayed_payment_base_key: *counterparty_delayed_payment_base_key, counterparty_htlc_base_key: *counterparty_htlc_base_key, on_counterparty_tx_csv, per_htlc: HashMap::new() };
1173
1174                 let mut onchain_tx_handler = OnchainTxHandler::new(destination_script.clone(), keys.clone(), on_holder_tx_csv);
1175
1176                 let holder_tx_sequence = initial_holder_commitment_tx.unsigned_tx.input[0].sequence as u64;
1177                 let holder_tx_locktime = initial_holder_commitment_tx.unsigned_tx.lock_time as u64;
1178                 let holder_commitment_tx = HolderSignedTx {
1179                         txid: initial_holder_commitment_tx.txid(),
1180                         revocation_key: initial_holder_commitment_tx.keys.revocation_key,
1181                         a_htlc_key: initial_holder_commitment_tx.keys.broadcaster_htlc_key,
1182                         b_htlc_key: initial_holder_commitment_tx.keys.countersignatory_htlc_key,
1183                         delayed_payment_key: initial_holder_commitment_tx.keys.broadcaster_delayed_payment_key,
1184                         per_commitment_point: initial_holder_commitment_tx.keys.per_commitment_point,
1185                         feerate_per_kw: initial_holder_commitment_tx.feerate_per_kw,
1186                         htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1187                 };
1188                 onchain_tx_handler.provide_latest_holder_tx(initial_holder_commitment_tx);
1189
1190                 ChannelMonitor {
1191                         latest_update_id: 0,
1192                         commitment_transaction_number_obscure_factor,
1193
1194                         destination_script: destination_script.clone(),
1195                         broadcasted_holder_revokable_script: None,
1196                         counterparty_payment_script,
1197                         shutdown_script,
1198
1199                         keys,
1200                         funding_info,
1201                         current_counterparty_commitment_txid: None,
1202                         prev_counterparty_commitment_txid: None,
1203
1204                         counterparty_tx_cache,
1205                         funding_redeemscript,
1206                         channel_value_satoshis: channel_value_satoshis,
1207                         their_cur_revocation_points: None,
1208
1209                         on_holder_tx_csv,
1210
1211                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1212                         counterparty_claimable_outpoints: HashMap::new(),
1213                         counterparty_commitment_txn_on_chain: HashMap::new(),
1214                         counterparty_hash_commitment_number: HashMap::new(),
1215
1216                         prev_holder_signed_commitment_tx: None,
1217                         current_holder_commitment_tx: holder_commitment_tx,
1218                         current_counterparty_commitment_number: 1 << 48,
1219                         current_holder_commitment_number: 0xffff_ffff_ffff - ((((holder_tx_sequence & 0xffffff) << 3*8) | (holder_tx_locktime as u64 & 0xffffff)) ^ commitment_transaction_number_obscure_factor),
1220
1221                         payment_preimages: HashMap::new(),
1222                         pending_monitor_events: Vec::new(),
1223                         pending_events: Vec::new(),
1224
1225                         onchain_events_waiting_threshold_conf: HashMap::new(),
1226                         outputs_to_watch: HashMap::new(),
1227
1228                         onchain_tx_handler,
1229
1230                         lockdown_from_offchain: false,
1231                         holder_tx_signed: false,
1232
1233                         last_block_hash: Default::default(),
1234                         secp_ctx: Secp256k1::new(),
1235                 }
1236         }
1237
1238         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1239         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1240         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1241         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1242                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1243                         return Err(MonitorUpdateError("Previous secret did not match new one"));
1244                 }
1245
1246                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1247                 // events for now-revoked/fulfilled HTLCs.
1248                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1249                         for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1250                                 *source = None;
1251                         }
1252                 }
1253
1254                 if !self.payment_preimages.is_empty() {
1255                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1256                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1257                         let min_idx = self.get_min_seen_secret();
1258                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1259
1260                         self.payment_preimages.retain(|&k, _| {
1261                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1262                                         if k == htlc.payment_hash {
1263                                                 return true
1264                                         }
1265                                 }
1266                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1267                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1268                                                 if k == htlc.payment_hash {
1269                                                         return true
1270                                                 }
1271                                         }
1272                                 }
1273                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1274                                         if *cn < min_idx {
1275                                                 return true
1276                                         }
1277                                         true
1278                                 } else { false };
1279                                 if contains {
1280                                         counterparty_hash_commitment_number.remove(&k);
1281                                 }
1282                                 false
1283                         });
1284                 }
1285
1286                 Ok(())
1287         }
1288
1289         /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1290         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1291         /// possibly future revocation/preimage information) to claim outputs where possible.
1292         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1293         pub(super) fn provide_latest_counterparty_commitment_tx_info<L: Deref>(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
1294                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1295                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1296                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1297                 // timeouts)
1298                 for &(ref htlc, _) in &htlc_outputs {
1299                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1300                 }
1301
1302                 let new_txid = unsigned_commitment_tx.txid();
1303                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1304                 log_trace!(logger, "New potential counterparty commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1305                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1306                 self.current_counterparty_commitment_txid = Some(new_txid);
1307                 self.counterparty_claimable_outpoints.insert(new_txid, htlc_outputs.clone());
1308                 self.current_counterparty_commitment_number = commitment_number;
1309                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1310                 match self.their_cur_revocation_points {
1311                         Some(old_points) => {
1312                                 if old_points.0 == commitment_number + 1 {
1313                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1314                                 } else if old_points.0 == commitment_number + 2 {
1315                                         if let Some(old_second_point) = old_points.2 {
1316                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1317                                         } else {
1318                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1319                                         }
1320                                 } else {
1321                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1322                                 }
1323                         },
1324                         None => {
1325                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1326                         }
1327                 }
1328                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1329                 for htlc in htlc_outputs {
1330                         if htlc.0.transaction_output_index.is_some() {
1331                                 htlcs.push(htlc.0);
1332                         }
1333                 }
1334                 self.counterparty_tx_cache.per_htlc.insert(new_txid, htlcs);
1335         }
1336
1337         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1338         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1339         /// is important that any clones of this channel monitor (including remote clones) by kept
1340         /// up-to-date as our holder commitment transaction is updated.
1341         /// Panics if set_on_holder_tx_csv has never been called.
1342         pub(super) fn provide_latest_holder_commitment_tx_info(&mut self, commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1343                 let txid = commitment_tx.txid();
1344                 let sequence = commitment_tx.unsigned_tx.input[0].sequence as u64;
1345                 let locktime = commitment_tx.unsigned_tx.lock_time as u64;
1346                 let mut new_holder_commitment_tx = HolderSignedTx {
1347                         txid,
1348                         revocation_key: commitment_tx.keys.revocation_key,
1349                         a_htlc_key: commitment_tx.keys.broadcaster_htlc_key,
1350                         b_htlc_key: commitment_tx.keys.countersignatory_htlc_key,
1351                         delayed_payment_key: commitment_tx.keys.broadcaster_delayed_payment_key,
1352                         per_commitment_point: commitment_tx.keys.per_commitment_point,
1353                         feerate_per_kw: commitment_tx.feerate_per_kw,
1354                         htlc_outputs: htlc_outputs,
1355                 };
1356                 self.onchain_tx_handler.provide_latest_holder_tx(commitment_tx);
1357                 self.current_holder_commitment_number = 0xffff_ffff_ffff - ((((sequence & 0xffffff) << 3*8) | (locktime as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
1358                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1359                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1360                 if self.holder_tx_signed {
1361                         return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1362                 }
1363                 Ok(())
1364         }
1365
1366         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1367         /// commitment_tx_infos which contain the payment hash have been revoked.
1368         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1369                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1370         }
1371
1372         pub(super) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1373                 where B::Target: BroadcasterInterface,
1374                                         L::Target: Logger,
1375         {
1376                 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1377                         broadcaster.broadcast_transaction(tx);
1378                 }
1379                 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1380         }
1381
1382         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1383         /// itself.
1384         ///
1385         /// panics if the given update is not the next update by update_id.
1386         pub fn update_monitor<B: Deref, L: Deref>(&mut self, mut updates: ChannelMonitorUpdate, broadcaster: &B, logger: &L) -> Result<(), MonitorUpdateError>
1387                 where B::Target: BroadcasterInterface,
1388                                         L::Target: Logger,
1389         {
1390                 if self.latest_update_id + 1 != updates.update_id {
1391                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1392                 }
1393                 for update in updates.updates.drain(..) {
1394                         match update {
1395                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1396                                         if self.lockdown_from_offchain { panic!(); }
1397                                         self.provide_latest_holder_commitment_tx_info(commitment_tx, htlc_outputs)?
1398                                 },
1399                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1400                                         self.provide_latest_counterparty_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point, logger),
1401                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1402                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1403                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1404                                         self.provide_secret(idx, secret)?,
1405                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1406                                         self.lockdown_from_offchain = true;
1407                                         if should_broadcast {
1408                                                 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1409                                         } else {
1410                                                 log_error!(logger, "You have a toxic holder commitment transaction avaible in channel monitor, read comment in ChannelMonitor::get_latest_holder_commitment_txn to be informed of manual action to take");
1411                                         }
1412                                 }
1413                         }
1414                 }
1415                 self.latest_update_id = updates.update_id;
1416                 Ok(())
1417         }
1418
1419         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1420         /// ChannelMonitor.
1421         pub fn get_latest_update_id(&self) -> u64 {
1422                 self.latest_update_id
1423         }
1424
1425         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1426         pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1427                 &self.funding_info
1428         }
1429
1430         /// Gets a list of txids, with their output scripts (in the order they appear in the
1431         /// transaction), which we must learn about spends of via block_connected().
1432         ///
1433         /// (C-not exported) because we have no HashMap bindings
1434         pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<Script>> {
1435                 &self.outputs_to_watch
1436         }
1437
1438         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1439         /// Generally useful when deserializing as during normal operation the return values of
1440         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1441         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1442         ///
1443         /// (C-not exported) as there is no practical way to track lifetimes of returned values.
1444         pub fn get_monitored_outpoints(&self) -> Vec<(Txid, u32, &Script)> {
1445                 let mut res = Vec::with_capacity(self.counterparty_commitment_txn_on_chain.len() * 2);
1446                 for (ref txid, &(_, ref outputs)) in self.counterparty_commitment_txn_on_chain.iter() {
1447                         for (idx, output) in outputs.iter().enumerate() {
1448                                 res.push(((*txid).clone(), idx as u32, output));
1449                         }
1450                 }
1451                 res
1452         }
1453
1454         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1455         /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1456         ///
1457         /// [`chain::Watch::release_pending_monitor_events`]: ../../chain/trait.Watch.html#tymethod.release_pending_monitor_events
1458         pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1459                 let mut ret = Vec::new();
1460                 mem::swap(&mut ret, &mut self.pending_monitor_events);
1461                 ret
1462         }
1463
1464         /// Gets the list of pending events which were generated by previous actions, clearing the list
1465         /// in the process.
1466         ///
1467         /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1468         /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1469         /// no internal locking in ChannelMonitors.
1470         pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1471                 let mut ret = Vec::new();
1472                 mem::swap(&mut ret, &mut self.pending_events);
1473                 ret
1474         }
1475
1476         /// Can only fail if idx is < get_min_seen_secret
1477         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1478                 self.commitment_secrets.get_secret(idx)
1479         }
1480
1481         pub(super) fn get_min_seen_secret(&self) -> u64 {
1482                 self.commitment_secrets.get_min_seen_secret()
1483         }
1484
1485         pub(super) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1486                 self.current_counterparty_commitment_number
1487         }
1488
1489         pub(super) fn get_cur_holder_commitment_number(&self) -> u64 {
1490                 self.current_holder_commitment_number
1491         }
1492
1493         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1494         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1495         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1496         /// HTLC-Success/HTLC-Timeout transactions.
1497         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1498         /// revoked counterparty commitment tx
1499         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<TxOut>)) where L::Target: Logger {
1500                 // Most secp and related errors trying to create keys means we have no hope of constructing
1501                 // a spend transaction...so we return no transactions to broadcast
1502                 let mut claimable_outpoints = Vec::new();
1503                 let mut watch_outputs = Vec::new();
1504
1505                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1506                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1507
1508                 macro_rules! ignore_error {
1509                         ( $thing : expr ) => {
1510                                 match $thing {
1511                                         Ok(a) => a,
1512                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1513                                 }
1514                         };
1515                 }
1516
1517                 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
1518                 if commitment_number >= self.get_min_seen_secret() {
1519                         let secret = self.get_secret(commitment_number).unwrap();
1520                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1521                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1522                         let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().revocation_basepoint));
1523                         let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_tx_cache.counterparty_delayed_payment_base_key));
1524
1525                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_tx_cache.on_counterparty_tx_csv, &delayed_key);
1526                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1527
1528                         // First, process non-htlc outputs (to_holder & to_counterparty)
1529                         for (idx, outp) in tx.output.iter().enumerate() {
1530                                 if outp.script_pubkey == revokeable_p2wsh {
1531                                         let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: outp.value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1532                                         claimable_outpoints.push(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
1533                                 }
1534                         }
1535
1536                         // Then, try to find revoked htlc outputs
1537                         if let Some(ref per_commitment_data) = per_commitment_option {
1538                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1539                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1540                                                 if transaction_output_index as usize >= tx.output.len() ||
1541                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1542                                                         return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1543                                                 }
1544                                                 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, amount: tx.output[transaction_output_index as usize].value, htlc: Some(htlc.clone()), on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1545                                                 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1546                                         }
1547                                 }
1548                         }
1549
1550                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1551                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1552                                 // We're definitely a counterparty commitment transaction!
1553                                 log_trace!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1554                                 watch_outputs.append(&mut tx.output.clone());
1555                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1556
1557                                 macro_rules! check_htlc_fails {
1558                                         ($txid: expr, $commitment_tx: expr) => {
1559                                                 if let Some(ref outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1560                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1561                                                                 if let &Some(ref source) = source_option {
1562                                                                         log_info!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of revoked counterparty commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1563                                                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1564                                                                                 hash_map::Entry::Occupied(mut entry) => {
1565                                                                                         let e = entry.get_mut();
1566                                                                                         e.retain(|ref event| {
1567                                                                                                 match **event {
1568                                                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1569                                                                                                                 return htlc_update.0 != **source
1570                                                                                                         },
1571                                                                                                         _ => true
1572                                                                                                 }
1573                                                                                         });
1574                                                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1575                                                                                 }
1576                                                                                 hash_map::Entry::Vacant(entry) => {
1577                                                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1578                                                                                 }
1579                                                                         }
1580                                                                 }
1581                                                         }
1582                                                 }
1583                                         }
1584                                 }
1585                                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
1586                                         check_htlc_fails!(txid, "current");
1587                                 }
1588                                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1589                                         check_htlc_fails!(txid, "counterparty");
1590                                 }
1591                                 // No need to check holder commitment txn, symmetric HTLCSource must be present as per-htlc data on counterparty commitment tx
1592                         }
1593                 } else if let Some(per_commitment_data) = per_commitment_option {
1594                         // While this isn't useful yet, there is a potential race where if a counterparty
1595                         // revokes a state at the same time as the commitment transaction for that state is
1596                         // confirmed, and the watchtower receives the block before the user, the user could
1597                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1598                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1599                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1600                         // insert it here.
1601                         watch_outputs.append(&mut tx.output.clone());
1602                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1603
1604                         log_trace!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1605
1606                         macro_rules! check_htlc_fails {
1607                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1608                                         if let Some(ref latest_outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1609                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1610                                                         if let &Some(ref source) = source_option {
1611                                                                 // Check if the HTLC is present in the commitment transaction that was
1612                                                                 // broadcast, but not if it was below the dust limit, which we should
1613                                                                 // fail backwards immediately as there is no way for us to learn the
1614                                                                 // payment_preimage.
1615                                                                 // Note that if the dust limit were allowed to change between
1616                                                                 // commitment transactions we'd want to be check whether *any*
1617                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1618                                                                 // cannot currently change after channel initialization, so we don't
1619                                                                 // need to here.
1620                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1621                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1622                                                                                 continue $id;
1623                                                                         }
1624                                                                 }
1625                                                                 log_trace!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of counterparty commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1626                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1627                                                                         hash_map::Entry::Occupied(mut entry) => {
1628                                                                                 let e = entry.get_mut();
1629                                                                                 e.retain(|ref event| {
1630                                                                                         match **event {
1631                                                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1632                                                                                                         return htlc_update.0 != **source
1633                                                                                                 },
1634                                                                                                 _ => true
1635                                                                                         }
1636                                                                                 });
1637                                                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1638                                                                         }
1639                                                                         hash_map::Entry::Vacant(entry) => {
1640                                                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1641                                                                         }
1642                                                                 }
1643                                                         }
1644                                                 }
1645                                         }
1646                                 }
1647                         }
1648                         if let Some(ref txid) = self.current_counterparty_commitment_txid {
1649                                 check_htlc_fails!(txid, "current", 'current_loop);
1650                         }
1651                         if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1652                                 check_htlc_fails!(txid, "previous", 'prev_loop);
1653                         }
1654
1655                         if let Some(revocation_points) = self.their_cur_revocation_points {
1656                                 let revocation_point_option =
1657                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1658                                         else if let Some(point) = revocation_points.2.as_ref() {
1659                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1660                                         } else { None };
1661                                 if let Some(revocation_point) = revocation_point_option {
1662                                         self.counterparty_payment_script = {
1663                                                 // Note that the Network here is ignored as we immediately drop the address for the
1664                                                 // script_pubkey version
1665                                                 let payment_hash160 = WPubkeyHash::hash(&self.keys.pubkeys().payment_point.serialize());
1666                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script()
1667                                         };
1668
1669                                         // Then, try to find htlc outputs
1670                                         for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1671                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1672                                                         if transaction_output_index as usize >= tx.output.len() ||
1673                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1674                                                                 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1675                                                         }
1676                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1677                                                         let aggregable = if !htlc.offered { false } else { true };
1678                                                         if preimage.is_some() || !htlc.offered {
1679                                                                 let witness_data = InputMaterial::CounterpartyHTLC { per_commitment_point: *revocation_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, preimage, htlc: htlc.clone() };
1680                                                                 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1681                                                         }
1682                                                 }
1683                                         }
1684                                 }
1685                         }
1686                 }
1687                 (claimable_outpoints, (commitment_txid, watch_outputs))
1688         }
1689
1690         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1691         fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<ClaimRequest>, Option<(Txid, Vec<TxOut>)>) where L::Target: Logger {
1692                 let htlc_txid = tx.txid();
1693                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1694                         return (Vec::new(), None)
1695                 }
1696
1697                 macro_rules! ignore_error {
1698                         ( $thing : expr ) => {
1699                                 match $thing {
1700                                         Ok(a) => a,
1701                                         Err(_) => return (Vec::new(), None)
1702                                 }
1703                         };
1704                 }
1705
1706                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1707                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1708                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1709
1710                 log_trace!(logger, "Counterparty HTLC broadcast {}:{}", htlc_txid, 0);
1711                 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key,  per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: tx.output[0].value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv };
1712                 let claimable_outpoints = vec!(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
1713                 (claimable_outpoints, Some((htlc_txid, tx.output.clone())))
1714         }
1715
1716         fn broadcast_by_holder_state(&self, commitment_tx: &Transaction, holder_tx: &HolderSignedTx) -> (Vec<ClaimRequest>, Vec<TxOut>, Option<(Script, PublicKey, PublicKey)>) {
1717                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
1718                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
1719
1720                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
1721                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
1722
1723                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1724                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1725                                 claim_requests.push(ClaimRequest { absolute_timelock: ::std::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
1726                                         witness_data: InputMaterial::HolderHTLC {
1727                                                 preimage: if !htlc.offered {
1728                                                                 if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1729                                                                         Some(preimage.clone())
1730                                                                 } else {
1731                                                                         // We can't build an HTLC-Success transaction without the preimage
1732                                                                         continue;
1733                                                                 }
1734                                                         } else { None },
1735                                                 amount: htlc.amount_msat,
1736                                 }});
1737                                 watch_outputs.push(commitment_tx.output[transaction_output_index as usize].clone());
1738                         }
1739                 }
1740
1741                 (claim_requests, watch_outputs, broadcasted_holder_revokable_script)
1742         }
1743
1744         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1745         /// revoked using data in holder_claimable_outpoints.
1746         /// Should not be used if check_spend_revoked_transaction succeeds.
1747         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<TxOut>)) where L::Target: Logger {
1748                 let commitment_txid = tx.txid();
1749                 let mut claim_requests = Vec::new();
1750                 let mut watch_outputs = Vec::new();
1751
1752                 macro_rules! wait_threshold_conf {
1753                         ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1754                                 log_trace!(logger, "Failing HTLC with payment_hash {} from {} holder commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1755                                 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
1756                                         hash_map::Entry::Occupied(mut entry) => {
1757                                                 let e = entry.get_mut();
1758                                                 e.retain(|ref event| {
1759                                                         match **event {
1760                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1761                                                                         return htlc_update.0 != $source
1762                                                                 },
1763                                                                 _ => true
1764                                                         }
1765                                                 });
1766                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
1767                                         }
1768                                         hash_map::Entry::Vacant(entry) => {
1769                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
1770                                         }
1771                                 }
1772                         }
1773                 }
1774
1775                 macro_rules! append_onchain_update {
1776                         ($updates: expr) => {
1777                                 claim_requests = $updates.0;
1778                                 watch_outputs.append(&mut $updates.1);
1779                                 self.broadcasted_holder_revokable_script = $updates.2;
1780                         }
1781                 }
1782
1783                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1784                 let mut is_holder_tx = false;
1785
1786                 if self.current_holder_commitment_tx.txid == commitment_txid {
1787                         is_holder_tx = true;
1788                         log_trace!(logger, "Got latest holder commitment tx broadcast, searching for available HTLCs to claim");
1789                         let mut res = self.broadcast_by_holder_state(tx, &self.current_holder_commitment_tx);
1790                         append_onchain_update!(res);
1791                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1792                         if holder_tx.txid == commitment_txid {
1793                                 is_holder_tx = true;
1794                                 log_trace!(logger, "Got previous holder commitment tx broadcast, searching for available HTLCs to claim");
1795                                 let mut res = self.broadcast_by_holder_state(tx, holder_tx);
1796                                 append_onchain_update!(res);
1797                         }
1798                 }
1799
1800                 macro_rules! fail_dust_htlcs_after_threshold_conf {
1801                         ($holder_tx: expr) => {
1802                                 for &(ref htlc, _, ref source) in &$holder_tx.htlc_outputs {
1803                                         if htlc.transaction_output_index.is_none() {
1804                                                 if let &Some(ref source) = source {
1805                                                         wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
1806                                                 }
1807                                         }
1808                                 }
1809                         }
1810                 }
1811
1812                 if is_holder_tx {
1813                         fail_dust_htlcs_after_threshold_conf!(self.current_holder_commitment_tx);
1814                         if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1815                                 fail_dust_htlcs_after_threshold_conf!(holder_tx);
1816                         }
1817                 }
1818
1819                 (claim_requests, (commitment_txid, watch_outputs))
1820         }
1821
1822         /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1823         /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1824         /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1825         /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1826         /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1827         /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1828         /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1829         /// out-of-band the other node operator to coordinate with him if option is available to you.
1830         /// In any-case, choice is up to the user.
1831         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1832                 log_trace!(logger, "Getting signed latest holder commitment transaction!");
1833                 self.holder_tx_signed = true;
1834                 if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
1835                         let txid = commitment_tx.txid();
1836                         let mut res = vec![commitment_tx];
1837                         for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1838                                 if let Some(vout) = htlc.0.transaction_output_index {
1839                                         let preimage = if !htlc.0.offered {
1840                                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1841                                                                 // We can't build an HTLC-Success transaction without the preimage
1842                                                                 continue;
1843                                                         }
1844                                                 } else { None };
1845                                         if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
1846                                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
1847                                                 res.push(htlc_tx);
1848                                         }
1849                                 }
1850                         }
1851                         // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
1852                         // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
1853                         return res
1854                 }
1855                 Vec::new()
1856         }
1857
1858         /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1859         /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1860         /// revoked commitment transaction.
1861         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1862         pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1863                 log_trace!(logger, "Getting signed copy of latest holder commitment transaction!");
1864                 if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript) {
1865                         let txid = commitment_tx.txid();
1866                         let mut res = vec![commitment_tx];
1867                         for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1868                                 if let Some(vout) = htlc.0.transaction_output_index {
1869                                         let preimage = if !htlc.0.offered {
1870                                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1871                                                                 // We can't build an HTLC-Success transaction without the preimage
1872                                                                 continue;
1873                                                         }
1874                                                 } else { None };
1875                                         if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
1876                                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
1877                                                 res.push(htlc_tx);
1878                                         }
1879                                 }
1880                         }
1881                         return res
1882                 }
1883                 Vec::new()
1884         }
1885
1886         /// Processes transactions in a newly connected block, which may result in any of the following:
1887         /// - update the monitor's state against resolved HTLCs
1888         /// - punish the counterparty in the case of seeing a revoked commitment transaction
1889         /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1890         /// - detect settled outputs for later spending
1891         /// - schedule and bump any in-flight claims
1892         ///
1893         /// Returns any transaction outputs from `txn_matched` that spends of should be watched for.
1894         /// After called these are also available via [`get_outputs_to_watch`].
1895         ///
1896         /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1897         pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txn_matched: &[(usize, &Transaction)], height: u32, broadcaster: B, fee_estimator: F, logger: L)-> Vec<(Txid, Vec<TxOut>)>
1898                 where B::Target: BroadcasterInterface,
1899                       F::Target: FeeEstimator,
1900                                         L::Target: Logger,
1901         {
1902                 for &(_, tx) in txn_matched {
1903                         let mut output_val = 0;
1904                         for out in tx.output.iter() {
1905                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1906                                 output_val += out.value;
1907                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1908                         }
1909                 }
1910
1911                 let block_hash = header.block_hash();
1912                 log_trace!(logger, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
1913
1914                 let mut watch_outputs = Vec::new();
1915                 let mut claimable_outpoints = Vec::new();
1916                 for &(_, tx) in txn_matched {
1917                         if tx.input.len() == 1 {
1918                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1919                                 // commitment transactions and HTLC transactions will all only ever have one input,
1920                                 // which is an easy way to filter out any potential non-matching txn for lazy
1921                                 // filters.
1922                                 let prevout = &tx.input[0].previous_output;
1923                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
1924                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1925                                                 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
1926                                                 if !new_outputs.1.is_empty() {
1927                                                         watch_outputs.push(new_outputs);
1928                                                 }
1929                                                 if new_outpoints.is_empty() {
1930                                                         let (mut new_outpoints, new_outputs) = self.check_spend_holder_transaction(&tx, height, &logger);
1931                                                         if !new_outputs.1.is_empty() {
1932                                                                 watch_outputs.push(new_outputs);
1933                                                         }
1934                                                         claimable_outpoints.append(&mut new_outpoints);
1935                                                 }
1936                                                 claimable_outpoints.append(&mut new_outpoints);
1937                                         }
1938                                 } else {
1939                                         if let Some(&(commitment_number, _)) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
1940                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
1941                                                 claimable_outpoints.append(&mut new_outpoints);
1942                                                 if let Some(new_outputs) = new_outputs_option {
1943                                                         watch_outputs.push(new_outputs);
1944                                                 }
1945                                         }
1946                                 }
1947                         }
1948                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
1949                         // can also be resolved in a few other ways which can have more than one output. Thus,
1950                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
1951                         self.is_resolving_htlc_output(&tx, height, &logger);
1952
1953                         self.is_paying_spendable_output(&tx, height, &logger);
1954                 }
1955                 let should_broadcast = self.would_broadcast_at_height(height, &logger);
1956                 if should_broadcast {
1957                         claimable_outpoints.push(ClaimRequest { absolute_timelock: height, aggregable: false, outpoint: BitcoinOutPoint { txid: self.funding_info.0.txid.clone(), vout: self.funding_info.0.index as u32 }, witness_data: InputMaterial::Funding { funding_redeemscript: self.funding_redeemscript.clone() }});
1958                 }
1959                 if should_broadcast {
1960                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1961                         if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
1962                                 self.holder_tx_signed = true;
1963                                 let (mut new_outpoints, new_outputs, _) = self.broadcast_by_holder_state(&commitment_tx, &self.current_holder_commitment_tx);
1964                                 if !new_outputs.is_empty() {
1965                                         watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
1966                                 }
1967                                 claimable_outpoints.append(&mut new_outpoints);
1968                         }
1969                 }
1970                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
1971                         for ev in events {
1972                                 match ev {
1973                                         OnchainEvent::HTLCUpdate { htlc_update } => {
1974                                                 log_trace!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
1975                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
1976                                                         payment_hash: htlc_update.1,
1977                                                         payment_preimage: None,
1978                                                         source: htlc_update.0,
1979                                                 }));
1980                                         },
1981                                         OnchainEvent::MaturingOutput { descriptor } => {
1982                                                 log_trace!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
1983                                                 self.pending_events.push(Event::SpendableOutputs {
1984                                                         outputs: vec![descriptor]
1985                                                 });
1986                                         }
1987                                 }
1988                         }
1989                 }
1990
1991                 self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, &*broadcaster, &*fee_estimator, &*logger);
1992
1993                 self.last_block_hash = block_hash;
1994                 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
1995                         self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
1996                 }
1997
1998                 watch_outputs
1999         }
2000
2001         /// Determines if the disconnected block contained any transactions of interest and updates
2002         /// appropriately.
2003         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2004                 where B::Target: BroadcasterInterface,
2005                       F::Target: FeeEstimator,
2006                       L::Target: Logger,
2007         {
2008                 let block_hash = header.block_hash();
2009                 log_trace!(logger, "Block {} at height {} disconnected", block_hash, height);
2010
2011                 if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2012                         //We may discard:
2013                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2014                         //- maturing spendable output has transaction paying us has been disconnected
2015                 }
2016
2017                 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2018
2019                 self.last_block_hash = block_hash;
2020         }
2021
2022         fn would_broadcast_at_height<L: Deref>(&self, height: u32, logger: &L) -> bool where L::Target: Logger {
2023                 // We need to consider all HTLCs which are:
2024                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
2025                 //    transactions and we'd end up in a race, or
2026                 //  * are in our latest holder commitment transaction, as this is the thing we will
2027                 //    broadcast if we go on-chain.
2028                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2029                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2030                 // to the source, and if we don't fail the channel we will have to ensure that the next
2031                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2032                 // easier to just fail the channel as this case should be rare enough anyway.
2033                 macro_rules! scan_commitment {
2034                         ($htlcs: expr, $holder_tx: expr) => {
2035                                 for ref htlc in $htlcs {
2036                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2037                                         // chain with enough room to claim the HTLC without our counterparty being able to
2038                                         // time out the HTLC first.
2039                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2040                                         // concern is being able to claim the corresponding inbound HTLC (on another
2041                                         // channel) before it expires. In fact, we don't even really care if our
2042                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2043                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2044                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2045                                         // we give ourselves a few blocks of headroom after expiration before going
2046                                         // on-chain for an expired HTLC.
2047                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2048                                         // from us until we've reached the point where we go on-chain with the
2049                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2050                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2051                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2052                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2053                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2054                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2055                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2056                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2057                                         //  The final, above, condition is checked for statically in channelmanager
2058                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2059                                         let htlc_outbound = $holder_tx == htlc.offered;
2060                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2061                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2062                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2063                                                 return true;
2064                                         }
2065                                 }
2066                         }
2067                 }
2068
2069                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2070
2071                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2072                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2073                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2074                         }
2075                 }
2076                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2077                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2078                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2079                         }
2080                 }
2081
2082                 false
2083         }
2084
2085         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2086         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2087         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2088                 'outer_loop: for input in &tx.input {
2089                         let mut payment_data = None;
2090                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2091                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2092                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2093                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2094
2095                         macro_rules! log_claim {
2096                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2097                                         // We found the output in question, but aren't failing it backwards
2098                                         // as we have no corresponding source and no valid counterparty commitment txid
2099                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2100                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2101                                         let outbound_htlc = $holder_tx == $htlc.offered;
2102                                         if ($holder_tx && revocation_sig_claim) ||
2103                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2104                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2105                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2106                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2107                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2108                                         } else {
2109                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2110                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2111                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2112                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2113                                         }
2114                                 }
2115                         }
2116
2117                         macro_rules! check_htlc_valid_counterparty {
2118                                 ($counterparty_txid: expr, $htlc_output: expr) => {
2119                                         if let Some(txid) = $counterparty_txid {
2120                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2121                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2122                                                                 if let &Some(ref source) = pending_source {
2123                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2124                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2125                                                                         break;
2126                                                                 }
2127                                                         }
2128                                                 }
2129                                         }
2130                                 }
2131                         }
2132
2133                         macro_rules! scan_commitment {
2134                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2135                                         for (ref htlc_output, source_option) in $htlcs {
2136                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2137                                                         if let Some(ref source) = source_option {
2138                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
2139                                                                 // We have a resolution of an HTLC either from one of our latest
2140                                                                 // holder commitment transactions or an unrevoked counterparty commitment
2141                                                                 // transaction. This implies we either learned a preimage, the HTLC
2142                                                                 // has timed out, or we screwed up. In any case, we should now
2143                                                                 // resolve the source HTLC with the original sender.
2144                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2145                                                         } else if !$holder_tx {
2146                                                                         check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2147                                                                 if payment_data.is_none() {
2148                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2149                                                                 }
2150                                                         }
2151                                                         if payment_data.is_none() {
2152                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
2153                                                                 continue 'outer_loop;
2154                                                         }
2155                                                 }
2156                                         }
2157                                 }
2158                         }
2159
2160                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2161                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2162                                         "our latest holder commitment tx", true);
2163                         }
2164                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2165                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2166                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2167                                                 "our previous holder commitment tx", true);
2168                                 }
2169                         }
2170                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2171                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2172                                         "counterparty commitment tx", false);
2173                         }
2174
2175                         // Check that scan_commitment, above, decided there is some source worth relaying an
2176                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2177                         if let Some((source, payment_hash)) = payment_data {
2178                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2179                                 if accepted_preimage_claim {
2180                                         if !self.pending_monitor_events.iter().any(
2181                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2182                                                 payment_preimage.0.copy_from_slice(&input.witness[3]);
2183                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2184                                                         source,
2185                                                         payment_preimage: Some(payment_preimage),
2186                                                         payment_hash
2187                                                 }));
2188                                         }
2189                                 } else if offered_preimage_claim {
2190                                         if !self.pending_monitor_events.iter().any(
2191                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2192                                                         upd.source == source
2193                                                 } else { false }) {
2194                                                 payment_preimage.0.copy_from_slice(&input.witness[1]);
2195                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2196                                                         source,
2197                                                         payment_preimage: Some(payment_preimage),
2198                                                         payment_hash
2199                                                 }));
2200                                         }
2201                                 } else {
2202                                         log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), height + ANTI_REORG_DELAY - 1);
2203                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2204                                                 hash_map::Entry::Occupied(mut entry) => {
2205                                                         let e = entry.get_mut();
2206                                                         e.retain(|ref event| {
2207                                                                 match **event {
2208                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2209                                                                                 return htlc_update.0 != source
2210                                                                         },
2211                                                                         _ => true
2212                                                                 }
2213                                                         });
2214                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2215                                                 }
2216                                                 hash_map::Entry::Vacant(entry) => {
2217                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2218                                                 }
2219                                         }
2220                                 }
2221                         }
2222                 }
2223         }
2224
2225         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2226         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2227                 let mut spendable_output = None;
2228                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2229                         if i > ::std::u16::MAX as usize {
2230                                 // While it is possible that an output exists on chain which is greater than the
2231                                 // 2^16th output in a given transaction, this is only possible if the output is not
2232                                 // in a lightning transaction and was instead placed there by some third party who
2233                                 // wishes to give us money for no reason.
2234                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
2235                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2236                                 // scripts are not longer than one byte in length and because they are inherently
2237                                 // non-standard due to their size.
2238                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
2239                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
2240                                 // nearly a full block with garbage just to hit this case.
2241                                 continue;
2242                         }
2243                         if outp.script_pubkey == self.destination_script {
2244                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
2245                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2246                                         output: outp.clone(),
2247                                 });
2248                                 break;
2249                         } else if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2250                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2251                                         spendable_output =  Some(SpendableOutputDescriptor::DynamicOutputP2WSH {
2252                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2253                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
2254                                                 to_self_delay: self.on_holder_tx_csv,
2255                                                 output: outp.clone(),
2256                                                 key_derivation_params: self.keys.key_derivation_params(),
2257                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2258                                         });
2259                                         break;
2260                                 }
2261                         } else if self.counterparty_payment_script == outp.script_pubkey {
2262                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
2263                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2264                                         output: outp.clone(),
2265                                         key_derivation_params: self.keys.key_derivation_params(),
2266                                 });
2267                                 break;
2268                         } else if outp.script_pubkey == self.shutdown_script {
2269                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2270                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2271                                         output: outp.clone(),
2272                                 });
2273                         }
2274                 }
2275                 if let Some(spendable_output) = spendable_output {
2276                         log_trace!(logger, "Maturing {} until {}", log_spendable!(spendable_output), height + ANTI_REORG_DELAY - 1);
2277                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2278                                 hash_map::Entry::Occupied(mut entry) => {
2279                                         let e = entry.get_mut();
2280                                         e.push(OnchainEvent::MaturingOutput { descriptor: spendable_output });
2281                                 }
2282                                 hash_map::Entry::Vacant(entry) => {
2283                                         entry.insert(vec![OnchainEvent::MaturingOutput { descriptor: spendable_output }]);
2284                                 }
2285                         }
2286                 }
2287         }
2288 }
2289
2290 const MAX_ALLOC_SIZE: usize = 64*1024;
2291
2292 impl<ChanSigner: ChannelKeys + Readable> Readable for (BlockHash, ChannelMonitor<ChanSigner>) {
2293         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
2294                 macro_rules! unwrap_obj {
2295                         ($key: expr) => {
2296                                 match $key {
2297                                         Ok(res) => res,
2298                                         Err(_) => return Err(DecodeError::InvalidValue),
2299                                 }
2300                         }
2301                 }
2302
2303                 let _ver: u8 = Readable::read(reader)?;
2304                 let min_ver: u8 = Readable::read(reader)?;
2305                 if min_ver > SERIALIZATION_VERSION {
2306                         return Err(DecodeError::UnknownVersion);
2307                 }
2308
2309                 let latest_update_id: u64 = Readable::read(reader)?;
2310                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2311
2312                 let destination_script = Readable::read(reader)?;
2313                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2314                         0 => {
2315                                 let revokable_address = Readable::read(reader)?;
2316                                 let per_commitment_point = Readable::read(reader)?;
2317                                 let revokable_script = Readable::read(reader)?;
2318                                 Some((revokable_address, per_commitment_point, revokable_script))
2319                         },
2320                         1 => { None },
2321                         _ => return Err(DecodeError::InvalidValue),
2322                 };
2323                 let counterparty_payment_script = Readable::read(reader)?;
2324                 let shutdown_script = Readable::read(reader)?;
2325
2326                 let keys = Readable::read(reader)?;
2327                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2328                 // barely-init'd ChannelMonitors that we can't do anything with.
2329                 let outpoint = OutPoint {
2330                         txid: Readable::read(reader)?,
2331                         index: Readable::read(reader)?,
2332                 };
2333                 let funding_info = (outpoint, Readable::read(reader)?);
2334                 let current_counterparty_commitment_txid = Readable::read(reader)?;
2335                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2336
2337                 let counterparty_tx_cache = Readable::read(reader)?;
2338                 let funding_redeemscript = Readable::read(reader)?;
2339                 let channel_value_satoshis = Readable::read(reader)?;
2340
2341                 let their_cur_revocation_points = {
2342                         let first_idx = <U48 as Readable>::read(reader)?.0;
2343                         if first_idx == 0 {
2344                                 None
2345                         } else {
2346                                 let first_point = Readable::read(reader)?;
2347                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2348                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2349                                         Some((first_idx, first_point, None))
2350                                 } else {
2351                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2352                                 }
2353                         }
2354                 };
2355
2356                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2357
2358                 let commitment_secrets = Readable::read(reader)?;
2359
2360                 macro_rules! read_htlc_in_commitment {
2361                         () => {
2362                                 {
2363                                         let offered: bool = Readable::read(reader)?;
2364                                         let amount_msat: u64 = Readable::read(reader)?;
2365                                         let cltv_expiry: u32 = Readable::read(reader)?;
2366                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2367                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2368
2369                                         HTLCOutputInCommitment {
2370                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2371                                         }
2372                                 }
2373                         }
2374                 }
2375
2376                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2377                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2378                 for _ in 0..counterparty_claimable_outpoints_len {
2379                         let txid: Txid = Readable::read(reader)?;
2380                         let htlcs_count: u64 = Readable::read(reader)?;
2381                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2382                         for _ in 0..htlcs_count {
2383                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2384                         }
2385                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2386                                 return Err(DecodeError::InvalidValue);
2387                         }
2388                 }
2389
2390                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2391                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2392                 for _ in 0..counterparty_commitment_txn_on_chain_len {
2393                         let txid: Txid = Readable::read(reader)?;
2394                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2395                         let outputs_count = <u64 as Readable>::read(reader)?;
2396                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2397                         for _ in 0..outputs_count {
2398                                 outputs.push(Readable::read(reader)?);
2399                         }
2400                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2401                                 return Err(DecodeError::InvalidValue);
2402                         }
2403                 }
2404
2405                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2406                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2407                 for _ in 0..counterparty_hash_commitment_number_len {
2408                         let payment_hash: PaymentHash = Readable::read(reader)?;
2409                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2410                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2411                                 return Err(DecodeError::InvalidValue);
2412                         }
2413                 }
2414
2415                 macro_rules! read_holder_tx {
2416                         () => {
2417                                 {
2418                                         let txid = Readable::read(reader)?;
2419                                         let revocation_key = Readable::read(reader)?;
2420                                         let a_htlc_key = Readable::read(reader)?;
2421                                         let b_htlc_key = Readable::read(reader)?;
2422                                         let delayed_payment_key = Readable::read(reader)?;
2423                                         let per_commitment_point = Readable::read(reader)?;
2424                                         let feerate_per_kw: u32 = Readable::read(reader)?;
2425
2426                                         let htlcs_len: u64 = Readable::read(reader)?;
2427                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2428                                         for _ in 0..htlcs_len {
2429                                                 let htlc = read_htlc_in_commitment!();
2430                                                 let sigs = match <u8 as Readable>::read(reader)? {
2431                                                         0 => None,
2432                                                         1 => Some(Readable::read(reader)?),
2433                                                         _ => return Err(DecodeError::InvalidValue),
2434                                                 };
2435                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
2436                                         }
2437
2438                                         HolderSignedTx {
2439                                                 txid,
2440                                                 revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
2441                                                 htlc_outputs: htlcs
2442                                         }
2443                                 }
2444                         }
2445                 }
2446
2447                 let prev_holder_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2448                         0 => None,
2449                         1 => {
2450                                 Some(read_holder_tx!())
2451                         },
2452                         _ => return Err(DecodeError::InvalidValue),
2453                 };
2454                 let current_holder_commitment_tx = read_holder_tx!();
2455
2456                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2457                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2458
2459                 let payment_preimages_len: u64 = Readable::read(reader)?;
2460                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2461                 for _ in 0..payment_preimages_len {
2462                         let preimage: PaymentPreimage = Readable::read(reader)?;
2463                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2464                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2465                                 return Err(DecodeError::InvalidValue);
2466                         }
2467                 }
2468
2469                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
2470                 let mut pending_monitor_events = Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2471                 for _ in 0..pending_monitor_events_len {
2472                         let ev = match <u8 as Readable>::read(reader)? {
2473                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
2474                                 1 => MonitorEvent::CommitmentTxBroadcasted(funding_info.0),
2475                                 _ => return Err(DecodeError::InvalidValue)
2476                         };
2477                         pending_monitor_events.push(ev);
2478                 }
2479
2480                 let pending_events_len: u64 = Readable::read(reader)?;
2481                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
2482                 for _ in 0..pending_events_len {
2483                         if let Some(event) = MaybeReadable::read(reader)? {
2484                                 pending_events.push(event);
2485                         }
2486                 }
2487
2488                 let last_block_hash: BlockHash = Readable::read(reader)?;
2489
2490                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2491                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2492                 for _ in 0..waiting_threshold_conf_len {
2493                         let height_target = Readable::read(reader)?;
2494                         let events_len: u64 = Readable::read(reader)?;
2495                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
2496                         for _ in 0..events_len {
2497                                 let ev = match <u8 as Readable>::read(reader)? {
2498                                         0 => {
2499                                                 let htlc_source = Readable::read(reader)?;
2500                                                 let hash = Readable::read(reader)?;
2501                                                 OnchainEvent::HTLCUpdate {
2502                                                         htlc_update: (htlc_source, hash)
2503                                                 }
2504                                         },
2505                                         1 => {
2506                                                 let descriptor = Readable::read(reader)?;
2507                                                 OnchainEvent::MaturingOutput {
2508                                                         descriptor
2509                                                 }
2510                                         },
2511                                         _ => return Err(DecodeError::InvalidValue),
2512                                 };
2513                                 events.push(ev);
2514                         }
2515                         onchain_events_waiting_threshold_conf.insert(height_target, events);
2516                 }
2517
2518                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2519                 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<Vec<Script>>())));
2520                 for _ in 0..outputs_to_watch_len {
2521                         let txid = Readable::read(reader)?;
2522                         let outputs_len: u64 = Readable::read(reader)?;
2523                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
2524                         for _ in 0..outputs_len {
2525                                 outputs.push(Readable::read(reader)?);
2526                         }
2527                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2528                                 return Err(DecodeError::InvalidValue);
2529                         }
2530                 }
2531                 let onchain_tx_handler = Readable::read(reader)?;
2532
2533                 let lockdown_from_offchain = Readable::read(reader)?;
2534                 let holder_tx_signed = Readable::read(reader)?;
2535
2536                 Ok((last_block_hash.clone(), ChannelMonitor {
2537                         latest_update_id,
2538                         commitment_transaction_number_obscure_factor,
2539
2540                         destination_script,
2541                         broadcasted_holder_revokable_script,
2542                         counterparty_payment_script,
2543                         shutdown_script,
2544
2545                         keys,
2546                         funding_info,
2547                         current_counterparty_commitment_txid,
2548                         prev_counterparty_commitment_txid,
2549
2550                         counterparty_tx_cache,
2551                         funding_redeemscript,
2552                         channel_value_satoshis,
2553                         their_cur_revocation_points,
2554
2555                         on_holder_tx_csv,
2556
2557                         commitment_secrets,
2558                         counterparty_claimable_outpoints,
2559                         counterparty_commitment_txn_on_chain,
2560                         counterparty_hash_commitment_number,
2561
2562                         prev_holder_signed_commitment_tx,
2563                         current_holder_commitment_tx,
2564                         current_counterparty_commitment_number,
2565                         current_holder_commitment_number,
2566
2567                         payment_preimages,
2568                         pending_monitor_events,
2569                         pending_events,
2570
2571                         onchain_events_waiting_threshold_conf,
2572                         outputs_to_watch,
2573
2574                         onchain_tx_handler,
2575
2576                         lockdown_from_offchain,
2577                         holder_tx_signed,
2578
2579                         last_block_hash,
2580                         secp_ctx: Secp256k1::new(),
2581                 }))
2582         }
2583 }
2584
2585 #[cfg(test)]
2586 mod tests {
2587         use bitcoin::blockdata::script::{Script, Builder};
2588         use bitcoin::blockdata::opcodes;
2589         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2590         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2591         use bitcoin::util::bip143;
2592         use bitcoin::hashes::Hash;
2593         use bitcoin::hashes::sha256::Hash as Sha256;
2594         use bitcoin::hashes::hex::FromHex;
2595         use bitcoin::hash_types::Txid;
2596         use hex;
2597         use chain::transaction::OutPoint;
2598         use ln::channelmanager::{PaymentPreimage, PaymentHash};
2599         use ln::channelmonitor::ChannelMonitor;
2600         use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
2601         use ln::chan_utils;
2602         use ln::chan_utils::{HTLCOutputInCommitment, HolderCommitmentTransaction};
2603         use util::test_utils::TestLogger;
2604         use bitcoin::secp256k1::key::{SecretKey,PublicKey};
2605         use bitcoin::secp256k1::Secp256k1;
2606         use std::sync::Arc;
2607         use chain::keysinterface::InMemoryChannelKeys;
2608
2609         #[test]
2610         fn test_prune_preimages() {
2611                 let secp_ctx = Secp256k1::new();
2612                 let logger = Arc::new(TestLogger::new());
2613
2614                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2615                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2616
2617                 let mut preimages = Vec::new();
2618                 {
2619                         for i in 0..20 {
2620                                 let preimage = PaymentPreimage([i; 32]);
2621                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2622                                 preimages.push((preimage, hash));
2623                         }
2624                 }
2625
2626                 macro_rules! preimages_slice_to_htlc_outputs {
2627                         ($preimages_slice: expr) => {
2628                                 {
2629                                         let mut res = Vec::new();
2630                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2631                                                 res.push((HTLCOutputInCommitment {
2632                                                         offered: true,
2633                                                         amount_msat: 0,
2634                                                         cltv_expiry: 0,
2635                                                         payment_hash: preimage.1.clone(),
2636                                                         transaction_output_index: Some(idx as u32),
2637                                                 }, None));
2638                                         }
2639                                         res
2640                                 }
2641                         }
2642                 }
2643                 macro_rules! preimages_to_holder_htlcs {
2644                         ($preimages_slice: expr) => {
2645                                 {
2646                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2647                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2648                                         res
2649                                 }
2650                         }
2651                 }
2652
2653                 macro_rules! test_preimages_exist {
2654                         ($preimages_slice: expr, $monitor: expr) => {
2655                                 for preimage in $preimages_slice {
2656                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2657                                 }
2658                         }
2659                 }
2660
2661                 let keys = InMemoryChannelKeys::new(
2662                         &secp_ctx,
2663                         SecretKey::from_slice(&[41; 32]).unwrap(),
2664                         SecretKey::from_slice(&[41; 32]).unwrap(),
2665                         SecretKey::from_slice(&[41; 32]).unwrap(),
2666                         SecretKey::from_slice(&[41; 32]).unwrap(),
2667                         SecretKey::from_slice(&[41; 32]).unwrap(),
2668                         [41; 32],
2669                         0,
2670                         (0, 0)
2671                 );
2672
2673                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
2674                 // old state.
2675                 let mut monitor = ChannelMonitor::new(keys,
2676                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
2677                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2678                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2679                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2680                         10, Script::new(), 46, 0, HolderCommitmentTransaction::dummy());
2681
2682                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
2683                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
2684                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
2685                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
2686                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
2687                 for &(ref preimage, ref hash) in preimages.iter() {
2688                         monitor.provide_payment_preimage(hash, preimage);
2689                 }
2690
2691                 // Now provide a secret, pruning preimages 10-15
2692                 let mut secret = [0; 32];
2693                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2694                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2695                 assert_eq!(monitor.payment_preimages.len(), 15);
2696                 test_preimages_exist!(&preimages[0..10], monitor);
2697                 test_preimages_exist!(&preimages[15..20], monitor);
2698
2699                 // Now provide a further secret, pruning preimages 15-17
2700                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2701                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2702                 assert_eq!(monitor.payment_preimages.len(), 13);
2703                 test_preimages_exist!(&preimages[0..10], monitor);
2704                 test_preimages_exist!(&preimages[17..20], monitor);
2705
2706                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
2707                 // previous commitment tx's preimages too
2708                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
2709                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2710                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2711                 assert_eq!(monitor.payment_preimages.len(), 12);
2712                 test_preimages_exist!(&preimages[0..10], monitor);
2713                 test_preimages_exist!(&preimages[18..20], monitor);
2714
2715                 // But if we do it again, we'll prune 5-10
2716                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
2717                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2718                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2719                 assert_eq!(monitor.payment_preimages.len(), 5);
2720                 test_preimages_exist!(&preimages[0..5], monitor);
2721         }
2722
2723         #[test]
2724         fn test_claim_txn_weight_computation() {
2725                 // We test Claim txn weight, knowing that we want expected weigth and
2726                 // not actual case to avoid sigs and time-lock delays hell variances.
2727
2728                 let secp_ctx = Secp256k1::new();
2729                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
2730                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
2731                 let mut sum_actual_sigs = 0;
2732
2733                 macro_rules! sign_input {
2734                         ($sighash_parts: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
2735                                 let htlc = HTLCOutputInCommitment {
2736                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
2737                                         amount_msat: 0,
2738                                         cltv_expiry: 2 << 16,
2739                                         payment_hash: PaymentHash([1; 32]),
2740                                         transaction_output_index: Some($idx as u32),
2741                                 };
2742                                 let redeem_script = if *$input_type == InputDescriptors::RevokedOutput { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
2743                                 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
2744                                 let sig = secp_ctx.sign(&sighash, &privkey);
2745                                 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
2746                                 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
2747                                 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
2748                                 if *$input_type == InputDescriptors::RevokedOutput {
2749                                         $sighash_parts.access_witness($idx).push(vec!(1));
2750                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
2751                                         $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
2752                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
2753                                         $sighash_parts.access_witness($idx).push(vec![0]);
2754                                 } else {
2755                                         $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
2756                                 }
2757                                 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
2758                                 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
2759                                 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
2760                                 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
2761                         }
2762                 }
2763
2764                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
2765                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
2766
2767                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
2768                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2769                 for i in 0..4 {
2770                         claim_tx.input.push(TxIn {
2771                                 previous_output: BitcoinOutPoint {
2772                                         txid,
2773                                         vout: i,
2774                                 },
2775                                 script_sig: Script::new(),
2776                                 sequence: 0xfffffffd,
2777                                 witness: Vec::new(),
2778                         });
2779                 }
2780                 claim_tx.output.push(TxOut {
2781                         script_pubkey: script_pubkey.clone(),
2782                         value: 0,
2783                 });
2784                 let base_weight = claim_tx.get_weight();
2785                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
2786                 {
2787                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2788                         for (idx, inp) in inputs_des.iter().enumerate() {
2789                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2790                         }
2791                 }
2792                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2793
2794                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
2795                 claim_tx.input.clear();
2796                 sum_actual_sigs = 0;
2797                 for i in 0..4 {
2798                         claim_tx.input.push(TxIn {
2799                                 previous_output: BitcoinOutPoint {
2800                                         txid,
2801                                         vout: i,
2802                                 },
2803                                 script_sig: Script::new(),
2804                                 sequence: 0xfffffffd,
2805                                 witness: Vec::new(),
2806                         });
2807                 }
2808                 let base_weight = claim_tx.get_weight();
2809                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
2810                 {
2811                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2812                         for (idx, inp) in inputs_des.iter().enumerate() {
2813                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2814                         }
2815                 }
2816                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2817
2818                 // Justice tx with 1 revoked HTLC-Success tx output
2819                 claim_tx.input.clear();
2820                 sum_actual_sigs = 0;
2821                 claim_tx.input.push(TxIn {
2822                         previous_output: BitcoinOutPoint {
2823                                 txid,
2824                                 vout: 0,
2825                         },
2826                         script_sig: Script::new(),
2827                         sequence: 0xfffffffd,
2828                         witness: Vec::new(),
2829                 });
2830                 let base_weight = claim_tx.get_weight();
2831                 let inputs_des = vec![InputDescriptors::RevokedOutput];
2832                 {
2833                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2834                         for (idx, inp) in inputs_des.iter().enumerate() {
2835                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2836                         }
2837                 }
2838                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
2839         }
2840
2841         // Further testing is done in the ChannelManager integration tests.
2842 }