Merge pull request #33 from jeandudey/funding_txo
[rust-lightning] / src / ln / channelmonitor.rs
1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
3 use bitcoin::blockdata::script::Script;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::util::bip143;
6
7 use crypto::digest::Digest;
8
9 use secp256k1::{Secp256k1,Message,Signature};
10 use secp256k1::key::{SecretKey,PublicKey};
11
12 use ln::msgs::HandleError;
13 use ln::chan_utils;
14 use ln::chan_utils::HTLCOutputInCommitment;
15 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
16 use chain::transaction::OutPoint;
17 use util::sha2::Sha256;
18
19 use std::collections::HashMap;
20 use std::sync::{Arc,Mutex};
21 use std::{hash,cmp};
22
23 pub enum ChannelMonitorUpdateErr {
24         /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
25         /// to succeed at some point in the future).
26         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
27         /// submitting new commitment transactions to the remote party.
28         /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
29         /// the channel to an operational state.
30         TemporaryFailure,
31         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
32         /// different watchtower and cannot update with all watchtowers that were previously informed
33         /// of this channel). This will force-close the channel in question.
34         PermanentFailure,
35 }
36
37 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
38 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
39 /// events to it, while also taking any add_update_monitor events and passing them to some remote
40 /// server(s).
41 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
42 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
43 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
44 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
45 pub trait ManyChannelMonitor: Send + Sync {
46         /// Adds or updates a monitor for the given `funding_txo`.
47         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
48 }
49
50 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
51 /// watchtower or watch our own channels.
52 /// Note that you must provide your own key by which to refer to channels.
53 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
54 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
55 /// index by a PublicKey which is required to sign any updates.
56 /// If you're using this for local monitoring of your own channels, you probably want to use
57 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
58 pub struct SimpleManyChannelMonitor<Key> {
59         monitors: Mutex<HashMap<Key, ChannelMonitor>>,
60         chain_monitor: Arc<ChainWatchInterface>,
61         broadcaster: Arc<BroadcasterInterface>
62 }
63
64 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
65         fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
66                 let monitors = self.monitors.lock().unwrap();
67                 for monitor in monitors.values() {
68                         monitor.block_connected(txn_matched, height, &*self.broadcaster);
69                 }
70         }
71
72         fn block_disconnected(&self, _: &BlockHeader) { }
73 }
74
75 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
76         pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
77                 let res = Arc::new(SimpleManyChannelMonitor {
78                         monitors: Mutex::new(HashMap::new()),
79                         chain_monitor,
80                         broadcaster
81                 });
82                 let weak_res = Arc::downgrade(&res);
83                 res.chain_monitor.register_listener(weak_res);
84                 res
85         }
86
87         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
88                 let mut monitors = self.monitors.lock().unwrap();
89                 match monitors.get_mut(&key) {
90                         Some(orig_monitor) => return orig_monitor.insert_combine(monitor),
91                         None => {}
92                 };
93                 match monitor.funding_txo {
94                         None => self.chain_monitor.watch_all_txn(),
95                         Some(outpoint) => self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32)),
96                 }
97                 monitors.insert(key, monitor);
98                 Ok(())
99         }
100 }
101
102 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
103         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
104                 match self.add_update_monitor_by_key(funding_txo, monitor) {
105                         Ok(_) => Ok(()),
106                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
107                 }
108         }
109 }
110
111 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
112 /// instead claiming it in its own individual transaction.
113 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
114 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
115 /// HTLC-Success transaction.
116 const CLTV_CLAIM_BUFFER: u32 = 6;
117
118 #[derive(Clone)]
119 enum KeyStorage {
120         PrivMode {
121                 revocation_base_key: SecretKey,
122                 htlc_base_key: SecretKey,
123         },
124         SigsMode {
125                 revocation_base_key: PublicKey,
126                 htlc_base_key: PublicKey,
127                 sigs: HashMap<Sha256dHash, Signature>,
128         }
129 }
130
131 #[derive(Clone)]
132 struct LocalSignedTx {
133         txid: Sha256dHash,
134         tx: Transaction,
135         revocation_key: PublicKey,
136         a_htlc_key: PublicKey,
137         b_htlc_key: PublicKey,
138         delayed_payment_key: PublicKey,
139         feerate_per_kw: u64,
140         htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
141 }
142
143 pub struct ChannelMonitor {
144         funding_txo: Option<OutPoint>,
145         commitment_transaction_number_obscure_factor: u64,
146
147         key_storage: KeyStorage,
148         delayed_payment_base_key: PublicKey,
149         their_htlc_base_key: Option<PublicKey>,
150         // first is the idx of the first of the two revocation points
151         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
152
153         our_to_self_delay: u16,
154         their_to_self_delay: Option<u16>,
155
156         old_secrets: [([u8; 32], u64); 49],
157         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
158         remote_htlc_outputs_on_chain: Mutex<HashMap<Sha256dHash, u64>>,
159         //hash to commitment number mapping use to determine the state of transaction owning it
160         // (revoked/non-revoked) and so lightnen pruning
161         remote_hash_commitment_number: HashMap<[u8; 32], u64>,
162
163         // We store two local commitment transactions to avoid any race conditions where we may update
164         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
165         // various monitors for one channel being out of sync, and us broadcasting a local
166         // transaction for which we have deleted claim information on some watchtowers.
167         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
168         current_local_signed_commitment_tx: Option<LocalSignedTx>,
169
170         payment_preimages: HashMap<[u8; 32], [u8; 32]>,
171
172         destination_script: Script,
173         secp_ctx: Secp256k1, //TODO: dedup this a bit...
174 }
175 impl Clone for ChannelMonitor {
176         fn clone(&self) -> Self {
177                 ChannelMonitor {
178                         funding_txo: self.funding_txo.clone(),
179                         commitment_transaction_number_obscure_factor: self.commitment_transaction_number_obscure_factor.clone(),
180
181                         key_storage: self.key_storage.clone(),
182                         delayed_payment_base_key: self.delayed_payment_base_key.clone(),
183                         their_htlc_base_key: self.their_htlc_base_key.clone(),
184                         their_cur_revocation_points: self.their_cur_revocation_points.clone(),
185
186                         our_to_self_delay: self.our_to_self_delay,
187                         their_to_self_delay: self.their_to_self_delay,
188
189                         old_secrets: self.old_secrets.clone(),
190                         remote_claimable_outpoints: self.remote_claimable_outpoints.clone(),
191                         remote_htlc_outputs_on_chain: Mutex::new((*self.remote_htlc_outputs_on_chain.lock().unwrap()).clone()),
192                         remote_hash_commitment_number: self.remote_hash_commitment_number.clone(),
193
194                         prev_local_signed_commitment_tx: self.prev_local_signed_commitment_tx.clone(),
195                         current_local_signed_commitment_tx: self.current_local_signed_commitment_tx.clone(),
196
197                         payment_preimages: self.payment_preimages.clone(),
198
199                         destination_script: self.destination_script.clone(),
200                         secp_ctx: self.secp_ctx.clone(),
201                 }
202         }
203 }
204
205 impl ChannelMonitor {
206         pub fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &PublicKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script) -> ChannelMonitor {
207                 ChannelMonitor {
208                         funding_txo: None,
209                         commitment_transaction_number_obscure_factor: 0,
210
211                         key_storage: KeyStorage::PrivMode {
212                                 revocation_base_key: revocation_base_key.clone(),
213                                 htlc_base_key: htlc_base_key.clone(),
214                         },
215                         delayed_payment_base_key: delayed_payment_base_key.clone(),
216                         their_htlc_base_key: None,
217                         their_cur_revocation_points: None,
218
219                         our_to_self_delay: our_to_self_delay,
220                         their_to_self_delay: None,
221
222                         old_secrets: [([0; 32], 1 << 48); 49],
223                         remote_claimable_outpoints: HashMap::new(),
224                         remote_htlc_outputs_on_chain: Mutex::new(HashMap::new()),
225                         remote_hash_commitment_number: HashMap::new(),
226
227                         prev_local_signed_commitment_tx: None,
228                         current_local_signed_commitment_tx: None,
229
230                         payment_preimages: HashMap::new(),
231
232                         destination_script: destination_script,
233                         secp_ctx: Secp256k1::new(),
234                 }
235         }
236
237         #[inline]
238         fn place_secret(idx: u64) -> u8 {
239                 for i in 0..48 {
240                         if idx & (1 << i) == (1 << i) {
241                                 return i
242                         }
243                 }
244                 48
245         }
246
247         #[inline]
248         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
249                 let mut res: [u8; 32] = secret;
250                 for i in 0..bits {
251                         let bitpos = bits - 1 - i;
252                         if idx & (1 << bitpos) == (1 << bitpos) {
253                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
254                                 let mut sha = Sha256::new();
255                                 sha.input(&res);
256                                 sha.result(&mut res);
257                         }
258                 }
259                 res
260         }
261
262         /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
263         /// revocation point which may be required to claim HTLC outputs which we know the preimage of
264         /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
265         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
266         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
267         pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
268                 let pos = ChannelMonitor::place_secret(idx);
269                 for i in 0..pos {
270                         let (old_secret, old_idx) = self.old_secrets[i as usize];
271                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
272                                 return Err(HandleError{err: "Previous secret did not match new one", msg: None})
273                         }
274                 }
275                 self.old_secrets[pos as usize] = (secret, idx);
276
277                 if let Some(new_revocation_point) = their_next_revocation_point {
278                         match self.their_cur_revocation_points {
279                                 Some(old_points) => {
280                                         if old_points.0 == new_revocation_point.0 + 1 {
281                                                 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
282                                         } else if old_points.0 == new_revocation_point.0 + 2 {
283                                                 if let Some(old_second_point) = old_points.2 {
284                                                         self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
285                                                 } else {
286                                                         self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
287                                                 }
288                                         } else {
289                                                 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
290                                         }
291                                 },
292                                 None => {
293                                         self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
294                                 }
295                         }
296                 }
297
298                 let mut waste_hash_state : Vec<[u8;32]> = Vec::new();
299                 {
300                         let local_signed_commitment_tx = &self.current_local_signed_commitment_tx;
301                         let remote_hash_commitment_number = &self.remote_hash_commitment_number;
302                         let min_idx = self.get_min_seen_secret();
303                         self.payment_preimages.retain(|&k, _| {
304                                         for &(ref htlc, _s1, _s2) in &local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !").htlc_outputs {
305                                                 if k == htlc.payment_hash {
306                                                         return true
307                                                 }
308                                         }
309                                         if let Some(cn) = remote_hash_commitment_number.get(&k) {
310                                                 if *cn < min_idx {
311                                                         return true
312                                                 }
313                                         }
314                                         waste_hash_state.push(k);
315                                         false
316                                 });
317                 }
318                 for h in waste_hash_state {
319                         self.remote_hash_commitment_number.remove(&h);
320                 }
321
322                 Ok(())
323         }
324
325         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
326         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
327         /// possibly future revocation/preimage information) to claim outputs where possible.
328         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
329         pub fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
330                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
331                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
332                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
333                 // timeouts)
334                 for htlc in &htlc_outputs {
335                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
336                 }
337                 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
338         }
339
340         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
341         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
342         /// is important that any clones of this channel monitor (including remote clones) by kept
343         /// up-to-date as our local commitment transaction is updated.
344         /// Panics if set_their_to_self_delay has never been called.
345         pub 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)>) {
346                 assert!(self.their_to_self_delay.is_some());
347                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
348                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
349                         txid: signed_commitment_tx.txid(),
350                         tx: signed_commitment_tx,
351                         revocation_key: local_keys.revocation_key,
352                         a_htlc_key: local_keys.a_htlc_key,
353                         b_htlc_key: local_keys.b_htlc_key,
354                         delayed_payment_key: local_keys.a_delayed_payment_key,
355                         feerate_per_kw,
356                         htlc_outputs,
357                 });
358         }
359
360         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
361         /// commitment_tx_infos which contain the payment hash have been revoked.
362         pub fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
363                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
364         }
365
366         pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
367                 match self.funding_txo {
368                         Some(txo) => if other.funding_txo.is_some() && other.funding_txo.unwrap() != txo {
369                                 return Err(HandleError{err: "Funding transaction outputs are not identical!", msg: None});
370                         },
371                         None => if other.funding_txo.is_some() {
372                                 self.funding_txo = other.funding_txo;
373                         }
374                 }
375                 let other_min_secret = other.get_min_seen_secret();
376                 let our_min_secret = self.get_min_seen_secret();
377                 if our_min_secret > other_min_secret {
378                         self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
379                 }
380                 if our_min_secret >= other_min_secret {
381                         self.their_cur_revocation_points = other.their_cur_revocation_points;
382                         for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
383                                 self.remote_claimable_outpoints.insert(txid, htlcs);
384                         }
385                         if let Some(local_tx) = other.prev_local_signed_commitment_tx {
386                                 self.prev_local_signed_commitment_tx = Some(local_tx);
387                         }
388                         if let Some(local_tx) = other.current_local_signed_commitment_tx {
389                                 self.current_local_signed_commitment_tx = Some(local_tx);
390                         }
391                         self.payment_preimages = other.payment_preimages;
392                 }
393                 Ok(())
394         }
395
396         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
397         pub fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
398                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
399                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
400         }
401
402         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
403         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
404         /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
405         /// provides slightly better privacy.
406         pub fn set_funding_info(&mut self, funding_info: OutPoint) {
407                 self.funding_txo = Some(funding_info);
408         }
409
410         pub fn set_their_htlc_base_key(&mut self, their_htlc_base_key: &PublicKey) {
411                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
412         }
413
414         pub fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
415                 self.their_to_self_delay = Some(their_to_self_delay);
416         }
417
418         pub fn unset_funding_info(&mut self) {
419                 self.funding_txo = None;
420         }
421
422         pub fn get_funding_txo(&self) -> Option<OutPoint> {
423                 self.funding_txo
424         }
425
426         //TODO: Functions to serialize/deserialize (with different forms depending on which information
427         //we want to leave out (eg funding_txo, etc).
428
429         /// Can only fail if idx is < get_min_seen_secret
430         pub fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
431                 for i in 0..self.old_secrets.len() {
432                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
433                                 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
434                         }
435                 }
436                 assert!(idx < self.get_min_seen_secret());
437                 Err(HandleError{err: "idx too low", msg: None})
438         }
439
440         pub fn get_min_seen_secret(&self) -> u64 {
441                 //TODO This can be optimized?
442                 let mut min = 1 << 48;
443                 for &(_, idx) in self.old_secrets.iter() {
444                         if idx < min {
445                                 min = idx;
446                         }
447                 }
448                 min
449         }
450
451         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
452         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
453         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
454         /// HTLC-Success/HTLC-Timeout transactions, and claim them using the revocation key (if
455         /// applicable) as well.
456         fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> Vec<Transaction> {
457                 // Most secp and related errors trying to create keys means we have no hope of constructing
458                 // a spend transaction...so we return no transactions to broadcast
459                 let mut txn_to_broadcast = Vec::new();
460                 macro_rules! ignore_error {
461                         ( $thing : expr ) => {
462                                 match $thing {
463                                         Ok(a) => a,
464                                         Err(_) => return txn_to_broadcast
465                                 }
466                         };
467                 }
468
469                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
470                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
471
472                 let commitment_number = (((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor;
473                 if commitment_number >= self.get_min_seen_secret() {
474                         let secret = self.get_secret(commitment_number).unwrap();
475                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
476                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
477                                 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
478                                         let per_commitment_point = ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key));
479                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))),
480                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key)))))
481                                 },
482                                 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
483                                         let per_commitment_point = ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key));
484                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
485                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
486                                 },
487                         };
488                         let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key)), &self.delayed_payment_base_key));
489                         let a_htlc_key = match self.their_htlc_base_key {
490                                 None => return txn_to_broadcast,
491                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key)), &their_htlc_base_key)),
492                         };
493
494                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
495                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
496
497                         let mut total_value = 0;
498                         let mut values = Vec::new();
499                         let mut inputs = Vec::new();
500                         let mut htlc_idxs = Vec::new();
501
502                         for (idx, outp) in tx.output.iter().enumerate() {
503                                 if outp.script_pubkey == revokeable_p2wsh {
504                                         inputs.push(TxIn {
505                                                 prev_hash: commitment_txid,
506                                                 prev_index: idx as u32,
507                                                 script_sig: Script::new(),
508                                                 sequence: 0xfffffffd,
509                                                 witness: Vec::new(),
510                                         });
511                                         htlc_idxs.push(None);
512                                         values.push(outp.value);
513                                         total_value += outp.value;
514                                         break; // There can only be one of these
515                                 }
516                         }
517
518                         macro_rules! sign_input {
519                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
520                                         {
521                                                 let (sig, redeemscript) = match self.key_storage {
522                                                         KeyStorage::PrivMode { ref revocation_base_key, .. } => {
523                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
524                                                                         let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
525                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
526                                                                 };
527                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
528                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
529                                                                 (ignore_error!(self.secp_ctx.sign(&sighash, &revocation_key)), redeemscript)
530                                                         },
531                                                         KeyStorage::SigsMode { .. } => {
532                                                                 unimplemented!();
533                                                         }
534                                                 };
535                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
536                                                 $input.witness[0].push(SigHashType::All as u8);
537                                                 if $htlc_idx.is_none() {
538                                                         $input.witness.push(vec!(1));
539                                                 } else {
540                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
541                                                 }
542                                                 $input.witness.push(redeemscript.into_vec());
543                                         }
544                                 }
545                         }
546
547                         if let Some(per_commitment_data) = per_commitment_option {
548                                 inputs.reserve_exact(per_commitment_data.len());
549
550                                 for (idx, htlc) in per_commitment_data.iter().enumerate() {
551                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
552                                         if htlc.transaction_output_index as usize >= tx.output.len() ||
553                                                         tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
554                                                         tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
555                                                 return txn_to_broadcast; // Corrupted per_commitment_data, fuck this user
556                                         }
557                                         let input = TxIn {
558                                                 prev_hash: commitment_txid,
559                                                 prev_index: htlc.transaction_output_index,
560                                                 script_sig: Script::new(),
561                                                 sequence: 0xfffffffd,
562                                                 witness: Vec::new(),
563                                         };
564                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
565                                                 inputs.push(input);
566                                                 htlc_idxs.push(Some(idx));
567                                                 values.push(tx.output[htlc.transaction_output_index as usize].value);
568                                                 total_value += htlc.amount_msat / 1000;
569                                         } else {
570                                                 let mut single_htlc_tx = Transaction {
571                                                         version: 2,
572                                                         lock_time: 0,
573                                                         input: vec![input],
574                                                         output: vec!(TxOut {
575                                                                 script_pubkey: self.destination_script.clone(),
576                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
577                                                         }),
578                                                 };
579                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
580                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
581                                                 txn_to_broadcast.push(single_htlc_tx); // TODO: This is not yet tested in ChannelManager!
582                                         }
583                                 }
584                         }
585
586                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() {
587                                 // We're definitely a remote commitment transaction!
588                                 // TODO: Register commitment_txid with the ChainWatchInterface!
589                                 self.remote_htlc_outputs_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
590                         }
591                         if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
592
593                         let outputs = vec!(TxOut {
594                                 script_pubkey: self.destination_script.clone(),
595                                 value: total_value, //TODO: - fee
596                         });
597                         let mut spend_tx = Transaction {
598                                 version: 2,
599                                 lock_time: 0,
600                                 input: inputs,
601                                 output: outputs,
602                         };
603
604                         let mut values_drain = values.drain(..);
605                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
606
607                         for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
608                                 let value = values_drain.next().unwrap();
609                                 sign_input!(sighash_parts, input, htlc_idx, value);
610                         }
611
612                         txn_to_broadcast.push(spend_tx);
613                 } else if let Some(per_commitment_data) = per_commitment_option {
614                         if let Some(revocation_points) = self.their_cur_revocation_points {
615                                 let revocation_point_option =
616                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
617                                         else if let Some(point) = revocation_points.2.as_ref() {
618                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
619                                         } else { None };
620                                 if let Some(revocation_point) = revocation_point_option {
621                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
622                                                 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
623                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))),
624                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key)))))
625                                                 },
626                                                 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
627                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
628                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
629                                                 },
630                                         };
631                                         let a_htlc_key = match self.their_htlc_base_key {
632                                                 None => return txn_to_broadcast,
633                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
634                                         };
635
636                                         let mut total_value = 0;
637                                         let mut values = Vec::new();
638                                         let mut inputs = Vec::new();
639
640                                         macro_rules! sign_input {
641                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
642                                                         {
643                                                                 let (sig, redeemscript) = match self.key_storage {
644                                                                         KeyStorage::PrivMode { ref htlc_base_key, .. } => {
645                                                                                 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
646                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
647                                                                                 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
648                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
649                                                                                 (ignore_error!(self.secp_ctx.sign(&sighash, &htlc_key)), redeemscript)
650                                                                         },
651                                                                         KeyStorage::SigsMode { .. } => {
652                                                                                 unimplemented!();
653                                                                         }
654                                                                 };
655                                                                 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
656                                                                 $input.witness[0].push(SigHashType::All as u8);
657                                                                 $input.witness.push($preimage);
658                                                                 $input.witness.push(redeemscript.into_vec());
659                                                         }
660                                                 }
661                                         }
662
663                                         for (idx, htlc) in per_commitment_data.iter().enumerate() {
664                                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
665                                                         let input = TxIn {
666                                                                 prev_hash: commitment_txid,
667                                                                 prev_index: htlc.transaction_output_index,
668                                                                 script_sig: Script::new(),
669                                                                 sequence: idx as u32, // reset to 0xfffffffd in sign_input
670                                                                 witness: Vec::new(),
671                                                         };
672                                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
673                                                                 inputs.push(input);
674                                                                 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
675                                                                 total_value += htlc.amount_msat / 1000;
676                                                         } else {
677                                                                 let mut single_htlc_tx = Transaction {
678                                                                         version: 2,
679                                                                         lock_time: 0,
680                                                                         input: vec![input],
681                                                                         output: vec!(TxOut {
682                                                                                 script_pubkey: self.destination_script.clone(),
683                                                                                 value: htlc.amount_msat / 1000, //TODO: - fee
684                                                                         }),
685                                                                 };
686                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
687                                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
688                                                                 txn_to_broadcast.push(single_htlc_tx);
689                                                         }
690                                                 }
691                                         }
692
693                                         if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
694
695                                         let outputs = vec!(TxOut {
696                                                 script_pubkey: self.destination_script.clone(),
697                                                 value: total_value, //TODO: - fee
698                                         });
699                                         let mut spend_tx = Transaction {
700                                                 version: 2,
701                                                 lock_time: 0,
702                                                 input: inputs,
703                                                 output: outputs,
704                                         };
705
706                                         let mut values_drain = values.drain(..);
707                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
708
709                                         for input in spend_tx.input.iter_mut() {
710                                                 let value = values_drain.next().unwrap();
711                                                 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
712                                         }
713
714                                         txn_to_broadcast.push(spend_tx);
715                                 }
716                         }
717                 } else {
718                         //TODO: For each input check if its in our remote_htlc_outputs_on_chain map!
719                 }
720
721                 txn_to_broadcast
722         }
723
724         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
725                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
726
727                 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
728                         if htlc.offered {
729                                 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);
730
731                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
732
733                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
734                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
735                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
736                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
737
738                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
739                                 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_vec());
740
741                                 res.push(htlc_timeout_tx);
742                         } else {
743                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
744                                         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);
745
746                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
747
748                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
749                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
750                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
751                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
752
753                                         htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
754                                         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_vec());
755
756                                         res.push(htlc_success_tx);
757                                 }
758                         }
759                 }
760
761                 res
762         }
763
764         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
765         /// revoked using data in local_claimable_outpoints.
766         /// Should not be used if check_spend_revoked_transaction succeeds.
767         fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
768                 let commitment_txid = tx.txid();
769                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
770                         if local_tx.txid == commitment_txid {
771                                 return self.broadcast_by_local_state(local_tx);
772                         }
773                 }
774                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
775                         if local_tx.txid == commitment_txid {
776                                 return self.broadcast_by_local_state(local_tx);
777                         }
778                 }
779                 Vec::new()
780         }
781
782         fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface) {
783                 for tx in txn_matched {
784                         for txin in tx.input.iter() {
785                                 if self.funding_txo.is_none() || (txin.prev_hash == self.funding_txo.unwrap().txid && txin.prev_index == self.funding_txo.unwrap().index as u32) {
786                                         let mut txn = self.check_spend_remote_transaction(tx, height);
787                                         if txn.is_empty() {
788                                                 txn = self.check_spend_local_transaction(tx, height);
789                                         }
790                                         for tx in txn.iter() {
791                                                 broadcaster.broadcast_transaction(tx);
792                                         }
793                                 }
794                         }
795                 }
796                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
797                         let mut needs_broadcast = false;
798                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
799                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
800                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
801                                                 needs_broadcast = true;
802                                         }
803                                 }
804                         }
805
806                         if needs_broadcast {
807                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
808                                 for tx in self.broadcast_by_local_state(&cur_local_tx) {
809                                         broadcaster.broadcast_transaction(&tx);
810                                 }
811                         }
812                 }
813         }
814
815         pub fn would_broadcast_at_height(&self, height: u32) -> bool {
816                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
817                         for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
818                                 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
819                                         if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
820                                                 return true;
821                                         }
822                                 }
823                         }
824                 }
825                 false
826         }
827 }
828
829 #[cfg(test)]
830 mod tests {
831         use bitcoin::util::misc::hex_bytes;
832         use bitcoin::blockdata::script::Script;
833         use bitcoin::util::hash::{Hash160,Sha256dHash};
834         use bitcoin::blockdata::transaction::Transaction;
835         use ln::channelmonitor::ChannelMonitor;
836         use ln::channelmonitor::LocalSignedTx;
837         use ln::chan_utils::HTLCOutputInCommitment;
838         use secp256k1::key::{SecretKey,PublicKey};
839         use secp256k1::{Secp256k1, Signature};
840         use rand::{thread_rng,Rng};
841         use std::collections::HashMap;
842
843         #[test]
844         fn test_per_commitment_storage() {
845                 // Test vectors from BOLT 3:
846                 let mut secrets: Vec<[u8; 32]> = Vec::new();
847                 let mut monitor: ChannelMonitor;
848                 let secp_ctx = Secp256k1::new();
849
850                 macro_rules! test_secrets {
851                         () => {
852                                 let mut idx = 281474976710655;
853                                 for secret in secrets.iter() {
854                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
855                                         idx -= 1;
856                                 }
857                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
858                                 assert!(monitor.get_secret(idx).is_err());
859                         };
860                 }
861
862                 {
863                         // insert_secret correct sequence
864                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
865                         secrets.clear();
866
867                         secrets.push([0; 32]);
868                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
869                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
870                         test_secrets!();
871
872                         secrets.push([0; 32]);
873                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
874                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
875                         test_secrets!();
876
877                         secrets.push([0; 32]);
878                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
879                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
880                         test_secrets!();
881
882                         secrets.push([0; 32]);
883                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
884                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
885                         test_secrets!();
886
887                         secrets.push([0; 32]);
888                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
889                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
890                         test_secrets!();
891
892                         secrets.push([0; 32]);
893                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
894                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
895                         test_secrets!();
896
897                         secrets.push([0; 32]);
898                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
899                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
900                         test_secrets!();
901
902                         secrets.push([0; 32]);
903                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
904                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
905                         test_secrets!();
906                 }
907
908                 {
909                         // insert_secret #1 incorrect
910                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
911                         secrets.clear();
912
913                         secrets.push([0; 32]);
914                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
915                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
916                         test_secrets!();
917
918                         secrets.push([0; 32]);
919                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
920                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
921                                         "Previous secret did not match new one");
922                 }
923
924                 {
925                         // insert_secret #2 incorrect (#1 derived from incorrect)
926                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
927                         secrets.clear();
928
929                         secrets.push([0; 32]);
930                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
931                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
932                         test_secrets!();
933
934                         secrets.push([0; 32]);
935                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
936                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
937                         test_secrets!();
938
939                         secrets.push([0; 32]);
940                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
941                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
942                         test_secrets!();
943
944                         secrets.push([0; 32]);
945                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
946                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
947                                         "Previous secret did not match new one");
948                 }
949
950                 {
951                         // insert_secret #3 incorrect
952                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
953                         secrets.clear();
954
955                         secrets.push([0; 32]);
956                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
957                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
958                         test_secrets!();
959
960                         secrets.push([0; 32]);
961                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
962                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
963                         test_secrets!();
964
965                         secrets.push([0; 32]);
966                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
967                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
968                         test_secrets!();
969
970                         secrets.push([0; 32]);
971                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
972                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
973                                         "Previous secret did not match new one");
974                 }
975
976                 {
977                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
978                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
979                         secrets.clear();
980
981                         secrets.push([0; 32]);
982                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
983                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
984                         test_secrets!();
985
986                         secrets.push([0; 32]);
987                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
988                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
989                         test_secrets!();
990
991                         secrets.push([0; 32]);
992                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
993                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
994                         test_secrets!();
995
996                         secrets.push([0; 32]);
997                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
998                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
999                         test_secrets!();
1000
1001                         secrets.push([0; 32]);
1002                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1003                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1004                         test_secrets!();
1005
1006                         secrets.push([0; 32]);
1007                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1008                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1009                         test_secrets!();
1010
1011                         secrets.push([0; 32]);
1012                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1013                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1014                         test_secrets!();
1015
1016                         secrets.push([0; 32]);
1017                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1018                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1019                                         "Previous secret did not match new one");
1020                 }
1021
1022                 {
1023                         // insert_secret #5 incorrect
1024                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1025                         secrets.clear();
1026
1027                         secrets.push([0; 32]);
1028                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1029                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1030                         test_secrets!();
1031
1032                         secrets.push([0; 32]);
1033                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1034                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1035                         test_secrets!();
1036
1037                         secrets.push([0; 32]);
1038                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1039                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1040                         test_secrets!();
1041
1042                         secrets.push([0; 32]);
1043                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1044                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1045                         test_secrets!();
1046
1047                         secrets.push([0; 32]);
1048                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1049                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1050                         test_secrets!();
1051
1052                         secrets.push([0; 32]);
1053                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1054                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1055                                         "Previous secret did not match new one");
1056                 }
1057
1058                 {
1059                         // insert_secret #6 incorrect (5 derived from incorrect)
1060                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1061                         secrets.clear();
1062
1063                         secrets.push([0; 32]);
1064                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1065                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1066                         test_secrets!();
1067
1068                         secrets.push([0; 32]);
1069                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1070                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1071                         test_secrets!();
1072
1073                         secrets.push([0; 32]);
1074                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1075                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1076                         test_secrets!();
1077
1078                         secrets.push([0; 32]);
1079                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1080                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1081                         test_secrets!();
1082
1083                         secrets.push([0; 32]);
1084                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1085                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1086                         test_secrets!();
1087
1088                         secrets.push([0; 32]);
1089                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1090                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1091                         test_secrets!();
1092
1093                         secrets.push([0; 32]);
1094                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1095                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1096                         test_secrets!();
1097
1098                         secrets.push([0; 32]);
1099                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1100                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1101                                         "Previous secret did not match new one");
1102                 }
1103
1104                 {
1105                         // insert_secret #7 incorrect
1106                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1107                         secrets.clear();
1108
1109                         secrets.push([0; 32]);
1110                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1111                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1112                         test_secrets!();
1113
1114                         secrets.push([0; 32]);
1115                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1116                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1117                         test_secrets!();
1118
1119                         secrets.push([0; 32]);
1120                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1121                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1122                         test_secrets!();
1123
1124                         secrets.push([0; 32]);
1125                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1126                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1127                         test_secrets!();
1128
1129                         secrets.push([0; 32]);
1130                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1131                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1132                         test_secrets!();
1133
1134                         secrets.push([0; 32]);
1135                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1136                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1137                         test_secrets!();
1138
1139                         secrets.push([0; 32]);
1140                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1141                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1142                         test_secrets!();
1143
1144                         secrets.push([0; 32]);
1145                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1146                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1147                                         "Previous secret did not match new one");
1148                 }
1149
1150                 {
1151                         // insert_secret #8 incorrect
1152                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1153                         secrets.clear();
1154
1155                         secrets.push([0; 32]);
1156                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1157                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1158                         test_secrets!();
1159
1160                         secrets.push([0; 32]);
1161                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1162                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1163                         test_secrets!();
1164
1165                         secrets.push([0; 32]);
1166                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1167                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1168                         test_secrets!();
1169
1170                         secrets.push([0; 32]);
1171                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1172                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1173                         test_secrets!();
1174
1175                         secrets.push([0; 32]);
1176                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1177                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1178                         test_secrets!();
1179
1180                         secrets.push([0; 32]);
1181                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1182                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1183                         test_secrets!();
1184
1185                         secrets.push([0; 32]);
1186                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1187                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1188                         test_secrets!();
1189
1190                         secrets.push([0; 32]);
1191                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1192                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1193                                         "Previous secret did not match new one");
1194                 }
1195         }
1196
1197         macro_rules! gen_local_tx {
1198                 ($hex : expr, $monitor : expr, $htlcs : expr, $rng : expr, $preimage : expr, $hash : expr) => {
1199                         {
1200
1201                                 let mut htlcs = Vec::new();
1202
1203                                 for _i in 0..$htlcs {
1204                                         $rng.fill_bytes(&mut $preimage);
1205                                         $hash[0..20].clone_from_slice(&Hash160::from_data(&$preimage)[0..20]);
1206                                         $monitor.provide_payment_preimage(&$hash, &$preimage);
1207                                         htlcs.push((HTLCOutputInCommitment {
1208                                                 offered : true,
1209                                                 amount_msat : 0,
1210                                                 cltv_expiry : 0,
1211                                                 payment_hash : $hash.clone(),
1212                                                 transaction_output_index : 0,
1213                                         }, Signature::from_der(&Secp256k1::new(), $hex).unwrap(),
1214                                         Signature::from_der(&Secp256k1::new(), $hex).unwrap()))
1215                                 }
1216
1217                                 Some(LocalSignedTx {
1218                                         txid: Sha256dHash::from_data(&[]),
1219                                         tx: Transaction {
1220                                                 version: 0,
1221                                                 lock_time: 0,
1222                                                 input: Vec::new(),
1223                                                 output: Vec::new(),
1224                                         },
1225                                         revocation_key: PublicKey::new(),
1226                                         a_htlc_key: PublicKey::new(),
1227                                         b_htlc_key: PublicKey::new(),
1228                                         delayed_payment_key: PublicKey::new(),
1229                                         feerate_per_kw: 0,
1230                                         htlc_outputs: htlcs,
1231                                 })
1232                         }
1233                 }
1234         }
1235
1236         macro_rules! gen_remote_outpoints {
1237                 ($monitor : expr, $tx : expr, $htlcs : expr, $rng : expr, $preimage : expr, $hash: expr, $number : expr) => {
1238                         {
1239                                 let mut commitment_number = $number;
1240
1241                                 for i in 0..$tx {
1242
1243                                         let tx_zero = Transaction {
1244                                                 version : 0,
1245                                                 lock_time : i,
1246                                                 input : Vec::new(),
1247                                                 output: Vec::new(),
1248                                         };
1249
1250                                         let mut htlcs = Vec::new();
1251
1252                                         for _i in 0..$htlcs {
1253                                                 $rng.fill_bytes(&mut $preimage);
1254                                                 $hash[0..20].clone_from_slice(&Hash160::from_data(&$preimage)[0..20]);
1255                                                 $monitor.provide_payment_preimage(&$hash, &$preimage);
1256                                                 htlcs.push(HTLCOutputInCommitment {
1257                                                         offered : true,
1258                                                         amount_msat : 0,
1259                                                         cltv_expiry : 0,
1260                                                         payment_hash : $hash.clone(),
1261                                                         transaction_output_index : 0,
1262                                                 });
1263                                         }
1264                                         commitment_number -= 1;
1265                                         $monitor.provide_latest_remote_commitment_tx_info(&tx_zero, htlcs, commitment_number);
1266                                 }
1267                         }
1268                 }
1269         }
1270
1271         #[test]
1272         fn test_prune_preimages() {
1273
1274                 let mut monitor: ChannelMonitor;
1275                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1276                 let secp_ctx = Secp256k1::new();
1277                 let mut preimage: [u8;32] = [0;32];
1278                 let mut hash: [u8;32] = [0;32];
1279                 let mut rng  = thread_rng();
1280
1281                 {
1282                         // insert 30 random hash, 10 from local, 10 from remote, prune 30/50
1283                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1284
1285                         for _i in 0..30 {
1286                                 rng.fill_bytes(&mut preimage);
1287                                 hash[0..20].clone_from_slice(&Hash160::from_data(&preimage)[0..20]);
1288                                 monitor.provide_payment_preimage(&hash, &preimage);
1289                         }
1290                         monitor.current_local_signed_commitment_tx = gen_local_tx!(&hex_bytes("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..], monitor, 10, rng, preimage, hash);
1291                         gen_remote_outpoints!(monitor, 1, 10, rng, preimage, hash, 281474976710654);
1292                         secrets.clear();
1293                         secrets.push([0; 32]);
1294                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1295                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None);
1296                         assert_eq!(monitor.payment_preimages.len(), 20);
1297                 }
1298
1299
1300                 {
1301                         // insert 30 random hash, prune 30/30
1302                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1303
1304                         for _i in 0..30 {
1305                                 rng.fill_bytes(&mut preimage);
1306                                 hash[0..20].clone_from_slice(&Hash160::from_data(&preimage)[0..20]);
1307                                 monitor.provide_payment_preimage(&hash, &preimage);
1308                         }
1309                         monitor.current_local_signed_commitment_tx = gen_local_tx!(&hex_bytes("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..], monitor, 0, rng, preimage, hash);
1310                         gen_remote_outpoints!(monitor, 0, 0, rng, preimage, hash, 281474976710655);
1311                         secrets.clear();
1312                         secrets.push([0; 32]);
1313                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1314                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None);
1315                         assert_eq!(monitor.payment_preimages.len(), 0);
1316                 }
1317
1318                 {
1319                         // insert 30 random hash, 25 on 5 remotes, prune 30/55
1320                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1321
1322                         for _i in 0..30 {
1323                                 rng.fill_bytes(&mut preimage);
1324                                 hash[0..20].clone_from_slice(&Hash160::from_data(&preimage)[0..20]);
1325                                 monitor.provide_payment_preimage(&hash, &preimage);
1326                         }
1327                         monitor.current_local_signed_commitment_tx = gen_local_tx!(&hex_bytes("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..], monitor, 0, rng, preimage, hash);
1328                         gen_remote_outpoints!(monitor, 5, 5, rng, preimage, hash, 281474976710654);
1329                         secrets.clear();
1330                         secrets.push([0; 32]);
1331                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1332                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None);
1333                         assert_eq!(monitor.payment_preimages.len(), 25);
1334                 }
1335
1336                 {
1337                         // insert 30 random hash, 25 from local, prune 30/55
1338                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1339
1340                         for _i in 0..30 {
1341                                 rng.fill_bytes(&mut preimage);
1342                                 hash[0..20].clone_from_slice(&Hash160::from_data(&preimage)[0..20]);
1343                                 monitor.provide_payment_preimage(&hash, &preimage);
1344                         }
1345                         monitor.current_local_signed_commitment_tx = gen_local_tx!(&hex_bytes("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..], monitor, 25, rng, preimage, hash);
1346                         gen_remote_outpoints!(monitor, 0, 0, rng, preimage, hash, 281474976710655);
1347                         secrets.clear();
1348                         secrets.push([0; 32]);
1349                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1350                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None);
1351                         assert_eq!(monitor.payment_preimages.len(), 25);
1352                 }
1353         }
1354
1355         // Further testing is done in the ChannelManager integration tests.
1356 }