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