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