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