Add registration of commitment tx's outputs from
[rust-lightning] / src / ln / channelmonitor.rs
1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
3 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
4 use bitcoin::blockdata::script::Script;
5 use bitcoin::network::serialize;
6 use bitcoin::util::hash::Sha256dHash;
7 use bitcoin::util::bip143;
8
9 use crypto::digest::Digest;
10
11 use secp256k1::{Secp256k1,Message,Signature};
12 use secp256k1::key::{SecretKey,PublicKey};
13 use secp256k1;
14
15 use ln::msgs::HandleError;
16 use ln::chan_utils;
17 use ln::chan_utils::HTLCOutputInCommitment;
18 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
19 use chain::transaction::OutPoint;
20 use util::sha2::Sha256;
21 use util::byte_utils;
22
23 use std::collections::HashMap;
24 use std::sync::{Arc,Mutex};
25 use std::{hash,cmp};
26
27 pub enum ChannelMonitorUpdateErr {
28         /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
29         /// to succeed at some point in the future).
30         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
31         /// submitting new commitment transactions to the remote party.
32         /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
33         /// the channel to an operational state.
34         TemporaryFailure,
35         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
36         /// different watchtower and cannot update with all watchtowers that were previously informed
37         /// of this channel). This will force-close the channel in question.
38         PermanentFailure,
39 }
40
41 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
42 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
43 /// events to it, while also taking any add_update_monitor events and passing them to some remote
44 /// server(s).
45 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
46 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
47 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
48 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
49 pub trait ManyChannelMonitor: Send + Sync {
50         /// Adds or updates a monitor for the given `funding_txo`.
51         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
52 }
53
54 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
55 /// watchtower or watch our own channels.
56 /// Note that you must provide your own key by which to refer to channels.
57 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
58 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
59 /// index by a PublicKey which is required to sign any updates.
60 /// If you're using this for local monitoring of your own channels, you probably want to use
61 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
62 pub struct SimpleManyChannelMonitor<Key> {
63         monitors: Mutex<HashMap<Key, ChannelMonitor>>,
64         chain_monitor: Arc<ChainWatchInterface>,
65         broadcaster: Arc<BroadcasterInterface>
66 }
67
68 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
69         fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
70                 let monitors = self.monitors.lock().unwrap();
71                 for monitor in monitors.values() {
72                         let outputs = monitor.block_connected(txn_matched, height, &*self.broadcaster);
73                         for output in outputs {
74                                 self.chain_monitor.install_watch_script(&output.script_pubkey);
75                         }
76                 }
77         }
78
79         fn block_disconnected(&self, _: &BlockHeader) { }
80 }
81
82 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
83         pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
84                 let res = Arc::new(SimpleManyChannelMonitor {
85                         monitors: Mutex::new(HashMap::new()),
86                         chain_monitor,
87                         broadcaster
88                 });
89                 let weak_res = Arc::downgrade(&res);
90                 res.chain_monitor.register_listener(weak_res);
91                 res
92         }
93
94         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
95                 let mut monitors = self.monitors.lock().unwrap();
96                 match monitors.get_mut(&key) {
97                         Some(orig_monitor) => return orig_monitor.insert_combine(monitor),
98                         None => {}
99                 };
100                 match &monitor.funding_txo {
101                         &None => self.chain_monitor.watch_all_txn(),
102                         &Some((ref outpoint, ref script)) => {
103                                 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
104                                 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
105                         },
106                 }
107                 monitors.insert(key, monitor);
108                 Ok(())
109         }
110 }
111
112 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
113         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
114                 match self.add_update_monitor_by_key(funding_txo, monitor) {
115                         Ok(_) => Ok(()),
116                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
117                 }
118         }
119 }
120
121 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
122 /// instead claiming it in its own individual transaction.
123 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
124 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
125 /// HTLC-Success transaction.
126 const CLTV_CLAIM_BUFFER: u32 = 6;
127
128 #[derive(Clone, PartialEq)]
129 enum KeyStorage {
130         PrivMode {
131                 revocation_base_key: SecretKey,
132                 htlc_base_key: SecretKey,
133         },
134         SigsMode {
135                 revocation_base_key: PublicKey,
136                 htlc_base_key: PublicKey,
137                 sigs: HashMap<Sha256dHash, Signature>,
138         }
139 }
140
141 #[derive(Clone, PartialEq)]
142 struct LocalSignedTx {
143         /// txid of the transaction in tx, just used to make comparison faster
144         txid: Sha256dHash,
145         tx: Transaction,
146         revocation_key: PublicKey,
147         a_htlc_key: PublicKey,
148         b_htlc_key: PublicKey,
149         delayed_payment_key: PublicKey,
150         feerate_per_kw: u64,
151         htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
152 }
153
154 const SERIALIZATION_VERSION: u8 = 1;
155 const MIN_SERIALIZATION_VERSION: u8 = 1;
156
157 pub struct ChannelMonitor {
158         funding_txo: Option<(OutPoint, Script)>,
159         commitment_transaction_number_obscure_factor: u64,
160
161         key_storage: KeyStorage,
162         delayed_payment_base_key: PublicKey,
163         their_htlc_base_key: Option<PublicKey>,
164         // first is the idx of the first of the two revocation points
165         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
166
167         our_to_self_delay: u16,
168         their_to_self_delay: Option<u16>,
169
170         old_secrets: [([u8; 32], u64); 49],
171         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
172         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
173         /// Nor can we figure out their commitment numbers without the commitment transaction they are
174         /// spending. Thus, in order to claim them via revocation key, we track all the remote
175         /// commitment transactions which we find on-chain, mapping them to the commitment number which
176         /// can be used to derive the revocation key and claim the transactions.
177         remote_commitment_txn_on_chain: Mutex<HashMap<Sha256dHash, u64>>,
178         /// Cache used to make pruning of payment_preimages faster.
179         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
180         /// remote transactions (ie should remain pretty small).
181         /// Serialized to disk but should generally not be sent to Watchtowers.
182         remote_hash_commitment_number: HashMap<[u8; 32], u64>,
183
184         // We store two local commitment transactions to avoid any race conditions where we may update
185         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
186         // various monitors for one channel being out of sync, and us broadcasting a local
187         // transaction for which we have deleted claim information on some watchtowers.
188         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
189         current_local_signed_commitment_tx: Option<LocalSignedTx>,
190
191         payment_preimages: HashMap<[u8; 32], [u8; 32]>,
192
193         destination_script: Script,
194         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
195 }
196 impl Clone for ChannelMonitor {
197         fn clone(&self) -> Self {
198                 ChannelMonitor {
199                         funding_txo: self.funding_txo.clone(),
200                         commitment_transaction_number_obscure_factor: self.commitment_transaction_number_obscure_factor.clone(),
201
202                         key_storage: self.key_storage.clone(),
203                         delayed_payment_base_key: self.delayed_payment_base_key.clone(),
204                         their_htlc_base_key: self.their_htlc_base_key.clone(),
205                         their_cur_revocation_points: self.their_cur_revocation_points.clone(),
206
207                         our_to_self_delay: self.our_to_self_delay,
208                         their_to_self_delay: self.their_to_self_delay,
209
210                         old_secrets: self.old_secrets.clone(),
211                         remote_claimable_outpoints: self.remote_claimable_outpoints.clone(),
212                         remote_commitment_txn_on_chain: Mutex::new((*self.remote_commitment_txn_on_chain.lock().unwrap()).clone()),
213                         remote_hash_commitment_number: self.remote_hash_commitment_number.clone(),
214
215                         prev_local_signed_commitment_tx: self.prev_local_signed_commitment_tx.clone(),
216                         current_local_signed_commitment_tx: self.current_local_signed_commitment_tx.clone(),
217
218                         payment_preimages: self.payment_preimages.clone(),
219
220                         destination_script: self.destination_script.clone(),
221                         secp_ctx: self.secp_ctx.clone(),
222                 }
223         }
224 }
225
226 #[cfg(any(test, feature = "fuzztarget"))]
227 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
228 /// underlying object
229 impl PartialEq for ChannelMonitor {
230         fn eq(&self, other: &Self) -> bool {
231                 if self.funding_txo != other.funding_txo ||
232                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
233                         self.key_storage != other.key_storage ||
234                         self.delayed_payment_base_key != other.delayed_payment_base_key ||
235                         self.their_htlc_base_key != other.their_htlc_base_key ||
236                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
237                         self.our_to_self_delay != other.our_to_self_delay ||
238                         self.their_to_self_delay != other.their_to_self_delay ||
239                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
240                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
241                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
242                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
243                         self.payment_preimages != other.payment_preimages ||
244                         self.destination_script != other.destination_script
245                 {
246                         false
247                 } else {
248                         for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
249                                 if secret != o_secret || idx != o_idx {
250                                         return false
251                                 }
252                         }
253                         let us = self.remote_commitment_txn_on_chain.lock().unwrap();
254                         let them = other.remote_commitment_txn_on_chain.lock().unwrap();
255                         *us == *them
256                 }
257         }
258 }
259
260 impl ChannelMonitor {
261         pub fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &PublicKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script) -> ChannelMonitor {
262                 ChannelMonitor {
263                         funding_txo: None,
264                         commitment_transaction_number_obscure_factor: 0,
265
266                         key_storage: KeyStorage::PrivMode {
267                                 revocation_base_key: revocation_base_key.clone(),
268                                 htlc_base_key: htlc_base_key.clone(),
269                         },
270                         delayed_payment_base_key: delayed_payment_base_key.clone(),
271                         their_htlc_base_key: None,
272                         their_cur_revocation_points: None,
273
274                         our_to_self_delay: our_to_self_delay,
275                         their_to_self_delay: None,
276
277                         old_secrets: [([0; 32], 1 << 48); 49],
278                         remote_claimable_outpoints: HashMap::new(),
279                         remote_commitment_txn_on_chain: Mutex::new(HashMap::new()),
280                         remote_hash_commitment_number: HashMap::new(),
281
282                         prev_local_signed_commitment_tx: None,
283                         current_local_signed_commitment_tx: None,
284
285                         payment_preimages: HashMap::new(),
286
287                         destination_script: destination_script,
288                         secp_ctx: Secp256k1::new(),
289                 }
290         }
291
292         #[inline]
293         fn place_secret(idx: u64) -> u8 {
294                 for i in 0..48 {
295                         if idx & (1 << i) == (1 << i) {
296                                 return i
297                         }
298                 }
299                 48
300         }
301
302         #[inline]
303         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
304                 let mut res: [u8; 32] = secret;
305                 for i in 0..bits {
306                         let bitpos = bits - 1 - i;
307                         if idx & (1 << bitpos) == (1 << bitpos) {
308                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
309                                 let mut sha = Sha256::new();
310                                 sha.input(&res);
311                                 sha.result(&mut res);
312                         }
313                 }
314                 res
315         }
316
317         /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
318         /// revocation point which may be required to claim HTLC outputs which we know the preimage of
319         /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
320         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
321         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
322         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
323                 let pos = ChannelMonitor::place_secret(idx);
324                 for i in 0..pos {
325                         let (old_secret, old_idx) = self.old_secrets[i as usize];
326                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
327                                 return Err(HandleError{err: "Previous secret did not match new one", action: None})
328                         }
329                 }
330                 self.old_secrets[pos as usize] = (secret, idx);
331
332                 if let Some(new_revocation_point) = their_next_revocation_point {
333                         match self.their_cur_revocation_points {
334                                 Some(old_points) => {
335                                         if old_points.0 == new_revocation_point.0 + 1 {
336                                                 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
337                                         } else if old_points.0 == new_revocation_point.0 + 2 {
338                                                 if let Some(old_second_point) = old_points.2 {
339                                                         self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
340                                                 } else {
341                                                         self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
342                                                 }
343                                         } else {
344                                                 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
345                                         }
346                                 },
347                                 None => {
348                                         self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
349                                 }
350                         }
351                 }
352
353                 if !self.payment_preimages.is_empty() {
354                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
355                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
356                         let min_idx = self.get_min_seen_secret();
357                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
358
359                         self.payment_preimages.retain(|&k, _| {
360                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
361                                         if k == htlc.payment_hash {
362                                                 return true
363                                         }
364                                 }
365                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
366                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
367                                                 if k == htlc.payment_hash {
368                                                         return true
369                                                 }
370                                         }
371                                 }
372                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
373                                         if *cn < min_idx {
374                                                 return true
375                                         }
376                                         true
377                                 } else { false };
378                                 if contains {
379                                         remote_hash_commitment_number.remove(&k);
380                                 }
381                                 false
382                         });
383                 }
384
385                 Ok(())
386         }
387
388         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
389         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
390         /// possibly future revocation/preimage information) to claim outputs where possible.
391         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
392         pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
393                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
394                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
395                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
396                 // timeouts)
397                 for htlc in &htlc_outputs {
398                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
399                 }
400                 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
401         }
402
403         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
404         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
405         /// is important that any clones of this channel monitor (including remote clones) by kept
406         /// up-to-date as our local commitment transaction is updated.
407         /// Panics if set_their_to_self_delay has never been called.
408         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)>) {
409                 assert!(self.their_to_self_delay.is_some());
410                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
411                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
412                         txid: signed_commitment_tx.txid(),
413                         tx: signed_commitment_tx,
414                         revocation_key: local_keys.revocation_key,
415                         a_htlc_key: local_keys.a_htlc_key,
416                         b_htlc_key: local_keys.b_htlc_key,
417                         delayed_payment_key: local_keys.a_delayed_payment_key,
418                         feerate_per_kw,
419                         htlc_outputs,
420                 });
421         }
422
423         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
424         /// commitment_tx_infos which contain the payment hash have been revoked.
425         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
426                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
427         }
428
429         pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
430                 if self.funding_txo.is_some() {
431                         // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
432                         // easy to collide the funding_txo hash and have a different scriptPubKey.
433                         if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
434                                 return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
435                         }
436                 } else {
437                         self.funding_txo = other.funding_txo.take();
438                 }
439                 let other_min_secret = other.get_min_seen_secret();
440                 let our_min_secret = self.get_min_seen_secret();
441                 if our_min_secret > other_min_secret {
442                         self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
443                 }
444                 if our_min_secret >= other_min_secret {
445                         self.their_cur_revocation_points = other.their_cur_revocation_points;
446                         for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
447                                 self.remote_claimable_outpoints.insert(txid, htlcs);
448                         }
449                         if let Some(local_tx) = other.prev_local_signed_commitment_tx {
450                                 self.prev_local_signed_commitment_tx = Some(local_tx);
451                         }
452                         if let Some(local_tx) = other.current_local_signed_commitment_tx {
453                                 self.current_local_signed_commitment_tx = Some(local_tx);
454                         }
455                         self.payment_preimages = other.payment_preimages;
456                 }
457                 Ok(())
458         }
459
460         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
461         pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
462                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
463                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
464         }
465
466         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
467         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
468         /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
469         /// provides slightly better privacy.
470         /// It is the responsability of the caller to register outpoint and script with passing the former 
471         /// value as key to update current monitor
472         pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
473                 self.funding_txo = Some(funding_info);
474         }
475
476         pub(super) fn set_their_htlc_base_key(&mut self, their_htlc_base_key: &PublicKey) {
477                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
478         }
479
480         pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
481                 self.their_to_self_delay = Some(their_to_self_delay);
482         }
483
484         pub(super) fn unset_funding_info(&mut self) {
485                 self.funding_txo = None;
486         }
487
488         pub fn get_funding_txo(&self) -> Option<OutPoint> {
489                 match self.funding_txo {
490                         Some((outpoint, _)) => Some(outpoint),
491                         None => None
492                 }
493         }
494
495         /// Serializes into a vec, with various modes for the exposed pub fns
496         fn serialize(&self, for_local_storage: bool) -> Vec<u8> {
497                 let mut res = Vec::new();
498                 res.push(SERIALIZATION_VERSION);
499                 res.push(MIN_SERIALIZATION_VERSION);
500
501                 match &self.funding_txo {
502                         &Some((ref outpoint, ref script)) => {
503                                 res.extend_from_slice(&outpoint.txid[..]);
504                                 res.extend_from_slice(&byte_utils::be16_to_array(outpoint.index));
505                                 res.extend_from_slice(&byte_utils::be64_to_array(script.len() as u64));
506                                 res.extend_from_slice(&script[..]);
507                         },
508                         &None => {
509                                 // We haven't even been initialized...not sure why anyone is serializing us, but
510                                 // not much to give them.
511                                 return res;
512                         },
513                 }
514
515                 // Set in initial Channel-object creation, so should always be set by now:
516                 res.extend_from_slice(&byte_utils::be48_to_array(self.commitment_transaction_number_obscure_factor));
517
518                 match self.key_storage {
519                         KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
520                                 res.push(0);
521                                 res.extend_from_slice(&revocation_base_key[..]);
522                                 res.extend_from_slice(&htlc_base_key[..]);
523                         },
524                         KeyStorage::SigsMode { .. } => unimplemented!(),
525                 }
526
527                 res.extend_from_slice(&self.delayed_payment_base_key.serialize());
528                 res.extend_from_slice(&self.their_htlc_base_key.as_ref().unwrap().serialize());
529
530                 match self.their_cur_revocation_points {
531                         Some((idx, pubkey, second_option)) => {
532                                 res.extend_from_slice(&byte_utils::be48_to_array(idx));
533                                 res.extend_from_slice(&pubkey.serialize());
534                                 match second_option {
535                                         Some(second_pubkey) => {
536                                                 res.extend_from_slice(&second_pubkey.serialize());
537                                         },
538                                         None => {
539                                                 res.extend_from_slice(&[0; 33]);
540                                         },
541                                 }
542                         },
543                         None => {
544                                 res.extend_from_slice(&byte_utils::be48_to_array(0));
545                         },
546                 }
547
548                 res.extend_from_slice(&byte_utils::be16_to_array(self.our_to_self_delay));
549                 res.extend_from_slice(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()));
550
551                 for &(ref secret, ref idx) in self.old_secrets.iter() {
552                         res.extend_from_slice(secret);
553                         res.extend_from_slice(&byte_utils::be64_to_array(*idx));
554                 }
555
556                 macro_rules! serialize_htlc_in_commitment {
557                         ($htlc_output: expr) => {
558                                 res.push($htlc_output.offered as u8);
559                                 res.extend_from_slice(&byte_utils::be64_to_array($htlc_output.amount_msat));
560                                 res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.cltv_expiry));
561                                 res.extend_from_slice(&$htlc_output.payment_hash);
562                                 res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.transaction_output_index));
563                         }
564                 }
565
566                 res.extend_from_slice(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64));
567                 for (txid, htlc_outputs) in self.remote_claimable_outpoints.iter() {
568                         res.extend_from_slice(&txid[..]);
569                         res.extend_from_slice(&byte_utils::be64_to_array(htlc_outputs.len() as u64));
570                         for htlc_output in htlc_outputs.iter() {
571                                 serialize_htlc_in_commitment!(htlc_output);
572                         }
573                 }
574
575                 {
576                         let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
577                         res.extend_from_slice(&byte_utils::be64_to_array(remote_commitment_txn_on_chain.len() as u64));
578                         for (txid, commitment_number) in remote_commitment_txn_on_chain.iter() {
579                                 res.extend_from_slice(&txid[..]);
580                                 res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
581                         }
582                 }
583
584                 if for_local_storage {
585                         res.extend_from_slice(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64));
586                         for (payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
587                                 res.extend_from_slice(payment_hash);
588                                 res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
589                         }
590                 } else {
591                         res.extend_from_slice(&byte_utils::be64_to_array(0));
592                 }
593
594                 macro_rules! serialize_local_tx {
595                         ($local_tx: expr) => {
596                                 let tx_ser = serialize::serialize(&$local_tx.tx).unwrap();
597                                 res.extend_from_slice(&byte_utils::be64_to_array(tx_ser.len() as u64));
598                                 res.extend_from_slice(&tx_ser);
599
600                                 res.extend_from_slice(&$local_tx.revocation_key.serialize());
601                                 res.extend_from_slice(&$local_tx.a_htlc_key.serialize());
602                                 res.extend_from_slice(&$local_tx.b_htlc_key.serialize());
603                                 res.extend_from_slice(&$local_tx.delayed_payment_key.serialize());
604
605                                 res.extend_from_slice(&byte_utils::be64_to_array($local_tx.feerate_per_kw));
606                                 res.extend_from_slice(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64));
607                                 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
608                                         serialize_htlc_in_commitment!(htlc_output);
609                                         res.extend_from_slice(&their_sig.serialize_compact(&self.secp_ctx));
610                                         res.extend_from_slice(&our_sig.serialize_compact(&self.secp_ctx));
611                                 }
612                         }
613                 }
614
615                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
616                         res.push(1);
617                         serialize_local_tx!(prev_local_tx);
618                 } else {
619                         res.push(0);
620                 }
621
622                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
623                         res.push(1);
624                         serialize_local_tx!(cur_local_tx);
625                 } else {
626                         res.push(0);
627                 }
628
629                 res.extend_from_slice(&byte_utils::be64_to_array(self.payment_preimages.len() as u64));
630                 for payment_preimage in self.payment_preimages.values() {
631                         res.extend_from_slice(payment_preimage);
632                 }
633
634                 res.extend_from_slice(&byte_utils::be64_to_array(self.destination_script.len() as u64));
635                 res.extend_from_slice(&self.destination_script[..]);
636
637                 res
638         }
639
640         /// Encodes this monitor into a byte array, suitable for writing to disk.
641         pub fn serialize_for_disk(&self) -> Vec<u8> {
642                 self.serialize(true)
643         }
644
645         /// Encodes this monitor into a byte array, suitable for sending to a remote watchtower
646         pub fn serialize_for_watchtower(&self) -> Vec<u8> {
647                 self.serialize(false)
648         }
649
650         /// Attempts to decode a serialized monitor
651         pub fn deserialize(data: &[u8]) -> Option<Self> {
652                 let mut read_pos = 0;
653                 macro_rules! read_bytes {
654                         ($byte_count: expr) => {
655                                 {
656                                         if ($byte_count as usize) > data.len() - read_pos {
657                                                 return None;
658                                         }
659                                         read_pos += $byte_count as usize;
660                                         &data[read_pos - $byte_count as usize..read_pos]
661                                 }
662                         }
663                 }
664
665                 let secp_ctx = Secp256k1::new();
666                 macro_rules! unwrap_obj {
667                         ($key: expr) => {
668                                 match $key {
669                                         Ok(res) => res,
670                                         Err(_) => return None,
671                                 }
672                         }
673                 }
674
675                 let _ver = read_bytes!(1)[0];
676                 let min_ver = read_bytes!(1)[0];
677                 if min_ver > SERIALIZATION_VERSION {
678                         return None;
679                 }
680
681                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
682                 // barely-init'd ChannelMonitors that we can't do anything with.
683                 let outpoint = OutPoint {
684                         txid: Sha256dHash::from(read_bytes!(32)),
685                         index: byte_utils::slice_to_be16(read_bytes!(2)),
686                 };
687                 let script_len = byte_utils::slice_to_be64(read_bytes!(8));
688                 let funding_txo = Some((outpoint, Script::from(read_bytes!(script_len).to_vec())));
689                 let commitment_transaction_number_obscure_factor = byte_utils::slice_to_be48(read_bytes!(6));
690
691                 let key_storage = match read_bytes!(1)[0] {
692                         0 => {
693                                 KeyStorage::PrivMode {
694                                         revocation_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
695                                         htlc_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
696                                 }
697                         },
698                         _ => return None,
699                 };
700
701                 let delayed_payment_base_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
702                 let their_htlc_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
703
704                 let their_cur_revocation_points = {
705                         let first_idx = byte_utils::slice_to_be48(read_bytes!(6));
706                         if first_idx == 0 {
707                                 None
708                         } else {
709                                 let first_point = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
710                                 let second_point_slice = read_bytes!(33);
711                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
712                                         Some((first_idx, first_point, None))
713                                 } else {
714                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, second_point_slice)))))
715                                 }
716                         }
717                 };
718
719                 let our_to_self_delay = byte_utils::slice_to_be16(read_bytes!(2));
720                 let their_to_self_delay = Some(byte_utils::slice_to_be16(read_bytes!(2)));
721
722                 let mut old_secrets = [([0; 32], 1 << 48); 49];
723                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
724                         secret.copy_from_slice(read_bytes!(32));
725                         *idx = byte_utils::slice_to_be64(read_bytes!(8));
726                 }
727
728                 macro_rules! read_htlc_in_commitment {
729                         () => {
730                                 {
731                                         let offered = match read_bytes!(1)[0] {
732                                                 0 => false, 1 => true,
733                                                 _ => return None,
734                                         };
735                                         let amount_msat = byte_utils::slice_to_be64(read_bytes!(8));
736                                         let cltv_expiry = byte_utils::slice_to_be32(read_bytes!(4));
737                                         let mut payment_hash = [0; 32];
738                                         payment_hash[..].copy_from_slice(read_bytes!(32));
739                                         let transaction_output_index = byte_utils::slice_to_be32(read_bytes!(4));
740
741                                         HTLCOutputInCommitment {
742                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
743                                         }
744                                 }
745                         }
746                 }
747
748                 let remote_claimable_outpoints_len = byte_utils::slice_to_be64(read_bytes!(8));
749                 if remote_claimable_outpoints_len > data.len() as u64 / 64 { return None; }
750                 let mut remote_claimable_outpoints = HashMap::with_capacity(remote_claimable_outpoints_len as usize);
751                 for _ in 0..remote_claimable_outpoints_len {
752                         let txid = Sha256dHash::from(read_bytes!(32));
753                         let outputs_count = byte_utils::slice_to_be64(read_bytes!(8));
754                         if outputs_count > data.len() as u64 / 32 { return None; }
755                         let mut outputs = Vec::with_capacity(outputs_count as usize);
756                         for _ in 0..outputs_count {
757                                 outputs.push(read_htlc_in_commitment!());
758                         }
759                         if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
760                                 return None;
761                         }
762                 }
763
764                 let remote_commitment_txn_on_chain_len = byte_utils::slice_to_be64(read_bytes!(8));
765                 if remote_commitment_txn_on_chain_len > data.len() as u64 / 32 { return None; }
766                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(remote_commitment_txn_on_chain_len as usize);
767                 for _ in 0..remote_commitment_txn_on_chain_len {
768                         let txid = Sha256dHash::from(read_bytes!(32));
769                         let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
770                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, commitment_number) {
771                                 return None;
772                         }
773                 }
774
775                 let remote_hash_commitment_number_len = byte_utils::slice_to_be64(read_bytes!(8));
776                 if remote_hash_commitment_number_len > data.len() as u64 / 32 { return None; }
777                 let mut remote_hash_commitment_number = HashMap::with_capacity(remote_hash_commitment_number_len as usize);
778                 for _ in 0..remote_hash_commitment_number_len {
779                         let mut txid = [0; 32];
780                         txid[..].copy_from_slice(read_bytes!(32));
781                         let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
782                         if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
783                                 return None;
784                         }
785                 }
786
787                 macro_rules! read_local_tx {
788                         () => {
789                                 {
790                                         let tx_len = byte_utils::slice_to_be64(read_bytes!(8));
791                                         let tx_ser = read_bytes!(tx_len);
792                                         let tx: Transaction = unwrap_obj!(serialize::deserialize(tx_ser));
793                                         if serialize::serialize(&tx).unwrap() != tx_ser {
794                                                 // We check that the tx re-serializes to the same form to ensure there is
795                                                 // no extra data, and as rust-bitcoin doesn't handle the 0-input ambiguity
796                                                 // all that well.
797                                                 return None;
798                                         }
799
800                                         let revocation_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
801                                         let a_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
802                                         let b_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
803                                         let delayed_payment_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
804                                         let feerate_per_kw = byte_utils::slice_to_be64(read_bytes!(8));
805
806                                         let htlc_outputs_len = byte_utils::slice_to_be64(read_bytes!(8));
807                                         if htlc_outputs_len > data.len() as u64 / 128 { return None; }
808                                         let mut htlc_outputs = Vec::with_capacity(htlc_outputs_len as usize);
809                                         for _ in 0..htlc_outputs_len {
810                                                 htlc_outputs.push((read_htlc_in_commitment!(),
811                                                                 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64))),
812                                                                 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64)))));
813                                         }
814
815                                         LocalSignedTx {
816                                                 txid: tx.txid(),
817                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
818                                         }
819                                 }
820                         }
821                 }
822
823                 let prev_local_signed_commitment_tx = match read_bytes!(1)[0] {
824                         0 => None,
825                         1 => {
826                                 Some(read_local_tx!())
827                         },
828                         _ => return None,
829                 };
830
831                 let current_local_signed_commitment_tx = match read_bytes!(1)[0] {
832                         0 => None,
833                         1 => {
834                                 Some(read_local_tx!())
835                         },
836                         _ => return None,
837                 };
838
839                 let payment_preimages_len = byte_utils::slice_to_be64(read_bytes!(8));
840                 if payment_preimages_len > data.len() as u64 / 32 { return None; }
841                 let mut payment_preimages = HashMap::with_capacity(payment_preimages_len as usize);
842                 let mut sha = Sha256::new();
843                 for _ in 0..payment_preimages_len {
844                         let mut preimage = [0; 32];
845                         preimage[..].copy_from_slice(read_bytes!(32));
846                         sha.reset();
847                         sha.input(&preimage);
848                         let mut hash = [0; 32];
849                         sha.result(&mut hash);
850                         if let Some(_) = payment_preimages.insert(hash, preimage) {
851                                 return None;
852                         }
853                 }
854
855                 let destination_script_len = byte_utils::slice_to_be64(read_bytes!(8));
856                 let destination_script = Script::from(read_bytes!(destination_script_len).to_vec());
857
858                 Some(ChannelMonitor {
859                         funding_txo,
860                         commitment_transaction_number_obscure_factor,
861
862                         key_storage,
863                         delayed_payment_base_key,
864                         their_htlc_base_key,
865                         their_cur_revocation_points,
866
867                         our_to_self_delay,
868                         their_to_self_delay,
869
870                         old_secrets,
871                         remote_claimable_outpoints,
872                         remote_commitment_txn_on_chain: Mutex::new(remote_commitment_txn_on_chain),
873                         remote_hash_commitment_number,
874
875                         prev_local_signed_commitment_tx,
876                         current_local_signed_commitment_tx,
877
878                         payment_preimages,
879
880                         destination_script,
881                         secp_ctx,
882                 })
883         }
884
885         //TODO: Functions to serialize/deserialize (with different forms depending on which information
886         //we want to leave out (eg funding_txo, etc).
887
888         /// Can only fail if idx is < get_min_seen_secret
889         pub fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
890                 for i in 0..self.old_secrets.len() {
891                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
892                                 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
893                         }
894                 }
895                 assert!(idx < self.get_min_seen_secret());
896                 Err(HandleError{err: "idx too low", action: None})
897         }
898
899         pub fn get_min_seen_secret(&self) -> u64 {
900                 //TODO This can be optimized?
901                 let mut min = 1 << 48;
902                 for &(_, idx) in self.old_secrets.iter() {
903                         if idx < min {
904                                 min = idx;
905                         }
906                 }
907                 min
908         }
909
910         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
911         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
912         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
913         /// HTLC-Success/HTLC-Timeout transactions, and claim them using the revocation key (if
914         /// applicable) as well.
915         fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<TxOut>) {
916                 // Most secp and related errors trying to create keys means we have no hope of constructing
917                 // a spend transaction...so we return no transactions to broadcast
918                 let mut txn_to_broadcast = Vec::new();
919                 let mut outputs = Vec::new();
920                 macro_rules! ignore_error {
921                         ( $thing : expr ) => {
922                                 match $thing {
923                                         Ok(a) => a,
924                                         Err(_) => return (txn_to_broadcast, outputs)
925                                 }
926                         };
927                 }
928
929                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
930                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
931
932                 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);
933                 if commitment_number >= self.get_min_seen_secret() {
934                         let secret = self.get_secret(commitment_number).unwrap();
935                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
936                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
937                                 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
938                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
939                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
940                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
941                                 },
942                                 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
943                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
944                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
945                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
946                                 },
947                         };
948                         let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.delayed_payment_base_key));
949                         let a_htlc_key = match self.their_htlc_base_key {
950                                 None => return (txn_to_broadcast, outputs),
951                                 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)),
952                         };
953
954                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
955                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
956
957                         let mut total_value = 0;
958                         let mut values = Vec::new();
959                         let mut inputs = Vec::new();
960                         let mut htlc_idxs = Vec::new();
961
962                         for (idx, outp) in tx.output.iter().enumerate() {
963                                 if outp.script_pubkey == revokeable_p2wsh {
964                                         inputs.push(TxIn {
965                                                 previous_output: BitcoinOutPoint {
966                                                         txid: commitment_txid,
967                                                         vout: idx as u32,
968                                                 },
969                                                 script_sig: Script::new(),
970                                                 sequence: 0xfffffffd,
971                                                 witness: Vec::new(),
972                                         });
973                                         htlc_idxs.push(None);
974                                         values.push(outp.value);
975                                         total_value += outp.value;
976                                         break; // There can only be one of these
977                                 }
978                         }
979
980                         macro_rules! sign_input {
981                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
982                                         {
983                                                 let (sig, redeemscript) = match self.key_storage {
984                                                         KeyStorage::PrivMode { ref revocation_base_key, .. } => {
985                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
986                                                                         let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
987                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
988                                                                 };
989                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
990                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
991                                                                 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
992                                                         },
993                                                         KeyStorage::SigsMode { .. } => {
994                                                                 unimplemented!();
995                                                         }
996                                                 };
997                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
998                                                 $input.witness[0].push(SigHashType::All as u8);
999                                                 if $htlc_idx.is_none() {
1000                                                         $input.witness.push(vec!(1));
1001                                                 } else {
1002                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
1003                                                 }
1004                                                 $input.witness.push(redeemscript.into_bytes());
1005                                         }
1006                                 }
1007                         }
1008
1009                         if let Some(per_commitment_data) = per_commitment_option {
1010                                 inputs.reserve_exact(per_commitment_data.len());
1011
1012                                 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1013                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1014                                         if htlc.transaction_output_index as usize >= tx.output.len() ||
1015                                                         tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1016                                                         tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1017                                                 return (txn_to_broadcast, outputs); // Corrupted per_commitment_data, fuck this user
1018                                         }
1019                                         let input = TxIn {
1020                                                 previous_output: BitcoinOutPoint {
1021                                                         txid: commitment_txid,
1022                                                         vout: htlc.transaction_output_index,
1023                                                 },
1024                                                 script_sig: Script::new(),
1025                                                 sequence: 0xfffffffd,
1026                                                 witness: Vec::new(),
1027                                         };
1028                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1029                                                 inputs.push(input);
1030                                                 htlc_idxs.push(Some(idx));
1031                                                 values.push(tx.output[htlc.transaction_output_index as usize].value);
1032                                                 total_value += htlc.amount_msat / 1000;
1033                                         } else {
1034                                                 let mut single_htlc_tx = Transaction {
1035                                                         version: 2,
1036                                                         lock_time: 0,
1037                                                         input: vec![input],
1038                                                         output: vec!(TxOut {
1039                                                                 script_pubkey: self.destination_script.clone(),
1040                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
1041                                                         }),
1042                                                 };
1043                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1044                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1045                                                 txn_to_broadcast.push(single_htlc_tx); // TODO: This is not yet tested in ChannelManager!
1046                                         }
1047                                 }
1048                         }
1049
1050                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1051                                 // We're definitely a remote commitment transaction!
1052                                 outputs.append(&mut tx.output.clone());
1053                                 self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
1054                         }
1055                         if inputs.is_empty() { return (txn_to_broadcast, outputs); } // Nothing to be done...probably a false positive/local tx
1056
1057                         let outputs = vec!(TxOut {
1058                                 script_pubkey: self.destination_script.clone(),
1059                                 value: total_value, //TODO: - fee
1060                         });
1061                         let mut spend_tx = Transaction {
1062                                 version: 2,
1063                                 lock_time: 0,
1064                                 input: inputs,
1065                                 output: outputs,
1066                         };
1067
1068                         let mut values_drain = values.drain(..);
1069                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1070
1071                         for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1072                                 let value = values_drain.next().unwrap();
1073                                 sign_input!(sighash_parts, input, htlc_idx, value);
1074                         }
1075
1076                         txn_to_broadcast.push(spend_tx);
1077                 } else if let Some(per_commitment_data) = per_commitment_option {
1078                         // While this isn't useful yet, there is a potential race where if a counterparty
1079                         // revokes a state at the same time as the commitment transaction for that state is
1080                         // confirmed, and the watchtower receives the block before the user, the user could
1081                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1082                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1083                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1084                         // insert it here.
1085                         outputs.append(&mut tx.output.clone());
1086                         self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
1087
1088                         if let Some(revocation_points) = self.their_cur_revocation_points {
1089                                 let revocation_point_option =
1090                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1091                                         else if let Some(point) = revocation_points.2.as_ref() {
1092                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1093                                         } else { None };
1094                                 if let Some(revocation_point) = revocation_point_option {
1095                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1096                                                 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
1097                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1098                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1099                                                 },
1100                                                 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1101                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1102                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1103                                                 },
1104                                         };
1105                                         let a_htlc_key = match self.their_htlc_base_key {
1106                                                 None => return (txn_to_broadcast, outputs),
1107                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1108                                         };
1109
1110                                         let mut total_value = 0;
1111                                         let mut values = Vec::new();
1112                                         let mut inputs = Vec::new();
1113
1114                                         macro_rules! sign_input {
1115                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1116                                                         {
1117                                                                 let (sig, redeemscript) = match self.key_storage {
1118                                                                         KeyStorage::PrivMode { ref htlc_base_key, .. } => {
1119                                                                                 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1120                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1121                                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1122                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1123                                                                                 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1124                                                                         },
1125                                                                         KeyStorage::SigsMode { .. } => {
1126                                                                                 unimplemented!();
1127                                                                         }
1128                                                                 };
1129                                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1130                                                                 $input.witness[0].push(SigHashType::All as u8);
1131                                                                 $input.witness.push($preimage);
1132                                                                 $input.witness.push(redeemscript.into_bytes());
1133                                                         }
1134                                                 }
1135                                         }
1136
1137                                         for (idx, htlc) in per_commitment_data.iter().enumerate() {
1138                                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1139                                                         let input = TxIn {
1140                                                                 previous_output: BitcoinOutPoint {
1141                                                                         txid: commitment_txid,
1142                                                                         vout: htlc.transaction_output_index,
1143                                                                 },
1144                                                                 script_sig: Script::new(),
1145                                                                 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1146                                                                 witness: Vec::new(),
1147                                                         };
1148                                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1149                                                                 inputs.push(input);
1150                                                                 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1151                                                                 total_value += htlc.amount_msat / 1000;
1152                                                         } else {
1153                                                                 let mut single_htlc_tx = Transaction {
1154                                                                         version: 2,
1155                                                                         lock_time: 0,
1156                                                                         input: vec![input],
1157                                                                         output: vec!(TxOut {
1158                                                                                 script_pubkey: self.destination_script.clone(),
1159                                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
1160                                                                         }),
1161                                                                 };
1162                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1163                                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1164                                                                 txn_to_broadcast.push(single_htlc_tx);
1165                                                         }
1166                                                 }
1167                                         }
1168
1169                                         if inputs.is_empty() { return (txn_to_broadcast, outputs); } // Nothing to be done...probably a false positive/local tx
1170
1171                                         let outputs = vec!(TxOut {
1172                                                 script_pubkey: self.destination_script.clone(),
1173                                                 value: total_value, //TODO: - fee
1174                                         });
1175                                         let mut spend_tx = Transaction {
1176                                                 version: 2,
1177                                                 lock_time: 0,
1178                                                 input: inputs,
1179                                                 output: outputs,
1180                                         };
1181
1182                                         let mut values_drain = values.drain(..);
1183                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1184
1185                                         for input in spend_tx.input.iter_mut() {
1186                                                 let value = values_drain.next().unwrap();
1187                                                 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1188                                         }
1189
1190                                         txn_to_broadcast.push(spend_tx);
1191                                 }
1192                         }
1193                 } else {
1194                         //TODO: For each input check if its in our remote_commitment_txn_on_chain map!
1195                 }
1196
1197                 (txn_to_broadcast, outputs)
1198         }
1199
1200         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
1201                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1202
1203                 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1204                         if htlc.offered {
1205                                 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);
1206
1207                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1208
1209                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1210                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1211                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1212                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1213
1214                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
1215                                 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());
1216
1217                                 res.push(htlc_timeout_tx);
1218                         } else {
1219                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1220                                         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);
1221
1222                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1223
1224                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1225                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1226                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1227                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1228
1229                                         htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1230                                         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());
1231
1232                                         res.push(htlc_success_tx);
1233                                 }
1234                         }
1235                 }
1236
1237                 res
1238         }
1239
1240         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1241         /// revoked using data in local_claimable_outpoints.
1242         /// Should not be used if check_spend_revoked_transaction succeeds.
1243         fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
1244                 let commitment_txid = tx.txid();
1245                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1246                         if local_tx.txid == commitment_txid {
1247                                 return self.broadcast_by_local_state(local_tx);
1248                         }
1249                 }
1250                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1251                         if local_tx.txid == commitment_txid {
1252                                 return self.broadcast_by_local_state(local_tx);
1253                         }
1254                 }
1255                 Vec::new()
1256         }
1257
1258         fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface) -> Vec<TxOut> {
1259                 let mut outputs = Vec::new();
1260                 for tx in txn_matched {
1261                         for txin in tx.input.iter() {
1262                                 if self.funding_txo.is_none() || (txin.previous_output.txid == self.funding_txo.as_ref().unwrap().0.txid && txin.previous_output.vout == self.funding_txo.as_ref().unwrap().0.index as u32) {
1263                                         let (mut txn, out) = self.check_spend_remote_transaction(tx, height);
1264                                         outputs = out;
1265                                         if txn.is_empty() {
1266                                                 txn = self.check_spend_local_transaction(tx, height);
1267                                         }
1268                                         for tx in txn.iter() {
1269                                                 broadcaster.broadcast_transaction(tx);
1270                                         }
1271                                 }
1272                         }
1273                 }
1274                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1275                         let mut needs_broadcast = false;
1276                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1277                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1278                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1279                                                 needs_broadcast = true;
1280                                         }
1281                                 }
1282                         }
1283
1284                         if needs_broadcast {
1285                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1286                                 for tx in self.broadcast_by_local_state(&cur_local_tx) {
1287                                         broadcaster.broadcast_transaction(&tx);
1288                                 }
1289                         }
1290                 }
1291                 outputs
1292         }
1293
1294         pub fn would_broadcast_at_height(&self, height: u32) -> bool {
1295                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1296                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1297                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1298                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1299                                                 return true;
1300                                         }
1301                                 }
1302                         }
1303                 }
1304                 false
1305         }
1306 }
1307
1308 #[cfg(test)]
1309 mod tests {
1310         use bitcoin::blockdata::script::Script;
1311         use bitcoin::blockdata::transaction::Transaction;
1312         use crypto::digest::Digest;
1313         use hex;
1314         use ln::channelmonitor::ChannelMonitor;
1315         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1316         use util::sha2::Sha256;
1317         use secp256k1::key::{SecretKey,PublicKey};
1318         use secp256k1::{Secp256k1, Signature};
1319         use rand::{thread_rng,Rng};
1320
1321         #[test]
1322         fn test_per_commitment_storage() {
1323                 // Test vectors from BOLT 3:
1324                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1325                 let mut monitor: ChannelMonitor;
1326                 let secp_ctx = Secp256k1::new();
1327
1328                 macro_rules! test_secrets {
1329                         () => {
1330                                 let mut idx = 281474976710655;
1331                                 for secret in secrets.iter() {
1332                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1333                                         idx -= 1;
1334                                 }
1335                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1336                                 assert!(monitor.get_secret(idx).is_err());
1337                         };
1338                 }
1339
1340                 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1341
1342                 {
1343                         // insert_secret correct sequence
1344                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1345                         secrets.clear();
1346
1347                         secrets.push([0; 32]);
1348                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1349                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1350                         test_secrets!();
1351
1352                         secrets.push([0; 32]);
1353                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1354                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1355                         test_secrets!();
1356
1357                         secrets.push([0; 32]);
1358                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1359                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1360                         test_secrets!();
1361
1362                         secrets.push([0; 32]);
1363                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1364                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1365                         test_secrets!();
1366
1367                         secrets.push([0; 32]);
1368                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1369                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1370                         test_secrets!();
1371
1372                         secrets.push([0; 32]);
1373                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1374                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1375                         test_secrets!();
1376
1377                         secrets.push([0; 32]);
1378                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1379                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1380                         test_secrets!();
1381
1382                         secrets.push([0; 32]);
1383                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1384                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1385                         test_secrets!();
1386                 }
1387
1388                 {
1389                         // insert_secret #1 incorrect
1390                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1391                         secrets.clear();
1392
1393                         secrets.push([0; 32]);
1394                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1395                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1396                         test_secrets!();
1397
1398                         secrets.push([0; 32]);
1399                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1400                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1401                                         "Previous secret did not match new one");
1402                 }
1403
1404                 {
1405                         // insert_secret #2 incorrect (#1 derived from incorrect)
1406                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1407                         secrets.clear();
1408
1409                         secrets.push([0; 32]);
1410                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1411                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1412                         test_secrets!();
1413
1414                         secrets.push([0; 32]);
1415                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1416                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1417                         test_secrets!();
1418
1419                         secrets.push([0; 32]);
1420                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1421                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1422                         test_secrets!();
1423
1424                         secrets.push([0; 32]);
1425                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1426                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1427                                         "Previous secret did not match new one");
1428                 }
1429
1430                 {
1431                         // insert_secret #3 incorrect
1432                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1433                         secrets.clear();
1434
1435                         secrets.push([0; 32]);
1436                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1437                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1438                         test_secrets!();
1439
1440                         secrets.push([0; 32]);
1441                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1442                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1443                         test_secrets!();
1444
1445                         secrets.push([0; 32]);
1446                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1447                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1448                         test_secrets!();
1449
1450                         secrets.push([0; 32]);
1451                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1452                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1453                                         "Previous secret did not match new one");
1454                 }
1455
1456                 {
1457                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1458                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1459                         secrets.clear();
1460
1461                         secrets.push([0; 32]);
1462                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1463                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1464                         test_secrets!();
1465
1466                         secrets.push([0; 32]);
1467                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1468                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1469                         test_secrets!();
1470
1471                         secrets.push([0; 32]);
1472                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1473                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1474                         test_secrets!();
1475
1476                         secrets.push([0; 32]);
1477                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1478                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1479                         test_secrets!();
1480
1481                         secrets.push([0; 32]);
1482                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1483                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1484                         test_secrets!();
1485
1486                         secrets.push([0; 32]);
1487                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1488                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1489                         test_secrets!();
1490
1491                         secrets.push([0; 32]);
1492                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1493                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1494                         test_secrets!();
1495
1496                         secrets.push([0; 32]);
1497                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1498                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1499                                         "Previous secret did not match new one");
1500                 }
1501
1502                 {
1503                         // insert_secret #5 incorrect
1504                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1505                         secrets.clear();
1506
1507                         secrets.push([0; 32]);
1508                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1509                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1510                         test_secrets!();
1511
1512                         secrets.push([0; 32]);
1513                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1514                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1515                         test_secrets!();
1516
1517                         secrets.push([0; 32]);
1518                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1519                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1520                         test_secrets!();
1521
1522                         secrets.push([0; 32]);
1523                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1524                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1525                         test_secrets!();
1526
1527                         secrets.push([0; 32]);
1528                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1529                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1530                         test_secrets!();
1531
1532                         secrets.push([0; 32]);
1533                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1534                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1535                                         "Previous secret did not match new one");
1536                 }
1537
1538                 {
1539                         // insert_secret #6 incorrect (5 derived from incorrect)
1540                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1541                         secrets.clear();
1542
1543                         secrets.push([0; 32]);
1544                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1545                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1546                         test_secrets!();
1547
1548                         secrets.push([0; 32]);
1549                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1550                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1551                         test_secrets!();
1552
1553                         secrets.push([0; 32]);
1554                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1555                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1556                         test_secrets!();
1557
1558                         secrets.push([0; 32]);
1559                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1560                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1561                         test_secrets!();
1562
1563                         secrets.push([0; 32]);
1564                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1565                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1566                         test_secrets!();
1567
1568                         secrets.push([0; 32]);
1569                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1570                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1571                         test_secrets!();
1572
1573                         secrets.push([0; 32]);
1574                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1575                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1576                         test_secrets!();
1577
1578                         secrets.push([0; 32]);
1579                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1580                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1581                                         "Previous secret did not match new one");
1582                 }
1583
1584                 {
1585                         // insert_secret #7 incorrect
1586                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1587                         secrets.clear();
1588
1589                         secrets.push([0; 32]);
1590                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1591                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1592                         test_secrets!();
1593
1594                         secrets.push([0; 32]);
1595                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1596                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1597                         test_secrets!();
1598
1599                         secrets.push([0; 32]);
1600                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1601                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1602                         test_secrets!();
1603
1604                         secrets.push([0; 32]);
1605                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1606                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1607                         test_secrets!();
1608
1609                         secrets.push([0; 32]);
1610                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1611                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1612                         test_secrets!();
1613
1614                         secrets.push([0; 32]);
1615                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1616                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1617                         test_secrets!();
1618
1619                         secrets.push([0; 32]);
1620                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1621                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1622                         test_secrets!();
1623
1624                         secrets.push([0; 32]);
1625                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1626                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1627                                         "Previous secret did not match new one");
1628                 }
1629
1630                 {
1631                         // insert_secret #8 incorrect
1632                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1633                         secrets.clear();
1634
1635                         secrets.push([0; 32]);
1636                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1637                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1638                         test_secrets!();
1639
1640                         secrets.push([0; 32]);
1641                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1642                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1643                         test_secrets!();
1644
1645                         secrets.push([0; 32]);
1646                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1647                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1648                         test_secrets!();
1649
1650                         secrets.push([0; 32]);
1651                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1652                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1653                         test_secrets!();
1654
1655                         secrets.push([0; 32]);
1656                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1657                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1658                         test_secrets!();
1659
1660                         secrets.push([0; 32]);
1661                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1662                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1663                         test_secrets!();
1664
1665                         secrets.push([0; 32]);
1666                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1667                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1668                         test_secrets!();
1669
1670                         secrets.push([0; 32]);
1671                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1672                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1673                                         "Previous secret did not match new one");
1674                 }
1675         }
1676
1677         #[test]
1678         fn test_prune_preimages() {
1679                 let secp_ctx = Secp256k1::new();
1680                 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
1681
1682                 macro_rules! dummy_keys {
1683                         () => {
1684                                 {
1685                                         let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1686                                         TxCreationKeys {
1687                                                 per_commitment_point: dummy_key.clone(),
1688                                                 revocation_key: dummy_key.clone(),
1689                                                 a_htlc_key: dummy_key.clone(),
1690                                                 b_htlc_key: dummy_key.clone(),
1691                                                 a_delayed_payment_key: dummy_key.clone(),
1692                                                 b_payment_key: dummy_key.clone(),
1693                                         }
1694                                 }
1695                         }
1696                 }
1697                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
1698
1699                 let mut preimages = Vec::new();
1700                 {
1701                         let mut rng  = thread_rng();
1702                         for _ in 0..20 {
1703                                 let mut preimage = [0; 32];
1704                                 rng.fill_bytes(&mut preimage);
1705                                 let mut sha = Sha256::new();
1706                                 sha.input(&preimage);
1707                                 let mut hash = [0; 32];
1708                                 sha.result(&mut hash);
1709                                 preimages.push((preimage, hash));
1710                         }
1711                 }
1712
1713                 macro_rules! preimages_slice_to_htlc_outputs {
1714                         ($preimages_slice: expr) => {
1715                                 {
1716                                         let mut res = Vec::new();
1717                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
1718                                                 res.push(HTLCOutputInCommitment {
1719                                                         offered: true,
1720                                                         amount_msat: 0,
1721                                                         cltv_expiry: 0,
1722                                                         payment_hash: preimage.1.clone(),
1723                                                         transaction_output_index: idx as u32,
1724                                                 });
1725                                         }
1726                                         res
1727                                 }
1728                         }
1729                 }
1730                 macro_rules! preimages_to_local_htlcs {
1731                         ($preimages_slice: expr) => {
1732                                 {
1733                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
1734                                         let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
1735                                         res
1736                                 }
1737                         }
1738                 }
1739
1740                 macro_rules! test_preimages_exist {
1741                         ($preimages_slice: expr, $monitor: expr) => {
1742                                 for preimage in $preimages_slice {
1743                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
1744                                 }
1745                         }
1746                 }
1747
1748                 // Prune with one old state and a local commitment tx holding a few overlaps with the
1749                 // old state.
1750                 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1751                 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1752                 monitor.set_their_to_self_delay(10);
1753
1754                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
1755                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
1756                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
1757                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
1758                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
1759                 for &(ref preimage, ref hash) in preimages.iter() {
1760                         monitor.provide_payment_preimage(hash, preimage);
1761                 }
1762
1763                 // Now provide a secret, pruning preimages 10-15
1764                 let mut secret = [0; 32];
1765                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1766                 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
1767                 assert_eq!(monitor.payment_preimages.len(), 15);
1768                 test_preimages_exist!(&preimages[0..10], monitor);
1769                 test_preimages_exist!(&preimages[15..20], monitor);
1770
1771                 // Now provide a further secret, pruning preimages 15-17
1772                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1773                 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
1774                 assert_eq!(monitor.payment_preimages.len(), 13);
1775                 test_preimages_exist!(&preimages[0..10], monitor);
1776                 test_preimages_exist!(&preimages[17..20], monitor);
1777
1778                 // Now update local commitment tx info, pruning only element 18 as we still care about the
1779                 // previous commitment tx's preimages too
1780                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
1781                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1782                 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
1783                 assert_eq!(monitor.payment_preimages.len(), 12);
1784                 test_preimages_exist!(&preimages[0..10], monitor);
1785                 test_preimages_exist!(&preimages[18..20], monitor);
1786
1787                 // But if we do it again, we'll prune 5-10
1788                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
1789                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1790                 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
1791                 assert_eq!(monitor.payment_preimages.len(), 5);
1792                 test_preimages_exist!(&preimages[0..5], monitor);
1793         }
1794
1795         // Further testing is done in the ChannelManager integration tests.
1796 }