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