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