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