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