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