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