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