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