Fail all pending HTLCs if the remote broadcasts a revoked tx
[rust-lightning] / src / ln / channelmonitor.rs
1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
2 //! here.
3 //!
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
7 //!
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
13
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode::{self, Decodable, Encodable};
20 use bitcoin::util::hash::{Hash160, BitcoinHash,Sha256dHash};
21 use bitcoin::util::bip143;
22
23 use crypto::digest::Digest;
24
25 use secp256k1::{Secp256k1,Message,Signature};
26 use secp256k1::key::{SecretKey,PublicKey};
27 use secp256k1;
28
29 use ln::msgs::DecodeError;
30 use ln::chan_utils;
31 use ln::chan_utils::HTLCOutputInCommitment;
32 use ln::channelmanager::HTLCSource;
33 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
34 use chain::transaction::OutPoint;
35 use chain::keysinterface::SpendableOutputDescriptor;
36 use util::logger::Logger;
37 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
38 use util::sha2::Sha256;
39 use util::{byte_utils, events};
40
41 use std::collections::{HashMap, hash_map};
42 use std::sync::{Arc,Mutex};
43 use std::{hash,cmp, mem};
44
45 /// An error enum representing a failure to persist a channel monitor update.
46 #[derive(Clone)]
47 pub enum ChannelMonitorUpdateErr {
48         /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
49         /// to succeed at some point in the future).
50         ///
51         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
52         /// submitting new commitment transactions to the remote party.
53         /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
54         /// the channel to an operational state.
55         ///
56         /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
57         /// persisted is unsafe - if you failed to store the update on your own local disk you should
58         /// instead return PermanentFailure to force closure of the channel ASAP.
59         ///
60         /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
61         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
62         /// to claim it on this channel) and those updates must be applied wherever they can be. At
63         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
64         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
65         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
66         /// been "frozen".
67         ///
68         /// Note that even if updates made after TemporaryFailure succeed you must still call
69         /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
70         /// channel operation.
71         TemporaryFailure,
72         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
73         /// different watchtower and cannot update with all watchtowers that were previously informed
74         /// of this channel). This will force-close the channel in question.
75         ///
76         /// Should also be used to indicate a failure to update the local copy of the channel monitor.
77         PermanentFailure,
78 }
79
80 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
81 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
82 /// means you tried to merge two monitors for different channels or for a channel which was
83 /// restored from a backup and then generated new commitment updates.
84 /// Contains a human-readable error message.
85 #[derive(Debug)]
86 pub struct MonitorUpdateError(pub &'static str);
87
88 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
89 /// forward channel and from which info are needed to update HTLC in a backward channel.
90 pub struct HTLCUpdate {
91         pub(super) payment_hash: [u8; 32],
92         pub(super) payment_preimage: Option<[u8; 32]>,
93         pub(super) source: HTLCSource
94 }
95
96 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
97 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
98 /// events to it, while also taking any add_update_monitor events and passing them to some remote
99 /// server(s).
100 ///
101 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
102 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
103 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
104 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
105 pub trait ManyChannelMonitor: Send + Sync {
106         /// Adds or updates a monitor for the given `funding_txo`.
107         ///
108         /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
109         /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
110         /// any spends of it.
111         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
112
113         /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
114         /// with success or failure backward
115         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate>;
116 }
117
118 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
119 /// watchtower or watch our own channels.
120 ///
121 /// Note that you must provide your own key by which to refer to channels.
122 ///
123 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
124 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
125 /// index by a PublicKey which is required to sign any updates.
126 ///
127 /// If you're using this for local monitoring of your own channels, you probably want to use
128 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
129 pub struct SimpleManyChannelMonitor<Key> {
130         #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
131         pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
132         #[cfg(not(test))]
133         monitors: Mutex<HashMap<Key, ChannelMonitor>>,
134         chain_monitor: Arc<ChainWatchInterface>,
135         broadcaster: Arc<BroadcasterInterface>,
136         pending_events: Mutex<Vec<events::Event>>,
137         pending_htlc_updated: Mutex<HashMap<[u8; 32], Vec<(HTLCSource, Option<[u8; 32]>)>>>,
138         logger: Arc<Logger>,
139 }
140
141 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
142         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
143                 let block_hash = header.bitcoin_hash();
144                 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
145                 let mut htlc_updated_infos = Vec::new();
146                 {
147                         let mut monitors = self.monitors.lock().unwrap();
148                         for monitor in monitors.values_mut() {
149                                 let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
150                                 if spendable_outputs.len() > 0 {
151                                         new_events.push(events::Event::SpendableOutputs {
152                                                 outputs: spendable_outputs,
153                                         });
154                                 }
155
156                                 for (ref txid, ref outputs) in txn_outputs {
157                                         for (idx, output) in outputs.iter().enumerate() {
158                                                 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
159                                         }
160                                 }
161                                 htlc_updated_infos.append(&mut htlc_updated);
162                         }
163                 }
164                 {
165                         // ChannelManager will just need to fetch pending_htlc_updated and pass state backward
166                         let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap();
167                         for htlc in htlc_updated_infos.drain(..) {
168                                 match pending_htlc_updated.entry(htlc.2) {
169                                         hash_map::Entry::Occupied(mut e) => {
170                                                 // In case of reorg we may have htlc outputs solved in a different way so
171                                                 // we prefer to keep claims but don't store duplicate updates for a given
172                                                 // (payment_hash, HTLCSource) pair.
173                                                 // TODO: Note that we currently don't really use this as ChannelManager
174                                                 // will fail/claim backwards after the first block. We really should delay
175                                                 // a few blocks before failing backwards (but can claim backwards
176                                                 // immediately) as long as we have a few blocks of headroom.
177                                                 let mut existing_claim = false;
178                                                 e.get_mut().retain(|htlc_data| {
179                                                         if htlc.0 == htlc_data.0 {
180                                                                 if htlc_data.1.is_some() {
181                                                                         existing_claim = true;
182                                                                         true
183                                                                 } else { false }
184                                                         } else { true }
185                                                 });
186                                                 if !existing_claim {
187                                                         e.get_mut().push((htlc.0, htlc.1));
188                                                 }
189                                         }
190                                         hash_map::Entry::Vacant(e) => {
191                                                 e.insert(vec![(htlc.0, htlc.1)]);
192                                         }
193                                 }
194                         }
195                 }
196                 let mut pending_events = self.pending_events.lock().unwrap();
197                 pending_events.append(&mut new_events);
198         }
199
200         fn block_disconnected(&self, _: &BlockHeader) { }
201 }
202
203 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
204         /// Creates a new object which can be used to monitor several channels given the chain
205         /// interface with which to register to receive notifications.
206         pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
207                 let res = Arc::new(SimpleManyChannelMonitor {
208                         monitors: Mutex::new(HashMap::new()),
209                         chain_monitor,
210                         broadcaster,
211                         pending_events: Mutex::new(Vec::new()),
212                         pending_htlc_updated: Mutex::new(HashMap::new()),
213                         logger,
214                 });
215                 let weak_res = Arc::downgrade(&res);
216                 res.chain_monitor.register_listener(weak_res);
217                 res
218         }
219
220         /// Adds or udpates the monitor which monitors the channel referred to by the given key.
221         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
222                 let mut monitors = self.monitors.lock().unwrap();
223                 match monitors.get_mut(&key) {
224                         Some(orig_monitor) => {
225                                 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
226                                 return orig_monitor.insert_combine(monitor);
227                         },
228                         None => {}
229                 };
230                 match monitor.key_storage {
231                         Storage::Local { ref funding_info, .. } => {
232                                 match funding_info {
233                                         &None => {
234                                                 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
235                                         },
236                                         &Some((ref outpoint, ref script)) => {
237                                                 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
238                                                 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
239                                                 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
240                                         },
241                                 }
242                         },
243                         Storage::Watchtower { .. } => {
244                                 self.chain_monitor.watch_all_txn();
245                         }
246                 }
247                 monitors.insert(key, monitor);
248                 Ok(())
249         }
250 }
251
252 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
253         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
254                 match self.add_update_monitor_by_key(funding_txo, monitor) {
255                         Ok(_) => Ok(()),
256                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
257                 }
258         }
259
260         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
261                 let mut updated = self.pending_htlc_updated.lock().unwrap();
262                 let mut pending_htlcs_updated = Vec::with_capacity(updated.len());
263                 for (k, v) in updated.drain() {
264                         for htlc_data in v {
265                                 pending_htlcs_updated.push(HTLCUpdate {
266                                         payment_hash: k,
267                                         payment_preimage: htlc_data.1,
268                                         source: htlc_data.0,
269                                 });
270                         }
271                 }
272                 pending_htlcs_updated
273         }
274 }
275
276 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
277         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
278                 let mut pending_events = self.pending_events.lock().unwrap();
279                 let mut ret = Vec::new();
280                 mem::swap(&mut ret, &mut *pending_events);
281                 ret
282         }
283 }
284
285 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
286 /// instead claiming it in its own individual transaction.
287 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
288 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
289 /// HTLC-Success transaction.
290 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
291 /// transaction confirmed (and we use it in a few more, equivalent, places).
292 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
293 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
294 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
295 /// copies of ChannelMonitors, including watchtowers).
296 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
297
298 #[derive(Clone, PartialEq)]
299 enum Storage {
300         Local {
301                 revocation_base_key: SecretKey,
302                 htlc_base_key: SecretKey,
303                 delayed_payment_base_key: SecretKey,
304                 payment_base_key: SecretKey,
305                 shutdown_pubkey: PublicKey,
306                 prev_latest_per_commitment_point: Option<PublicKey>,
307                 latest_per_commitment_point: Option<PublicKey>,
308                 funding_info: Option<(OutPoint, Script)>,
309                 current_remote_commitment_txid: Option<Sha256dHash>,
310                 prev_remote_commitment_txid: Option<Sha256dHash>,
311         },
312         Watchtower {
313                 revocation_base_key: PublicKey,
314                 htlc_base_key: PublicKey,
315         }
316 }
317
318 #[derive(Clone, PartialEq)]
319 struct LocalSignedTx {
320         /// txid of the transaction in tx, just used to make comparison faster
321         txid: Sha256dHash,
322         tx: Transaction,
323         revocation_key: PublicKey,
324         a_htlc_key: PublicKey,
325         b_htlc_key: PublicKey,
326         delayed_payment_key: PublicKey,
327         feerate_per_kw: u64,
328         htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
329         htlc_sources: Vec<([u8; 32], HTLCSource, Option<u32>)>,
330 }
331
332 const SERIALIZATION_VERSION: u8 = 1;
333 const MIN_SERIALIZATION_VERSION: u8 = 1;
334
335 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
336 /// on-chain transactions to ensure no loss of funds occurs.
337 ///
338 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
339 /// information and are actively monitoring the chain.
340 #[derive(Clone)]
341 pub struct ChannelMonitor {
342         commitment_transaction_number_obscure_factor: u64,
343
344         key_storage: Storage,
345         their_htlc_base_key: Option<PublicKey>,
346         their_delayed_payment_base_key: Option<PublicKey>,
347         // first is the idx of the first of the two revocation points
348         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
349
350         our_to_self_delay: u16,
351         their_to_self_delay: Option<u16>,
352
353         old_secrets: [([u8; 32], u64); 49],
354         remote_claimable_outpoints: HashMap<Sha256dHash, (Vec<HTLCOutputInCommitment>, Vec<([u8; 32], HTLCSource, Option<u32>)>)>,
355         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
356         /// Nor can we figure out their commitment numbers without the commitment transaction they are
357         /// spending. Thus, in order to claim them via revocation key, we track all the remote
358         /// commitment transactions which we find on-chain, mapping them to the commitment number which
359         /// can be used to derive the revocation key and claim the transactions.
360         remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
361         /// Cache used to make pruning of payment_preimages faster.
362         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
363         /// remote transactions (ie should remain pretty small).
364         /// Serialized to disk but should generally not be sent to Watchtowers.
365         remote_hash_commitment_number: HashMap<[u8; 32], u64>,
366
367         // We store two local commitment transactions to avoid any race conditions where we may update
368         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
369         // various monitors for one channel being out of sync, and us broadcasting a local
370         // transaction for which we have deleted claim information on some watchtowers.
371         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
372         current_local_signed_commitment_tx: Option<LocalSignedTx>,
373
374         // Used just for ChannelManager to make sure it has the latest channel data during
375         // deserialization
376         current_remote_commitment_number: u64,
377
378         payment_preimages: HashMap<[u8; 32], [u8; 32]>,
379
380         destination_script: Script,
381
382         // We simply modify last_block_hash in Channel's block_connected so that serialization is
383         // consistent but hopefully the users' copy handles block_connected in a consistent way.
384         // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
385         // their last_block_hash from its state and not based on updated copies that didn't run through
386         // the full block_connected).
387         pub(crate) last_block_hash: Sha256dHash,
388         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
389         logger: Arc<Logger>,
390 }
391
392 #[cfg(any(test, feature = "fuzztarget"))]
393 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
394 /// underlying object
395 impl PartialEq for ChannelMonitor {
396         fn eq(&self, other: &Self) -> bool {
397                 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
398                         self.key_storage != other.key_storage ||
399                         self.their_htlc_base_key != other.their_htlc_base_key ||
400                         self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
401                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
402                         self.our_to_self_delay != other.our_to_self_delay ||
403                         self.their_to_self_delay != other.their_to_self_delay ||
404                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
405                         self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
406                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
407                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
408                         self.current_remote_commitment_number != other.current_remote_commitment_number ||
409                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
410                         self.payment_preimages != other.payment_preimages ||
411                         self.destination_script != other.destination_script
412                 {
413                         false
414                 } else {
415                         for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
416                                 if secret != o_secret || idx != o_idx {
417                                         return false
418                                 }
419                         }
420                         true
421                 }
422         }
423 }
424
425 impl ChannelMonitor {
426         pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
427                 ChannelMonitor {
428                         commitment_transaction_number_obscure_factor: 0,
429
430                         key_storage: Storage::Local {
431                                 revocation_base_key: revocation_base_key.clone(),
432                                 htlc_base_key: htlc_base_key.clone(),
433                                 delayed_payment_base_key: delayed_payment_base_key.clone(),
434                                 payment_base_key: payment_base_key.clone(),
435                                 shutdown_pubkey: shutdown_pubkey.clone(),
436                                 prev_latest_per_commitment_point: None,
437                                 latest_per_commitment_point: None,
438                                 funding_info: None,
439                                 current_remote_commitment_txid: None,
440                                 prev_remote_commitment_txid: None,
441                         },
442                         their_htlc_base_key: None,
443                         their_delayed_payment_base_key: None,
444                         their_cur_revocation_points: None,
445
446                         our_to_self_delay: our_to_self_delay,
447                         their_to_self_delay: None,
448
449                         old_secrets: [([0; 32], 1 << 48); 49],
450                         remote_claimable_outpoints: HashMap::new(),
451                         remote_commitment_txn_on_chain: HashMap::new(),
452                         remote_hash_commitment_number: HashMap::new(),
453
454                         prev_local_signed_commitment_tx: None,
455                         current_local_signed_commitment_tx: None,
456                         current_remote_commitment_number: 1 << 48,
457
458                         payment_preimages: HashMap::new(),
459                         destination_script: destination_script,
460
461                         last_block_hash: Default::default(),
462                         secp_ctx: Secp256k1::new(),
463                         logger,
464                 }
465         }
466
467         #[inline]
468         fn place_secret(idx: u64) -> u8 {
469                 for i in 0..48 {
470                         if idx & (1 << i) == (1 << i) {
471                                 return i
472                         }
473                 }
474                 48
475         }
476
477         #[inline]
478         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
479                 let mut res: [u8; 32] = secret;
480                 for i in 0..bits {
481                         let bitpos = bits - 1 - i;
482                         if idx & (1 << bitpos) == (1 << bitpos) {
483                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
484                                 let mut sha = Sha256::new();
485                                 sha.input(&res);
486                                 sha.result(&mut res);
487                         }
488                 }
489                 res
490         }
491
492         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
493         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
494         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
495         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
496                 let pos = ChannelMonitor::place_secret(idx);
497                 for i in 0..pos {
498                         let (old_secret, old_idx) = self.old_secrets[i as usize];
499                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
500                                 return Err(MonitorUpdateError("Previous secret did not match new one"));
501                         }
502                 }
503                 if self.get_min_seen_secret() <= idx {
504                         return Ok(());
505                 }
506                 self.old_secrets[pos as usize] = (secret, idx);
507
508                 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
509                 // events for now-revoked/fulfilled HTLCs.
510                 // TODO: We should probably consider whether we're really getting the next secret here.
511                 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
512                         if let Some(txid) = prev_remote_commitment_txid.take() {
513                                 self.remote_claimable_outpoints.get_mut(&txid).unwrap().1 = Vec::new();
514                         }
515                 }
516
517                 if !self.payment_preimages.is_empty() {
518                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
519                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
520                         let min_idx = self.get_min_seen_secret();
521                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
522
523                         self.payment_preimages.retain(|&k, _| {
524                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
525                                         if k == htlc.payment_hash {
526                                                 return true
527                                         }
528                                 }
529                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
530                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
531                                                 if k == htlc.payment_hash {
532                                                         return true
533                                                 }
534                                         }
535                                 }
536                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
537                                         if *cn < min_idx {
538                                                 return true
539                                         }
540                                         true
541                                 } else { false };
542                                 if contains {
543                                         remote_hash_commitment_number.remove(&k);
544                                 }
545                                 false
546                         });
547                 }
548
549                 Ok(())
550         }
551
552         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
553         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
554         /// possibly future revocation/preimage information) to claim outputs where possible.
555         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
556         pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, htlc_sources: Vec<([u8; 32], HTLCSource, Option<u32>)>, commitment_number: u64, their_revocation_point: PublicKey) {
557                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
558                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
559                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
560                 // timeouts)
561                 for ref htlc in &htlc_outputs {
562                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
563                 }
564
565                 let new_txid = unsigned_commitment_tx.txid();
566                 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
567                         *prev_remote_commitment_txid = current_remote_commitment_txid.take();
568                         *current_remote_commitment_txid = Some(new_txid);
569                 }
570                 self.remote_claimable_outpoints.insert(new_txid, (htlc_outputs, htlc_sources));
571                 self.current_remote_commitment_number = commitment_number;
572                 //TODO: Merge this into the other per-remote-transaction output storage stuff
573                 match self.their_cur_revocation_points {
574                         Some(old_points) => {
575                                 if old_points.0 == commitment_number + 1 {
576                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
577                                 } else if old_points.0 == commitment_number + 2 {
578                                         if let Some(old_second_point) = old_points.2 {
579                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
580                                         } else {
581                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
582                                         }
583                                 } else {
584                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
585                                 }
586                         },
587                         None => {
588                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
589                         }
590                 }
591         }
592
593         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
594         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
595         /// is important that any clones of this channel monitor (including remote clones) by kept
596         /// up-to-date as our local commitment transaction is updated.
597         /// Panics if set_their_to_self_delay has never been called.
598         /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
599         /// case of onchain HTLC tx
600         pub(super) fn provide_latest_local_commitment_tx_info(&mut self, signed_commitment_tx: Transaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>, htlc_sources: Vec<([u8; 32], HTLCSource, Option<u32>)>) {
601                 assert!(self.their_to_self_delay.is_some());
602                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
603                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
604                         txid: signed_commitment_tx.txid(),
605                         tx: signed_commitment_tx,
606                         revocation_key: local_keys.revocation_key,
607                         a_htlc_key: local_keys.a_htlc_key,
608                         b_htlc_key: local_keys.b_htlc_key,
609                         delayed_payment_key: local_keys.a_delayed_payment_key,
610                         feerate_per_kw,
611                         htlc_outputs,
612                         htlc_sources,
613                 });
614
615                 if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
616                         *latest_per_commitment_point = Some(local_keys.per_commitment_point);
617                 } else {
618                         panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
619                 }
620         }
621
622         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
623         /// commitment_tx_infos which contain the payment hash have been revoked.
624         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
625                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
626         }
627
628         /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
629         /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
630         /// chain for new blocks/transactions.
631         pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
632                 match self.key_storage {
633                         Storage::Local { ref funding_info, .. } => {
634                                 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
635                                 let our_funding_info = funding_info;
636                                 if let Storage::Local { ref funding_info, .. } = other.key_storage {
637                                         if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
638                                         // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
639                                         // easy to collide the funding_txo hash and have a different scriptPubKey.
640                                         if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
641                                                 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
642                                         }
643                                 } else {
644                                         return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
645                                 }
646                         },
647                         Storage::Watchtower { .. } => {
648                                 if let Storage::Watchtower { .. } = other.key_storage {
649                                         unimplemented!();
650                                 } else {
651                                         return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
652                                 }
653                         },
654                 }
655                 let other_min_secret = other.get_min_seen_secret();
656                 let our_min_secret = self.get_min_seen_secret();
657                 if our_min_secret > other_min_secret {
658                         self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
659                 }
660                 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
661                         if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
662                                 let our_commitment_number = 0xffffffffffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
663                                 let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
664                                 if our_commitment_number >= other_commitment_number {
665                                         self.key_storage = other.key_storage;
666                                 }
667                         }
668                 }
669                 // TODO: We should use current_remote_commitment_number and the commitment number out of
670                 // local transactions to decide how to merge
671                 if our_min_secret >= other_min_secret {
672                         self.their_cur_revocation_points = other.their_cur_revocation_points;
673                         for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
674                                 self.remote_claimable_outpoints.insert(txid, htlcs);
675                         }
676                         if let Some(local_tx) = other.prev_local_signed_commitment_tx {
677                                 self.prev_local_signed_commitment_tx = Some(local_tx);
678                         }
679                         if let Some(local_tx) = other.current_local_signed_commitment_tx {
680                                 self.current_local_signed_commitment_tx = Some(local_tx);
681                         }
682                         self.payment_preimages = other.payment_preimages;
683                 }
684
685                 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
686                 Ok(())
687         }
688
689         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
690         pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
691                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
692                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
693         }
694
695         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
696         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
697         /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
698         /// provides slightly better privacy.
699         /// It's the responsibility of the caller to register outpoint and script with passing the former
700         /// value as key to add_update_monitor.
701         pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
702                 match self.key_storage {
703                         Storage::Local { ref mut funding_info, .. } => {
704                                 *funding_info = Some(new_funding_info);
705                         },
706                         Storage::Watchtower { .. } => {
707                                 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
708                         }
709                 }
710         }
711
712         /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
713         pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
714                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
715                 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
716         }
717
718         pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
719                 self.their_to_self_delay = Some(their_to_self_delay);
720         }
721
722         pub(super) fn unset_funding_info(&mut self) {
723                 match self.key_storage {
724                         Storage::Local { ref mut funding_info, .. } => {
725                                 *funding_info = None;
726                         },
727                         Storage::Watchtower { .. } => {
728                                 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
729                         },
730                 }
731         }
732
733         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
734         pub fn get_funding_txo(&self) -> Option<OutPoint> {
735                 match self.key_storage {
736                         Storage::Local { ref funding_info, .. } => {
737                                 match funding_info {
738                                         &Some((outpoint, _)) => Some(outpoint),
739                                         &None => None
740                                 }
741                         },
742                         Storage::Watchtower { .. } => {
743                                 return None;
744                         }
745                 }
746         }
747
748         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
749         /// Generally useful when deserializing as during normal operation the return values of
750         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
751         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
752         pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
753                 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
754                 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
755                         for (idx, output) in outputs.iter().enumerate() {
756                                 res.push(((*txid).clone(), idx as u32, output));
757                         }
758                 }
759                 res
760         }
761
762         /// Serializes into a vec, with various modes for the exposed pub fns
763         fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
764                 //TODO: We still write out all the serialization here manually instead of using the fancy
765                 //serialization framework we have, we should migrate things over to it.
766                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
767                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
768
769                 // Set in initial Channel-object creation, so should always be set by now:
770                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
771
772                 match self.key_storage {
773                         Storage::Local { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info, current_remote_commitment_txid, prev_remote_commitment_txid } => {
774                                 writer.write_all(&[0; 1])?;
775                                 writer.write_all(&revocation_base_key[..])?;
776                                 writer.write_all(&htlc_base_key[..])?;
777                                 writer.write_all(&delayed_payment_base_key[..])?;
778                                 writer.write_all(&payment_base_key[..])?;
779                                 writer.write_all(&shutdown_pubkey.serialize())?;
780                                 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
781                                         writer.write_all(&[1; 1])?;
782                                         writer.write_all(&prev_latest_per_commitment_point.serialize())?;
783                                 } else {
784                                         writer.write_all(&[0; 1])?;
785                                 }
786                                 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
787                                         writer.write_all(&[1; 1])?;
788                                         writer.write_all(&latest_per_commitment_point.serialize())?;
789                                 } else {
790                                         writer.write_all(&[0; 1])?;
791                                 }
792                                 match funding_info  {
793                                         &Some((ref outpoint, ref script)) => {
794                                                 writer.write_all(&outpoint.txid[..])?;
795                                                 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
796                                                 script.write(writer)?;
797                                         },
798                                         &None => {
799                                                 debug_assert!(false, "Try to serialize a useless Local monitor !");
800                                         },
801                                 }
802                                 if let Some(ref txid) = current_remote_commitment_txid {
803                                         writer.write_all(&[1; 1])?;
804                                         writer.write_all(&txid[..])?;
805                                 } else {
806                                         writer.write_all(&[0; 1])?;
807                                 }
808                                 if let Some(ref txid) = prev_remote_commitment_txid {
809                                         writer.write_all(&[1; 1])?;
810                                         writer.write_all(&txid[..])?;
811                                 } else {
812                                         writer.write_all(&[0; 1])?;
813                                 }
814                         },
815                         Storage::Watchtower { .. } => unimplemented!(),
816                 }
817
818                 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
819                 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
820
821                 match self.their_cur_revocation_points {
822                         Some((idx, pubkey, second_option)) => {
823                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
824                                 writer.write_all(&pubkey.serialize())?;
825                                 match second_option {
826                                         Some(second_pubkey) => {
827                                                 writer.write_all(&second_pubkey.serialize())?;
828                                         },
829                                         None => {
830                                                 writer.write_all(&[0; 33])?;
831                                         },
832                                 }
833                         },
834                         None => {
835                                 writer.write_all(&byte_utils::be48_to_array(0))?;
836                         },
837                 }
838
839                 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
840                 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
841
842                 for &(ref secret, ref idx) in self.old_secrets.iter() {
843                         writer.write_all(secret)?;
844                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
845                 }
846
847                 macro_rules! serialize_htlc_in_commitment {
848                         ($htlc_output: expr) => {
849                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
850                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
851                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
852                                 writer.write_all(&$htlc_output.payment_hash)?;
853                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
854                         }
855                 }
856
857                 macro_rules! serialize_htlc_source {
858                         ($htlc_source: expr) => {
859                                 $htlc_source.0.write(writer)?;
860                                 $htlc_source.1.write(writer)?;
861                                 if let &Some(ref txo) = &$htlc_source.2 {
862                                         writer.write_all(&[1; 1])?;
863                                         txo.write(writer)?;
864                                 } else {
865                                         writer.write_all(&[0; 1])?;
866                                 }
867                         }
868                 }
869
870
871                 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
872                 for (ref txid, &(ref htlc_infos, ref htlc_sources)) in self.remote_claimable_outpoints.iter() {
873                         writer.write_all(&txid[..])?;
874                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
875                         for ref htlc_output in htlc_infos.iter() {
876                                 serialize_htlc_in_commitment!(htlc_output);
877                         }
878                         writer.write_all(&byte_utils::be64_to_array(htlc_sources.len() as u64))?;
879                         for ref htlc_source in htlc_sources.iter() {
880                                 serialize_htlc_source!(htlc_source);
881                         }
882                 }
883
884                 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
885                 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
886                         writer.write_all(&txid[..])?;
887                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
888                         (txouts.len() as u64).write(writer)?;
889                         for script in txouts.iter() {
890                                 script.write(writer)?;
891                         }
892                 }
893
894                 if for_local_storage {
895                         writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
896                         for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
897                                 writer.write_all(*payment_hash)?;
898                                 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
899                         }
900                 } else {
901                         writer.write_all(&byte_utils::be64_to_array(0))?;
902                 }
903
904                 macro_rules! serialize_local_tx {
905                         ($local_tx: expr) => {
906                                 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
907                                         match e {
908                                                 encode::Error::Io(e) => return Err(e),
909                                                 _ => panic!("local tx must have been well-formed!"),
910                                         }
911                                 }
912
913                                 writer.write_all(&$local_tx.revocation_key.serialize())?;
914                                 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
915                                 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
916                                 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
917
918                                 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
919                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
920                                 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
921                                         serialize_htlc_in_commitment!(htlc_output);
922                                         writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
923                                         writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
924                                 }
925                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_sources.len() as u64))?;
926                                 for ref htlc_source in $local_tx.htlc_sources.iter() {
927                                         serialize_htlc_source!(htlc_source);
928                                 }
929                         }
930                 }
931
932                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
933                         writer.write_all(&[1; 1])?;
934                         serialize_local_tx!(prev_local_tx);
935                 } else {
936                         writer.write_all(&[0; 1])?;
937                 }
938
939                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
940                         writer.write_all(&[1; 1])?;
941                         serialize_local_tx!(cur_local_tx);
942                 } else {
943                         writer.write_all(&[0; 1])?;
944                 }
945
946                 if for_local_storage {
947                         writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
948                 } else {
949                         writer.write_all(&byte_utils::be48_to_array(0))?;
950                 }
951
952                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
953                 for payment_preimage in self.payment_preimages.values() {
954                         writer.write_all(payment_preimage)?;
955                 }
956
957                 self.last_block_hash.write(writer)?;
958                 self.destination_script.write(writer)?;
959
960                 Ok(())
961         }
962
963         /// Writes this monitor into the given writer, suitable for writing to disk.
964         ///
965         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
966         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
967         /// the "reorg path" (ie not just starting at the same height but starting at the highest
968         /// common block that appears on your best chain as well as on the chain which contains the
969         /// last block hash returned) upon deserializing the object!
970         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
971                 self.write(writer, true)
972         }
973
974         /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
975         ///
976         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
977         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
978         /// the "reorg path" (ie not just starting at the same height but starting at the highest
979         /// common block that appears on your best chain as well as on the chain which contains the
980         /// last block hash returned) upon deserializing the object!
981         pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
982                 self.write(writer, false)
983         }
984
985         //TODO: Functions to serialize/deserialize (with different forms depending on which information
986         //we want to leave out (eg funding_txo, etc).
987
988         /// Can only fail if idx is < get_min_seen_secret
989         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
990                 for i in 0..self.old_secrets.len() {
991                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
992                                 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
993                         }
994                 }
995                 assert!(idx < self.get_min_seen_secret());
996                 None
997         }
998
999         pub(super) fn get_min_seen_secret(&self) -> u64 {
1000                 //TODO This can be optimized?
1001                 let mut min = 1 << 48;
1002                 for &(_, idx) in self.old_secrets.iter() {
1003                         if idx < min {
1004                                 min = idx;
1005                         }
1006                 }
1007                 min
1008         }
1009
1010         pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1011                 self.current_remote_commitment_number
1012         }
1013
1014         pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1015                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1016                         0xffff_ffff_ffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor)
1017                 } else { 0xffff_ffff_ffff }
1018         }
1019
1020         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1021         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1022         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1023         /// HTLC-Success/HTLC-Timeout transactions.
1024         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1025         /// revoked remote commitment tx
1026         fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<[u8;32]>, [u8;32])>)  {
1027                 // Most secp and related errors trying to create keys means we have no hope of constructing
1028                 // a spend transaction...so we return no transactions to broadcast
1029                 let mut txn_to_broadcast = Vec::new();
1030                 let mut watch_outputs = Vec::new();
1031                 let mut spendable_outputs = Vec::new();
1032                 let mut htlc_updated = Vec::new();
1033
1034                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1035                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1036
1037                 macro_rules! ignore_error {
1038                         ( $thing : expr ) => {
1039                                 match $thing {
1040                                         Ok(a) => a,
1041                                         Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1042                                 }
1043                         };
1044                 }
1045
1046                 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);
1047                 if commitment_number >= self.get_min_seen_secret() {
1048                         let secret = self.get_secret(commitment_number).unwrap();
1049                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1050                         let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1051                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1052                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1053                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1054                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1055                                         Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1056                                 },
1057                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1058                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1059                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1060                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1061                                         None)
1062                                 },
1063                         };
1064                         let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key.unwrap()));
1065                         let a_htlc_key = match self.their_htlc_base_key {
1066                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1067                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &their_htlc_base_key)),
1068                         };
1069
1070                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1071                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1072
1073                         let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1074                                 // Note that the Network here is ignored as we immediately drop the address for the
1075                                 // script_pubkey version.
1076                                 let payment_hash160 = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1077                                 Some(Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1078                         } else { None };
1079
1080                         let mut total_value = 0;
1081                         let mut values = Vec::new();
1082                         let mut inputs = Vec::new();
1083                         let mut htlc_idxs = Vec::new();
1084
1085                         for (idx, outp) in tx.output.iter().enumerate() {
1086                                 if outp.script_pubkey == revokeable_p2wsh {
1087                                         inputs.push(TxIn {
1088                                                 previous_output: BitcoinOutPoint {
1089                                                         txid: commitment_txid,
1090                                                         vout: idx as u32,
1091                                                 },
1092                                                 script_sig: Script::new(),
1093                                                 sequence: 0xfffffffd,
1094                                                 witness: Vec::new(),
1095                                         });
1096                                         htlc_idxs.push(None);
1097                                         values.push(outp.value);
1098                                         total_value += outp.value;
1099                                 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1100                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1101                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1102                                                 key: local_payment_key.unwrap(),
1103                                                 output: outp.clone(),
1104                                         });
1105                                 }
1106                         }
1107
1108                         macro_rules! sign_input {
1109                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1110                                         {
1111                                                 let (sig, redeemscript) = match self.key_storage {
1112                                                         Storage::Local { ref revocation_base_key, .. } => {
1113                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1114                                                                         let htlc = &per_commitment_option.unwrap().0[$htlc_idx.unwrap()];
1115                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1116                                                                 };
1117                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1118                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1119                                                                 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1120                                                         },
1121                                                         Storage::Watchtower { .. } => {
1122                                                                 unimplemented!();
1123                                                         }
1124                                                 };
1125                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1126                                                 $input.witness[0].push(SigHashType::All as u8);
1127                                                 if $htlc_idx.is_none() {
1128                                                         $input.witness.push(vec!(1));
1129                                                 } else {
1130                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
1131                                                 }
1132                                                 $input.witness.push(redeemscript.into_bytes());
1133                                         }
1134                                 }
1135                         }
1136
1137                         if let Some(&(ref per_commitment_data, _)) = per_commitment_option {
1138                                 inputs.reserve_exact(per_commitment_data.len());
1139
1140                                 for (idx, ref htlc) in per_commitment_data.iter().enumerate() {
1141                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1142                                         if htlc.transaction_output_index as usize >= tx.output.len() ||
1143                                                         tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1144                                                         tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1145                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1146                                         }
1147                                         let input = TxIn {
1148                                                 previous_output: BitcoinOutPoint {
1149                                                         txid: commitment_txid,
1150                                                         vout: htlc.transaction_output_index,
1151                                                 },
1152                                                 script_sig: Script::new(),
1153                                                 sequence: 0xfffffffd,
1154                                                 witness: Vec::new(),
1155                                         };
1156                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1157                                                 inputs.push(input);
1158                                                 htlc_idxs.push(Some(idx));
1159                                                 values.push(tx.output[htlc.transaction_output_index as usize].value);
1160                                                 total_value += htlc.amount_msat / 1000;
1161                                         } else {
1162                                                 let mut single_htlc_tx = Transaction {
1163                                                         version: 2,
1164                                                         lock_time: 0,
1165                                                         input: vec![input],
1166                                                         output: vec!(TxOut {
1167                                                                 script_pubkey: self.destination_script.clone(),
1168                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
1169                                                         }),
1170                                                 };
1171                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1172                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1173                                                 txn_to_broadcast.push(single_htlc_tx);
1174                                         }
1175                                 }
1176                         }
1177
1178                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1179                                 // We're definitely a remote commitment transaction!
1180                                 watch_outputs.append(&mut tx.output.clone());
1181                                 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1182                         }
1183                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); } // Nothing to be done...probably a false positive/local tx
1184
1185                         let outputs = vec!(TxOut {
1186                                 script_pubkey: self.destination_script.clone(),
1187                                 value: total_value, //TODO: - fee
1188                         });
1189                         let mut spend_tx = Transaction {
1190                                 version: 2,
1191                                 lock_time: 0,
1192                                 input: inputs,
1193                                 output: outputs,
1194                         };
1195
1196                         let mut values_drain = values.drain(..);
1197                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1198
1199                         for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1200                                 let value = values_drain.next().unwrap();
1201                                 sign_input!(sighash_parts, input, htlc_idx, value);
1202                         }
1203
1204                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1205                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1206                                 output: spend_tx.output[0].clone(),
1207                         });
1208                         txn_to_broadcast.push(spend_tx);
1209
1210                         // TODO: We really should only fail backwards after our revocation claims have been
1211                         // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1212                         // on-chain claims, so we can do that at the same time.
1213                         if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1214                                 if let &Some(ref txid) = current_remote_commitment_txid {
1215                                         if let Some(&(_, ref latest_outpoints)) = self.remote_claimable_outpoints.get(&txid) {
1216                                                 for &(ref payment_hash, ref source, _) in latest_outpoints.iter() {
1217                                                         htlc_updated.push(((*source).clone(), None, *payment_hash));
1218                                                 }
1219                                         }
1220                                 }
1221                                 if let &Some(ref txid) = prev_remote_commitment_txid {
1222                                         if let Some(&(_, ref prev_outpoint)) = self.remote_claimable_outpoints.get(&txid) {
1223                                                 for &(ref payment_hash, ref source, _) in prev_outpoint.iter() {
1224                                                         htlc_updated.push(((*source).clone(), None, *payment_hash));
1225                                                 }
1226                                         }
1227                                 }
1228                         }
1229                         // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1230                 } else if let Some(per_commitment_data) = per_commitment_option {
1231                         // While this isn't useful yet, there is a potential race where if a counterparty
1232                         // revokes a state at the same time as the commitment transaction for that state is
1233                         // confirmed, and the watchtower receives the block before the user, the user could
1234                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1235                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1236                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1237                         // insert it here.
1238                         watch_outputs.append(&mut tx.output.clone());
1239                         self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1240
1241                         if let Some(revocation_points) = self.their_cur_revocation_points {
1242                                 let revocation_point_option =
1243                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1244                                         else if let Some(point) = revocation_points.2.as_ref() {
1245                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1246                                         } else { None };
1247                                 if let Some(revocation_point) = revocation_point_option {
1248                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1249                                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1250                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1251                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1252                                                 },
1253                                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1254                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1255                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1256                                                 },
1257                                         };
1258                                         let a_htlc_key = match self.their_htlc_base_key {
1259                                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1260                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1261                                         };
1262
1263                                         for (idx, outp) in tx.output.iter().enumerate() {
1264                                                 if outp.script_pubkey.is_v0_p2wpkh() {
1265                                                         match self.key_storage {
1266                                                                 Storage::Local { ref payment_base_key, .. } => {
1267                                                                         if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1268                                                                                 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1269                                                                                         outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1270                                                                                         key: local_key,
1271                                                                                         output: outp.clone(),
1272                                                                                 });
1273                                                                         }
1274                                                                 },
1275                                                                 Storage::Watchtower { .. } => {}
1276                                                         }
1277                                                         break; // Only to_remote ouput is claimable
1278                                                 }
1279                                         }
1280
1281                                         let mut total_value = 0;
1282                                         let mut values = Vec::new();
1283                                         let mut inputs = Vec::new();
1284
1285                                         macro_rules! sign_input {
1286                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1287                                                         {
1288                                                                 let (sig, redeemscript) = match self.key_storage {
1289                                                                         Storage::Local { ref htlc_base_key, .. } => {
1290                                                                                 let htlc = &per_commitment_option.unwrap().0[$input.sequence as usize];
1291                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1292                                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1293                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1294                                                                                 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1295                                                                         },
1296                                                                         Storage::Watchtower { .. } => {
1297                                                                                 unimplemented!();
1298                                                                         }
1299                                                                 };
1300                                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1301                                                                 $input.witness[0].push(SigHashType::All as u8);
1302                                                                 $input.witness.push($preimage);
1303                                                                 $input.witness.push(redeemscript.into_bytes());
1304                                                         }
1305                                                 }
1306                                         }
1307
1308                                         for (idx, ref htlc) in per_commitment_data.0.iter().enumerate() {
1309                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1310                                                 if htlc.transaction_output_index as usize >= tx.output.len() ||
1311                                                                 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1312                                                                 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1313                                                         return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1314                                                 }
1315                                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1316                                                         let input = TxIn {
1317                                                                 previous_output: BitcoinOutPoint {
1318                                                                         txid: commitment_txid,
1319                                                                         vout: htlc.transaction_output_index,
1320                                                                 },
1321                                                                 script_sig: Script::new(),
1322                                                                 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1323                                                                 witness: Vec::new(),
1324                                                         };
1325                                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1326                                                                 inputs.push(input);
1327                                                                 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1328                                                                 total_value += htlc.amount_msat / 1000;
1329                                                         } else {
1330                                                                 let mut single_htlc_tx = Transaction {
1331                                                                         version: 2,
1332                                                                         lock_time: 0,
1333                                                                         input: vec![input],
1334                                                                         output: vec!(TxOut {
1335                                                                                 script_pubkey: self.destination_script.clone(),
1336                                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
1337                                                                         }),
1338                                                                 };
1339                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1340                                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1341                                                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1342                                                                         outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1343                                                                         output: single_htlc_tx.output[0].clone(),
1344                                                                 });
1345                                                                 txn_to_broadcast.push(single_htlc_tx);
1346                                                         }
1347                                                 }
1348                                                 if !htlc.offered {
1349                                                         // TODO: If the HTLC has already expired, potentially merge it with the
1350                                                         // rest of the claim transaction, as above.
1351                                                         let input = TxIn {
1352                                                                 previous_output: BitcoinOutPoint {
1353                                                                         txid: commitment_txid,
1354                                                                         vout: htlc.transaction_output_index,
1355                                                                 },
1356                                                                 script_sig: Script::new(),
1357                                                                 sequence: idx as u32,
1358                                                                 witness: Vec::new(),
1359                                                         };
1360                                                         let mut timeout_tx = Transaction {
1361                                                                 version: 2,
1362                                                                 lock_time: htlc.cltv_expiry,
1363                                                                 input: vec![input],
1364                                                                 output: vec!(TxOut {
1365                                                                         script_pubkey: self.destination_script.clone(),
1366                                                                         value: htlc.amount_msat / 1000,
1367                                                                 }),
1368                                                         };
1369                                                         let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1370                                                         sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1371                                                         txn_to_broadcast.push(timeout_tx);
1372                                                 }
1373                                         }
1374
1375                                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); } // Nothing to be done...probably a false positive/local tx
1376
1377                                         let outputs = vec!(TxOut {
1378                                                 script_pubkey: self.destination_script.clone(),
1379                                                 value: total_value, //TODO: - fee
1380                                         });
1381                                         let mut spend_tx = Transaction {
1382                                                 version: 2,
1383                                                 lock_time: 0,
1384                                                 input: inputs,
1385                                                 output: outputs,
1386                                         };
1387
1388                                         let mut values_drain = values.drain(..);
1389                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1390
1391                                         for input in spend_tx.input.iter_mut() {
1392                                                 let value = values_drain.next().unwrap();
1393                                                 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1394                                         }
1395
1396                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1397                                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1398                                                 output: spend_tx.output[0].clone(),
1399                                         });
1400                                         txn_to_broadcast.push(spend_tx);
1401                                 }
1402                         }
1403                 }
1404
1405                 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1406         }
1407
1408         /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1409         fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1410                 if tx.input.len() != 1 || tx.output.len() != 1 {
1411                         return (None, None)
1412                 }
1413
1414                 macro_rules! ignore_error {
1415                         ( $thing : expr ) => {
1416                                 match $thing {
1417                                         Ok(a) => a,
1418                                         Err(_) => return (None, None)
1419                                 }
1420                         };
1421                 }
1422
1423                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1424                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1425                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1426                 let revocation_pubkey = match self.key_storage {
1427                         Storage::Local { ref revocation_base_key, .. } => {
1428                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1429                         },
1430                         Storage::Watchtower { ref revocation_base_key, .. } => {
1431                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1432                         },
1433                 };
1434                 let delayed_key = match self.their_delayed_payment_base_key {
1435                         None => return (None, None),
1436                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1437                 };
1438                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1439                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1440                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1441
1442                 let mut inputs = Vec::new();
1443                 let mut amount = 0;
1444
1445                 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1446                         inputs.push(TxIn {
1447                                 previous_output: BitcoinOutPoint {
1448                                         txid: htlc_txid,
1449                                         vout: 0,
1450                                 },
1451                                 script_sig: Script::new(),
1452                                 sequence: 0xfffffffd,
1453                                 witness: Vec::new(),
1454                         });
1455                         amount = tx.output[0].value;
1456                 }
1457
1458                 if !inputs.is_empty() {
1459                         let outputs = vec!(TxOut {
1460                                 script_pubkey: self.destination_script.clone(),
1461                                 value: amount, //TODO: - fee
1462                         });
1463
1464                         let mut spend_tx = Transaction {
1465                                 version: 2,
1466                                 lock_time: 0,
1467                                 input: inputs,
1468                                 output: outputs,
1469                         };
1470
1471                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1472
1473                         let sig = match self.key_storage {
1474                                 Storage::Local { ref revocation_base_key, .. } => {
1475                                         let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1476                                         let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1477                                         self.secp_ctx.sign(&sighash, &revocation_key)
1478                                 }
1479                                 Storage::Watchtower { .. } => {
1480                                         unimplemented!();
1481                                 }
1482                         };
1483                         spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1484                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1485                         spend_tx.input[0].witness.push(vec!(1));
1486                         spend_tx.input[0].witness.push(redeemscript.into_bytes());
1487
1488                         let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1489                         let output = spend_tx.output[0].clone();
1490                         (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1491                 } else { (None, None) }
1492         }
1493
1494         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>) {
1495                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1496                 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1497                 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1498
1499                 macro_rules! add_dynamic_output {
1500                         ($father_tx: expr, $vout: expr) => {
1501                                 if let Some(ref per_commitment_point) = *per_commitment_point {
1502                                         if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1503                                                 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1504                                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1505                                                                 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1506                                                                 key: local_delayedkey,
1507                                                                 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1508                                                                 to_self_delay: self.our_to_self_delay,
1509                                                                 output: $father_tx.output[$vout as usize].clone(),
1510                                                         });
1511                                                 }
1512                                         }
1513                                 }
1514                         }
1515                 }
1516
1517
1518                 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1519                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1520                 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1521                         if output.script_pubkey == revokeable_p2wsh {
1522                                 add_dynamic_output!(local_tx.tx, idx as u32);
1523                                 break;
1524                         }
1525                 }
1526
1527                 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1528                         if htlc.offered {
1529                                 let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
1530
1531                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1532
1533                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1534                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1535                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1536                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1537
1538                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
1539                                 htlc_timeout_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
1540
1541                                 add_dynamic_output!(htlc_timeout_tx, 0);
1542                                 res.push(htlc_timeout_tx);
1543                         } else {
1544                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1545                                         let mut htlc_success_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
1546
1547                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1548
1549                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1550                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1551                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1552                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1553
1554                                         htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1555                                         htlc_success_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
1556
1557                                         add_dynamic_output!(htlc_success_tx, 0);
1558                                         res.push(htlc_success_tx);
1559                                 }
1560                         }
1561                         watch_outputs.push(local_tx.tx.output[htlc.transaction_output_index as usize].clone());
1562                 }
1563
1564                 (res, spendable_outputs, watch_outputs)
1565         }
1566
1567         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1568         /// revoked using data in local_claimable_outpoints.
1569         /// Should not be used if check_spend_revoked_transaction succeeds.
1570         fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1571                 let commitment_txid = tx.txid();
1572                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1573                         if local_tx.txid == commitment_txid {
1574                                 match self.key_storage {
1575                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1576                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1577                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1578                                         },
1579                                         Storage::Watchtower { .. } => {
1580                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1581                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1582                                         }
1583                                 }
1584                         }
1585                 }
1586                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1587                         if local_tx.txid == commitment_txid {
1588                                 match self.key_storage {
1589                                         Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1590                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1591                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1592                                         },
1593                                         Storage::Watchtower { .. } => {
1594                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1595                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1596                                         }
1597                                 }
1598                         }
1599                 }
1600                 (Vec::new(), Vec::new(), (commitment_txid, Vec::new()))
1601         }
1602
1603         /// Generate a spendable output event when closing_transaction get registered onchain.
1604         fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1605                 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1606                         match self.key_storage {
1607                                 Storage::Local { ref shutdown_pubkey, .. } =>  {
1608                                         let our_channel_close_key_hash = Hash160::from_data(&shutdown_pubkey.serialize());
1609                                         let shutdown_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1610                                         for (idx, output) in tx.output.iter().enumerate() {
1611                                                 if shutdown_script == output.script_pubkey {
1612                                                         return Some(SpendableOutputDescriptor::StaticOutput {
1613                                                                 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1614                                                                 output: output.clone(),
1615                                                         });
1616                                                 }
1617                                         }
1618                                 }
1619                                 Storage::Watchtower { .. } => {
1620                                         //TODO: we need to ensure an offline client will generate the event when it
1621                                         // cames back online after only the watchtower saw the transaction
1622                                 }
1623                         }
1624                 }
1625                 None
1626         }
1627
1628         /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1629         /// the Channel was out-of-date.
1630         pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1631                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1632                         let mut res = vec![local_tx.tx.clone()];
1633                         match self.key_storage {
1634                                 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1635                                         res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1636                                 },
1637                                 _ => panic!("Can only broadcast by local channelmonitor"),
1638                         };
1639                         res
1640                 } else {
1641                         Vec::new()
1642                 }
1643         }
1644
1645         fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<[u8 ; 32]>, [u8; 32])>) {
1646                 let mut watch_outputs = Vec::new();
1647                 let mut spendable_outputs = Vec::new();
1648                 let mut htlc_updated = Vec::new();
1649                 for tx in txn_matched {
1650                         if tx.input.len() == 1 {
1651                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1652                                 // commitment transactions and HTLC transactions will all only ever have one input,
1653                                 // which is an easy way to filter out any potential non-matching txn for lazy
1654                                 // filters.
1655                                 let prevout = &tx.input[0].previous_output;
1656                                 let mut txn: Vec<Transaction> = Vec::new();
1657                                 let funding_txo = match self.key_storage {
1658                                         Storage::Local { ref funding_info, .. } => {
1659                                                 funding_info.clone()
1660                                         }
1661                                         Storage::Watchtower { .. } => {
1662                                                 unimplemented!();
1663                                         }
1664                                 };
1665                                 if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
1666                                         let (remote_txn, new_outputs, mut spendable_output, mut updated) = self.check_spend_remote_transaction(tx, height);
1667                                         txn = remote_txn;
1668                                         spendable_outputs.append(&mut spendable_output);
1669                                         if !new_outputs.1.is_empty() {
1670                                                 watch_outputs.push(new_outputs);
1671                                         }
1672                                         if txn.is_empty() {
1673                                                 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
1674                                                 spendable_outputs.append(&mut spendable_output);
1675                                                 txn = local_txn;
1676                                                 if !new_outputs.1.is_empty() {
1677                                                         watch_outputs.push(new_outputs);
1678                                                 }
1679                                         }
1680                                         if !funding_txo.is_none() && txn.is_empty() {
1681                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1682                                                         spendable_outputs.push(spendable_output);
1683                                                 }
1684                                         }
1685                                         if updated.len() > 0 {
1686                                                 htlc_updated.append(&mut updated);
1687                                         }
1688                                 } else {
1689                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1690                                                 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1691                                                 if let Some(tx) = tx {
1692                                                         txn.push(tx);
1693                                                 }
1694                                                 if let Some(spendable_output) = spendable_output {
1695                                                         spendable_outputs.push(spendable_output);
1696                                                 }
1697                                         }
1698                                 }
1699                                 for tx in txn.iter() {
1700                                         broadcaster.broadcast_transaction(tx);
1701                                 }
1702                                 let mut updated = self.is_resolving_htlc_output(tx);
1703                                 if updated.len() > 0 {
1704                                         htlc_updated.append(&mut updated);
1705                                 }
1706                         }
1707                 }
1708                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1709                         if self.would_broadcast_at_height(height) {
1710                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1711                                 match self.key_storage {
1712                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1713                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1714                                                 spendable_outputs.append(&mut spendable_output);
1715                                                 if !new_outputs.is_empty() {
1716                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1717                                                 }
1718                                                 for tx in txs {
1719                                                         broadcaster.broadcast_transaction(&tx);
1720                                                 }
1721                                         },
1722                                         Storage::Watchtower { .. } => {
1723                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1724                                                 spendable_outputs.append(&mut spendable_output);
1725                                                 if !new_outputs.is_empty() {
1726                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1727                                                 }
1728                                                 for tx in txs {
1729                                                         broadcaster.broadcast_transaction(&tx);
1730                                                 }
1731                                         }
1732                                 }
1733                         }
1734                 }
1735                 self.last_block_hash = block_hash.clone();
1736                 (watch_outputs, spendable_outputs, htlc_updated)
1737         }
1738
1739         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1740                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1741                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1742                                 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1743                                 // chain with enough room to claim the HTLC without our counterparty being able to
1744                                 // time out the HTLC first.
1745                                 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1746                                 // concern is being able to claim the corresponding inbound HTLC (on another
1747                                 // channel) before it expires. In fact, we don't even really care if our
1748                                 // counterparty here claims such an outbound HTLC after it expired as long as we
1749                                 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1750                                 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1751                                 // we give ourselves a few blocks of headroom after expiration before going
1752                                 // on-chain for an expired HTLC.
1753                                 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1754                                 // from us until we've reached the point where we go on-chain with the
1755                                 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1756                                 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1757                                 //  aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1758                                 //      inbound_cltv == height + CLTV_CLAIM_BUFFER
1759                                 //      outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1760                                 //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1761                                 //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1762                                 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1763                                    (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1764                                         return true;
1765                                 }
1766                         }
1767                 }
1768                 false
1769         }
1770
1771         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
1772         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
1773         fn is_resolving_htlc_output(&mut self, tx: &Transaction) -> Vec<(HTLCSource, Option<[u8;32]>, [u8;32])> {
1774                 let mut htlc_updated = Vec::new();
1775
1776                 'outer_loop: for input in &tx.input {
1777                         let mut payment_data = None;
1778
1779                         macro_rules! scan_commitment {
1780                                 ($htlc_outputs: expr, $htlc_sources: expr) => {
1781                                         for &(ref payment_hash, ref source, ref vout) in $htlc_sources.iter() {
1782                                                 if &Some(input.previous_output.vout) == vout {
1783                                                         payment_data = Some((source.clone(), *payment_hash));
1784                                                 }
1785                                         }
1786                                         if payment_data.is_none() {
1787                                                 for htlc_output in $htlc_outputs {
1788                                                         if input.previous_output.vout == htlc_output.transaction_output_index {
1789                                                                 log_info!(self, "Inbound HTLC timeout at {} from {} resolved by {}", input.previous_output.vout, input.previous_output.txid, tx.txid());
1790                                                                 continue 'outer_loop;
1791                                                         }
1792                                                 }
1793                                         }
1794                                 }
1795                         }
1796
1797                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
1798                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
1799                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), current_local_signed_commitment_tx.htlc_sources);
1800                                 }
1801                         }
1802                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
1803                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
1804                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), prev_local_signed_commitment_tx.htlc_sources);
1805                                 }
1806                         }
1807                         if let Some(&(ref htlc_outputs, ref htlc_sources)) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
1808                                 scan_commitment!(htlc_outputs, htlc_sources);
1809                         }
1810
1811                         // If tx isn't solving htlc output from local/remote commitment tx and htlc isn't outbound we don't need
1812                         // to broadcast solving backward
1813                         if let Some((source, payment_hash)) = payment_data {
1814                                 let mut payment_preimage = [0; 32];
1815                                 if input.witness.len() == 5 && input.witness[4].len() == 138 {
1816                                         payment_preimage.copy_from_slice(&tx.input[0].witness[3]);
1817                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
1818                                 } else if input.witness.len() == 3 && input.witness[2].len() == 133 {
1819                                         payment_preimage.copy_from_slice(&tx.input[0].witness[1]);
1820                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
1821                                 } else {
1822                                         htlc_updated.push((source, None, payment_hash));
1823                                 }
1824                         }
1825                 }
1826                 htlc_updated
1827         }
1828 }
1829
1830 const MAX_ALLOC_SIZE: usize = 64*1024;
1831
1832 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1833         fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1834                 let secp_ctx = Secp256k1::new();
1835                 macro_rules! unwrap_obj {
1836                         ($key: expr) => {
1837                                 match $key {
1838                                         Ok(res) => res,
1839                                         Err(_) => return Err(DecodeError::InvalidValue),
1840                                 }
1841                         }
1842                 }
1843
1844                 let _ver: u8 = Readable::read(reader)?;
1845                 let min_ver: u8 = Readable::read(reader)?;
1846                 if min_ver > SERIALIZATION_VERSION {
1847                         return Err(DecodeError::UnknownVersion);
1848                 }
1849
1850                 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1851
1852                 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1853                         0 => {
1854                                 let revocation_base_key = Readable::read(reader)?;
1855                                 let htlc_base_key = Readable::read(reader)?;
1856                                 let delayed_payment_base_key = Readable::read(reader)?;
1857                                 let payment_base_key = Readable::read(reader)?;
1858                                 let shutdown_pubkey = Readable::read(reader)?;
1859                                 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1860                                         0 => None,
1861                                         1 => Some(Readable::read(reader)?),
1862                                         _ => return Err(DecodeError::InvalidValue),
1863                                 };
1864                                 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1865                                         0 => None,
1866                                         1 => Some(Readable::read(reader)?),
1867                                         _ => return Err(DecodeError::InvalidValue),
1868                                 };
1869                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1870                                 // barely-init'd ChannelMonitors that we can't do anything with.
1871                                 let outpoint = OutPoint {
1872                                         txid: Readable::read(reader)?,
1873                                         index: Readable::read(reader)?,
1874                                 };
1875                                 let funding_info = Some((outpoint, Readable::read(reader)?));
1876                                 let current_remote_commitment_txid = match <u8 as Readable<R>>::read(reader)? {
1877                                         0 => None,
1878                                         1 => Some(Readable::read(reader)?),
1879                                         _ => return Err(DecodeError::InvalidValue),
1880                                 };
1881                                 let prev_remote_commitment_txid = match <u8 as Readable<R>>::read(reader)? {
1882                                         0 => None,
1883                                         1 => Some(Readable::read(reader)?),
1884                                         _ => return Err(DecodeError::InvalidValue),
1885                                 };
1886                                 Storage::Local {
1887                                         revocation_base_key,
1888                                         htlc_base_key,
1889                                         delayed_payment_base_key,
1890                                         payment_base_key,
1891                                         shutdown_pubkey,
1892                                         prev_latest_per_commitment_point,
1893                                         latest_per_commitment_point,
1894                                         funding_info,
1895                                         current_remote_commitment_txid,
1896                                         prev_remote_commitment_txid,
1897                                 }
1898                         },
1899                         _ => return Err(DecodeError::InvalidValue),
1900                 };
1901
1902                 let their_htlc_base_key = Some(Readable::read(reader)?);
1903                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1904
1905                 let their_cur_revocation_points = {
1906                         let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1907                         if first_idx == 0 {
1908                                 None
1909                         } else {
1910                                 let first_point = Readable::read(reader)?;
1911                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1912                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1913                                         Some((first_idx, first_point, None))
1914                                 } else {
1915                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1916                                 }
1917                         }
1918                 };
1919
1920                 let our_to_self_delay: u16 = Readable::read(reader)?;
1921                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1922
1923                 let mut old_secrets = [([0; 32], 1 << 48); 49];
1924                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1925                         *secret = Readable::read(reader)?;
1926                         *idx = Readable::read(reader)?;
1927                 }
1928
1929                 macro_rules! read_htlc_in_commitment {
1930                         () => {
1931                                 {
1932                                         let offered: bool = Readable::read(reader)?;
1933                                         let amount_msat: u64 = Readable::read(reader)?;
1934                                         let cltv_expiry: u32 = Readable::read(reader)?;
1935                                         let payment_hash: [u8; 32] = Readable::read(reader)?;
1936                                         let transaction_output_index: u32 = Readable::read(reader)?;
1937
1938                                         HTLCOutputInCommitment {
1939                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1940                                         }
1941                                 }
1942                         }
1943                 }
1944
1945                 macro_rules! read_htlc_source {
1946                         () => {
1947                                 {
1948                                         (Readable::read(reader)?, Readable::read(reader)?,
1949                                                 match <u8 as Readable<R>>::read(reader)? {
1950                                                         0 => None,
1951                                                         1 => Some(Readable::read(reader)?),
1952                                                         _ => return Err(DecodeError::InvalidValue),
1953                                                 }
1954                                         )
1955                                 }
1956                         }
1957                 }
1958
1959                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1960                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1961                 for _ in 0..remote_claimable_outpoints_len {
1962                         let txid: Sha256dHash = Readable::read(reader)?;
1963                         let outputs_count: u64 = Readable::read(reader)?;
1964                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1965                         for _ in 0..outputs_count {
1966                                 outputs.push(read_htlc_in_commitment!());
1967                         }
1968                         let sources_count: u64 = Readable::read(reader)?;
1969                         let mut sources = Vec::with_capacity(cmp::min(sources_count as usize, MAX_ALLOC_SIZE / 32));
1970                         for _ in 0..sources_count {
1971                                 sources.push(read_htlc_source!());
1972                         }
1973                         if let Some(_) = remote_claimable_outpoints.insert(txid, (outputs, sources)) {
1974                                 return Err(DecodeError::InvalidValue);
1975                         }
1976                 }
1977
1978                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
1979                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
1980                 for _ in 0..remote_commitment_txn_on_chain_len {
1981                         let txid: Sha256dHash = Readable::read(reader)?;
1982                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1983                         let outputs_count = <u64 as Readable<R>>::read(reader)?;
1984                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
1985                         for _ in 0..outputs_count {
1986                                 outputs.push(Readable::read(reader)?);
1987                         }
1988                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
1989                                 return Err(DecodeError::InvalidValue);
1990                         }
1991                 }
1992
1993                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
1994                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
1995                 for _ in 0..remote_hash_commitment_number_len {
1996                         let txid: [u8; 32] = Readable::read(reader)?;
1997                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1998                         if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1999                                 return Err(DecodeError::InvalidValue);
2000                         }
2001                 }
2002
2003                 macro_rules! read_local_tx {
2004                         () => {
2005                                 {
2006                                         let tx = match Transaction::consensus_decode(reader.by_ref()) {
2007                                                 Ok(tx) => tx,
2008                                                 Err(e) => match e {
2009                                                         encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
2010                                                         _ => return Err(DecodeError::InvalidValue),
2011                                                 },
2012                                         };
2013
2014                                         if tx.input.is_empty() {
2015                                                 // Ensure tx didn't hit the 0-input ambiguity case.
2016                                                 return Err(DecodeError::InvalidValue);
2017                                         }
2018
2019                                         let revocation_key = Readable::read(reader)?;
2020                                         let a_htlc_key = Readable::read(reader)?;
2021                                         let b_htlc_key = Readable::read(reader)?;
2022                                         let delayed_payment_key = Readable::read(reader)?;
2023                                         let feerate_per_kw: u64 = Readable::read(reader)?;
2024
2025                                         let htlc_outputs_len: u64 = Readable::read(reader)?;
2026                                         let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
2027                                         for _ in 0..htlc_outputs_len {
2028                                                 let out = read_htlc_in_commitment!();
2029                                                 let sigs = (Readable::read(reader)?, Readable::read(reader)?);
2030                                                 htlc_outputs.push((out, sigs.0, sigs.1));
2031                                         }
2032
2033                                         let htlc_sources_len: u64 = Readable::read(reader)?;
2034                                         let mut htlc_sources = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
2035                                         for _ in 0..htlc_sources_len {
2036                                                 htlc_sources.push(read_htlc_source!());
2037                                         }
2038
2039                                         LocalSignedTx {
2040                                                 txid: tx.txid(),
2041                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs, htlc_sources
2042                                         }
2043                                 }
2044                         }
2045                 }
2046
2047                 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2048                         0 => None,
2049                         1 => {
2050                                 Some(read_local_tx!())
2051                         },
2052                         _ => return Err(DecodeError::InvalidValue),
2053                 };
2054
2055                 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2056                         0 => None,
2057                         1 => {
2058                                 Some(read_local_tx!())
2059                         },
2060                         _ => return Err(DecodeError::InvalidValue),
2061                 };
2062
2063                 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2064
2065                 let payment_preimages_len: u64 = Readable::read(reader)?;
2066                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2067                 let mut sha = Sha256::new();
2068                 for _ in 0..payment_preimages_len {
2069                         let preimage: [u8; 32] = Readable::read(reader)?;
2070                         sha.reset();
2071                         sha.input(&preimage);
2072                         let mut hash = [0; 32];
2073                         sha.result(&mut hash);
2074                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2075                                 return Err(DecodeError::InvalidValue);
2076                         }
2077                 }
2078
2079                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2080                 let destination_script = Readable::read(reader)?;
2081
2082                 Ok((last_block_hash.clone(), ChannelMonitor {
2083                         commitment_transaction_number_obscure_factor,
2084
2085                         key_storage,
2086                         their_htlc_base_key,
2087                         their_delayed_payment_base_key,
2088                         their_cur_revocation_points,
2089
2090                         our_to_self_delay,
2091                         their_to_self_delay,
2092
2093                         old_secrets,
2094                         remote_claimable_outpoints,
2095                         remote_commitment_txn_on_chain,
2096                         remote_hash_commitment_number,
2097
2098                         prev_local_signed_commitment_tx,
2099                         current_local_signed_commitment_tx,
2100                         current_remote_commitment_number,
2101
2102                         payment_preimages,
2103
2104                         destination_script,
2105                         last_block_hash,
2106                         secp_ctx,
2107                         logger,
2108                 }))
2109         }
2110
2111 }
2112
2113 #[cfg(test)]
2114 mod tests {
2115         use bitcoin::blockdata::script::Script;
2116         use bitcoin::blockdata::transaction::Transaction;
2117         use crypto::digest::Digest;
2118         use hex;
2119         use ln::channelmonitor::ChannelMonitor;
2120         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
2121         use util::sha2::Sha256;
2122         use util::test_utils::TestLogger;
2123         use secp256k1::key::{SecretKey,PublicKey};
2124         use secp256k1::{Secp256k1, Signature};
2125         use rand::{thread_rng,Rng};
2126         use std::sync::Arc;
2127
2128         #[test]
2129         fn test_per_commitment_storage() {
2130                 // Test vectors from BOLT 3:
2131                 let mut secrets: Vec<[u8; 32]> = Vec::new();
2132                 let mut monitor: ChannelMonitor;
2133                 let secp_ctx = Secp256k1::new();
2134                 let logger = Arc::new(TestLogger::new());
2135
2136                 macro_rules! test_secrets {
2137                         () => {
2138                                 let mut idx = 281474976710655;
2139                                 for secret in secrets.iter() {
2140                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2141                                         idx -= 1;
2142                                 }
2143                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2144                                 assert!(monitor.get_secret(idx).is_none());
2145                         };
2146                 }
2147
2148                 {
2149                         // insert_secret correct sequence
2150                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2151                         secrets.clear();
2152
2153                         secrets.push([0; 32]);
2154                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2155                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2156                         test_secrets!();
2157
2158                         secrets.push([0; 32]);
2159                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2160                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2161                         test_secrets!();
2162
2163                         secrets.push([0; 32]);
2164                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2165                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2166                         test_secrets!();
2167
2168                         secrets.push([0; 32]);
2169                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2170                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2171                         test_secrets!();
2172
2173                         secrets.push([0; 32]);
2174                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2175                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2176                         test_secrets!();
2177
2178                         secrets.push([0; 32]);
2179                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2180                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2181                         test_secrets!();
2182
2183                         secrets.push([0; 32]);
2184                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2185                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2186                         test_secrets!();
2187
2188                         secrets.push([0; 32]);
2189                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2190                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2191                         test_secrets!();
2192                 }
2193
2194                 {
2195                         // insert_secret #1 incorrect
2196                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2197                         secrets.clear();
2198
2199                         secrets.push([0; 32]);
2200                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2201                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2202                         test_secrets!();
2203
2204                         secrets.push([0; 32]);
2205                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2206                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
2207                                         "Previous secret did not match new one");
2208                 }
2209
2210                 {
2211                         // insert_secret #2 incorrect (#1 derived from incorrect)
2212                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2213                         secrets.clear();
2214
2215                         secrets.push([0; 32]);
2216                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2217                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2218                         test_secrets!();
2219
2220                         secrets.push([0; 32]);
2221                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2222                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2223                         test_secrets!();
2224
2225                         secrets.push([0; 32]);
2226                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2227                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2228                         test_secrets!();
2229
2230                         secrets.push([0; 32]);
2231                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2232                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2233                                         "Previous secret did not match new one");
2234                 }
2235
2236                 {
2237                         // insert_secret #3 incorrect
2238                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2239                         secrets.clear();
2240
2241                         secrets.push([0; 32]);
2242                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2243                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2244                         test_secrets!();
2245
2246                         secrets.push([0; 32]);
2247                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2248                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2249                         test_secrets!();
2250
2251                         secrets.push([0; 32]);
2252                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2253                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2254                         test_secrets!();
2255
2256                         secrets.push([0; 32]);
2257                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2258                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2259                                         "Previous secret did not match new one");
2260                 }
2261
2262                 {
2263                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2264                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2265                         secrets.clear();
2266
2267                         secrets.push([0; 32]);
2268                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2269                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2270                         test_secrets!();
2271
2272                         secrets.push([0; 32]);
2273                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2274                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2275                         test_secrets!();
2276
2277                         secrets.push([0; 32]);
2278                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2279                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2280                         test_secrets!();
2281
2282                         secrets.push([0; 32]);
2283                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2284                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2285                         test_secrets!();
2286
2287                         secrets.push([0; 32]);
2288                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2289                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2290                         test_secrets!();
2291
2292                         secrets.push([0; 32]);
2293                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2294                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2295                         test_secrets!();
2296
2297                         secrets.push([0; 32]);
2298                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2299                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2300                         test_secrets!();
2301
2302                         secrets.push([0; 32]);
2303                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2304                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2305                                         "Previous secret did not match new one");
2306                 }
2307
2308                 {
2309                         // insert_secret #5 incorrect
2310                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2311                         secrets.clear();
2312
2313                         secrets.push([0; 32]);
2314                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2315                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2316                         test_secrets!();
2317
2318                         secrets.push([0; 32]);
2319                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2320                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2321                         test_secrets!();
2322
2323                         secrets.push([0; 32]);
2324                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2325                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2326                         test_secrets!();
2327
2328                         secrets.push([0; 32]);
2329                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2330                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2331                         test_secrets!();
2332
2333                         secrets.push([0; 32]);
2334                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2335                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2336                         test_secrets!();
2337
2338                         secrets.push([0; 32]);
2339                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2340                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2341                                         "Previous secret did not match new one");
2342                 }
2343
2344                 {
2345                         // insert_secret #6 incorrect (5 derived from incorrect)
2346                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2347                         secrets.clear();
2348
2349                         secrets.push([0; 32]);
2350                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2351                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2352                         test_secrets!();
2353
2354                         secrets.push([0; 32]);
2355                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2356                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2357                         test_secrets!();
2358
2359                         secrets.push([0; 32]);
2360                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2361                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2362                         test_secrets!();
2363
2364                         secrets.push([0; 32]);
2365                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2366                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2367                         test_secrets!();
2368
2369                         secrets.push([0; 32]);
2370                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2371                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2372                         test_secrets!();
2373
2374                         secrets.push([0; 32]);
2375                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2376                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2377                         test_secrets!();
2378
2379                         secrets.push([0; 32]);
2380                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2381                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2382                         test_secrets!();
2383
2384                         secrets.push([0; 32]);
2385                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2386                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2387                                         "Previous secret did not match new one");
2388                 }
2389
2390                 {
2391                         // insert_secret #7 incorrect
2392                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2393                         secrets.clear();
2394
2395                         secrets.push([0; 32]);
2396                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2397                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2398                         test_secrets!();
2399
2400                         secrets.push([0; 32]);
2401                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2402                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2403                         test_secrets!();
2404
2405                         secrets.push([0; 32]);
2406                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2407                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2408                         test_secrets!();
2409
2410                         secrets.push([0; 32]);
2411                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2412                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2413                         test_secrets!();
2414
2415                         secrets.push([0; 32]);
2416                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2417                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2418                         test_secrets!();
2419
2420                         secrets.push([0; 32]);
2421                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2422                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2423                         test_secrets!();
2424
2425                         secrets.push([0; 32]);
2426                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2427                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2428                         test_secrets!();
2429
2430                         secrets.push([0; 32]);
2431                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2432                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2433                                         "Previous secret did not match new one");
2434                 }
2435
2436                 {
2437                         // insert_secret #8 incorrect
2438                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2439                         secrets.clear();
2440
2441                         secrets.push([0; 32]);
2442                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2443                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2444                         test_secrets!();
2445
2446                         secrets.push([0; 32]);
2447                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2448                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2449                         test_secrets!();
2450
2451                         secrets.push([0; 32]);
2452                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2453                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2454                         test_secrets!();
2455
2456                         secrets.push([0; 32]);
2457                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2458                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2459                         test_secrets!();
2460
2461                         secrets.push([0; 32]);
2462                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2463                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2464                         test_secrets!();
2465
2466                         secrets.push([0; 32]);
2467                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2468                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2469                         test_secrets!();
2470
2471                         secrets.push([0; 32]);
2472                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2473                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2474                         test_secrets!();
2475
2476                         secrets.push([0; 32]);
2477                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2478                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2479                                         "Previous secret did not match new one");
2480                 }
2481         }
2482
2483         #[test]
2484         fn test_prune_preimages() {
2485                 let secp_ctx = Secp256k1::new();
2486                 let logger = Arc::new(TestLogger::new());
2487                 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2488
2489                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2490                 macro_rules! dummy_keys {
2491                         () => {
2492                                 {
2493                                         TxCreationKeys {
2494                                                 per_commitment_point: dummy_key.clone(),
2495                                                 revocation_key: dummy_key.clone(),
2496                                                 a_htlc_key: dummy_key.clone(),
2497                                                 b_htlc_key: dummy_key.clone(),
2498                                                 a_delayed_payment_key: dummy_key.clone(),
2499                                                 b_payment_key: dummy_key.clone(),
2500                                         }
2501                                 }
2502                         }
2503                 }
2504                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2505
2506                 let mut preimages = Vec::new();
2507                 {
2508                         let mut rng  = thread_rng();
2509                         for _ in 0..20 {
2510                                 let mut preimage = [0; 32];
2511                                 rng.fill_bytes(&mut preimage);
2512                                 let mut sha = Sha256::new();
2513                                 sha.input(&preimage);
2514                                 let mut hash = [0; 32];
2515                                 sha.result(&mut hash);
2516                                 preimages.push((preimage, hash));
2517                         }
2518                 }
2519
2520                 macro_rules! preimages_slice_to_htlc_outputs {
2521                         ($preimages_slice: expr) => {
2522                                 {
2523                                         let mut res = Vec::new();
2524                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2525                                                 res.push(HTLCOutputInCommitment {
2526                                                         offered: true,
2527                                                         amount_msat: 0,
2528                                                         cltv_expiry: 0,
2529                                                         payment_hash: preimage.1.clone(),
2530                                                         transaction_output_index: idx as u32,
2531                                                 });
2532                                         }
2533                                         res
2534                                 }
2535                         }
2536                 }
2537                 macro_rules! preimages_to_local_htlcs {
2538                         ($preimages_slice: expr) => {
2539                                 {
2540                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2541                                         let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2542                                         res
2543                                 }
2544                         }
2545                 }
2546
2547                 macro_rules! test_preimages_exist {
2548                         ($preimages_slice: expr, $monitor: expr) => {
2549                                 for preimage in $preimages_slice {
2550                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2551                                 }
2552                         }
2553                 }
2554
2555                 // Prune with one old state and a local commitment tx holding a few overlaps with the
2556                 // old state.
2557                 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2558                 monitor.set_their_to_self_delay(10);
2559
2560                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]), Vec::new());
2561                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), Vec::new(), 281474976710655, dummy_key);
2562                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), Vec::new(), 281474976710654, dummy_key);
2563                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), Vec::new(), 281474976710653, dummy_key);
2564                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), Vec::new(), 281474976710652, dummy_key);
2565                 for &(ref preimage, ref hash) in preimages.iter() {
2566                         monitor.provide_payment_preimage(hash, preimage);
2567                 }
2568
2569                 // Now provide a secret, pruning preimages 10-15
2570                 let mut secret = [0; 32];
2571                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2572                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2573                 assert_eq!(monitor.payment_preimages.len(), 15);
2574                 test_preimages_exist!(&preimages[0..10], monitor);
2575                 test_preimages_exist!(&preimages[15..20], monitor);
2576
2577                 // Now provide a further secret, pruning preimages 15-17
2578                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2579                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2580                 assert_eq!(monitor.payment_preimages.len(), 13);
2581                 test_preimages_exist!(&preimages[0..10], monitor);
2582                 test_preimages_exist!(&preimages[17..20], monitor);
2583
2584                 // Now update local commitment tx info, pruning only element 18 as we still care about the
2585                 // previous commitment tx's preimages too
2586                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]), Vec::new());
2587                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2588                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2589                 assert_eq!(monitor.payment_preimages.len(), 12);
2590                 test_preimages_exist!(&preimages[0..10], monitor);
2591                 test_preimages_exist!(&preimages[18..20], monitor);
2592
2593                 // But if we do it again, we'll prune 5-10
2594                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]), Vec::new());
2595                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2596                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2597                 assert_eq!(monitor.payment_preimages.len(), 5);
2598                 test_preimages_exist!(&preimages[0..5], monitor);
2599         }
2600
2601         // Further testing is done in the ChannelManager integration tests.
2602 }