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