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