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