e463b936e61011dd5b2adfab2ef2f87d387495d0
[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::sha2::Sha256;
8 use crypto::digest::Digest;
9
10 use secp256k1::{Secp256k1,Message,Signature};
11 use secp256k1::key::{SecretKey,PublicKey};
12
13 use ln::msgs::HandleError;
14 use ln::chan_utils;
15 use ln::chan_utils::HTLCOutputInCommitment;
16 use chain::chaininterface::{ChainListener,ChainWatchInterface};
17
18 use std::collections::HashMap;
19 use std::sync::{Arc,Mutex};
20 use std::{hash,cmp};
21
22 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
23 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
24 /// events to it, while also taking any add_update_monitor events and passing them to some remote
25 /// server(s).
26 pub trait ManyChannelMonitor: Send + Sync {
27         /// Adds or updates a monitor for the given funding_txid+funding_output_index.
28         fn add_update_monitor(&self, funding_txo: (Sha256dHash, u16), monitor: ChannelMonitor) -> Result<(), HandleError>;
29 }
30
31 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
32 /// watchtower or watch our own channels.
33 /// Note that you must provide your own key by which to refer to channels.
34 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
35 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
36 /// index by a PublicKey which is required to sign any updates.
37 /// If you're using this for local monitoring of your own channels, you probably want to use
38 /// (Sha256dHash, u16) as the key, which will give you a ManyChannelMonitor implementation.
39 pub struct SimpleManyChannelMonitor<Key> {
40         monitors: Mutex<HashMap<Key, ChannelMonitor>>,
41         chain_monitor: Arc<ChainWatchInterface>,
42 }
43
44 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
45         fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
46                 let monitors = self.monitors.lock().unwrap();
47                 for monitor in monitors.values() {
48                         monitor.block_connected(txn_matched, height, &*self.chain_monitor);
49                 }
50         }
51
52         fn block_disconnected(&self, _: &BlockHeader) { }
53 }
54
55 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
56         pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
57                 let res = Arc::new(SimpleManyChannelMonitor {
58                         monitors: Mutex::new(HashMap::new()),
59                         chain_monitor: chain_monitor,
60                 });
61                 let weak_res = Arc::downgrade(&res);
62                 res.chain_monitor.register_listener(weak_res);
63                 res
64         }
65
66         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
67                 let mut monitors = self.monitors.lock().unwrap();
68                 match monitors.get_mut(&key) {
69                         Some(orig_monitor) => return orig_monitor.insert_combine(monitor),
70                         None => {}
71                 };
72                 match monitor.funding_txo {
73                         None => self.chain_monitor.watch_all_txn(),
74                         Some((funding_txid, funding_output_index)) => self.chain_monitor.install_watch_outpoint((funding_txid, funding_output_index as u32)),
75                 }
76                 monitors.insert(key, monitor);
77                 Ok(())
78         }
79 }
80
81 impl ManyChannelMonitor for SimpleManyChannelMonitor<(Sha256dHash, u16)> {
82         fn add_update_monitor(&self, funding_txo: (Sha256dHash, u16), monitor: ChannelMonitor) -> Result<(), HandleError> {
83                 self.add_update_monitor_by_key(funding_txo, monitor)
84         }
85 }
86
87 /// If an HTLC expires within this many blocks, don't try to claim it directly, instead broadcast
88 /// the HTLC-Success/HTLC-Timeout transaction and claim the revocation from that.
89 const CLTV_CLAIM_BUFFER: u32 = 12;
90
91 #[derive(Clone)]
92 enum RevocationStorage {
93         PrivMode {
94                 revocation_base_key: SecretKey,
95         },
96         SigsMode {
97                 revocation_base_key: PublicKey,
98                 sigs: HashMap<Sha256dHash, Signature>,
99         }
100 }
101
102 #[derive(Clone)]
103 struct PerCommitmentTransactionData {
104         revoked_output_index: u32,
105         htlcs: Vec<(HTLCOutputInCommitment, Signature)>,
106 }
107
108 #[derive(Clone)]
109 pub struct ChannelMonitor {
110         funding_txo: Option<(Sha256dHash, u16)>,
111         commitment_transaction_number_obscure_factor: u64,
112
113         revocation_base_key: RevocationStorage,
114         delayed_payment_base_key: PublicKey,
115         htlc_base_key: PublicKey,
116         their_htlc_base_key: Option<PublicKey>,
117         to_self_delay: u16,
118
119         old_secrets: [([u8; 32], u64); 49],
120         claimable_outpoints: HashMap<Sha256dHash, PerCommitmentTransactionData>,
121         payment_preimages: Vec<[u8; 32]>,
122
123         destination_script: Script,
124         secp_ctx: Secp256k1, //TODO: dedup this a bit...
125 }
126
127 impl ChannelMonitor {
128         pub fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &PublicKey, htlc_base_key: &PublicKey, to_self_delay: u16, destination_script: Script) -> ChannelMonitor {
129                 ChannelMonitor {
130                         funding_txo: None,
131                         commitment_transaction_number_obscure_factor: 0,
132
133                         revocation_base_key: RevocationStorage::PrivMode {
134                                 revocation_base_key: revocation_base_key.clone(),
135                         },
136                         delayed_payment_base_key: delayed_payment_base_key.clone(),
137                         htlc_base_key: htlc_base_key.clone(),
138                         their_htlc_base_key: None,
139                         to_self_delay: to_self_delay,
140
141                         old_secrets: [([0; 32], 1 << 48); 49],
142                         claimable_outpoints: HashMap::new(),
143                         payment_preimages: Vec::new(),
144
145                         destination_script: destination_script,
146                         secp_ctx: Secp256k1::new(),
147                 }
148         }
149
150         #[inline]
151         fn place_secret(idx: u64) -> u8 {
152                 for i in 0..48 {
153                         if idx & (1 << i) == (1 << i) {
154                                 return i
155                         }
156                 }
157                 48
158         }
159
160         #[inline]
161         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
162                 let mut res: [u8; 32] = secret;
163                 for i in 0..bits {
164                         let bitpos = bits - 1 - i;
165                         if idx & (1 << bitpos) == (1 << bitpos) {
166                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
167                                 let mut sha = Sha256::new();
168                                 sha.input(&res);
169                                 sha.result(&mut res);
170                         }
171                 }
172                 res
173         }
174
175         /// Inserts a revocation secret into this channel monitor. Requires the revocation_base_key of
176         /// the node which we are monitoring the channel on behalf of in order to generate signatures
177         /// over revocation-claim transactions.
178         pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), HandleError> {
179                 let pos = ChannelMonitor::place_secret(idx);
180                 for i in 0..pos {
181                         let (old_secret, old_idx) = self.old_secrets[i as usize];
182                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
183                                 return Err(HandleError{err: "Previous secret did not match new one", msg: None})
184                         }
185                 }
186                 self.old_secrets[pos as usize] = (secret, idx);
187                 Ok(())
188         }
189
190         /// Informs this watcher of the set of HTLC outputs in a commitment transaction which our
191         /// counterparty may broadcast. This allows us to reconstruct the commitment transaction's
192         /// outputs fully, claiming revoked, unexpired HTLC outputs as well as revoked refund outputs.
193         /// TODO: Doc new params!
194         /// TODO: This seems to be wrong...we should be calling this from commitment_signed, but we
195         /// should be calling this about remote transactions, ie ones that they can revoke_and_ack...
196         pub fn provide_tx_info(&mut self, commitment_tx: &Transaction, revokeable_out_index: u32, htlc_outputs: Vec<(HTLCOutputInCommitment, Signature)>) {
197                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
198                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
199                 self.claimable_outpoints.insert(commitment_tx.txid(), PerCommitmentTransactionData{
200                         revoked_output_index: revokeable_out_index,
201                         htlcs: htlc_outputs
202                 });
203         }
204
205         pub fn insert_combine(&mut self, other: ChannelMonitor) -> Result<(), HandleError> {
206                 match self.funding_txo {
207                         Some(txo) => if other.funding_txo.is_some() && other.funding_txo.unwrap() != txo {
208                                 return Err(HandleError{err: "Funding transaction outputs are not identical!", msg: None});
209                         },
210                         None => if other.funding_txo.is_some() {
211                                 self.funding_txo = other.funding_txo;
212                         }
213                 }
214                 let other_max_secret = other.get_min_seen_secret();
215                 if self.get_min_seen_secret() > other_max_secret {
216                         self.provide_secret(other_max_secret, other.get_secret(other_max_secret).unwrap())
217                 } else { Ok(()) }
218         }
219
220         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
221         pub fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
222                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
223                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
224         }
225
226         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
227         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
228         /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
229         /// provides slightly better privacy.
230         pub fn set_funding_info(&mut self, funding_txid: Sha256dHash, funding_output_index: u16) {
231                 self.funding_txo = Some((funding_txid, funding_output_index));
232         }
233
234         pub fn set_their_htlc_base_key(&mut self, their_htlc_base_key: &PublicKey) {
235                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
236         }
237
238         pub fn unset_funding_info(&mut self) {
239                 self.funding_txo = None;
240         }
241
242         pub fn get_funding_txo(&self) -> Option<(Sha256dHash, u16)> {
243                 self.funding_txo
244         }
245
246         //TODO: Functions to serialize/deserialize (with different forms depending on which information
247         //we want to leave out (eg funding_txo, etc).
248
249         /// Can only fail if idx is < get_min_seen_secret
250         pub fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
251                 for i in 0..self.old_secrets.len() {
252                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
253                                 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
254                         }
255                 }
256                 assert!(idx < self.get_min_seen_secret());
257                 Err(HandleError{err: "idx too low", msg: None})
258         }
259
260         pub fn get_min_seen_secret(&self) -> u64 {
261                 //TODO This can be optimized?
262                 let mut min = 1 << 48;
263                 for &(_, idx) in self.old_secrets.iter() {
264                         if idx < min {
265                                 min = idx;
266                         }
267                 }
268                 min
269         }
270
271         #[inline]
272         fn check_spend_transaction(&self, tx: &Transaction, height: u32) -> Vec<Transaction> {
273                 // Most secp and related errors trying to create keys means we have no hope of constructing
274                 // a spend transaction...so we return no transactions to broadcast
275                 macro_rules! ignore_error {
276                         ( $thing : expr ) => {
277                                 match $thing {
278                                         Ok(a) => a,
279                                         Err(_) => return Vec::new()
280                                 }
281                         };
282                 }
283
284                 let mut txn_to_broadcast = Vec::new();
285
286                 let commitment_number = (((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor;
287                 if commitment_number >= self.get_min_seen_secret() {
288                         let secret = self.get_secret(commitment_number).unwrap();
289                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
290                         let revocation_pubkey = match self.revocation_base_key {
291                                 RevocationStorage::PrivMode { ref revocation_base_key } => {
292                                         ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key)), &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))))
293                                 },
294                                 RevocationStorage::SigsMode { ref revocation_base_key, .. } => {
295                                         ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key)), &revocation_base_key))
296                                 },
297                         };
298                         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));
299                         let a_htlc_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key)), &self.htlc_base_key));
300                         let b_htlc_key = match self.their_htlc_base_key {
301                                 None => return Vec::new(),
302                                 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)),
303                         };
304
305                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.to_self_delay, &delayed_key);
306
307                         let commitment_txid = tx.txid();
308
309                         let mut total_value = 0;
310                         let mut values = Vec::new();
311                         let inputs = match self.claimable_outpoints.get(&commitment_txid) {
312                                 Some(per_commitment_data) => {
313                                         let mut inp = Vec::with_capacity(per_commitment_data.htlcs.len() + 1);
314
315                                         if per_commitment_data.revoked_output_index as usize >= tx.output.len() || tx.output[per_commitment_data.revoked_output_index as usize].script_pubkey != revokeable_redeemscript.to_v0_p2wsh() {
316                                                 return Vec::new(); // Corrupted per_commitment_data, not much we can do
317                                         }
318
319                                         inp.push(TxIn {
320                                                 prev_hash: commitment_txid,
321                                                 prev_index: per_commitment_data.revoked_output_index,
322                                                 script_sig: Script::new(),
323                                                 sequence: 0xffffffff,
324                                         });
325                                         values.push(tx.output[per_commitment_data.revoked_output_index as usize].value);
326                                         total_value += tx.output[per_commitment_data.revoked_output_index as usize].value;
327
328                                         for &(ref htlc, ref _next_tx_sig) in per_commitment_data.htlcs.iter() {
329                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey, htlc.offered);
330                                                 if htlc.transaction_output_index as usize >= tx.output.len() ||
331                                                                 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
332                                                                 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
333                                                         return Vec::new(); // Corrupted per_commitment_data, fuck this user
334                                                 }
335                                                 if htlc.cltv_expiry > height + CLTV_CLAIM_BUFFER {
336                                                         inp.push(TxIn {
337                                                                 prev_hash: commitment_txid,
338                                                                 prev_index: htlc.transaction_output_index,
339                                                                 script_sig: Script::new(),
340                                                                 sequence: 0xffffffff,
341                                                         });
342                                                         values.push(tx.output[htlc.transaction_output_index as usize].value);
343                                                         total_value += htlc.amount_msat / 1000;
344                                                 } else {
345                                                         //TODO: Mark as "bad"
346                                                         //then broadcast using next_tx_sig
347                                                 }
348                                         }
349                                         inp
350                                 }, None => {
351                                         let mut inp = Vec::new(); // This is unlikely to succeed
352                                         for (idx, outp) in tx.output.iter().enumerate() {
353                                                 if outp.script_pubkey == revokeable_redeemscript.to_v0_p2wsh() {
354                                                         inp.push(TxIn {
355                                                                 prev_hash: commitment_txid,
356                                                                 prev_index: idx as u32,
357                                                                 script_sig: Script::new(),
358                                                                 sequence: 0xffffffff,
359                                                         });
360                                                         values.push(outp.value);
361                                                         total_value += outp.value;
362                                                         break; // There can only be one of these
363                                                 }
364                                         }
365                                         if inp.is_empty() { return Vec::new(); } // Nothing to be done...probably a false positive
366                                         inp
367                                 }
368                         };
369
370                         let outputs = vec!(TxOut {
371                                 script_pubkey: self.destination_script.clone(),
372                                 value: total_value, //TODO: - fee
373                         });
374                         let mut spend_tx = Transaction {
375                                 version: 2,
376                                 lock_time: 0,
377                                 input: inputs,
378                                 output: outputs,
379                                 witness: Vec::new(),
380                         };
381
382                         let mut values_drain = values.drain(..);
383
384                         // First input is the generic revokeable_redeemscript
385                         // TODO: Make one SighashComponents and use that throughout instead of re-building it
386                         // each time.
387                         {
388                                 let sig = match self.revocation_base_key {
389                                         RevocationStorage::PrivMode { ref revocation_base_key } => {
390                                                 let sighash = ignore_error!(Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx, 0, &revokeable_redeemscript, values_drain.next().unwrap())[..]));
391                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
392                                                 ignore_error!(self.secp_ctx.sign(&sighash, &revocation_key))
393                                         },
394                                         RevocationStorage::SigsMode { .. } => {
395                                                 unimplemented!();
396                                         }
397                                 };
398
399                                 spend_tx.witness.push(Vec::new());
400                                 spend_tx.witness[0].push(sig.serialize_der(&self.secp_ctx).to_vec());
401                                 spend_tx.witness[0][0].push(SigHashType::All as u8);
402                                 spend_tx.witness[0].push(vec!(1)); // First if branch is revocation_key
403                         }
404
405                         match self.claimable_outpoints.get(&commitment_txid) {
406                                 None => {},
407                                 Some(per_commitment_data) => {
408                                         let mut htlc_idx = 0;
409                                         for (idx, _) in spend_tx.input.iter().enumerate() {
410                                                 if idx == 0 { continue; } // We already signed the first input
411
412                                                 let mut htlc;
413                                                 while {
414                                                         htlc = &per_commitment_data.htlcs[htlc_idx].0;
415                                                         htlc_idx += 1;
416                                                         htlc.cltv_expiry > height + CLTV_CLAIM_BUFFER
417                                                 } {}
418
419                                                 let sig = match self.revocation_base_key {
420                                                         RevocationStorage::PrivMode { ref revocation_base_key } => {
421                                                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey, htlc.offered);
422                                                                 let sighash = ignore_error!(Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx, idx, &htlc_redeemscript, values_drain.next().unwrap())[..]));
423
424                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
425                                                                 ignore_error!(self.secp_ctx.sign(&sighash, &revocation_key))
426                                                         },
427                                                         RevocationStorage::SigsMode { .. } => {
428                                                                 unimplemented!();
429                                                         }
430                                                 };
431
432                                                 spend_tx.witness.push(Vec::new());
433                                                 spend_tx.witness[0].push(revocation_pubkey.serialize().to_vec()); // First if branch is revocation_key
434                                                 spend_tx.witness[0].push(sig.serialize_der(&self.secp_ctx).to_vec());
435                                                 spend_tx.witness[0][0].push(SigHashType::All as u8);
436                                         }
437                                 }
438                         }
439
440                         txn_to_broadcast.push(spend_tx);
441                 }
442
443                 txn_to_broadcast
444         }
445
446         fn block_connected(&self, txn_matched: &[&Transaction], height: u32, chain_monitor: &ChainWatchInterface) {
447                 for tx in txn_matched {
448                         if tx.input.len() != 1 {
449                                 // We currently only ever sign something spending a commitment or HTLC
450                                 // transaction with 1 input, so we can skip most transactions trivially.
451                                 continue;
452                         }
453
454                         for txin in tx.input.iter() {
455                                 if self.funding_txo.is_none() || (txin.prev_hash == self.funding_txo.unwrap().0 && txin.prev_index == self.funding_txo.unwrap().1 as u32) {
456                                         for tx in self.check_spend_transaction(tx, height).iter() {
457                                                 chain_monitor.broadcast_transaction(tx);
458                                         }
459                                 }
460                         }
461                 }
462         }
463 }
464
465 #[cfg(test)]
466 mod tests {
467         use bitcoin::util::misc::hex_bytes;
468         use bitcoin::blockdata::script::Script;
469         use ln::channelmonitor::ChannelMonitor;
470         use secp256k1::key::{SecretKey,PublicKey};
471         use secp256k1::Secp256k1;
472
473         #[test]
474         fn test_per_commitment_storage() {
475                 // Test vectors from BOLT 3:
476                 let mut secrets: Vec<[u8; 32]> = Vec::new();
477                 let mut monitor: ChannelMonitor;
478                 let secp_ctx = Secp256k1::new();
479
480                 macro_rules! test_secrets {
481                         () => {
482                                 let mut idx = 281474976710655;
483                                 for secret in secrets.iter() {
484                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
485                                         idx -= 1;
486                                 }
487                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
488                                 assert!(monitor.get_secret(idx).is_err());
489                         };
490                 }
491
492                 {
493                         // insert_secret correct sequence
494                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
495                         secrets.clear();
496
497                         secrets.push([0; 32]);
498                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
499                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
500                         test_secrets!();
501
502                         secrets.push([0; 32]);
503                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
504                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
505                         test_secrets!();
506
507                         secrets.push([0; 32]);
508                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
509                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
510                         test_secrets!();
511
512                         secrets.push([0; 32]);
513                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
514                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
515                         test_secrets!();
516
517                         secrets.push([0; 32]);
518                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
519                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
520                         test_secrets!();
521
522                         secrets.push([0; 32]);
523                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
524                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
525                         test_secrets!();
526
527                         secrets.push([0; 32]);
528                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
529                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
530                         test_secrets!();
531
532                         secrets.push([0; 32]);
533                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
534                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
535                         test_secrets!();
536                 }
537
538                 {
539                         // insert_secret #1 incorrect
540                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
541                         secrets.clear();
542
543                         secrets.push([0; 32]);
544                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
545                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
546                         test_secrets!();
547
548                         secrets.push([0; 32]);
549                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
550                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().err,
551                                         "Previous secret did not match new one");
552                 }
553
554                 {
555                         // insert_secret #2 incorrect (#1 derived from incorrect)
556                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
557                         secrets.clear();
558
559                         secrets.push([0; 32]);
560                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
561                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
562                         test_secrets!();
563
564                         secrets.push([0; 32]);
565                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
566                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
567                         test_secrets!();
568
569                         secrets.push([0; 32]);
570                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
571                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
572                         test_secrets!();
573
574                         secrets.push([0; 32]);
575                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
576                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().err,
577                                         "Previous secret did not match new one");
578                 }
579
580                 {
581                         // insert_secret #3 incorrect
582                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
583                         secrets.clear();
584
585                         secrets.push([0; 32]);
586                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
587                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
588                         test_secrets!();
589
590                         secrets.push([0; 32]);
591                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
592                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
593                         test_secrets!();
594
595                         secrets.push([0; 32]);
596                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
597                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
598                         test_secrets!();
599
600                         secrets.push([0; 32]);
601                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
602                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().err,
603                                         "Previous secret did not match new one");
604                 }
605
606                 {
607                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
608                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
609                         secrets.clear();
610
611                         secrets.push([0; 32]);
612                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
613                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
614                         test_secrets!();
615
616                         secrets.push([0; 32]);
617                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
618                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
619                         test_secrets!();
620
621                         secrets.push([0; 32]);
622                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
623                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
624                         test_secrets!();
625
626                         secrets.push([0; 32]);
627                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
628                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
629                         test_secrets!();
630
631                         secrets.push([0; 32]);
632                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
633                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
634                         test_secrets!();
635
636                         secrets.push([0; 32]);
637                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
638                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
639                         test_secrets!();
640
641                         secrets.push([0; 32]);
642                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
643                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
644                         test_secrets!();
645
646                         secrets.push([0; 32]);
647                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
648                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().err,
649                                         "Previous secret did not match new one");
650                 }
651
652                 {
653                         // insert_secret #5 incorrect
654                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
655                         secrets.clear();
656
657                         secrets.push([0; 32]);
658                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
659                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
660                         test_secrets!();
661
662                         secrets.push([0; 32]);
663                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
664                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
665                         test_secrets!();
666
667                         secrets.push([0; 32]);
668                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
669                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
670                         test_secrets!();
671
672                         secrets.push([0; 32]);
673                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
674                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
675                         test_secrets!();
676
677                         secrets.push([0; 32]);
678                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
679                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
680                         test_secrets!();
681
682                         secrets.push([0; 32]);
683                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
684                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().err,
685                                         "Previous secret did not match new one");
686                 }
687
688                 {
689                         // insert_secret #6 incorrect (5 derived from incorrect)
690                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
691                         secrets.clear();
692
693                         secrets.push([0; 32]);
694                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
695                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
696                         test_secrets!();
697
698                         secrets.push([0; 32]);
699                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
700                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
701                         test_secrets!();
702
703                         secrets.push([0; 32]);
704                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
705                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
706                         test_secrets!();
707
708                         secrets.push([0; 32]);
709                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
710                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
711                         test_secrets!();
712
713                         secrets.push([0; 32]);
714                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
715                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
716                         test_secrets!();
717
718                         secrets.push([0; 32]);
719                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
720                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
721                         test_secrets!();
722
723                         secrets.push([0; 32]);
724                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
725                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
726                         test_secrets!();
727
728                         secrets.push([0; 32]);
729                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
730                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().err,
731                                         "Previous secret did not match new one");
732                 }
733
734                 {
735                         // insert_secret #7 incorrect
736                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
737                         secrets.clear();
738
739                         secrets.push([0; 32]);
740                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
741                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
742                         test_secrets!();
743
744                         secrets.push([0; 32]);
745                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
746                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
747                         test_secrets!();
748
749                         secrets.push([0; 32]);
750                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
751                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
752                         test_secrets!();
753
754                         secrets.push([0; 32]);
755                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
756                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
757                         test_secrets!();
758
759                         secrets.push([0; 32]);
760                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
761                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
762                         test_secrets!();
763
764                         secrets.push([0; 32]);
765                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
766                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
767                         test_secrets!();
768
769                         secrets.push([0; 32]);
770                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
771                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
772                         test_secrets!();
773
774                         secrets.push([0; 32]);
775                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
776                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().err,
777                                         "Previous secret did not match new one");
778                 }
779
780                 {
781                         // insert_secret #8 incorrect
782                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &PublicKey::new(), 0, Script::new());
783                         secrets.clear();
784
785                         secrets.push([0; 32]);
786                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
787                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
788                         test_secrets!();
789
790                         secrets.push([0; 32]);
791                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
792                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
793                         test_secrets!();
794
795                         secrets.push([0; 32]);
796                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
797                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
798                         test_secrets!();
799
800                         secrets.push([0; 32]);
801                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
802                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
803                         test_secrets!();
804
805                         secrets.push([0; 32]);
806                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
807                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
808                         test_secrets!();
809
810                         secrets.push([0; 32]);
811                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
812                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
813                         test_secrets!();
814
815                         secrets.push([0; 32]);
816                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
817                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
818                         test_secrets!();
819
820                         secrets.push([0; 32]);
821                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
822                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().err,
823                                         "Previous secret did not match new one");
824                 }
825         }
826 }