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