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