8e1ba12f2ab8445f5bd6400bcd4fd03cee8832be
[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,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, Option<(Signature, Signature)>, Option<HTLCSource>)>,
336 }
337
338 const SERIALIZATION_VERSION: u8 = 1;
339 const MIN_SERIALIZATION_VERSION: u8 = 1;
340
341 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
342 /// on-chain transactions to ensure no loss of funds occurs.
343 ///
344 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
345 /// information and are actively monitoring the chain.
346 #[derive(Clone)]
347 pub struct ChannelMonitor {
348         commitment_transaction_number_obscure_factor: u64,
349
350         key_storage: Storage,
351         their_htlc_base_key: Option<PublicKey>,
352         their_delayed_payment_base_key: Option<PublicKey>,
353         // first is the idx of the first of the two revocation points
354         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
355
356         our_to_self_delay: u16,
357         their_to_self_delay: Option<u16>,
358
359         old_secrets: [([u8; 32], u64); 49],
360         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
361         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
362         /// Nor can we figure out their commitment numbers without the commitment transaction they are
363         /// spending. Thus, in order to claim them via revocation key, we track all the remote
364         /// commitment transactions which we find on-chain, mapping them to the commitment number which
365         /// can be used to derive the revocation key and claim the transactions.
366         remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
367         /// Cache used to make pruning of payment_preimages faster.
368         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
369         /// remote transactions (ie should remain pretty small).
370         /// Serialized to disk but should generally not be sent to Watchtowers.
371         remote_hash_commitment_number: HashMap<PaymentHash, u64>,
372
373         // We store two local commitment transactions to avoid any race conditions where we may update
374         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
375         // various monitors for one channel being out of sync, and us broadcasting a local
376         // transaction for which we have deleted claim information on some watchtowers.
377         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
378         current_local_signed_commitment_tx: Option<LocalSignedTx>,
379
380         // Used just for ChannelManager to make sure it has the latest channel data during
381         // deserialization
382         current_remote_commitment_number: u64,
383
384         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
385
386         destination_script: Script,
387
388         // We simply modify last_block_hash in Channel's block_connected so that serialization is
389         // consistent but hopefully the users' copy handles block_connected in a consistent way.
390         // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
391         // their last_block_hash from its state and not based on updated copies that didn't run through
392         // the full block_connected).
393         pub(crate) last_block_hash: Sha256dHash,
394         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
395         logger: Arc<Logger>,
396 }
397
398 #[cfg(any(test, feature = "fuzztarget"))]
399 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
400 /// underlying object
401 impl PartialEq for ChannelMonitor {
402         fn eq(&self, other: &Self) -> bool {
403                 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
404                         self.key_storage != other.key_storage ||
405                         self.their_htlc_base_key != other.their_htlc_base_key ||
406                         self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
407                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
408                         self.our_to_self_delay != other.our_to_self_delay ||
409                         self.their_to_self_delay != other.their_to_self_delay ||
410                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
411                         self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
412                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
413                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
414                         self.current_remote_commitment_number != other.current_remote_commitment_number ||
415                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
416                         self.payment_preimages != other.payment_preimages ||
417                         self.destination_script != other.destination_script
418                 {
419                         false
420                 } else {
421                         for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
422                                 if secret != o_secret || idx != o_idx {
423                                         return false
424                                 }
425                         }
426                         true
427                 }
428         }
429 }
430
431 impl ChannelMonitor {
432         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 {
433                 ChannelMonitor {
434                         commitment_transaction_number_obscure_factor: 0,
435
436                         key_storage: Storage::Local {
437                                 revocation_base_key: revocation_base_key.clone(),
438                                 htlc_base_key: htlc_base_key.clone(),
439                                 delayed_payment_base_key: delayed_payment_base_key.clone(),
440                                 payment_base_key: payment_base_key.clone(),
441                                 shutdown_pubkey: shutdown_pubkey.clone(),
442                                 prev_latest_per_commitment_point: None,
443                                 latest_per_commitment_point: None,
444                                 funding_info: None,
445                                 current_remote_commitment_txid: None,
446                                 prev_remote_commitment_txid: None,
447                         },
448                         their_htlc_base_key: None,
449                         their_delayed_payment_base_key: None,
450                         their_cur_revocation_points: None,
451
452                         our_to_self_delay: our_to_self_delay,
453                         their_to_self_delay: None,
454
455                         old_secrets: [([0; 32], 1 << 48); 49],
456                         remote_claimable_outpoints: HashMap::new(),
457                         remote_commitment_txn_on_chain: HashMap::new(),
458                         remote_hash_commitment_number: HashMap::new(),
459
460                         prev_local_signed_commitment_tx: None,
461                         current_local_signed_commitment_tx: None,
462                         current_remote_commitment_number: 1 << 48,
463
464                         payment_preimages: HashMap::new(),
465                         destination_script: destination_script,
466
467                         last_block_hash: Default::default(),
468                         secp_ctx: Secp256k1::new(),
469                         logger,
470                 }
471         }
472
473         #[inline]
474         fn place_secret(idx: u64) -> u8 {
475                 for i in 0..48 {
476                         if idx & (1 << i) == (1 << i) {
477                                 return i
478                         }
479                 }
480                 48
481         }
482
483         #[inline]
484         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
485                 let mut res: [u8; 32] = secret;
486                 for i in 0..bits {
487                         let bitpos = bits - 1 - i;
488                         if idx & (1 << bitpos) == (1 << bitpos) {
489                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
490                                 res = Sha256::hash(&res).into_inner();
491                         }
492                 }
493                 res
494         }
495
496         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
497         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
498         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
499         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
500                 let pos = ChannelMonitor::place_secret(idx);
501                 for i in 0..pos {
502                         let (old_secret, old_idx) = self.old_secrets[i as usize];
503                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
504                                 return Err(MonitorUpdateError("Previous secret did not match new one"));
505                         }
506                 }
507                 if self.get_min_seen_secret() <= idx {
508                         return Ok(());
509                 }
510                 self.old_secrets[pos as usize] = (secret, idx);
511
512                 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
513                 // events for now-revoked/fulfilled HTLCs.
514                 // TODO: We should probably consider whether we're really getting the next secret here.
515                 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
516                         if let Some(txid) = prev_remote_commitment_txid.take() {
517                                 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
518                                         *source = None;
519                                 }
520                         }
521                 }
522
523                 if !self.payment_preimages.is_empty() {
524                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
525                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
526                         let min_idx = self.get_min_seen_secret();
527                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
528
529                         self.payment_preimages.retain(|&k, _| {
530                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
531                                         if k == htlc.payment_hash {
532                                                 return true
533                                         }
534                                 }
535                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
536                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
537                                                 if k == htlc.payment_hash {
538                                                         return true
539                                                 }
540                                         }
541                                 }
542                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
543                                         if *cn < min_idx {
544                                                 return true
545                                         }
546                                         true
547                                 } else { false };
548                                 if contains {
549                                         remote_hash_commitment_number.remove(&k);
550                                 }
551                                 false
552                         });
553                 }
554
555                 Ok(())
556         }
557
558         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
559         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
560         /// possibly future revocation/preimage information) to claim outputs where possible.
561         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
562         pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey) {
563                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
564                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
565                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
566                 // timeouts)
567                 for &(ref htlc, _) in &htlc_outputs {
568                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
569                 }
570
571                 let new_txid = unsigned_commitment_tx.txid();
572                 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
573                 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
574                 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
575                         *prev_remote_commitment_txid = current_remote_commitment_txid.take();
576                         *current_remote_commitment_txid = Some(new_txid);
577                 }
578                 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
579                 self.current_remote_commitment_number = commitment_number;
580                 //TODO: Merge this into the other per-remote-transaction output storage stuff
581                 match self.their_cur_revocation_points {
582                         Some(old_points) => {
583                                 if old_points.0 == commitment_number + 1 {
584                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
585                                 } else if old_points.0 == commitment_number + 2 {
586                                         if let Some(old_second_point) = old_points.2 {
587                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
588                                         } else {
589                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
590                                         }
591                                 } else {
592                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
593                                 }
594                         },
595                         None => {
596                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
597                         }
598                 }
599         }
600
601         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
602         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
603         /// is important that any clones of this channel monitor (including remote clones) by kept
604         /// up-to-date as our local commitment transaction is updated.
605         /// Panics if set_their_to_self_delay has never been called.
606         /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
607         /// case of onchain HTLC tx
608         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, Option<(Signature, Signature)>, Option<HTLCSource>)>) {
609                 assert!(self.their_to_self_delay.is_some());
610                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
611                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
612                         txid: signed_commitment_tx.txid(),
613                         tx: signed_commitment_tx,
614                         revocation_key: local_keys.revocation_key,
615                         a_htlc_key: local_keys.a_htlc_key,
616                         b_htlc_key: local_keys.b_htlc_key,
617                         delayed_payment_key: local_keys.a_delayed_payment_key,
618                         feerate_per_kw,
619                         htlc_outputs,
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                 macro_rules! write_option {
780                         ($thing: expr) => {
781                                 match $thing {
782                                         &Some(ref t) => {
783                                                 1u8.write(writer)?;
784                                                 t.write(writer)?;
785                                         },
786                                         &None => 0u8.write(writer)?,
787                                 }
788                         }
789                 }
790
791                 match self.key_storage {
792                         Storage::Local { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
793                                 writer.write_all(&[0; 1])?;
794                                 writer.write_all(&revocation_base_key[..])?;
795                                 writer.write_all(&htlc_base_key[..])?;
796                                 writer.write_all(&delayed_payment_base_key[..])?;
797                                 writer.write_all(&payment_base_key[..])?;
798                                 writer.write_all(&shutdown_pubkey.serialize())?;
799                                 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
800                                         writer.write_all(&[1; 1])?;
801                                         writer.write_all(&prev_latest_per_commitment_point.serialize())?;
802                                 } else {
803                                         writer.write_all(&[0; 1])?;
804                                 }
805                                 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
806                                         writer.write_all(&[1; 1])?;
807                                         writer.write_all(&latest_per_commitment_point.serialize())?;
808                                 } else {
809                                         writer.write_all(&[0; 1])?;
810                                 }
811                                 match funding_info  {
812                                         &Some((ref outpoint, ref script)) => {
813                                                 writer.write_all(&outpoint.txid[..])?;
814                                                 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
815                                                 script.write(writer)?;
816                                         },
817                                         &None => {
818                                                 debug_assert!(false, "Try to serialize a useless Local monitor !");
819                                         },
820                                 }
821                                 write_option!(current_remote_commitment_txid);
822                                 write_option!(prev_remote_commitment_txid);
823                         },
824                         Storage::Watchtower { .. } => unimplemented!(),
825                 }
826
827                 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
828                 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
829
830                 match self.their_cur_revocation_points {
831                         Some((idx, pubkey, second_option)) => {
832                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
833                                 writer.write_all(&pubkey.serialize())?;
834                                 match second_option {
835                                         Some(second_pubkey) => {
836                                                 writer.write_all(&second_pubkey.serialize())?;
837                                         },
838                                         None => {
839                                                 writer.write_all(&[0; 33])?;
840                                         },
841                                 }
842                         },
843                         None => {
844                                 writer.write_all(&byte_utils::be48_to_array(0))?;
845                         },
846                 }
847
848                 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
849                 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
850
851                 for &(ref secret, ref idx) in self.old_secrets.iter() {
852                         writer.write_all(secret)?;
853                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
854                 }
855
856                 macro_rules! serialize_htlc_in_commitment {
857                         ($htlc_output: expr) => {
858                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
859                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
860                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
861                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
862                                 write_option!(&$htlc_output.transaction_output_index);
863                         }
864                 }
865
866                 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
867                 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
868                         writer.write_all(&txid[..])?;
869                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
870                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
871                                 serialize_htlc_in_commitment!(htlc_output);
872                                 write_option!(htlc_source);
873                         }
874                 }
875
876                 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
877                 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
878                         writer.write_all(&txid[..])?;
879                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
880                         (txouts.len() as u64).write(writer)?;
881                         for script in txouts.iter() {
882                                 script.write(writer)?;
883                         }
884                 }
885
886                 if for_local_storage {
887                         writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
888                         for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
889                                 writer.write_all(&payment_hash.0[..])?;
890                                 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
891                         }
892                 } else {
893                         writer.write_all(&byte_utils::be64_to_array(0))?;
894                 }
895
896                 macro_rules! serialize_local_tx {
897                         ($local_tx: expr) => {
898                                 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
899                                         match e {
900                                                 encode::Error::Io(e) => return Err(e),
901                                                 _ => panic!("local tx must have been well-formed!"),
902                                         }
903                                 }
904
905                                 writer.write_all(&$local_tx.revocation_key.serialize())?;
906                                 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
907                                 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
908                                 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
909
910                                 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
911                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
912                                 for &(ref htlc_output, ref sigs, ref htlc_source) in $local_tx.htlc_outputs.iter() {
913                                         serialize_htlc_in_commitment!(htlc_output);
914                                         if let &Some((ref their_sig, ref our_sig)) = sigs {
915                                                 1u8.write(writer)?;
916                                                 writer.write_all(&their_sig.serialize_compact())?;
917                                                 writer.write_all(&our_sig.serialize_compact())?;
918                                         } else {
919                                                 0u8.write(writer)?;
920                                         }
921                                         write_option!(htlc_source);
922                                 }
923                         }
924                 }
925
926                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
927                         writer.write_all(&[1; 1])?;
928                         serialize_local_tx!(prev_local_tx);
929                 } else {
930                         writer.write_all(&[0; 1])?;
931                 }
932
933                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
934                         writer.write_all(&[1; 1])?;
935                         serialize_local_tx!(cur_local_tx);
936                 } else {
937                         writer.write_all(&[0; 1])?;
938                 }
939
940                 if for_local_storage {
941                         writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
942                 } else {
943                         writer.write_all(&byte_utils::be48_to_array(0))?;
944                 }
945
946                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
947                 for payment_preimage in self.payment_preimages.values() {
948                         writer.write_all(&payment_preimage.0[..])?;
949                 }
950
951                 self.last_block_hash.write(writer)?;
952                 self.destination_script.write(writer)?;
953
954                 Ok(())
955         }
956
957         /// Writes this monitor into the given writer, suitable for writing to disk.
958         ///
959         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
960         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
961         /// the "reorg path" (ie not just starting at the same height but starting at the highest
962         /// common block that appears on your best chain as well as on the chain which contains the
963         /// last block hash returned) upon deserializing the object!
964         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
965                 self.write(writer, true)
966         }
967
968         /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
969         ///
970         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
971         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
972         /// the "reorg path" (ie not just starting at the same height but starting at the highest
973         /// common block that appears on your best chain as well as on the chain which contains the
974         /// last block hash returned) upon deserializing the object!
975         pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
976                 self.write(writer, false)
977         }
978
979         /// Can only fail if idx is < get_min_seen_secret
980         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
981                 for i in 0..self.old_secrets.len() {
982                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
983                                 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
984                         }
985                 }
986                 assert!(idx < self.get_min_seen_secret());
987                 None
988         }
989
990         pub(super) fn get_min_seen_secret(&self) -> u64 {
991                 //TODO This can be optimized?
992                 let mut min = 1 << 48;
993                 for &(_, idx) in self.old_secrets.iter() {
994                         if idx < min {
995                                 min = idx;
996                         }
997                 }
998                 min
999         }
1000
1001         pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1002                 self.current_remote_commitment_number
1003         }
1004
1005         pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1006                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1007                         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)
1008                 } else { 0xffff_ffff_ffff }
1009         }
1010
1011         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1012         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1013         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1014         /// HTLC-Success/HTLC-Timeout transactions.
1015         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1016         /// revoked remote commitment tx
1017         fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>)  {
1018                 // Most secp and related errors trying to create keys means we have no hope of constructing
1019                 // a spend transaction...so we return no transactions to broadcast
1020                 let mut txn_to_broadcast = Vec::new();
1021                 let mut watch_outputs = Vec::new();
1022                 let mut spendable_outputs = Vec::new();
1023                 let mut htlc_updated = Vec::new();
1024
1025                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1026                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1027
1028                 macro_rules! ignore_error {
1029                         ( $thing : expr ) => {
1030                                 match $thing {
1031                                         Ok(a) => a,
1032                                         Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1033                                 }
1034                         };
1035                 }
1036
1037                 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);
1038                 if commitment_number >= self.get_min_seen_secret() {
1039                         let secret = self.get_secret(commitment_number).unwrap();
1040                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1041                         let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1042                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1043                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1044                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1045                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1046                                         Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1047                                 },
1048                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1049                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1050                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1051                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1052                                         None)
1053                                 },
1054                         };
1055                         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()));
1056                         let a_htlc_key = match self.their_htlc_base_key {
1057                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1058                                 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)),
1059                         };
1060
1061                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1062                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1063
1064                         let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1065                                 // Note that the Network here is ignored as we immediately drop the address for the
1066                                 // script_pubkey version.
1067                                 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1068                                 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1069                         } else { None };
1070
1071                         let mut total_value = 0;
1072                         let mut values = Vec::new();
1073                         let mut inputs = Vec::new();
1074                         let mut htlc_idxs = Vec::new();
1075
1076                         for (idx, outp) in tx.output.iter().enumerate() {
1077                                 if outp.script_pubkey == revokeable_p2wsh {
1078                                         inputs.push(TxIn {
1079                                                 previous_output: BitcoinOutPoint {
1080                                                         txid: commitment_txid,
1081                                                         vout: idx as u32,
1082                                                 },
1083                                                 script_sig: Script::new(),
1084                                                 sequence: 0xfffffffd,
1085                                                 witness: Vec::new(),
1086                                         });
1087                                         htlc_idxs.push(None);
1088                                         values.push(outp.value);
1089                                         total_value += outp.value;
1090                                 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1091                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1092                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1093                                                 key: local_payment_key.unwrap(),
1094                                                 output: outp.clone(),
1095                                         });
1096                                 }
1097                         }
1098
1099                         macro_rules! sign_input {
1100                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1101                                         {
1102                                                 let (sig, redeemscript) = match self.key_storage {
1103                                                         Storage::Local { ref revocation_base_key, .. } => {
1104                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1105                                                                         let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1106                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1107                                                                 };
1108                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1109                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1110                                                                 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1111                                                         },
1112                                                         Storage::Watchtower { .. } => {
1113                                                                 unimplemented!();
1114                                                         }
1115                                                 };
1116                                                 $input.witness.push(sig.serialize_der().to_vec());
1117                                                 $input.witness[0].push(SigHashType::All as u8);
1118                                                 if $htlc_idx.is_none() {
1119                                                         $input.witness.push(vec!(1));
1120                                                 } else {
1121                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
1122                                                 }
1123                                                 $input.witness.push(redeemscript.into_bytes());
1124                                         }
1125                                 }
1126                         }
1127
1128                         if let Some(ref per_commitment_data) = per_commitment_option {
1129                                 inputs.reserve_exact(per_commitment_data.len());
1130
1131                                 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1132                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1133                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1134                                                 if transaction_output_index as usize >= tx.output.len() ||
1135                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1136                                                                 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1137                                                         return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1138                                                 }
1139                                                 let input = TxIn {
1140                                                         previous_output: BitcoinOutPoint {
1141                                                                 txid: commitment_txid,
1142                                                                 vout: transaction_output_index,
1143                                                         },
1144                                                         script_sig: Script::new(),
1145                                                         sequence: 0xfffffffd,
1146                                                         witness: Vec::new(),
1147                                                 };
1148                                                 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1149                                                         inputs.push(input);
1150                                                         htlc_idxs.push(Some(idx));
1151                                                         values.push(tx.output[transaction_output_index as usize].value);
1152                                                         total_value += htlc.amount_msat / 1000;
1153                                                 } else {
1154                                                         let mut single_htlc_tx = Transaction {
1155                                                                 version: 2,
1156                                                                 lock_time: 0,
1157                                                                 input: vec![input],
1158                                                                 output: vec!(TxOut {
1159                                                                         script_pubkey: self.destination_script.clone(),
1160                                                                         value: htlc.amount_msat / 1000, //TODO: - fee
1161                                                                 }),
1162                                                         };
1163                                                         let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1164                                                         sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1165                                                         txn_to_broadcast.push(single_htlc_tx);
1166                                                 }
1167                                         }
1168                                 }
1169                         }
1170
1171                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1172                                 // We're definitely a remote commitment transaction!
1173                                 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());
1174                                 watch_outputs.append(&mut tx.output.clone());
1175                                 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1176
1177                                 // TODO: We really should only fail backwards after our revocation claims have been
1178                                 // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1179                                 // on-chain claims, so we can do that at the same time.
1180                                 macro_rules! check_htlc_fails {
1181                                         ($txid: expr, $commitment_tx: expr) => {
1182                                                 if let Some(ref outpoints) = self.remote_claimable_outpoints.get(&$txid) {
1183                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1184                                                                 if let &Some(ref source) = source_option {
1185                                                                         log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of revoked remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1186                                                                         htlc_updated.push(((**source).clone(), None, htlc.payment_hash.clone()));
1187                                                                 }
1188                                                         }
1189                                                 }
1190                                         }
1191                                 }
1192                                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1193                                         if let &Some(ref txid) = current_remote_commitment_txid {
1194                                                 check_htlc_fails!(txid, "current");
1195                                         }
1196                                         if let &Some(ref txid) = prev_remote_commitment_txid {
1197                                                 check_htlc_fails!(txid, "remote");
1198                                         }
1199                                 }
1200                                 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1201                         }
1202                         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
1203
1204                         let outputs = vec!(TxOut {
1205                                 script_pubkey: self.destination_script.clone(),
1206                                 value: total_value, //TODO: - fee
1207                         });
1208                         let mut spend_tx = Transaction {
1209                                 version: 2,
1210                                 lock_time: 0,
1211                                 input: inputs,
1212                                 output: outputs,
1213                         };
1214
1215                         let mut values_drain = values.drain(..);
1216                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1217
1218                         for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1219                                 let value = values_drain.next().unwrap();
1220                                 sign_input!(sighash_parts, input, htlc_idx, value);
1221                         }
1222
1223                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1224                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1225                                 output: spend_tx.output[0].clone(),
1226                         });
1227                         txn_to_broadcast.push(spend_tx);
1228                 } else if let Some(per_commitment_data) = per_commitment_option {
1229                         // While this isn't useful yet, there is a potential race where if a counterparty
1230                         // revokes a state at the same time as the commitment transaction for that state is
1231                         // confirmed, and the watchtower receives the block before the user, the user could
1232                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1233                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1234                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1235                         // insert it here.
1236                         watch_outputs.append(&mut tx.output.clone());
1237                         self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1238
1239                         log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1240
1241                         // TODO: We really should only fail backwards after our revocation claims have been
1242                         // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1243                         // on-chain claims, so we can do that at the same time.
1244                         macro_rules! check_htlc_fails {
1245                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1246                                         if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get(&$txid) {
1247                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1248                                                         if let &Some(ref source) = source_option {
1249                                                                 // Check if the HTLC is present in the commitment transaction that was
1250                                                                 // broadcast, but not if it was below the dust limit, which we should
1251                                                                 // fail backwards immediately as there is no way for us to learn the
1252                                                                 // payment_preimage.
1253                                                                 // Note that if the dust limit were allowed to change between
1254                                                                 // commitment transactions we'd want to be check whether *any*
1255                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1256                                                                 // cannot currently change after channel initialization, so we don't
1257                                                                 // need to here.
1258                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1259                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1260                                                                                 continue $id;
1261                                                                         }
1262                                                                 }
1263                                                                 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1264                                                                 htlc_updated.push(((**source).clone(), None, htlc.payment_hash.clone()));
1265                                                         }
1266                                                 }
1267                                         }
1268                                 }
1269                         }
1270                         if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1271                                 if let &Some(ref txid) = current_remote_commitment_txid {
1272                                         check_htlc_fails!(txid, "current", 'current_loop);
1273                                 }
1274                                 if let &Some(ref txid) = prev_remote_commitment_txid {
1275                                         check_htlc_fails!(txid, "previous", 'prev_loop);
1276                                 }
1277                         }
1278
1279                         if let Some(revocation_points) = self.their_cur_revocation_points {
1280                                 let revocation_point_option =
1281                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1282                                         else if let Some(point) = revocation_points.2.as_ref() {
1283                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1284                                         } else { None };
1285                                 if let Some(revocation_point) = revocation_point_option {
1286                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1287                                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1288                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1289                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1290                                                 },
1291                                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1292                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1293                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1294                                                 },
1295                                         };
1296                                         let a_htlc_key = match self.their_htlc_base_key {
1297                                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1298                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1299                                         };
1300
1301                                         for (idx, outp) in tx.output.iter().enumerate() {
1302                                                 if outp.script_pubkey.is_v0_p2wpkh() {
1303                                                         match self.key_storage {
1304                                                                 Storage::Local { ref payment_base_key, .. } => {
1305                                                                         if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1306                                                                                 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1307                                                                                         outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1308                                                                                         key: local_key,
1309                                                                                         output: outp.clone(),
1310                                                                                 });
1311                                                                         }
1312                                                                 },
1313                                                                 Storage::Watchtower { .. } => {}
1314                                                         }
1315                                                         break; // Only to_remote ouput is claimable
1316                                                 }
1317                                         }
1318
1319                                         let mut total_value = 0;
1320                                         let mut values = Vec::new();
1321                                         let mut inputs = Vec::new();
1322
1323                                         macro_rules! sign_input {
1324                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1325                                                         {
1326                                                                 let (sig, redeemscript) = match self.key_storage {
1327                                                                         Storage::Local { ref htlc_base_key, .. } => {
1328                                                                                 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize].0;
1329                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1330                                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1331                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1332                                                                                 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1333                                                                         },
1334                                                                         Storage::Watchtower { .. } => {
1335                                                                                 unimplemented!();
1336                                                                         }
1337                                                                 };
1338                                                                 $input.witness.push(sig.serialize_der().to_vec());
1339                                                                 $input.witness[0].push(SigHashType::All as u8);
1340                                                                 $input.witness.push($preimage);
1341                                                                 $input.witness.push(redeemscript.into_bytes());
1342                                                         }
1343                                                 }
1344                                         }
1345
1346                                         for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1347                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1348                                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1349                                                         if transaction_output_index as usize >= tx.output.len() ||
1350                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1351                                                                         tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1352                                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1353                                                         }
1354                                                         if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1355                                                                 let input = TxIn {
1356                                                                         previous_output: BitcoinOutPoint {
1357                                                                                 txid: commitment_txid,
1358                                                                                 vout: transaction_output_index,
1359                                                                         },
1360                                                                         script_sig: Script::new(),
1361                                                                         sequence: idx as u32, // reset to 0xfffffffd in sign_input
1362                                                                         witness: Vec::new(),
1363                                                                 };
1364                                                                 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1365                                                                         inputs.push(input);
1366                                                                         values.push((tx.output[transaction_output_index as usize].value, payment_preimage));
1367                                                                         total_value += htlc.amount_msat / 1000;
1368                                                                 } else {
1369                                                                         let mut single_htlc_tx = Transaction {
1370                                                                                 version: 2,
1371                                                                                 lock_time: 0,
1372                                                                                 input: vec![input],
1373                                                                                 output: vec!(TxOut {
1374                                                                                         script_pubkey: self.destination_script.clone(),
1375                                                                                         value: htlc.amount_msat / 1000, //TODO: - fee
1376                                                                                 }),
1377                                                                         };
1378                                                                         let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1379                                                                         sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
1380                                                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1381                                                                                 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1382                                                                                 output: single_htlc_tx.output[0].clone(),
1383                                                                         });
1384                                                                         txn_to_broadcast.push(single_htlc_tx);
1385                                                                 }
1386                                                         }
1387                                                         if !htlc.offered {
1388                                                                 // TODO: If the HTLC has already expired, potentially merge it with the
1389                                                                 // rest of the claim transaction, as above.
1390                                                                 let input = TxIn {
1391                                                                         previous_output: BitcoinOutPoint {
1392                                                                                 txid: commitment_txid,
1393                                                                                 vout: transaction_output_index,
1394                                                                         },
1395                                                                         script_sig: Script::new(),
1396                                                                         sequence: idx as u32,
1397                                                                         witness: Vec::new(),
1398                                                                 };
1399                                                                 let mut timeout_tx = Transaction {
1400                                                                         version: 2,
1401                                                                         lock_time: htlc.cltv_expiry,
1402                                                                         input: vec![input],
1403                                                                         output: vec!(TxOut {
1404                                                                                 script_pubkey: self.destination_script.clone(),
1405                                                                                 value: htlc.amount_msat / 1000,
1406                                                                         }),
1407                                                                 };
1408                                                                 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1409                                                                 sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1410                                                                 txn_to_broadcast.push(timeout_tx);
1411                                                         }
1412                                                 }
1413                                         }
1414
1415                                         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
1416
1417                                         let outputs = vec!(TxOut {
1418                                                 script_pubkey: self.destination_script.clone(),
1419                                                 value: total_value, //TODO: - fee
1420                                         });
1421                                         let mut spend_tx = Transaction {
1422                                                 version: 2,
1423                                                 lock_time: 0,
1424                                                 input: inputs,
1425                                                 output: outputs,
1426                                         };
1427
1428                                         let mut values_drain = values.drain(..);
1429                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1430
1431                                         for input in spend_tx.input.iter_mut() {
1432                                                 let value = values_drain.next().unwrap();
1433                                                 sign_input!(sighash_parts, input, value.0, (value.1).0.to_vec());
1434                                         }
1435
1436                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1437                                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1438                                                 output: spend_tx.output[0].clone(),
1439                                         });
1440                                         txn_to_broadcast.push(spend_tx);
1441                                 }
1442                         }
1443                 }
1444
1445                 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1446         }
1447
1448         /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1449         fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1450                 if tx.input.len() != 1 || tx.output.len() != 1 {
1451                         return (None, None)
1452                 }
1453
1454                 macro_rules! ignore_error {
1455                         ( $thing : expr ) => {
1456                                 match $thing {
1457                                         Ok(a) => a,
1458                                         Err(_) => return (None, None)
1459                                 }
1460                         };
1461                 }
1462
1463                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1464                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1465                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1466                 let revocation_pubkey = match self.key_storage {
1467                         Storage::Local { ref revocation_base_key, .. } => {
1468                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1469                         },
1470                         Storage::Watchtower { ref revocation_base_key, .. } => {
1471                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1472                         },
1473                 };
1474                 let delayed_key = match self.their_delayed_payment_base_key {
1475                         None => return (None, None),
1476                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1477                 };
1478                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1479                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1480                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1481
1482                 let mut inputs = Vec::new();
1483                 let mut amount = 0;
1484
1485                 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1486                         inputs.push(TxIn {
1487                                 previous_output: BitcoinOutPoint {
1488                                         txid: htlc_txid,
1489                                         vout: 0,
1490                                 },
1491                                 script_sig: Script::new(),
1492                                 sequence: 0xfffffffd,
1493                                 witness: Vec::new(),
1494                         });
1495                         amount = tx.output[0].value;
1496                 }
1497
1498                 if !inputs.is_empty() {
1499                         let outputs = vec!(TxOut {
1500                                 script_pubkey: self.destination_script.clone(),
1501                                 value: amount, //TODO: - fee
1502                         });
1503
1504                         let mut spend_tx = Transaction {
1505                                 version: 2,
1506                                 lock_time: 0,
1507                                 input: inputs,
1508                                 output: outputs,
1509                         };
1510
1511                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1512
1513                         let sig = match self.key_storage {
1514                                 Storage::Local { ref revocation_base_key, .. } => {
1515                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
1516                                         let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1517                                         self.secp_ctx.sign(&sighash, &revocation_key)
1518                                 }
1519                                 Storage::Watchtower { .. } => {
1520                                         unimplemented!();
1521                                 }
1522                         };
1523                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
1524                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1525                         spend_tx.input[0].witness.push(vec!(1));
1526                         spend_tx.input[0].witness.push(redeemscript.into_bytes());
1527
1528                         let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1529                         let output = spend_tx.output[0].clone();
1530                         (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1531                 } else { (None, None) }
1532         }
1533
1534         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>) {
1535                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1536                 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1537                 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1538
1539                 macro_rules! add_dynamic_output {
1540                         ($father_tx: expr, $vout: expr) => {
1541                                 if let Some(ref per_commitment_point) = *per_commitment_point {
1542                                         if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1543                                                 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1544                                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1545                                                                 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1546                                                                 key: local_delayedkey,
1547                                                                 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1548                                                                 to_self_delay: self.our_to_self_delay,
1549                                                                 output: $father_tx.output[$vout as usize].clone(),
1550                                                         });
1551                                                 }
1552                                         }
1553                                 }
1554                         }
1555                 }
1556
1557
1558                 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1559                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1560                 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1561                         if output.script_pubkey == revokeable_p2wsh {
1562                                 add_dynamic_output!(local_tx.tx, idx as u32);
1563                                 break;
1564                         }
1565                 }
1566
1567                 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
1568                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1569                                 if let &Some((ref their_sig, ref our_sig)) = sigs {
1570                                         if htlc.offered {
1571                                                 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
1572                                                 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);
1573
1574                                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1575
1576                                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1577                                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1578                                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1579                                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1580
1581                                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
1582                                                 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());
1583
1584                                                 add_dynamic_output!(htlc_timeout_tx, 0);
1585                                                 res.push(htlc_timeout_tx);
1586                                         } else {
1587                                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1588                                                         log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
1589                                                         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);
1590
1591                                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1592
1593                                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1594                                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1595                                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1596                                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1597
1598                                                         htlc_success_tx.input[0].witness.push(payment_preimage.0.to_vec());
1599                                                         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());
1600
1601                                                         add_dynamic_output!(htlc_success_tx, 0);
1602                                                         res.push(htlc_success_tx);
1603                                                 }
1604                                         }
1605                                         watch_outputs.push(local_tx.tx.output[transaction_output_index as usize].clone());
1606                                 } else { panic!("Should have sigs for non-dust local tx outputs!") }
1607                         }
1608                 }
1609
1610                 (res, spendable_outputs, watch_outputs)
1611         }
1612
1613         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1614         /// revoked using data in local_claimable_outpoints.
1615         /// Should not be used if check_spend_revoked_transaction succeeds.
1616         fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1617                 let commitment_txid = tx.txid();
1618                 // TODO: If we find a match here we need to fail back HTLCs that were't included in the
1619                 // broadcast commitment transaction, either because they didn't meet dust or because they
1620                 // weren't yet included in our commitment transaction(s).
1621                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1622                         if local_tx.txid == commitment_txid {
1623                                 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
1624                                 match self.key_storage {
1625                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1626                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1627                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1628                                         },
1629                                         Storage::Watchtower { .. } => {
1630                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1631                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1632                                         }
1633                                 }
1634                         }
1635                 }
1636                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1637                         if local_tx.txid == commitment_txid {
1638                                 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
1639                                 match self.key_storage {
1640                                         Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1641                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1642                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1643                                         },
1644                                         Storage::Watchtower { .. } => {
1645                                                 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1646                                                 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1647                                         }
1648                                 }
1649                         }
1650                 }
1651                 (Vec::new(), Vec::new(), (commitment_txid, Vec::new()))
1652         }
1653
1654         /// Generate a spendable output event when closing_transaction get registered onchain.
1655         fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1656                 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1657                         match self.key_storage {
1658                                 Storage::Local { ref shutdown_pubkey, .. } =>  {
1659                                         let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
1660                                         let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1661                                         for (idx, output) in tx.output.iter().enumerate() {
1662                                                 if shutdown_script == output.script_pubkey {
1663                                                         return Some(SpendableOutputDescriptor::StaticOutput {
1664                                                                 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1665                                                                 output: output.clone(),
1666                                                         });
1667                                                 }
1668                                         }
1669                                 }
1670                                 Storage::Watchtower { .. } => {
1671                                         //TODO: we need to ensure an offline client will generate the event when it
1672                                         // cames back online after only the watchtower saw the transaction
1673                                 }
1674                         }
1675                 }
1676                 None
1677         }
1678
1679         /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1680         /// the Channel was out-of-date.
1681         pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1682                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1683                         let mut res = vec![local_tx.tx.clone()];
1684                         match self.key_storage {
1685                                 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1686                                         res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1687                                 },
1688                                 _ => panic!("Can only broadcast by local channelmonitor"),
1689                         };
1690                         res
1691                 } else {
1692                         Vec::new()
1693                 }
1694         }
1695
1696         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)>) {
1697                 let mut watch_outputs = Vec::new();
1698                 let mut spendable_outputs = Vec::new();
1699                 let mut htlc_updated = Vec::new();
1700                 for tx in txn_matched {
1701                         if tx.input.len() == 1 {
1702                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1703                                 // commitment transactions and HTLC transactions will all only ever have one input,
1704                                 // which is an easy way to filter out any potential non-matching txn for lazy
1705                                 // filters.
1706                                 let prevout = &tx.input[0].previous_output;
1707                                 let mut txn: Vec<Transaction> = Vec::new();
1708                                 let funding_txo = match self.key_storage {
1709                                         Storage::Local { ref funding_info, .. } => {
1710                                                 funding_info.clone()
1711                                         }
1712                                         Storage::Watchtower { .. } => {
1713                                                 unimplemented!();
1714                                         }
1715                                 };
1716                                 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) {
1717                                         let (remote_txn, new_outputs, mut spendable_output, mut updated) = self.check_spend_remote_transaction(tx, height);
1718                                         txn = remote_txn;
1719                                         spendable_outputs.append(&mut spendable_output);
1720                                         if !new_outputs.1.is_empty() {
1721                                                 watch_outputs.push(new_outputs);
1722                                         }
1723                                         if txn.is_empty() {
1724                                                 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
1725                                                 spendable_outputs.append(&mut spendable_output);
1726                                                 txn = local_txn;
1727                                                 if !new_outputs.1.is_empty() {
1728                                                         watch_outputs.push(new_outputs);
1729                                                 }
1730                                         }
1731                                         if !funding_txo.is_none() && txn.is_empty() {
1732                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1733                                                         spendable_outputs.push(spendable_output);
1734                                                 }
1735                                         }
1736                                         if updated.len() > 0 {
1737                                                 htlc_updated.append(&mut updated);
1738                                         }
1739                                 } else {
1740                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1741                                                 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1742                                                 if let Some(tx) = tx {
1743                                                         txn.push(tx);
1744                                                 }
1745                                                 if let Some(spendable_output) = spendable_output {
1746                                                         spendable_outputs.push(spendable_output);
1747                                                 }
1748                                         }
1749                                 }
1750                                 for tx in txn.iter() {
1751                                         broadcaster.broadcast_transaction(tx);
1752                                 }
1753                         }
1754                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
1755                         // can also be resolved in a few other ways which can have more than one output. Thus,
1756                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
1757                         let mut updated = self.is_resolving_htlc_output(tx);
1758                         if updated.len() > 0 {
1759                                 htlc_updated.append(&mut updated);
1760                         }
1761                 }
1762                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1763                         if self.would_broadcast_at_height(height) {
1764                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1765                                 match self.key_storage {
1766                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1767                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1768                                                 spendable_outputs.append(&mut spendable_output);
1769                                                 if !new_outputs.is_empty() {
1770                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1771                                                 }
1772                                                 for tx in txs {
1773                                                         broadcaster.broadcast_transaction(&tx);
1774                                                 }
1775                                         },
1776                                         Storage::Watchtower { .. } => {
1777                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1778                                                 spendable_outputs.append(&mut spendable_output);
1779                                                 if !new_outputs.is_empty() {
1780                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1781                                                 }
1782                                                 for tx in txs {
1783                                                         broadcaster.broadcast_transaction(&tx);
1784                                                 }
1785                                         }
1786                                 }
1787                         }
1788                 }
1789                 self.last_block_hash = block_hash.clone();
1790                 (watch_outputs, spendable_outputs, htlc_updated)
1791         }
1792
1793         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1794                 // We need to consider all HTLCs which are:
1795                 //  * in any unrevoked remote commitment transaction, as they could broadcast said
1796                 //    transactions and we'd end up in a race, or
1797                 //  * are in our latest local commitment transaction, as this is the thing we will
1798                 //    broadcast if we go on-chain.
1799                 // Note that we consider HTLCs which were below dust threshold here - while they don't
1800                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
1801                 // to the source, and if we don't fail the channel we will have to ensure that the next
1802                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
1803                 // easier to just fail the channel as this case should be rare enough anyway.
1804                 macro_rules! scan_commitment {
1805                         ($htlcs: expr, $local_tx: expr) => {
1806                                 for ref htlc in $htlcs {
1807                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1808                                         // chain with enough room to claim the HTLC without our counterparty being able to
1809                                         // time out the HTLC first.
1810                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1811                                         // concern is being able to claim the corresponding inbound HTLC (on another
1812                                         // channel) before it expires. In fact, we don't even really care if our
1813                                         // counterparty here claims such an outbound HTLC after it expired as long as we
1814                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1815                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1816                                         // we give ourselves a few blocks of headroom after expiration before going
1817                                         // on-chain for an expired HTLC.
1818                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1819                                         // from us until we've reached the point where we go on-chain with the
1820                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1821                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1822                                         //  aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1823                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
1824                                         //      outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1825                                         //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
1826                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
1827                                         //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
1828                                         //  The final, above, condition is checked for statically in channelmanager
1829                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
1830                                         let htlc_outbound = $local_tx == htlc.offered;
1831                                         if ( htlc_outbound && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1832                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1833                                                 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
1834                                                 return true;
1835                                         }
1836                                 }
1837                         }
1838                 }
1839
1840                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1841                         scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
1842                 }
1843
1844                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1845                         if let &Some(ref txid) = current_remote_commitment_txid {
1846                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
1847                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
1848                                 }
1849                         }
1850                         if let &Some(ref txid) = prev_remote_commitment_txid {
1851                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
1852                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
1853                                 }
1854                         }
1855                 }
1856
1857                 false
1858         }
1859
1860         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
1861         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
1862         fn is_resolving_htlc_output(&mut self, tx: &Transaction) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
1863                 let mut htlc_updated = Vec::new();
1864
1865                 'outer_loop: for input in &tx.input {
1866                         let mut payment_data = None;
1867                         let revocation_sig_claim = (input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33)
1868                                 || (input.witness.len() == 3 && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33);
1869                         let accepted_preimage_claim = input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT;
1870                         let offered_preimage_claim = input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT;
1871
1872                         macro_rules! log_claim {
1873                                 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
1874                                         // We found the output in question, but aren't failing it backwards
1875                                         // as we have no corresponding source. This implies either it is an
1876                                         // inbound HTLC or an outbound HTLC on a revoked transaction.
1877                                         let outbound_htlc = $local_tx == $htlc.offered;
1878                                         if ($local_tx && revocation_sig_claim) ||
1879                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
1880                                                 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
1881                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
1882                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
1883                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
1884                                         } else {
1885                                                 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
1886                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
1887                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
1888                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
1889                                         }
1890                                 }
1891                         }
1892
1893                         macro_rules! scan_commitment {
1894                                 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
1895                                         for (ref htlc_output, source_option) in $htlcs {
1896                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
1897                                                         if let Some(ref source) = source_option {
1898                                                                 log_claim!($tx_info, $local_tx, htlc_output, true);
1899                                                                 // We have a resolution of an HTLC either from one of our latest
1900                                                                 // local commitment transactions or an unrevoked remote commitment
1901                                                                 // transaction. This implies we either learned a preimage, the HTLC
1902                                                                 // has timed out, or we screwed up. In any case, we should now
1903                                                                 // resolve the source HTLC with the original sender.
1904                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
1905                                                         } else {
1906                                                                 log_claim!($tx_info, $local_tx, htlc_output, false);
1907                                                                 continue 'outer_loop;
1908                                                         }
1909                                                 }
1910                                         }
1911                                 }
1912                         }
1913
1914                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
1915                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
1916                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
1917                                                 "our latest local commitment tx", true);
1918                                 }
1919                         }
1920                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
1921                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
1922                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
1923                                                 "our previous local commitment tx", true);
1924                                 }
1925                         }
1926                         if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
1927                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
1928                                         "remote commitment tx", false);
1929                         }
1930
1931                         // Check that scan_commitment, above, decided there is some source worth relaying an
1932                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
1933                         if let Some((source, payment_hash)) = payment_data {
1934                                 let mut payment_preimage = PaymentPreimage([0; 32]);
1935                                 if accepted_preimage_claim {
1936                                         payment_preimage.0.copy_from_slice(&input.witness[3]);
1937                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
1938                                 } else if offered_preimage_claim {
1939                                         payment_preimage.0.copy_from_slice(&input.witness[1]);
1940                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
1941                                 } else {
1942                                         htlc_updated.push((source, None, payment_hash));
1943                                 }
1944                         }
1945                 }
1946                 htlc_updated
1947         }
1948 }
1949
1950 const MAX_ALLOC_SIZE: usize = 64*1024;
1951
1952 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1953         fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1954                 let secp_ctx = Secp256k1::new();
1955                 macro_rules! unwrap_obj {
1956                         ($key: expr) => {
1957                                 match $key {
1958                                         Ok(res) => res,
1959                                         Err(_) => return Err(DecodeError::InvalidValue),
1960                                 }
1961                         }
1962                 }
1963
1964                 let _ver: u8 = Readable::read(reader)?;
1965                 let min_ver: u8 = Readable::read(reader)?;
1966                 if min_ver > SERIALIZATION_VERSION {
1967                         return Err(DecodeError::UnknownVersion);
1968                 }
1969
1970                 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1971
1972                 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1973                         0 => {
1974                                 let revocation_base_key = Readable::read(reader)?;
1975                                 let htlc_base_key = Readable::read(reader)?;
1976                                 let delayed_payment_base_key = Readable::read(reader)?;
1977                                 let payment_base_key = Readable::read(reader)?;
1978                                 let shutdown_pubkey = Readable::read(reader)?;
1979                                 let prev_latest_per_commitment_point = Readable::read(reader)?;
1980                                 let latest_per_commitment_point = Readable::read(reader)?;
1981                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1982                                 // barely-init'd ChannelMonitors that we can't do anything with.
1983                                 let outpoint = OutPoint {
1984                                         txid: Readable::read(reader)?,
1985                                         index: Readable::read(reader)?,
1986                                 };
1987                                 let funding_info = Some((outpoint, Readable::read(reader)?));
1988                                 let current_remote_commitment_txid = Readable::read(reader)?;
1989                                 let prev_remote_commitment_txid = Readable::read(reader)?;
1990                                 Storage::Local {
1991                                         revocation_base_key,
1992                                         htlc_base_key,
1993                                         delayed_payment_base_key,
1994                                         payment_base_key,
1995                                         shutdown_pubkey,
1996                                         prev_latest_per_commitment_point,
1997                                         latest_per_commitment_point,
1998                                         funding_info,
1999                                         current_remote_commitment_txid,
2000                                         prev_remote_commitment_txid,
2001                                 }
2002                         },
2003                         _ => return Err(DecodeError::InvalidValue),
2004                 };
2005
2006                 let their_htlc_base_key = Some(Readable::read(reader)?);
2007                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
2008
2009                 let their_cur_revocation_points = {
2010                         let first_idx = <U48 as Readable<R>>::read(reader)?.0;
2011                         if first_idx == 0 {
2012                                 None
2013                         } else {
2014                                 let first_point = Readable::read(reader)?;
2015                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2016                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2017                                         Some((first_idx, first_point, None))
2018                                 } else {
2019                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2020                                 }
2021                         }
2022                 };
2023
2024                 let our_to_self_delay: u16 = Readable::read(reader)?;
2025                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
2026
2027                 let mut old_secrets = [([0; 32], 1 << 48); 49];
2028                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
2029                         *secret = Readable::read(reader)?;
2030                         *idx = Readable::read(reader)?;
2031                 }
2032
2033                 macro_rules! read_htlc_in_commitment {
2034                         () => {
2035                                 {
2036                                         let offered: bool = Readable::read(reader)?;
2037                                         let amount_msat: u64 = Readable::read(reader)?;
2038                                         let cltv_expiry: u32 = Readable::read(reader)?;
2039                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2040                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2041
2042                                         HTLCOutputInCommitment {
2043                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2044                                         }
2045                                 }
2046                         }
2047                 }
2048
2049                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
2050                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2051                 for _ in 0..remote_claimable_outpoints_len {
2052                         let txid: Sha256dHash = Readable::read(reader)?;
2053                         let htlcs_count: u64 = Readable::read(reader)?;
2054                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2055                         for _ in 0..htlcs_count {
2056                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2057                         }
2058                         if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
2059                                 return Err(DecodeError::InvalidValue);
2060                         }
2061                 }
2062
2063                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2064                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2065                 for _ in 0..remote_commitment_txn_on_chain_len {
2066                         let txid: Sha256dHash = Readable::read(reader)?;
2067                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2068                         let outputs_count = <u64 as Readable<R>>::read(reader)?;
2069                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2070                         for _ in 0..outputs_count {
2071                                 outputs.push(Readable::read(reader)?);
2072                         }
2073                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2074                                 return Err(DecodeError::InvalidValue);
2075                         }
2076                 }
2077
2078                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2079                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2080                 for _ in 0..remote_hash_commitment_number_len {
2081                         let payment_hash: PaymentHash = Readable::read(reader)?;
2082                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2083                         if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2084                                 return Err(DecodeError::InvalidValue);
2085                         }
2086                 }
2087
2088                 macro_rules! read_local_tx {
2089                         () => {
2090                                 {
2091                                         let tx = match Transaction::consensus_decode(reader.by_ref()) {
2092                                                 Ok(tx) => tx,
2093                                                 Err(e) => match e {
2094                                                         encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
2095                                                         _ => return Err(DecodeError::InvalidValue),
2096                                                 },
2097                                         };
2098
2099                                         if tx.input.is_empty() {
2100                                                 // Ensure tx didn't hit the 0-input ambiguity case.
2101                                                 return Err(DecodeError::InvalidValue);
2102                                         }
2103
2104                                         let revocation_key = Readable::read(reader)?;
2105                                         let a_htlc_key = Readable::read(reader)?;
2106                                         let b_htlc_key = Readable::read(reader)?;
2107                                         let delayed_payment_key = Readable::read(reader)?;
2108                                         let feerate_per_kw: u64 = Readable::read(reader)?;
2109
2110                                         let htlcs_len: u64 = Readable::read(reader)?;
2111                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2112                                         for _ in 0..htlcs_len {
2113                                                 let htlc = read_htlc_in_commitment!();
2114                                                 let sigs = match <u8 as Readable<R>>::read(reader)? {
2115                                                         0 => None,
2116                                                         1 => Some((Readable::read(reader)?, Readable::read(reader)?)),
2117                                                         _ => return Err(DecodeError::InvalidValue),
2118                                                 };
2119                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
2120                                         }
2121
2122                                         LocalSignedTx {
2123                                                 txid: tx.txid(),
2124                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw,
2125                                                 htlc_outputs: htlcs
2126                                         }
2127                                 }
2128                         }
2129                 }
2130
2131                 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2132                         0 => None,
2133                         1 => {
2134                                 Some(read_local_tx!())
2135                         },
2136                         _ => return Err(DecodeError::InvalidValue),
2137                 };
2138
2139                 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2140                         0 => None,
2141                         1 => {
2142                                 Some(read_local_tx!())
2143                         },
2144                         _ => return Err(DecodeError::InvalidValue),
2145                 };
2146
2147                 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2148
2149                 let payment_preimages_len: u64 = Readable::read(reader)?;
2150                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2151                 for _ in 0..payment_preimages_len {
2152                         let preimage: PaymentPreimage = Readable::read(reader)?;
2153                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2154                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2155                                 return Err(DecodeError::InvalidValue);
2156                         }
2157                 }
2158
2159                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2160                 let destination_script = Readable::read(reader)?;
2161
2162                 Ok((last_block_hash.clone(), ChannelMonitor {
2163                         commitment_transaction_number_obscure_factor,
2164
2165                         key_storage,
2166                         their_htlc_base_key,
2167                         their_delayed_payment_base_key,
2168                         their_cur_revocation_points,
2169
2170                         our_to_self_delay,
2171                         their_to_self_delay,
2172
2173                         old_secrets,
2174                         remote_claimable_outpoints,
2175                         remote_commitment_txn_on_chain,
2176                         remote_hash_commitment_number,
2177
2178                         prev_local_signed_commitment_tx,
2179                         current_local_signed_commitment_tx,
2180                         current_remote_commitment_number,
2181
2182                         payment_preimages,
2183
2184                         destination_script,
2185                         last_block_hash,
2186                         secp_ctx,
2187                         logger,
2188                 }))
2189         }
2190
2191 }
2192
2193 #[cfg(test)]
2194 mod tests {
2195         use bitcoin::blockdata::script::Script;
2196         use bitcoin::blockdata::transaction::Transaction;
2197         use bitcoin_hashes::Hash;
2198         use bitcoin_hashes::sha256::Hash as Sha256;
2199         use hex;
2200         use ln::channelmanager::{PaymentPreimage, PaymentHash};
2201         use ln::channelmonitor::ChannelMonitor;
2202         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
2203         use util::test_utils::TestLogger;
2204         use secp256k1::key::{SecretKey,PublicKey};
2205         use secp256k1::Secp256k1;
2206         use rand::{thread_rng,Rng};
2207         use std::sync::Arc;
2208
2209         #[test]
2210         fn test_per_commitment_storage() {
2211                 // Test vectors from BOLT 3:
2212                 let mut secrets: Vec<[u8; 32]> = Vec::new();
2213                 let mut monitor: ChannelMonitor;
2214                 let secp_ctx = Secp256k1::new();
2215                 let logger = Arc::new(TestLogger::new());
2216
2217                 macro_rules! test_secrets {
2218                         () => {
2219                                 let mut idx = 281474976710655;
2220                                 for secret in secrets.iter() {
2221                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2222                                         idx -= 1;
2223                                 }
2224                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2225                                 assert!(monitor.get_secret(idx).is_none());
2226                         };
2227                 }
2228
2229                 {
2230                         // insert_secret correct sequence
2231                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2232                         secrets.clear();
2233
2234                         secrets.push([0; 32]);
2235                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2236                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2237                         test_secrets!();
2238
2239                         secrets.push([0; 32]);
2240                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2241                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2242                         test_secrets!();
2243
2244                         secrets.push([0; 32]);
2245                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2246                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2247                         test_secrets!();
2248
2249                         secrets.push([0; 32]);
2250                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2251                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2252                         test_secrets!();
2253
2254                         secrets.push([0; 32]);
2255                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2256                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2257                         test_secrets!();
2258
2259                         secrets.push([0; 32]);
2260                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2261                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2262                         test_secrets!();
2263
2264                         secrets.push([0; 32]);
2265                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2266                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2267                         test_secrets!();
2268
2269                         secrets.push([0; 32]);
2270                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2271                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2272                         test_secrets!();
2273                 }
2274
2275                 {
2276                         // insert_secret #1 incorrect
2277                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2278                         secrets.clear();
2279
2280                         secrets.push([0; 32]);
2281                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2282                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2283                         test_secrets!();
2284
2285                         secrets.push([0; 32]);
2286                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2287                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
2288                                         "Previous secret did not match new one");
2289                 }
2290
2291                 {
2292                         // insert_secret #2 incorrect (#1 derived from incorrect)
2293                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2294                         secrets.clear();
2295
2296                         secrets.push([0; 32]);
2297                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2298                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2299                         test_secrets!();
2300
2301                         secrets.push([0; 32]);
2302                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2303                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2304                         test_secrets!();
2305
2306                         secrets.push([0; 32]);
2307                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2308                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2309                         test_secrets!();
2310
2311                         secrets.push([0; 32]);
2312                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2313                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2314                                         "Previous secret did not match new one");
2315                 }
2316
2317                 {
2318                         // insert_secret #3 incorrect
2319                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2320                         secrets.clear();
2321
2322                         secrets.push([0; 32]);
2323                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2324                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2325                         test_secrets!();
2326
2327                         secrets.push([0; 32]);
2328                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2329                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2330                         test_secrets!();
2331
2332                         secrets.push([0; 32]);
2333                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2334                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2335                         test_secrets!();
2336
2337                         secrets.push([0; 32]);
2338                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2339                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2340                                         "Previous secret did not match new one");
2341                 }
2342
2343                 {
2344                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2345                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2346                         secrets.clear();
2347
2348                         secrets.push([0; 32]);
2349                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2350                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2351                         test_secrets!();
2352
2353                         secrets.push([0; 32]);
2354                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2355                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2356                         test_secrets!();
2357
2358                         secrets.push([0; 32]);
2359                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2360                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2361                         test_secrets!();
2362
2363                         secrets.push([0; 32]);
2364                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2365                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2366                         test_secrets!();
2367
2368                         secrets.push([0; 32]);
2369                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2370                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2371                         test_secrets!();
2372
2373                         secrets.push([0; 32]);
2374                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2375                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2376                         test_secrets!();
2377
2378                         secrets.push([0; 32]);
2379                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2380                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2381                         test_secrets!();
2382
2383                         secrets.push([0; 32]);
2384                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2385                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2386                                         "Previous secret did not match new one");
2387                 }
2388
2389                 {
2390                         // insert_secret #5 incorrect
2391                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2392                         secrets.clear();
2393
2394                         secrets.push([0; 32]);
2395                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2396                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2397                         test_secrets!();
2398
2399                         secrets.push([0; 32]);
2400                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2401                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2402                         test_secrets!();
2403
2404                         secrets.push([0; 32]);
2405                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2406                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2407                         test_secrets!();
2408
2409                         secrets.push([0; 32]);
2410                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2411                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2412                         test_secrets!();
2413
2414                         secrets.push([0; 32]);
2415                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2416                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2417                         test_secrets!();
2418
2419                         secrets.push([0; 32]);
2420                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2421                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2422                                         "Previous secret did not match new one");
2423                 }
2424
2425                 {
2426                         // insert_secret #6 incorrect (5 derived from incorrect)
2427                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2428                         secrets.clear();
2429
2430                         secrets.push([0; 32]);
2431                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2432                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2433                         test_secrets!();
2434
2435                         secrets.push([0; 32]);
2436                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2437                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2438                         test_secrets!();
2439
2440                         secrets.push([0; 32]);
2441                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2442                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2443                         test_secrets!();
2444
2445                         secrets.push([0; 32]);
2446                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2447                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2448                         test_secrets!();
2449
2450                         secrets.push([0; 32]);
2451                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2452                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2453                         test_secrets!();
2454
2455                         secrets.push([0; 32]);
2456                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2457                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2458                         test_secrets!();
2459
2460                         secrets.push([0; 32]);
2461                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2462                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2463                         test_secrets!();
2464
2465                         secrets.push([0; 32]);
2466                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2467                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2468                                         "Previous secret did not match new one");
2469                 }
2470
2471                 {
2472                         // insert_secret #7 incorrect
2473                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2474                         secrets.clear();
2475
2476                         secrets.push([0; 32]);
2477                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2478                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2479                         test_secrets!();
2480
2481                         secrets.push([0; 32]);
2482                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2483                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2484                         test_secrets!();
2485
2486                         secrets.push([0; 32]);
2487                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2488                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2489                         test_secrets!();
2490
2491                         secrets.push([0; 32]);
2492                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2493                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2494                         test_secrets!();
2495
2496                         secrets.push([0; 32]);
2497                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2498                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2499                         test_secrets!();
2500
2501                         secrets.push([0; 32]);
2502                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2503                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2504                         test_secrets!();
2505
2506                         secrets.push([0; 32]);
2507                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2508                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2509                         test_secrets!();
2510
2511                         secrets.push([0; 32]);
2512                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2513                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2514                                         "Previous secret did not match new one");
2515                 }
2516
2517                 {
2518                         // insert_secret #8 incorrect
2519                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2520                         secrets.clear();
2521
2522                         secrets.push([0; 32]);
2523                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2524                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2525                         test_secrets!();
2526
2527                         secrets.push([0; 32]);
2528                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2529                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2530                         test_secrets!();
2531
2532                         secrets.push([0; 32]);
2533                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2534                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2535                         test_secrets!();
2536
2537                         secrets.push([0; 32]);
2538                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2539                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2540                         test_secrets!();
2541
2542                         secrets.push([0; 32]);
2543                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2544                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2545                         test_secrets!();
2546
2547                         secrets.push([0; 32]);
2548                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2549                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2550                         test_secrets!();
2551
2552                         secrets.push([0; 32]);
2553                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2554                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2555                         test_secrets!();
2556
2557                         secrets.push([0; 32]);
2558                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2559                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2560                                         "Previous secret did not match new one");
2561                 }
2562         }
2563
2564         #[test]
2565         fn test_prune_preimages() {
2566                 let secp_ctx = Secp256k1::new();
2567                 let logger = Arc::new(TestLogger::new());
2568
2569                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2570                 macro_rules! dummy_keys {
2571                         () => {
2572                                 {
2573                                         TxCreationKeys {
2574                                                 per_commitment_point: dummy_key.clone(),
2575                                                 revocation_key: dummy_key.clone(),
2576                                                 a_htlc_key: dummy_key.clone(),
2577                                                 b_htlc_key: dummy_key.clone(),
2578                                                 a_delayed_payment_key: dummy_key.clone(),
2579                                                 b_payment_key: dummy_key.clone(),
2580                                         }
2581                                 }
2582                         }
2583                 }
2584                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2585
2586                 let mut preimages = Vec::new();
2587                 {
2588                         let mut rng  = thread_rng();
2589                         for _ in 0..20 {
2590                                 let mut preimage = PaymentPreimage([0; 32]);
2591                                 rng.fill_bytes(&mut preimage.0[..]);
2592                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2593                                 preimages.push((preimage, hash));
2594                         }
2595                 }
2596
2597                 macro_rules! preimages_slice_to_htlc_outputs {
2598                         ($preimages_slice: expr) => {
2599                                 {
2600                                         let mut res = Vec::new();
2601                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2602                                                 res.push((HTLCOutputInCommitment {
2603                                                         offered: true,
2604                                                         amount_msat: 0,
2605                                                         cltv_expiry: 0,
2606                                                         payment_hash: preimage.1.clone(),
2607                                                         transaction_output_index: Some(idx as u32),
2608                                                 }, None));
2609                                         }
2610                                         res
2611                                 }
2612                         }
2613                 }
2614                 macro_rules! preimages_to_local_htlcs {
2615                         ($preimages_slice: expr) => {
2616                                 {
2617                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2618                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2619                                         res
2620                                 }
2621                         }
2622                 }
2623
2624                 macro_rules! test_preimages_exist {
2625                         ($preimages_slice: expr, $monitor: expr) => {
2626                                 for preimage in $preimages_slice {
2627                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2628                                 }
2629                         }
2630                 }
2631
2632                 // Prune with one old state and a local commitment tx holding a few overlaps with the
2633                 // old state.
2634                 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2635                 monitor.set_their_to_self_delay(10);
2636
2637                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2638                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2639                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2640                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2641                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2642                 for &(ref preimage, ref hash) in preimages.iter() {
2643                         monitor.provide_payment_preimage(hash, preimage);
2644                 }
2645
2646                 // Now provide a secret, pruning preimages 10-15
2647                 let mut secret = [0; 32];
2648                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2649                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2650                 assert_eq!(monitor.payment_preimages.len(), 15);
2651                 test_preimages_exist!(&preimages[0..10], monitor);
2652                 test_preimages_exist!(&preimages[15..20], monitor);
2653
2654                 // Now provide a further secret, pruning preimages 15-17
2655                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2656                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2657                 assert_eq!(monitor.payment_preimages.len(), 13);
2658                 test_preimages_exist!(&preimages[0..10], monitor);
2659                 test_preimages_exist!(&preimages[17..20], monitor);
2660
2661                 // Now update local commitment tx info, pruning only element 18 as we still care about the
2662                 // previous commitment tx's preimages too
2663                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2664                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2665                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2666                 assert_eq!(monitor.payment_preimages.len(), 12);
2667                 test_preimages_exist!(&preimages[0..10], monitor);
2668                 test_preimages_exist!(&preimages[18..20], monitor);
2669
2670                 // But if we do it again, we'll prune 5-10
2671                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2672                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2673                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2674                 assert_eq!(monitor.payment_preimages.len(), 5);
2675                 test_preimages_exist!(&preimages[0..5], monitor);
2676         }
2677
2678         // Further testing is done in the ChannelManager integration tests.
2679 }