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