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;
7 use crypto::digest::Digest;
9 use secp256k1::{Secp256k1,Message,Signature};
10 use secp256k1::key::{SecretKey,PublicKey};
12 use ln::msgs::HandleError;
14 use ln::chan_utils::HTLCOutputInCommitment;
15 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
16 use chain::transaction::OutPoint;
17 use util::sha2::Sha256;
19 use std::collections::HashMap;
20 use std::sync::{Arc,Mutex};
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.
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.
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
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>;
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>
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);
72 fn block_disconnected(&self, _: &BlockHeader) { }
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()),
82 let weak_res = Arc::downgrade(&res);
83 res.chain_monitor.register_listener(weak_res);
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),
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)),
97 monitors.insert(key, monitor);
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) {
106 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
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;
121 revocation_base_key: SecretKey,
122 htlc_base_key: SecretKey,
125 revocation_base_key: PublicKey,
126 htlc_base_key: PublicKey,
127 sigs: HashMap<Sha256dHash, Signature>,
132 struct LocalSignedTx {
135 revocation_key: PublicKey,
136 a_htlc_key: PublicKey,
137 b_htlc_key: PublicKey,
138 delayed_payment_key: PublicKey,
140 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
143 pub struct ChannelMonitor {
144 funding_txo: Option<OutPoint>,
145 commitment_transaction_number_obscure_factor: u64,
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>)>,
153 our_to_self_delay: u16,
154 their_to_self_delay: Option<u16>,
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>,
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>,
170 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
172 destination_script: Script,
173 secp_ctx: Secp256k1, //TODO: dedup this a bit...
175 impl Clone for ChannelMonitor {
176 fn clone(&self) -> Self {
178 funding_txo: self.funding_txo.clone(),
179 commitment_transaction_number_obscure_factor: self.commitment_transaction_number_obscure_factor.clone(),
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(),
186 our_to_self_delay: self.our_to_self_delay,
187 their_to_self_delay: self.their_to_self_delay,
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(),
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(),
197 payment_preimages: self.payment_preimages.clone(),
199 destination_script: self.destination_script.clone(),
200 secp_ctx: self.secp_ctx.clone(),
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 {
209 commitment_transaction_number_obscure_factor: 0,
211 key_storage: KeyStorage::PrivMode {
212 revocation_base_key: revocation_base_key.clone(),
213 htlc_base_key: htlc_base_key.clone(),
215 delayed_payment_base_key: delayed_payment_base_key.clone(),
216 their_htlc_base_key: None,
217 their_cur_revocation_points: None,
219 our_to_self_delay: our_to_self_delay,
220 their_to_self_delay: None,
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(),
227 prev_local_signed_commitment_tx: None,
228 current_local_signed_commitment_tx: None,
230 payment_preimages: HashMap::new(),
232 destination_script: destination_script,
233 secp_ctx: Secp256k1::new(),
238 fn place_secret(idx: u64) -> u8 {
240 if idx & (1 << i) == (1 << i) {
248 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
249 let mut res: [u8; 32] = secret;
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();
256 sha.result(&mut res);
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(super) 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);
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})
275 self.old_secrets[pos as usize] = (secret, idx);
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)));
286 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
289 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
293 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
298 if !self.payment_preimages.is_empty() {
299 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
300 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
301 let min_idx = self.get_min_seen_secret();
302 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
304 self.payment_preimages.retain(|&k, _| {
305 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
306 if k == htlc.payment_hash {
310 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
311 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
312 if k == htlc.payment_hash {
317 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
324 remote_hash_commitment_number.remove(&k);
333 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
334 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
335 /// possibly future revocation/preimage information) to claim outputs where possible.
336 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
337 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
338 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
339 // so that a remote monitor doesn't learn anything unless there is a malicious close.
340 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
342 for htlc in &htlc_outputs {
343 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
345 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
348 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
349 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
350 /// is important that any clones of this channel monitor (including remote clones) by kept
351 /// up-to-date as our local commitment transaction is updated.
352 /// Panics if set_their_to_self_delay has never been called.
353 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, signed_commitment_tx: Transaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>) {
354 assert!(self.their_to_self_delay.is_some());
355 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
356 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
357 txid: signed_commitment_tx.txid(),
358 tx: signed_commitment_tx,
359 revocation_key: local_keys.revocation_key,
360 a_htlc_key: local_keys.a_htlc_key,
361 b_htlc_key: local_keys.b_htlc_key,
362 delayed_payment_key: local_keys.a_delayed_payment_key,
368 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
369 /// commitment_tx_infos which contain the payment hash have been revoked.
370 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
371 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
374 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
375 match self.funding_txo {
376 Some(txo) => if other.funding_txo.is_some() && other.funding_txo.unwrap() != txo {
377 return Err(HandleError{err: "Funding transaction outputs are not identical!", msg: None});
379 None => if other.funding_txo.is_some() {
380 self.funding_txo = other.funding_txo;
383 let other_min_secret = other.get_min_seen_secret();
384 let our_min_secret = self.get_min_seen_secret();
385 if our_min_secret > other_min_secret {
386 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
388 if our_min_secret >= other_min_secret {
389 self.their_cur_revocation_points = other.their_cur_revocation_points;
390 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
391 self.remote_claimable_outpoints.insert(txid, htlcs);
393 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
394 self.prev_local_signed_commitment_tx = Some(local_tx);
396 if let Some(local_tx) = other.current_local_signed_commitment_tx {
397 self.current_local_signed_commitment_tx = Some(local_tx);
399 self.payment_preimages = other.payment_preimages;
404 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
405 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
406 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
407 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
410 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
411 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
412 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
413 /// provides slightly better privacy.
414 pub(super) fn set_funding_info(&mut self, funding_info: OutPoint) {
415 self.funding_txo = Some(funding_info);
418 pub(super) fn set_their_htlc_base_key(&mut self, their_htlc_base_key: &PublicKey) {
419 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
422 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
423 self.their_to_self_delay = Some(their_to_self_delay);
426 pub(super) fn unset_funding_info(&mut self) {
427 self.funding_txo = None;
430 pub fn get_funding_txo(&self) -> Option<OutPoint> {
434 //TODO: Functions to serialize/deserialize (with different forms depending on which information
435 //we want to leave out (eg funding_txo, etc).
437 /// Can only fail if idx is < get_min_seen_secret
438 pub fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
439 for i in 0..self.old_secrets.len() {
440 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
441 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
444 assert!(idx < self.get_min_seen_secret());
445 Err(HandleError{err: "idx too low", msg: None})
448 pub fn get_min_seen_secret(&self) -> u64 {
449 //TODO This can be optimized?
450 let mut min = 1 << 48;
451 for &(_, idx) in self.old_secrets.iter() {
459 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
460 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
461 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
462 /// HTLC-Success/HTLC-Timeout transactions, and claim them using the revocation key (if
463 /// applicable) as well.
464 fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> Vec<Transaction> {
465 // Most secp and related errors trying to create keys means we have no hope of constructing
466 // a spend transaction...so we return no transactions to broadcast
467 let mut txn_to_broadcast = Vec::new();
468 macro_rules! ignore_error {
469 ( $thing : expr ) => {
472 Err(_) => return txn_to_broadcast
477 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
478 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
480 let commitment_number = (((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor;
481 if commitment_number >= self.get_min_seen_secret() {
482 let secret = self.get_secret(commitment_number).unwrap();
483 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
484 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
485 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
486 let per_commitment_point = ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key));
487 (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)))),
488 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)))))
490 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
491 let per_commitment_point = ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key));
492 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
493 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
496 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));
497 let a_htlc_key = match self.their_htlc_base_key {
498 None => return txn_to_broadcast,
499 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)),
502 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
503 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
505 let mut total_value = 0;
506 let mut values = Vec::new();
507 let mut inputs = Vec::new();
508 let mut htlc_idxs = Vec::new();
510 for (idx, outp) in tx.output.iter().enumerate() {
511 if outp.script_pubkey == revokeable_p2wsh {
513 prev_hash: commitment_txid,
514 prev_index: idx as u32,
515 script_sig: Script::new(),
516 sequence: 0xfffffffd,
519 htlc_idxs.push(None);
520 values.push(outp.value);
521 total_value += outp.value;
522 break; // There can only be one of these
526 macro_rules! sign_input {
527 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
529 let (sig, redeemscript) = match self.key_storage {
530 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
531 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
532 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
533 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
535 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
536 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
537 (ignore_error!(self.secp_ctx.sign(&sighash, &revocation_key)), redeemscript)
539 KeyStorage::SigsMode { .. } => {
543 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
544 $input.witness[0].push(SigHashType::All as u8);
545 if $htlc_idx.is_none() {
546 $input.witness.push(vec!(1));
548 $input.witness.push(revocation_pubkey.serialize().to_vec());
550 $input.witness.push(redeemscript.into_vec());
555 if let Some(per_commitment_data) = per_commitment_option {
556 inputs.reserve_exact(per_commitment_data.len());
558 for (idx, htlc) in per_commitment_data.iter().enumerate() {
559 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
560 if htlc.transaction_output_index as usize >= tx.output.len() ||
561 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
562 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
563 return txn_to_broadcast; // Corrupted per_commitment_data, fuck this user
566 prev_hash: commitment_txid,
567 prev_index: htlc.transaction_output_index,
568 script_sig: Script::new(),
569 sequence: 0xfffffffd,
572 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
574 htlc_idxs.push(Some(idx));
575 values.push(tx.output[htlc.transaction_output_index as usize].value);
576 total_value += htlc.amount_msat / 1000;
578 let mut single_htlc_tx = Transaction {
583 script_pubkey: self.destination_script.clone(),
584 value: htlc.amount_msat / 1000, //TODO: - fee
587 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
588 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
589 txn_to_broadcast.push(single_htlc_tx); // TODO: This is not yet tested in ChannelManager!
594 if !inputs.is_empty() || !txn_to_broadcast.is_empty() {
595 // We're definitely a remote commitment transaction!
596 // TODO: Register commitment_txid with the ChainWatchInterface!
597 self.remote_htlc_outputs_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
599 if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
601 let outputs = vec!(TxOut {
602 script_pubkey: self.destination_script.clone(),
603 value: total_value, //TODO: - fee
605 let mut spend_tx = Transaction {
612 let mut values_drain = values.drain(..);
613 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
615 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
616 let value = values_drain.next().unwrap();
617 sign_input!(sighash_parts, input, htlc_idx, value);
620 txn_to_broadcast.push(spend_tx);
621 } else if let Some(per_commitment_data) = per_commitment_option {
622 if let Some(revocation_points) = self.their_cur_revocation_points {
623 let revocation_point_option =
624 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
625 else if let Some(point) = revocation_points.2.as_ref() {
626 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
628 if let Some(revocation_point) = revocation_point_option {
629 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
630 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
631 (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)))),
632 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &ignore_error!(PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key)))))
634 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
635 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
636 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
639 let a_htlc_key = match self.their_htlc_base_key {
640 None => return txn_to_broadcast,
641 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
644 let mut total_value = 0;
645 let mut values = Vec::new();
646 let mut inputs = Vec::new();
648 macro_rules! sign_input {
649 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
651 let (sig, redeemscript) = match self.key_storage {
652 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
653 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
654 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
655 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
656 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
657 (ignore_error!(self.secp_ctx.sign(&sighash, &htlc_key)), redeemscript)
659 KeyStorage::SigsMode { .. } => {
663 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
664 $input.witness[0].push(SigHashType::All as u8);
665 $input.witness.push($preimage);
666 $input.witness.push(redeemscript.into_vec());
671 for (idx, htlc) in per_commitment_data.iter().enumerate() {
672 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
674 prev_hash: commitment_txid,
675 prev_index: htlc.transaction_output_index,
676 script_sig: Script::new(),
677 sequence: idx as u32, // reset to 0xfffffffd in sign_input
680 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
682 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
683 total_value += htlc.amount_msat / 1000;
685 let mut single_htlc_tx = Transaction {
690 script_pubkey: self.destination_script.clone(),
691 value: htlc.amount_msat / 1000, //TODO: - fee
694 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
695 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
696 txn_to_broadcast.push(single_htlc_tx);
701 if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
703 let outputs = vec!(TxOut {
704 script_pubkey: self.destination_script.clone(),
705 value: total_value, //TODO: - fee
707 let mut spend_tx = Transaction {
714 let mut values_drain = values.drain(..);
715 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
717 for input in spend_tx.input.iter_mut() {
718 let value = values_drain.next().unwrap();
719 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
722 txn_to_broadcast.push(spend_tx);
726 //TODO: For each input check if its in our remote_htlc_outputs_on_chain map!
732 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
733 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
735 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
737 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);
739 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
741 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
742 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
743 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
744 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
746 htlc_timeout_tx.input[0].witness.push(Vec::new());
747 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());
749 res.push(htlc_timeout_tx);
751 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
752 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);
754 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
756 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
757 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
758 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
759 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
761 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
762 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());
764 res.push(htlc_success_tx);
772 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
773 /// revoked using data in local_claimable_outpoints.
774 /// Should not be used if check_spend_revoked_transaction succeeds.
775 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
776 let commitment_txid = tx.txid();
777 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
778 if local_tx.txid == commitment_txid {
779 return self.broadcast_by_local_state(local_tx);
782 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
783 if local_tx.txid == commitment_txid {
784 return self.broadcast_by_local_state(local_tx);
790 fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface) {
791 for tx in txn_matched {
792 for txin in tx.input.iter() {
793 if self.funding_txo.is_none() || (txin.prev_hash == self.funding_txo.unwrap().txid && txin.prev_index == self.funding_txo.unwrap().index as u32) {
794 let mut txn = self.check_spend_remote_transaction(tx, height);
796 txn = self.check_spend_local_transaction(tx, height);
798 for tx in txn.iter() {
799 broadcaster.broadcast_transaction(tx);
804 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
805 let mut needs_broadcast = false;
806 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
807 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
808 if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
809 needs_broadcast = true;
815 broadcaster.broadcast_transaction(&cur_local_tx.tx);
816 for tx in self.broadcast_by_local_state(&cur_local_tx) {
817 broadcaster.broadcast_transaction(&tx);
823 pub fn would_broadcast_at_height(&self, height: u32) -> bool {
824 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
825 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
826 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
827 if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
839 use bitcoin::util::misc::hex_bytes;
840 use bitcoin::blockdata::script::Script;
841 use bitcoin::blockdata::transaction::Transaction;
842 use crypto::digest::Digest;
843 use ln::channelmonitor::ChannelMonitor;
844 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
845 use util::sha2::Sha256;
846 use secp256k1::key::{SecretKey,PublicKey};
847 use secp256k1::{Secp256k1, Signature};
848 use rand::{thread_rng,Rng};
851 fn test_per_commitment_storage() {
852 // Test vectors from BOLT 3:
853 let mut secrets: Vec<[u8; 32]> = Vec::new();
854 let mut monitor: ChannelMonitor;
855 let secp_ctx = Secp256k1::new();
857 macro_rules! test_secrets {
859 let mut idx = 281474976710655;
860 for secret in secrets.iter() {
861 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
864 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
865 assert!(monitor.get_secret(idx).is_err());
870 // insert_secret correct sequence
871 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
874 secrets.push([0; 32]);
875 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
876 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
879 secrets.push([0; 32]);
880 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
881 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
884 secrets.push([0; 32]);
885 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
886 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
889 secrets.push([0; 32]);
890 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
891 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
894 secrets.push([0; 32]);
895 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
896 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
899 secrets.push([0; 32]);
900 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
901 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
904 secrets.push([0; 32]);
905 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
906 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
909 secrets.push([0; 32]);
910 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
911 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
916 // insert_secret #1 incorrect
917 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
920 secrets.push([0; 32]);
921 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
922 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
925 secrets.push([0; 32]);
926 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
927 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
928 "Previous secret did not match new one");
932 // insert_secret #2 incorrect (#1 derived from incorrect)
933 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
936 secrets.push([0; 32]);
937 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
938 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
941 secrets.push([0; 32]);
942 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
943 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
946 secrets.push([0; 32]);
947 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
948 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
951 secrets.push([0; 32]);
952 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
953 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
954 "Previous secret did not match new one");
958 // insert_secret #3 incorrect
959 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
962 secrets.push([0; 32]);
963 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
964 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
967 secrets.push([0; 32]);
968 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
969 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
972 secrets.push([0; 32]);
973 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
974 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
977 secrets.push([0; 32]);
978 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
979 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
980 "Previous secret did not match new one");
984 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
985 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
988 secrets.push([0; 32]);
989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
990 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
993 secrets.push([0; 32]);
994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
995 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
998 secrets.push([0; 32]);
999 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1000 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1003 secrets.push([0; 32]);
1004 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1005 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1008 secrets.push([0; 32]);
1009 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1010 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1013 secrets.push([0; 32]);
1014 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1015 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1018 secrets.push([0; 32]);
1019 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1020 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1023 secrets.push([0; 32]);
1024 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1025 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1026 "Previous secret did not match new one");
1030 // insert_secret #5 incorrect
1031 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1034 secrets.push([0; 32]);
1035 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1036 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1039 secrets.push([0; 32]);
1040 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1041 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1044 secrets.push([0; 32]);
1045 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1046 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1049 secrets.push([0; 32]);
1050 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1051 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1054 secrets.push([0; 32]);
1055 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1056 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1059 secrets.push([0; 32]);
1060 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1061 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1062 "Previous secret did not match new one");
1066 // insert_secret #6 incorrect (5 derived from incorrect)
1067 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1070 secrets.push([0; 32]);
1071 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1072 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1075 secrets.push([0; 32]);
1076 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1077 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1080 secrets.push([0; 32]);
1081 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1082 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1085 secrets.push([0; 32]);
1086 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1087 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1090 secrets.push([0; 32]);
1091 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1092 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1095 secrets.push([0; 32]);
1096 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1097 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1100 secrets.push([0; 32]);
1101 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1102 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1105 secrets.push([0; 32]);
1106 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1107 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1108 "Previous secret did not match new one");
1112 // insert_secret #7 incorrect
1113 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1116 secrets.push([0; 32]);
1117 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1118 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1121 secrets.push([0; 32]);
1122 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1123 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1126 secrets.push([0; 32]);
1127 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1128 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1131 secrets.push([0; 32]);
1132 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1133 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1136 secrets.push([0; 32]);
1137 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1138 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1141 secrets.push([0; 32]);
1142 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1143 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1146 secrets.push([0; 32]);
1147 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1148 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1151 secrets.push([0; 32]);
1152 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1153 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1154 "Previous secret did not match new one");
1158 // insert_secret #8 incorrect
1159 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1162 secrets.push([0; 32]);
1163 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1164 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1167 secrets.push([0; 32]);
1168 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1169 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1172 secrets.push([0; 32]);
1173 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1174 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1177 secrets.push([0; 32]);
1178 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1179 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1182 secrets.push([0; 32]);
1183 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1184 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1187 secrets.push([0; 32]);
1188 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1189 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1192 secrets.push([0; 32]);
1193 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1194 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1197 secrets.push([0; 32]);
1198 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex_bytes("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1199 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1200 "Previous secret did not match new one");
1205 fn test_prune_preimages() {
1206 let secp_ctx = Secp256k1::new();
1207 let dummy_sig = Signature::from_der(&secp_ctx, &hex_bytes("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
1209 macro_rules! dummy_keys {
1212 per_commitment_point: PublicKey::new(),
1213 revocation_key: PublicKey::new(),
1214 a_htlc_key: PublicKey::new(),
1215 b_htlc_key: PublicKey::new(),
1216 a_delayed_payment_key: PublicKey::new(),
1217 b_payment_key: PublicKey::new(),
1221 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
1223 let mut preimages = Vec::new();
1225 let mut rng = thread_rng();
1227 let mut preimage = [0; 32];
1228 rng.fill_bytes(&mut preimage);
1229 let mut sha = Sha256::new();
1230 sha.input(&preimage);
1231 let mut hash = [0; 32];
1232 sha.result(&mut hash);
1233 preimages.push((preimage, hash));
1237 macro_rules! preimages_slice_to_htlc_outputs {
1238 ($preimages_slice: expr) => {
1240 let mut res = Vec::new();
1241 for (idx, preimage) in $preimages_slice.iter().enumerate() {
1242 res.push(HTLCOutputInCommitment {
1246 payment_hash: preimage.1.clone(),
1247 transaction_output_index: idx as u32,
1254 macro_rules! preimages_to_local_htlcs {
1255 ($preimages_slice: expr) => {
1257 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
1258 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
1264 macro_rules! test_preimages_exist {
1265 ($preimages_slice: expr, $monitor: expr) => {
1266 for preimage in $preimages_slice {
1267 assert!($monitor.payment_preimages.contains_key(&preimage.1));
1272 // Prune with one old state and a local commitment tx holding a few overlaps with the
1274 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &PublicKey::new(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1275 monitor.set_their_to_self_delay(10);
1277 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
1278 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
1279 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
1280 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
1281 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
1282 for &(ref preimage, ref hash) in preimages.iter() {
1283 monitor.provide_payment_preimage(hash, preimage);
1286 // Now provide a secret, pruning preimages 10-15
1287 let mut secret = [0; 32];
1288 secret[0..32].clone_from_slice(&hex_bytes("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1289 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
1290 assert_eq!(monitor.payment_preimages.len(), 15);
1291 test_preimages_exist!(&preimages[0..10], monitor);
1292 test_preimages_exist!(&preimages[15..20], monitor);
1294 // Now provide a further secret, pruning preimages 15-17
1295 secret[0..32].clone_from_slice(&hex_bytes("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1296 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
1297 assert_eq!(monitor.payment_preimages.len(), 13);
1298 test_preimages_exist!(&preimages[0..10], monitor);
1299 test_preimages_exist!(&preimages[17..20], monitor);
1301 // Now update local commitment tx info, pruning only element 18 as we still care about the
1302 // previous commitment tx's preimages too
1303 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
1304 secret[0..32].clone_from_slice(&hex_bytes("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1305 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
1306 assert_eq!(monitor.payment_preimages.len(), 12);
1307 test_preimages_exist!(&preimages[0..10], monitor);
1308 test_preimages_exist!(&preimages[18..20], monitor);
1310 // But if we do it again, we'll prune 5-10
1311 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
1312 secret[0..32].clone_from_slice(&hex_bytes("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1313 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
1314 assert_eq!(monitor.payment_preimages.len(), 5);
1315 test_preimages_exist!(&preimages[0..5], monitor);
1318 // Further testing is done in the ChannelManager integration tests.