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