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