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