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