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