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