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