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