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