]> git.bitcoin.ninja Git - rust-lightning/blob - src/ln/channelmonitor.rs
Merge pull request #193 from SWvheerden/Bolt2-specs-errors-of-closing-messages-
[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.delayed_payment_base_key));
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); // TODO: This is not yet tested in ChannelManager!
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                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1015
1016                 macro_rules! ignore_error {
1017                         ( $thing : expr ) => {
1018                                 match $thing {
1019                                         Ok(a) => a,
1020                                         Err(_) => return None
1021                                 }
1022                         };
1023                 }
1024
1025                 let secret = ignore_error!(self.get_secret(commitment_number));
1026                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1027                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1028                 let revocation_pubkey = match self.key_storage {
1029                         KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1030                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1031                         },
1032                         KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1033                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1034                         },
1035                 };
1036                 let delayed_key = match self.their_delayed_payment_base_key {
1037                         None => return None,
1038                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1039                 };
1040                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1041                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1042
1043                 let mut inputs = Vec::new();
1044                 let mut amount = 0;
1045
1046                 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1047                         inputs.push(TxIn {
1048                                 previous_output: BitcoinOutPoint {
1049                                         txid: htlc_txid,
1050                                         vout: 0,
1051                                 },
1052                                 script_sig: Script::new(),
1053                                 sequence: 0xfffffffd,
1054                                 witness: Vec::new(),
1055                         });
1056                         amount = tx.output[0].value;
1057                 }
1058
1059                 if !inputs.is_empty() {
1060                         let outputs = vec!(TxOut {
1061                                 script_pubkey: self.destination_script.clone(),
1062                                 value: amount, //TODO: - fee
1063                         });
1064
1065                         let mut spend_tx = Transaction {
1066                                 version: 2,
1067                                 lock_time: 0,
1068                                 input: inputs,
1069                                 output: outputs,
1070                         };
1071
1072                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1073
1074                         let sig = match self.key_storage {
1075                                 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1076                                         let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1077                                         let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1078                                         self.secp_ctx.sign(&sighash, &revocation_key)
1079                                 }
1080                                 KeyStorage::SigsMode { .. } => {
1081                                         unimplemented!();
1082                                 }
1083                         };
1084                         spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1085                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1086                         spend_tx.input[0].witness.push(vec!(1));
1087                         spend_tx.input[0].witness.push(redeemscript.into_bytes());
1088
1089                         Some(spend_tx)
1090                 } else { None }
1091         }
1092
1093         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
1094                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1095
1096                 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1097                         if htlc.offered {
1098                                 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);
1099
1100                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1101
1102                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1103                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1104                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1105                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1106
1107                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
1108                                 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());
1109
1110                                 res.push(htlc_timeout_tx);
1111                         } else {
1112                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1113                                         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);
1114
1115                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1116
1117                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1118                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1119                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1120                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1121
1122                                         htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1123                                         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());
1124
1125                                         res.push(htlc_success_tx);
1126                                 }
1127                         }
1128                 }
1129
1130                 res
1131         }
1132
1133         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1134         /// revoked using data in local_claimable_outpoints.
1135         /// Should not be used if check_spend_revoked_transaction succeeds.
1136         fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
1137                 let commitment_txid = tx.txid();
1138                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1139                         if local_tx.txid == commitment_txid {
1140                                 return self.broadcast_by_local_state(local_tx);
1141                         }
1142                 }
1143                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1144                         if local_tx.txid == commitment_txid {
1145                                 return self.broadcast_by_local_state(local_tx);
1146                         }
1147                 }
1148                 Vec::new()
1149         }
1150
1151         fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface)-> Vec<(Sha256dHash, Vec<TxOut>)> {
1152                 let mut watch_outputs = Vec::new();
1153                 for tx in txn_matched {
1154                         if tx.input.len() == 1 {
1155                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1156                                 // commitment transactions and HTLC transactions will all only ever have one input,
1157                                 // which is an easy way to filter out any potential non-matching txn for lazy
1158                                 // filters.
1159                                 let prevout = &tx.input[0].previous_output;
1160                                 let mut txn: Vec<Transaction> = Vec::new();
1161                                 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) {
1162                                         let (remote_txn, new_outputs) = self.check_spend_remote_transaction(tx, height);
1163                                         txn = remote_txn;
1164                                         if !new_outputs.1.is_empty() {
1165                                                 watch_outputs.push(new_outputs);
1166                                         }
1167                                         if txn.is_empty() {
1168                                                 txn = self.check_spend_local_transaction(tx, height);
1169                                         }
1170                                 } else {
1171                                         let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
1172                                         if let Some(commitment_number) = remote_commitment_txn_on_chain.get(&prevout.txid) {
1173                                                 if let Some(tx) = self.check_spend_remote_htlc(tx, *commitment_number) {
1174                                                         txn.push(tx);
1175                                                 }
1176                                         }
1177                                 }
1178                                 for tx in txn.iter() {
1179                                         broadcaster.broadcast_transaction(tx);
1180                                 }
1181                         }
1182                 }
1183                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1184                         let mut needs_broadcast = false;
1185                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1186                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1187                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1188                                                 needs_broadcast = true;
1189                                         }
1190                                 }
1191                         }
1192
1193                         if needs_broadcast {
1194                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1195                                 for tx in self.broadcast_by_local_state(&cur_local_tx) {
1196                                         broadcaster.broadcast_transaction(&tx);
1197                                 }
1198                         }
1199                 }
1200                 watch_outputs
1201         }
1202
1203         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1204                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1205                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1206                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1207                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1208                                                 return true;
1209                                         }
1210                                 }
1211                         }
1212                 }
1213                 false
1214         }
1215 }
1216
1217 impl<R: ::std::io::Read> Readable<R> for ChannelMonitor {
1218         fn read(reader: &mut R) -> Result<Self, DecodeError> {
1219                 // TODO: read_to_end and then deserializing from that vector is really dumb, we should
1220                 // actually use the fancy serialization framework we have instead of hacking around it.
1221                 let mut datavec = Vec::new();
1222                 reader.read_to_end(&mut datavec)?;
1223                 let data = &datavec;
1224
1225                 let mut read_pos = 0;
1226                 macro_rules! read_bytes {
1227                         ($byte_count: expr) => {
1228                                 {
1229                                         if ($byte_count as usize) > data.len() - read_pos {
1230                                                 return Err(DecodeError::ShortRead);
1231                                         }
1232                                         read_pos += $byte_count as usize;
1233                                         &data[read_pos - $byte_count as usize..read_pos]
1234                                 }
1235                         }
1236                 }
1237
1238                 let secp_ctx = Secp256k1::new();
1239                 macro_rules! unwrap_obj {
1240                         ($key: expr) => {
1241                                 match $key {
1242                                         Ok(res) => res,
1243                                         Err(_) => return Err(DecodeError::InvalidValue),
1244                                 }
1245                         }
1246                 }
1247
1248                 let _ver = read_bytes!(1)[0];
1249                 let min_ver = read_bytes!(1)[0];
1250                 if min_ver > SERIALIZATION_VERSION {
1251                         return Err(DecodeError::UnknownVersion);
1252                 }
1253
1254                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1255                 // barely-init'd ChannelMonitors that we can't do anything with.
1256                 let outpoint = OutPoint {
1257                         txid: Sha256dHash::from(read_bytes!(32)),
1258                         index: byte_utils::slice_to_be16(read_bytes!(2)),
1259                 };
1260                 let script_len = byte_utils::slice_to_be64(read_bytes!(8));
1261                 let funding_txo = Some((outpoint, Script::from(read_bytes!(script_len).to_vec())));
1262                 let commitment_transaction_number_obscure_factor = byte_utils::slice_to_be48(read_bytes!(6));
1263
1264                 let key_storage = match read_bytes!(1)[0] {
1265                         0 => {
1266                                 KeyStorage::PrivMode {
1267                                         revocation_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
1268                                         htlc_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
1269                                 }
1270                         },
1271                         _ => return Err(DecodeError::InvalidValue),
1272                 };
1273
1274                 let delayed_payment_base_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1275                 let their_htlc_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
1276                 let their_delayed_payment_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
1277
1278                 let their_cur_revocation_points = {
1279                         let first_idx = byte_utils::slice_to_be48(read_bytes!(6));
1280                         if first_idx == 0 {
1281                                 None
1282                         } else {
1283                                 let first_point = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1284                                 let second_point_slice = read_bytes!(33);
1285                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1286                                         Some((first_idx, first_point, None))
1287                                 } else {
1288                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, second_point_slice)))))
1289                                 }
1290                         }
1291                 };
1292
1293                 let our_to_self_delay = byte_utils::slice_to_be16(read_bytes!(2));
1294                 let their_to_self_delay = Some(byte_utils::slice_to_be16(read_bytes!(2)));
1295
1296                 let mut old_secrets = [([0; 32], 1 << 48); 49];
1297                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1298                         secret.copy_from_slice(read_bytes!(32));
1299                         *idx = byte_utils::slice_to_be64(read_bytes!(8));
1300                 }
1301
1302                 macro_rules! read_htlc_in_commitment {
1303                         () => {
1304                                 {
1305                                         let offered = match read_bytes!(1)[0] {
1306                                                 0 => false, 1 => true,
1307                                                 _ => return Err(DecodeError::InvalidValue),
1308                                         };
1309                                         let amount_msat = byte_utils::slice_to_be64(read_bytes!(8));
1310                                         let cltv_expiry = byte_utils::slice_to_be32(read_bytes!(4));
1311                                         let mut payment_hash = [0; 32];
1312                                         payment_hash[..].copy_from_slice(read_bytes!(32));
1313                                         let transaction_output_index = byte_utils::slice_to_be32(read_bytes!(4));
1314
1315                                         HTLCOutputInCommitment {
1316                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1317                                         }
1318                                 }
1319                         }
1320                 }
1321
1322                 let remote_claimable_outpoints_len = byte_utils::slice_to_be64(read_bytes!(8));
1323                 if remote_claimable_outpoints_len > data.len() as u64 / 64 { return Err(DecodeError::BadLengthDescriptor); }
1324                 let mut remote_claimable_outpoints = HashMap::with_capacity(remote_claimable_outpoints_len as usize);
1325                 for _ in 0..remote_claimable_outpoints_len {
1326                         let txid = Sha256dHash::from(read_bytes!(32));
1327                         let outputs_count = byte_utils::slice_to_be64(read_bytes!(8));
1328                         if outputs_count > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1329                         let mut outputs = Vec::with_capacity(outputs_count as usize);
1330                         for _ in 0..outputs_count {
1331                                 outputs.push(read_htlc_in_commitment!());
1332                         }
1333                         if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1334                                 return Err(DecodeError::InvalidValue);
1335                         }
1336                 }
1337
1338                 let remote_commitment_txn_on_chain_len = byte_utils::slice_to_be64(read_bytes!(8));
1339                 if remote_commitment_txn_on_chain_len > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1340                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(remote_commitment_txn_on_chain_len as usize);
1341                 for _ in 0..remote_commitment_txn_on_chain_len {
1342                         let txid = Sha256dHash::from(read_bytes!(32));
1343                         let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
1344                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, commitment_number) {
1345                                 return Err(DecodeError::InvalidValue);
1346                         }
1347                 }
1348
1349                 let remote_hash_commitment_number_len = byte_utils::slice_to_be64(read_bytes!(8));
1350                 if remote_hash_commitment_number_len > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1351                 let mut remote_hash_commitment_number = HashMap::with_capacity(remote_hash_commitment_number_len as usize);
1352                 for _ in 0..remote_hash_commitment_number_len {
1353                         let mut txid = [0; 32];
1354                         txid[..].copy_from_slice(read_bytes!(32));
1355                         let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
1356                         if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1357                                 return Err(DecodeError::InvalidValue);
1358                         }
1359                 }
1360
1361                 macro_rules! read_local_tx {
1362                         () => {
1363                                 {
1364                                         let tx_len = byte_utils::slice_to_be64(read_bytes!(8));
1365                                         let tx_ser = read_bytes!(tx_len);
1366                                         let tx: Transaction = unwrap_obj!(serialize::deserialize(tx_ser));
1367                                         if serialize::serialize(&tx).unwrap() != tx_ser {
1368                                                 // We check that the tx re-serializes to the same form to ensure there is
1369                                                 // no extra data, and as rust-bitcoin doesn't handle the 0-input ambiguity
1370                                                 // all that well.
1371                                                 return Err(DecodeError::InvalidValue);
1372                                         }
1373
1374                                         let revocation_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1375                                         let a_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1376                                         let b_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1377                                         let delayed_payment_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1378                                         let feerate_per_kw = byte_utils::slice_to_be64(read_bytes!(8));
1379
1380                                         let htlc_outputs_len = byte_utils::slice_to_be64(read_bytes!(8));
1381                                         if htlc_outputs_len > data.len() as u64 / 128 { return Err(DecodeError::BadLengthDescriptor); }
1382                                         let mut htlc_outputs = Vec::with_capacity(htlc_outputs_len as usize);
1383                                         for _ in 0..htlc_outputs_len {
1384                                                 htlc_outputs.push((read_htlc_in_commitment!(),
1385                                                                 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64))),
1386                                                                 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64)))));
1387                                         }
1388
1389                                         LocalSignedTx {
1390                                                 txid: tx.txid(),
1391                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1392                                         }
1393                                 }
1394                         }
1395                 }
1396
1397                 let prev_local_signed_commitment_tx = match read_bytes!(1)[0] {
1398                         0 => None,
1399                         1 => {
1400                                 Some(read_local_tx!())
1401                         },
1402                         _ => return Err(DecodeError::InvalidValue),
1403                 };
1404
1405                 let current_local_signed_commitment_tx = match read_bytes!(1)[0] {
1406                         0 => None,
1407                         1 => {
1408                                 Some(read_local_tx!())
1409                         },
1410                         _ => return Err(DecodeError::InvalidValue),
1411                 };
1412
1413                 let payment_preimages_len = byte_utils::slice_to_be64(read_bytes!(8));
1414                 if payment_preimages_len > data.len() as u64 / 32 { return Err(DecodeError::InvalidValue); }
1415                 let mut payment_preimages = HashMap::with_capacity(payment_preimages_len as usize);
1416                 let mut sha = Sha256::new();
1417                 for _ in 0..payment_preimages_len {
1418                         let mut preimage = [0; 32];
1419                         preimage[..].copy_from_slice(read_bytes!(32));
1420                         sha.reset();
1421                         sha.input(&preimage);
1422                         let mut hash = [0; 32];
1423                         sha.result(&mut hash);
1424                         if let Some(_) = payment_preimages.insert(hash, preimage) {
1425                                 return Err(DecodeError::InvalidValue);
1426                         }
1427                 }
1428
1429                 let destination_script_len = byte_utils::slice_to_be64(read_bytes!(8));
1430                 let destination_script = Script::from(read_bytes!(destination_script_len).to_vec());
1431
1432                 Ok(ChannelMonitor {
1433                         funding_txo,
1434                         commitment_transaction_number_obscure_factor,
1435
1436                         key_storage,
1437                         delayed_payment_base_key,
1438                         their_htlc_base_key,
1439                         their_delayed_payment_base_key,
1440                         their_cur_revocation_points,
1441
1442                         our_to_self_delay,
1443                         their_to_self_delay,
1444
1445                         old_secrets,
1446                         remote_claimable_outpoints,
1447                         remote_commitment_txn_on_chain: Mutex::new(remote_commitment_txn_on_chain),
1448                         remote_hash_commitment_number,
1449
1450                         prev_local_signed_commitment_tx,
1451                         current_local_signed_commitment_tx,
1452
1453                         payment_preimages,
1454
1455                         destination_script,
1456                         secp_ctx,
1457                 })
1458         }
1459
1460 }
1461
1462 #[cfg(test)]
1463 mod tests {
1464         use bitcoin::blockdata::script::Script;
1465         use bitcoin::blockdata::transaction::Transaction;
1466         use crypto::digest::Digest;
1467         use hex;
1468         use ln::channelmonitor::ChannelMonitor;
1469         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1470         use util::sha2::Sha256;
1471         use secp256k1::key::{SecretKey,PublicKey};
1472         use secp256k1::{Secp256k1, Signature};
1473         use rand::{thread_rng,Rng};
1474
1475         #[test]
1476         fn test_per_commitment_storage() {
1477                 // Test vectors from BOLT 3:
1478                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1479                 let mut monitor: ChannelMonitor;
1480                 let secp_ctx = Secp256k1::new();
1481
1482                 macro_rules! test_secrets {
1483                         () => {
1484                                 let mut idx = 281474976710655;
1485                                 for secret in secrets.iter() {
1486                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1487                                         idx -= 1;
1488                                 }
1489                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1490                                 assert!(monitor.get_secret(idx).is_err());
1491                         };
1492                 }
1493
1494                 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1495
1496                 {
1497                         // insert_secret correct sequence
1498                         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());
1499                         secrets.clear();
1500
1501                         secrets.push([0; 32]);
1502                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1503                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1504                         test_secrets!();
1505
1506                         secrets.push([0; 32]);
1507                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1508                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1509                         test_secrets!();
1510
1511                         secrets.push([0; 32]);
1512                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1513                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1514                         test_secrets!();
1515
1516                         secrets.push([0; 32]);
1517                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1518                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1519                         test_secrets!();
1520
1521                         secrets.push([0; 32]);
1522                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1523                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1524                         test_secrets!();
1525
1526                         secrets.push([0; 32]);
1527                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1528                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1529                         test_secrets!();
1530
1531                         secrets.push([0; 32]);
1532                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1533                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1534                         test_secrets!();
1535
1536                         secrets.push([0; 32]);
1537                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1538                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1539                         test_secrets!();
1540                 }
1541
1542                 {
1543                         // insert_secret #1 incorrect
1544                         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());
1545                         secrets.clear();
1546
1547                         secrets.push([0; 32]);
1548                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1549                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1550                         test_secrets!();
1551
1552                         secrets.push([0; 32]);
1553                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1554                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1555                                         "Previous secret did not match new one");
1556                 }
1557
1558                 {
1559                         // insert_secret #2 incorrect (#1 derived from incorrect)
1560                         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());
1561                         secrets.clear();
1562
1563                         secrets.push([0; 32]);
1564                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1565                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1566                         test_secrets!();
1567
1568                         secrets.push([0; 32]);
1569                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1570                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1571                         test_secrets!();
1572
1573                         secrets.push([0; 32]);
1574                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1575                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1576                         test_secrets!();
1577
1578                         secrets.push([0; 32]);
1579                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1580                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1581                                         "Previous secret did not match new one");
1582                 }
1583
1584                 {
1585                         // insert_secret #3 incorrect
1586                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1587                         secrets.clear();
1588
1589                         secrets.push([0; 32]);
1590                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1591                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1592                         test_secrets!();
1593
1594                         secrets.push([0; 32]);
1595                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1596                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1597                         test_secrets!();
1598
1599                         secrets.push([0; 32]);
1600                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1601                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1602                         test_secrets!();
1603
1604                         secrets.push([0; 32]);
1605                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1606                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1607                                         "Previous secret did not match new one");
1608                 }
1609
1610                 {
1611                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1612                         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());
1613                         secrets.clear();
1614
1615                         secrets.push([0; 32]);
1616                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1617                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1618                         test_secrets!();
1619
1620                         secrets.push([0; 32]);
1621                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1622                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1623                         test_secrets!();
1624
1625                         secrets.push([0; 32]);
1626                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1627                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1628                         test_secrets!();
1629
1630                         secrets.push([0; 32]);
1631                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1632                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1633                         test_secrets!();
1634
1635                         secrets.push([0; 32]);
1636                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1637                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1638                         test_secrets!();
1639
1640                         secrets.push([0; 32]);
1641                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1642                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1643                         test_secrets!();
1644
1645                         secrets.push([0; 32]);
1646                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1647                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1648                         test_secrets!();
1649
1650                         secrets.push([0; 32]);
1651                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1652                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1653                                         "Previous secret did not match new one");
1654                 }
1655
1656                 {
1657                         // insert_secret #5 incorrect
1658                         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());
1659                         secrets.clear();
1660
1661                         secrets.push([0; 32]);
1662                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1663                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1664                         test_secrets!();
1665
1666                         secrets.push([0; 32]);
1667                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1668                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1669                         test_secrets!();
1670
1671                         secrets.push([0; 32]);
1672                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1673                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1674                         test_secrets!();
1675
1676                         secrets.push([0; 32]);
1677                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1678                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1679                         test_secrets!();
1680
1681                         secrets.push([0; 32]);
1682                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1683                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1684                         test_secrets!();
1685
1686                         secrets.push([0; 32]);
1687                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1688                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1689                                         "Previous secret did not match new one");
1690                 }
1691
1692                 {
1693                         // insert_secret #6 incorrect (5 derived from incorrect)
1694                         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());
1695                         secrets.clear();
1696
1697                         secrets.push([0; 32]);
1698                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1699                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1700                         test_secrets!();
1701
1702                         secrets.push([0; 32]);
1703                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1704                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1705                         test_secrets!();
1706
1707                         secrets.push([0; 32]);
1708                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1709                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1710                         test_secrets!();
1711
1712                         secrets.push([0; 32]);
1713                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1714                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1715                         test_secrets!();
1716
1717                         secrets.push([0; 32]);
1718                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1719                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1720                         test_secrets!();
1721
1722                         secrets.push([0; 32]);
1723                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1724                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1725                         test_secrets!();
1726
1727                         secrets.push([0; 32]);
1728                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1729                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1730                         test_secrets!();
1731
1732                         secrets.push([0; 32]);
1733                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1734                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1735                                         "Previous secret did not match new one");
1736                 }
1737
1738                 {
1739                         // insert_secret #7 incorrect
1740                         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());
1741                         secrets.clear();
1742
1743                         secrets.push([0; 32]);
1744                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1745                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1746                         test_secrets!();
1747
1748                         secrets.push([0; 32]);
1749                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1750                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1751                         test_secrets!();
1752
1753                         secrets.push([0; 32]);
1754                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1755                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1756                         test_secrets!();
1757
1758                         secrets.push([0; 32]);
1759                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1760                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1761                         test_secrets!();
1762
1763                         secrets.push([0; 32]);
1764                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1765                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1766                         test_secrets!();
1767
1768                         secrets.push([0; 32]);
1769                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1770                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1771                         test_secrets!();
1772
1773                         secrets.push([0; 32]);
1774                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1775                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1776                         test_secrets!();
1777
1778                         secrets.push([0; 32]);
1779                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1780                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1781                                         "Previous secret did not match new one");
1782                 }
1783
1784                 {
1785                         // insert_secret #8 incorrect
1786                         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());
1787                         secrets.clear();
1788
1789                         secrets.push([0; 32]);
1790                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1791                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1792                         test_secrets!();
1793
1794                         secrets.push([0; 32]);
1795                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1796                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1797                         test_secrets!();
1798
1799                         secrets.push([0; 32]);
1800                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1801                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1802                         test_secrets!();
1803
1804                         secrets.push([0; 32]);
1805                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1806                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1807                         test_secrets!();
1808
1809                         secrets.push([0; 32]);
1810                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1811                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1812                         test_secrets!();
1813
1814                         secrets.push([0; 32]);
1815                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1816                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1817                         test_secrets!();
1818
1819                         secrets.push([0; 32]);
1820                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1821                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1822                         test_secrets!();
1823
1824                         secrets.push([0; 32]);
1825                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1826                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1827                                         "Previous secret did not match new one");
1828                 }
1829         }
1830
1831         #[test]
1832         fn test_prune_preimages() {
1833                 let secp_ctx = Secp256k1::new();
1834                 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
1835
1836                 macro_rules! dummy_keys {
1837                         () => {
1838                                 {
1839                                         let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1840                                         TxCreationKeys {
1841                                                 per_commitment_point: dummy_key.clone(),
1842                                                 revocation_key: dummy_key.clone(),
1843                                                 a_htlc_key: dummy_key.clone(),
1844                                                 b_htlc_key: dummy_key.clone(),
1845                                                 a_delayed_payment_key: dummy_key.clone(),
1846                                                 b_payment_key: dummy_key.clone(),
1847                                         }
1848                                 }
1849                         }
1850                 }
1851                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
1852
1853                 let mut preimages = Vec::new();
1854                 {
1855                         let mut rng  = thread_rng();
1856                         for _ in 0..20 {
1857                                 let mut preimage = [0; 32];
1858                                 rng.fill_bytes(&mut preimage);
1859                                 let mut sha = Sha256::new();
1860                                 sha.input(&preimage);
1861                                 let mut hash = [0; 32];
1862                                 sha.result(&mut hash);
1863                                 preimages.push((preimage, hash));
1864                         }
1865                 }
1866
1867                 macro_rules! preimages_slice_to_htlc_outputs {
1868                         ($preimages_slice: expr) => {
1869                                 {
1870                                         let mut res = Vec::new();
1871                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
1872                                                 res.push(HTLCOutputInCommitment {
1873                                                         offered: true,
1874                                                         amount_msat: 0,
1875                                                         cltv_expiry: 0,
1876                                                         payment_hash: preimage.1.clone(),
1877                                                         transaction_output_index: idx as u32,
1878                                                 });
1879                                         }
1880                                         res
1881                                 }
1882                         }
1883                 }
1884                 macro_rules! preimages_to_local_htlcs {
1885                         ($preimages_slice: expr) => {
1886                                 {
1887                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
1888                                         let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
1889                                         res
1890                                 }
1891                         }
1892                 }
1893
1894                 macro_rules! test_preimages_exist {
1895                         ($preimages_slice: expr, $monitor: expr) => {
1896                                 for preimage in $preimages_slice {
1897                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
1898                                 }
1899                         }
1900                 }
1901
1902                 // Prune with one old state and a local commitment tx holding a few overlaps with the
1903                 // old state.
1904                 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1905                 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());
1906                 monitor.set_their_to_self_delay(10);
1907
1908                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
1909                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
1910                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
1911                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
1912                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
1913                 for &(ref preimage, ref hash) in preimages.iter() {
1914                         monitor.provide_payment_preimage(hash, preimage);
1915                 }
1916
1917                 // Now provide a secret, pruning preimages 10-15
1918                 let mut secret = [0; 32];
1919                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1920                 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
1921                 assert_eq!(monitor.payment_preimages.len(), 15);
1922                 test_preimages_exist!(&preimages[0..10], monitor);
1923                 test_preimages_exist!(&preimages[15..20], monitor);
1924
1925                 // Now provide a further secret, pruning preimages 15-17
1926                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1927                 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
1928                 assert_eq!(monitor.payment_preimages.len(), 13);
1929                 test_preimages_exist!(&preimages[0..10], monitor);
1930                 test_preimages_exist!(&preimages[17..20], monitor);
1931
1932                 // Now update local commitment tx info, pruning only element 18 as we still care about the
1933                 // previous commitment tx's preimages too
1934                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
1935                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1936                 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
1937                 assert_eq!(monitor.payment_preimages.len(), 12);
1938                 test_preimages_exist!(&preimages[0..10], monitor);
1939                 test_preimages_exist!(&preimages[18..20], monitor);
1940
1941                 // But if we do it again, we'll prune 5-10
1942                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
1943                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1944                 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
1945                 assert_eq!(monitor.payment_preimages.len(), 5);
1946                 test_preimages_exist!(&preimages[0..5], monitor);
1947         }
1948
1949         // Further testing is done in the ChannelManager integration tests.
1950 }