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