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