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