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