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