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