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