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