1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
3 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
4 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
5 //! be made in responding to certain messages, see ManyChannelMonitor for more.
6 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
7 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
8 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
9 //! security-domain-separated system design, you should consider having multiple paths for
10 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
12 use bitcoin::blockdata::block::BlockHeader;
13 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
14 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
15 use bitcoin::blockdata::script::Script;
16 use bitcoin::network::serialize;
17 use bitcoin::util::hash::Sha256dHash;
18 use bitcoin::util::bip143;
20 use crypto::digest::Digest;
22 use secp256k1::{Secp256k1,Message,Signature};
23 use secp256k1::key::{SecretKey,PublicKey};
26 use ln::msgs::HandleError;
28 use ln::chan_utils::HTLCOutputInCommitment;
29 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
30 use chain::transaction::OutPoint;
31 use util::sha2::Sha256;
34 use std::collections::HashMap;
35 use std::sync::{Arc,Mutex};
38 /// An error enum representing a failure to persist a channel monitor update.
39 pub enum ChannelMonitorUpdateErr {
40 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
41 /// to succeed at some point in the future).
42 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
43 /// submitting new commitment transactions to the remote party.
44 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
45 /// the channel to an operational state.
47 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
48 /// different watchtower and cannot update with all watchtowers that were previously informed
49 /// of this channel). This will force-close the channel in question.
53 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
54 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
55 /// events to it, while also taking any add_update_monitor events and passing them to some remote
57 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
58 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
59 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
60 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
61 pub trait ManyChannelMonitor: Send + Sync {
62 /// Adds or updates a monitor for the given `funding_txo`.
63 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
64 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
66 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
69 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
70 /// watchtower or watch our own channels.
71 /// Note that you must provide your own key by which to refer to channels.
72 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
73 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
74 /// index by a PublicKey which is required to sign any updates.
75 /// If you're using this for local monitoring of your own channels, you probably want to use
76 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
77 pub struct SimpleManyChannelMonitor<Key> {
78 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
79 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
81 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
82 chain_monitor: Arc<ChainWatchInterface>,
83 broadcaster: Arc<BroadcasterInterface>
86 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
87 fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
88 let monitors = self.monitors.lock().unwrap();
89 for monitor in monitors.values() {
90 let txn_outputs = monitor.block_connected(txn_matched, height, &*self.broadcaster);
91 for (ref txid, ref outputs) in txn_outputs {
92 for (idx, output) in outputs.iter().enumerate() {
93 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
99 fn block_disconnected(&self, _: &BlockHeader) { }
102 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
103 /// Creates a new object which can be used to monitor several channels given the chain
104 /// interface with which to register to receive notifications.
105 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
106 let res = Arc::new(SimpleManyChannelMonitor {
107 monitors: Mutex::new(HashMap::new()),
111 let weak_res = Arc::downgrade(&res);
112 res.chain_monitor.register_listener(weak_res);
116 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
117 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
118 let mut monitors = self.monitors.lock().unwrap();
119 match monitors.get_mut(&key) {
120 Some(orig_monitor) => return orig_monitor.insert_combine(monitor),
123 match &monitor.funding_txo {
124 &None => self.chain_monitor.watch_all_txn(),
125 &Some((ref outpoint, ref script)) => {
126 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
127 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
130 monitors.insert(key, monitor);
135 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
136 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
137 match self.add_update_monitor_by_key(funding_txo, monitor) {
139 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
144 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
145 /// instead claiming it in its own individual transaction.
146 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
147 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
148 /// HTLC-Success transaction.
149 const CLTV_CLAIM_BUFFER: u32 = 6;
151 #[derive(Clone, PartialEq)]
154 revocation_base_key: SecretKey,
155 htlc_base_key: SecretKey,
158 revocation_base_key: PublicKey,
159 htlc_base_key: PublicKey,
160 sigs: HashMap<Sha256dHash, Signature>,
164 #[derive(Clone, PartialEq)]
165 struct LocalSignedTx {
166 /// txid of the transaction in tx, just used to make comparison faster
169 revocation_key: PublicKey,
170 a_htlc_key: PublicKey,
171 b_htlc_key: PublicKey,
172 delayed_payment_key: PublicKey,
174 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
177 const SERIALIZATION_VERSION: u8 = 1;
178 const MIN_SERIALIZATION_VERSION: u8 = 1;
180 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
181 /// on-chain transactions to ensure no loss of funds occurs.
182 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
183 /// information and are actively monitoring the chain.
184 pub struct ChannelMonitor {
185 funding_txo: Option<(OutPoint, Script)>,
186 commitment_transaction_number_obscure_factor: u64,
188 key_storage: KeyStorage,
189 delayed_payment_base_key: PublicKey,
190 their_htlc_base_key: Option<PublicKey>,
191 their_delayed_payment_base_key: Option<PublicKey>,
192 // first is the idx of the first of the two revocation points
193 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
195 our_to_self_delay: u16,
196 their_to_self_delay: Option<u16>,
198 old_secrets: [([u8; 32], u64); 49],
199 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
200 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
201 /// Nor can we figure out their commitment numbers without the commitment transaction they are
202 /// spending. Thus, in order to claim them via revocation key, we track all the remote
203 /// commitment transactions which we find on-chain, mapping them to the commitment number which
204 /// can be used to derive the revocation key and claim the transactions.
205 remote_commitment_txn_on_chain: Mutex<HashMap<Sha256dHash, u64>>,
206 /// Cache used to make pruning of payment_preimages faster.
207 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
208 /// remote transactions (ie should remain pretty small).
209 /// Serialized to disk but should generally not be sent to Watchtowers.
210 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
212 // We store two local commitment transactions to avoid any race conditions where we may update
213 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
214 // various monitors for one channel being out of sync, and us broadcasting a local
215 // transaction for which we have deleted claim information on some watchtowers.
216 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
217 current_local_signed_commitment_tx: Option<LocalSignedTx>,
219 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
221 destination_script: Script,
222 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
224 impl Clone for ChannelMonitor {
225 fn clone(&self) -> Self {
227 funding_txo: self.funding_txo.clone(),
228 commitment_transaction_number_obscure_factor: self.commitment_transaction_number_obscure_factor.clone(),
230 key_storage: self.key_storage.clone(),
231 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
232 their_htlc_base_key: self.their_htlc_base_key.clone(),
233 their_delayed_payment_base_key: self.their_delayed_payment_base_key.clone(),
234 their_cur_revocation_points: self.their_cur_revocation_points.clone(),
236 our_to_self_delay: self.our_to_self_delay,
237 their_to_self_delay: self.their_to_self_delay,
239 old_secrets: self.old_secrets.clone(),
240 remote_claimable_outpoints: self.remote_claimable_outpoints.clone(),
241 remote_commitment_txn_on_chain: Mutex::new((*self.remote_commitment_txn_on_chain.lock().unwrap()).clone()),
242 remote_hash_commitment_number: self.remote_hash_commitment_number.clone(),
244 prev_local_signed_commitment_tx: self.prev_local_signed_commitment_tx.clone(),
245 current_local_signed_commitment_tx: self.current_local_signed_commitment_tx.clone(),
247 payment_preimages: self.payment_preimages.clone(),
249 destination_script: self.destination_script.clone(),
250 secp_ctx: self.secp_ctx.clone(),
255 #[cfg(any(test, feature = "fuzztarget"))]
256 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
257 /// underlying object
258 impl PartialEq for ChannelMonitor {
259 fn eq(&self, other: &Self) -> bool {
260 if self.funding_txo != other.funding_txo ||
261 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
262 self.key_storage != other.key_storage ||
263 self.delayed_payment_base_key != other.delayed_payment_base_key ||
264 self.their_htlc_base_key != other.their_htlc_base_key ||
265 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
266 self.their_cur_revocation_points != other.their_cur_revocation_points ||
267 self.our_to_self_delay != other.our_to_self_delay ||
268 self.their_to_self_delay != other.their_to_self_delay ||
269 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
270 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
271 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
272 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
273 self.payment_preimages != other.payment_preimages ||
274 self.destination_script != other.destination_script
278 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
279 if secret != o_secret || idx != o_idx {
283 let us = self.remote_commitment_txn_on_chain.lock().unwrap();
284 let them = other.remote_commitment_txn_on_chain.lock().unwrap();
290 impl ChannelMonitor {
291 pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &PublicKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script) -> ChannelMonitor {
294 commitment_transaction_number_obscure_factor: 0,
296 key_storage: KeyStorage::PrivMode {
297 revocation_base_key: revocation_base_key.clone(),
298 htlc_base_key: htlc_base_key.clone(),
300 delayed_payment_base_key: delayed_payment_base_key.clone(),
301 their_htlc_base_key: None,
302 their_delayed_payment_base_key: None,
303 their_cur_revocation_points: None,
305 our_to_self_delay: our_to_self_delay,
306 their_to_self_delay: None,
308 old_secrets: [([0; 32], 1 << 48); 49],
309 remote_claimable_outpoints: HashMap::new(),
310 remote_commitment_txn_on_chain: Mutex::new(HashMap::new()),
311 remote_hash_commitment_number: HashMap::new(),
313 prev_local_signed_commitment_tx: None,
314 current_local_signed_commitment_tx: None,
316 payment_preimages: HashMap::new(),
318 destination_script: destination_script,
319 secp_ctx: Secp256k1::new(),
324 fn place_secret(idx: u64) -> u8 {
326 if idx & (1 << i) == (1 << i) {
334 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
335 let mut res: [u8; 32] = secret;
337 let bitpos = bits - 1 - i;
338 if idx & (1 << bitpos) == (1 << bitpos) {
339 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
340 let mut sha = Sha256::new();
342 sha.result(&mut res);
348 /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
349 /// revocation point which may be required to claim HTLC outputs which we know the preimage of
350 /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
351 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
352 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
353 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
354 let pos = ChannelMonitor::place_secret(idx);
356 let (old_secret, old_idx) = self.old_secrets[i as usize];
357 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
358 return Err(HandleError{err: "Previous secret did not match new one", action: None})
361 self.old_secrets[pos as usize] = (secret, idx);
363 if let Some(new_revocation_point) = their_next_revocation_point {
364 match self.their_cur_revocation_points {
365 Some(old_points) => {
366 if old_points.0 == new_revocation_point.0 + 1 {
367 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
368 } else if old_points.0 == new_revocation_point.0 + 2 {
369 if let Some(old_second_point) = old_points.2 {
370 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
372 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
375 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
379 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
384 if !self.payment_preimages.is_empty() {
385 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
386 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
387 let min_idx = self.get_min_seen_secret();
388 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
390 self.payment_preimages.retain(|&k, _| {
391 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
392 if k == htlc.payment_hash {
396 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
397 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
398 if k == htlc.payment_hash {
403 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
410 remote_hash_commitment_number.remove(&k);
419 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
420 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
421 /// possibly future revocation/preimage information) to claim outputs where possible.
422 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
423 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
424 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
425 // so that a remote monitor doesn't learn anything unless there is a malicious close.
426 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
428 for htlc in &htlc_outputs {
429 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
431 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
434 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
435 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
436 /// is important that any clones of this channel monitor (including remote clones) by kept
437 /// up-to-date as our local commitment transaction is updated.
438 /// Panics if set_their_to_self_delay has never been called.
439 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)>) {
440 assert!(self.their_to_self_delay.is_some());
441 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
442 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
443 txid: signed_commitment_tx.txid(),
444 tx: signed_commitment_tx,
445 revocation_key: local_keys.revocation_key,
446 a_htlc_key: local_keys.a_htlc_key,
447 b_htlc_key: local_keys.b_htlc_key,
448 delayed_payment_key: local_keys.a_delayed_payment_key,
454 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
455 /// commitment_tx_infos which contain the payment hash have been revoked.
456 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
457 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
460 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
461 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
462 /// chain for new blocks/transactions.
463 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
464 if self.funding_txo.is_some() {
465 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
466 // easy to collide the funding_txo hash and have a different scriptPubKey.
467 if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
468 return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
471 self.funding_txo = other.funding_txo.take();
473 let other_min_secret = other.get_min_seen_secret();
474 let our_min_secret = self.get_min_seen_secret();
475 if our_min_secret > other_min_secret {
476 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
478 if our_min_secret >= other_min_secret {
479 self.their_cur_revocation_points = other.their_cur_revocation_points;
480 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
481 self.remote_claimable_outpoints.insert(txid, htlcs);
483 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
484 self.prev_local_signed_commitment_tx = Some(local_tx);
486 if let Some(local_tx) = other.current_local_signed_commitment_tx {
487 self.current_local_signed_commitment_tx = Some(local_tx);
489 self.payment_preimages = other.payment_preimages;
494 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
495 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
496 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
497 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
500 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
501 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
502 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
503 /// provides slightly better privacy.
504 /// It's the responsibility of the caller to register outpoint and script with passing the former
505 /// value as key to add_update_monitor.
506 pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
507 self.funding_txo = Some(funding_info);
510 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
511 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
512 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
513 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
516 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
517 self.their_to_self_delay = Some(their_to_self_delay);
520 pub(super) fn unset_funding_info(&mut self) {
521 self.funding_txo = None;
524 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
525 pub fn get_funding_txo(&self) -> Option<OutPoint> {
526 match self.funding_txo {
527 Some((outpoint, _)) => Some(outpoint),
532 /// Serializes into a vec, with various modes for the exposed pub fns
533 fn serialize(&self, for_local_storage: bool) -> Vec<u8> {
534 let mut res = Vec::new();
535 res.push(SERIALIZATION_VERSION);
536 res.push(MIN_SERIALIZATION_VERSION);
538 match &self.funding_txo {
539 &Some((ref outpoint, ref script)) => {
540 res.extend_from_slice(&outpoint.txid[..]);
541 res.extend_from_slice(&byte_utils::be16_to_array(outpoint.index));
542 res.extend_from_slice(&byte_utils::be64_to_array(script.len() as u64));
543 res.extend_from_slice(&script[..]);
546 // We haven't even been initialized...not sure why anyone is serializing us, but
547 // not much to give them.
552 // Set in initial Channel-object creation, so should always be set by now:
553 res.extend_from_slice(&byte_utils::be48_to_array(self.commitment_transaction_number_obscure_factor));
555 match self.key_storage {
556 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
558 res.extend_from_slice(&revocation_base_key[..]);
559 res.extend_from_slice(&htlc_base_key[..]);
561 KeyStorage::SigsMode { .. } => unimplemented!(),
564 res.extend_from_slice(&self.delayed_payment_base_key.serialize());
565 res.extend_from_slice(&self.their_htlc_base_key.as_ref().unwrap().serialize());
566 res.extend_from_slice(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize());
568 match self.their_cur_revocation_points {
569 Some((idx, pubkey, second_option)) => {
570 res.extend_from_slice(&byte_utils::be48_to_array(idx));
571 res.extend_from_slice(&pubkey.serialize());
572 match second_option {
573 Some(second_pubkey) => {
574 res.extend_from_slice(&second_pubkey.serialize());
577 res.extend_from_slice(&[0; 33]);
582 res.extend_from_slice(&byte_utils::be48_to_array(0));
586 res.extend_from_slice(&byte_utils::be16_to_array(self.our_to_self_delay));
587 res.extend_from_slice(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()));
589 for &(ref secret, ref idx) in self.old_secrets.iter() {
590 res.extend_from_slice(secret);
591 res.extend_from_slice(&byte_utils::be64_to_array(*idx));
594 macro_rules! serialize_htlc_in_commitment {
595 ($htlc_output: expr) => {
596 res.push($htlc_output.offered as u8);
597 res.extend_from_slice(&byte_utils::be64_to_array($htlc_output.amount_msat));
598 res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.cltv_expiry));
599 res.extend_from_slice(&$htlc_output.payment_hash);
600 res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.transaction_output_index));
604 res.extend_from_slice(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64));
605 for (txid, htlc_outputs) in self.remote_claimable_outpoints.iter() {
606 res.extend_from_slice(&txid[..]);
607 res.extend_from_slice(&byte_utils::be64_to_array(htlc_outputs.len() as u64));
608 for htlc_output in htlc_outputs.iter() {
609 serialize_htlc_in_commitment!(htlc_output);
614 let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
615 res.extend_from_slice(&byte_utils::be64_to_array(remote_commitment_txn_on_chain.len() as u64));
616 for (txid, commitment_number) in remote_commitment_txn_on_chain.iter() {
617 res.extend_from_slice(&txid[..]);
618 res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
622 if for_local_storage {
623 res.extend_from_slice(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64));
624 for (payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
625 res.extend_from_slice(payment_hash);
626 res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
629 res.extend_from_slice(&byte_utils::be64_to_array(0));
632 macro_rules! serialize_local_tx {
633 ($local_tx: expr) => {
634 let tx_ser = serialize::serialize(&$local_tx.tx).unwrap();
635 res.extend_from_slice(&byte_utils::be64_to_array(tx_ser.len() as u64));
636 res.extend_from_slice(&tx_ser);
638 res.extend_from_slice(&$local_tx.revocation_key.serialize());
639 res.extend_from_slice(&$local_tx.a_htlc_key.serialize());
640 res.extend_from_slice(&$local_tx.b_htlc_key.serialize());
641 res.extend_from_slice(&$local_tx.delayed_payment_key.serialize());
643 res.extend_from_slice(&byte_utils::be64_to_array($local_tx.feerate_per_kw));
644 res.extend_from_slice(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64));
645 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
646 serialize_htlc_in_commitment!(htlc_output);
647 res.extend_from_slice(&their_sig.serialize_compact(&self.secp_ctx));
648 res.extend_from_slice(&our_sig.serialize_compact(&self.secp_ctx));
653 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
655 serialize_local_tx!(prev_local_tx);
660 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
662 serialize_local_tx!(cur_local_tx);
667 res.extend_from_slice(&byte_utils::be64_to_array(self.payment_preimages.len() as u64));
668 for payment_preimage in self.payment_preimages.values() {
669 res.extend_from_slice(payment_preimage);
672 res.extend_from_slice(&byte_utils::be64_to_array(self.destination_script.len() as u64));
673 res.extend_from_slice(&self.destination_script[..]);
678 /// Encodes this monitor into a byte array, suitable for writing to disk.
679 pub fn serialize_for_disk(&self) -> Vec<u8> {
683 /// Encodes this monitor into a byte array, suitable for sending to a remote watchtower
684 pub fn serialize_for_watchtower(&self) -> Vec<u8> {
685 self.serialize(false)
688 /// Attempts to decode a serialized monitor
689 pub fn deserialize(data: &[u8]) -> Option<Self> {
690 let mut read_pos = 0;
691 macro_rules! read_bytes {
692 ($byte_count: expr) => {
694 if ($byte_count as usize) > data.len() - read_pos {
697 read_pos += $byte_count as usize;
698 &data[read_pos - $byte_count as usize..read_pos]
703 let secp_ctx = Secp256k1::new();
704 macro_rules! unwrap_obj {
708 Err(_) => return None,
713 let _ver = read_bytes!(1)[0];
714 let min_ver = read_bytes!(1)[0];
715 if min_ver > SERIALIZATION_VERSION {
719 // Technically this can fail and serialize fail a round-trip, but only for serialization of
720 // barely-init'd ChannelMonitors that we can't do anything with.
721 let outpoint = OutPoint {
722 txid: Sha256dHash::from(read_bytes!(32)),
723 index: byte_utils::slice_to_be16(read_bytes!(2)),
725 let script_len = byte_utils::slice_to_be64(read_bytes!(8));
726 let funding_txo = Some((outpoint, Script::from(read_bytes!(script_len).to_vec())));
727 let commitment_transaction_number_obscure_factor = byte_utils::slice_to_be48(read_bytes!(6));
729 let key_storage = match read_bytes!(1)[0] {
731 KeyStorage::PrivMode {
732 revocation_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
733 htlc_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
739 let delayed_payment_base_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
740 let their_htlc_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
741 let their_delayed_payment_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
743 let their_cur_revocation_points = {
744 let first_idx = byte_utils::slice_to_be48(read_bytes!(6));
748 let first_point = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
749 let second_point_slice = read_bytes!(33);
750 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
751 Some((first_idx, first_point, None))
753 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, second_point_slice)))))
758 let our_to_self_delay = byte_utils::slice_to_be16(read_bytes!(2));
759 let their_to_self_delay = Some(byte_utils::slice_to_be16(read_bytes!(2)));
761 let mut old_secrets = [([0; 32], 1 << 48); 49];
762 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
763 secret.copy_from_slice(read_bytes!(32));
764 *idx = byte_utils::slice_to_be64(read_bytes!(8));
767 macro_rules! read_htlc_in_commitment {
770 let offered = match read_bytes!(1)[0] {
771 0 => false, 1 => true,
774 let amount_msat = byte_utils::slice_to_be64(read_bytes!(8));
775 let cltv_expiry = byte_utils::slice_to_be32(read_bytes!(4));
776 let mut payment_hash = [0; 32];
777 payment_hash[..].copy_from_slice(read_bytes!(32));
778 let transaction_output_index = byte_utils::slice_to_be32(read_bytes!(4));
780 HTLCOutputInCommitment {
781 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
787 let remote_claimable_outpoints_len = byte_utils::slice_to_be64(read_bytes!(8));
788 if remote_claimable_outpoints_len > data.len() as u64 / 64 { return None; }
789 let mut remote_claimable_outpoints = HashMap::with_capacity(remote_claimable_outpoints_len as usize);
790 for _ in 0..remote_claimable_outpoints_len {
791 let txid = Sha256dHash::from(read_bytes!(32));
792 let outputs_count = byte_utils::slice_to_be64(read_bytes!(8));
793 if outputs_count > data.len() as u64 / 32 { return None; }
794 let mut outputs = Vec::with_capacity(outputs_count as usize);
795 for _ in 0..outputs_count {
796 outputs.push(read_htlc_in_commitment!());
798 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
803 let remote_commitment_txn_on_chain_len = byte_utils::slice_to_be64(read_bytes!(8));
804 if remote_commitment_txn_on_chain_len > data.len() as u64 / 32 { return None; }
805 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(remote_commitment_txn_on_chain_len as usize);
806 for _ in 0..remote_commitment_txn_on_chain_len {
807 let txid = Sha256dHash::from(read_bytes!(32));
808 let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
809 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, commitment_number) {
814 let remote_hash_commitment_number_len = byte_utils::slice_to_be64(read_bytes!(8));
815 if remote_hash_commitment_number_len > data.len() as u64 / 32 { return None; }
816 let mut remote_hash_commitment_number = HashMap::with_capacity(remote_hash_commitment_number_len as usize);
817 for _ in 0..remote_hash_commitment_number_len {
818 let mut txid = [0; 32];
819 txid[..].copy_from_slice(read_bytes!(32));
820 let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
821 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
826 macro_rules! read_local_tx {
829 let tx_len = byte_utils::slice_to_be64(read_bytes!(8));
830 let tx_ser = read_bytes!(tx_len);
831 let tx: Transaction = unwrap_obj!(serialize::deserialize(tx_ser));
832 if serialize::serialize(&tx).unwrap() != tx_ser {
833 // We check that the tx re-serializes to the same form to ensure there is
834 // no extra data, and as rust-bitcoin doesn't handle the 0-input ambiguity
839 let revocation_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
840 let a_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
841 let b_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
842 let delayed_payment_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
843 let feerate_per_kw = byte_utils::slice_to_be64(read_bytes!(8));
845 let htlc_outputs_len = byte_utils::slice_to_be64(read_bytes!(8));
846 if htlc_outputs_len > data.len() as u64 / 128 { return None; }
847 let mut htlc_outputs = Vec::with_capacity(htlc_outputs_len as usize);
848 for _ in 0..htlc_outputs_len {
849 htlc_outputs.push((read_htlc_in_commitment!(),
850 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64))),
851 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64)))));
856 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
862 let prev_local_signed_commitment_tx = match read_bytes!(1)[0] {
865 Some(read_local_tx!())
870 let current_local_signed_commitment_tx = match read_bytes!(1)[0] {
873 Some(read_local_tx!())
878 let payment_preimages_len = byte_utils::slice_to_be64(read_bytes!(8));
879 if payment_preimages_len > data.len() as u64 / 32 { return None; }
880 let mut payment_preimages = HashMap::with_capacity(payment_preimages_len as usize);
881 let mut sha = Sha256::new();
882 for _ in 0..payment_preimages_len {
883 let mut preimage = [0; 32];
884 preimage[..].copy_from_slice(read_bytes!(32));
886 sha.input(&preimage);
887 let mut hash = [0; 32];
888 sha.result(&mut hash);
889 if let Some(_) = payment_preimages.insert(hash, preimage) {
894 let destination_script_len = byte_utils::slice_to_be64(read_bytes!(8));
895 let destination_script = Script::from(read_bytes!(destination_script_len).to_vec());
897 Some(ChannelMonitor {
899 commitment_transaction_number_obscure_factor,
902 delayed_payment_base_key,
904 their_delayed_payment_base_key,
905 their_cur_revocation_points,
911 remote_claimable_outpoints,
912 remote_commitment_txn_on_chain: Mutex::new(remote_commitment_txn_on_chain),
913 remote_hash_commitment_number,
915 prev_local_signed_commitment_tx,
916 current_local_signed_commitment_tx,
925 //TODO: Functions to serialize/deserialize (with different forms depending on which information
926 //we want to leave out (eg funding_txo, etc).
928 /// Can only fail if idx is < get_min_seen_secret
929 pub(super) fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
930 for i in 0..self.old_secrets.len() {
931 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
932 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
935 assert!(idx < self.get_min_seen_secret());
936 Err(HandleError{err: "idx too low", action: None})
939 pub(super) fn get_min_seen_secret(&self) -> u64 {
940 //TODO This can be optimized?
941 let mut min = 1 << 48;
942 for &(_, idx) in self.old_secrets.iter() {
950 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
951 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
952 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
953 /// HTLC-Success/HTLC-Timeout transactions.
954 fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>)) {
955 // Most secp and related errors trying to create keys means we have no hope of constructing
956 // a spend transaction...so we return no transactions to broadcast
957 let mut txn_to_broadcast = Vec::new();
958 let mut watch_outputs = Vec::new();
960 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
961 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
963 macro_rules! ignore_error {
964 ( $thing : expr ) => {
967 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs))
972 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
973 if commitment_number >= self.get_min_seen_secret() {
974 let secret = self.get_secret(commitment_number).unwrap();
975 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
976 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
977 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
978 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
979 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
980 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
982 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
983 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
984 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
985 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
988 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.delayed_payment_base_key));
989 let a_htlc_key = match self.their_htlc_base_key {
990 None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
991 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &their_htlc_base_key)),
994 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
995 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
997 let mut total_value = 0;
998 let mut values = Vec::new();
999 let mut inputs = Vec::new();
1000 let mut htlc_idxs = Vec::new();
1002 for (idx, outp) in tx.output.iter().enumerate() {
1003 if outp.script_pubkey == revokeable_p2wsh {
1005 previous_output: BitcoinOutPoint {
1006 txid: commitment_txid,
1009 script_sig: Script::new(),
1010 sequence: 0xfffffffd,
1011 witness: Vec::new(),
1013 htlc_idxs.push(None);
1014 values.push(outp.value);
1015 total_value += outp.value;
1016 break; // There can only be one of these
1020 macro_rules! sign_input {
1021 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1023 let (sig, redeemscript) = match self.key_storage {
1024 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1025 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1026 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
1027 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1029 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1030 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1031 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1033 KeyStorage::SigsMode { .. } => {
1037 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1038 $input.witness[0].push(SigHashType::All as u8);
1039 if $htlc_idx.is_none() {
1040 $input.witness.push(vec!(1));
1042 $input.witness.push(revocation_pubkey.serialize().to_vec());
1044 $input.witness.push(redeemscript.into_bytes());
1049 if let Some(per_commitment_data) = per_commitment_option {
1050 inputs.reserve_exact(per_commitment_data.len());
1052 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1053 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1054 if htlc.transaction_output_index as usize >= tx.output.len() ||
1055 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1056 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1057 return (txn_to_broadcast, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1060 previous_output: BitcoinOutPoint {
1061 txid: commitment_txid,
1062 vout: htlc.transaction_output_index,
1064 script_sig: Script::new(),
1065 sequence: 0xfffffffd,
1066 witness: Vec::new(),
1068 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1070 htlc_idxs.push(Some(idx));
1071 values.push(tx.output[htlc.transaction_output_index as usize].value);
1072 total_value += htlc.amount_msat / 1000;
1074 let mut single_htlc_tx = Transaction {
1078 output: vec!(TxOut {
1079 script_pubkey: self.destination_script.clone(),
1080 value: htlc.amount_msat / 1000, //TODO: - fee
1083 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1084 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1085 txn_to_broadcast.push(single_htlc_tx); // TODO: This is not yet tested in ChannelManager!
1090 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1091 // We're definitely a remote commitment transaction!
1092 watch_outputs.append(&mut tx.output.clone());
1093 self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
1095 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
1097 let outputs = vec!(TxOut {
1098 script_pubkey: self.destination_script.clone(),
1099 value: total_value, //TODO: - fee
1101 let mut spend_tx = Transaction {
1108 let mut values_drain = values.drain(..);
1109 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1111 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1112 let value = values_drain.next().unwrap();
1113 sign_input!(sighash_parts, input, htlc_idx, value);
1116 txn_to_broadcast.push(spend_tx);
1117 } else if let Some(per_commitment_data) = per_commitment_option {
1118 // While this isn't useful yet, there is a potential race where if a counterparty
1119 // revokes a state at the same time as the commitment transaction for that state is
1120 // confirmed, and the watchtower receives the block before the user, the user could
1121 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1122 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1123 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1125 watch_outputs.append(&mut tx.output.clone());
1126 self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
1128 if let Some(revocation_points) = self.their_cur_revocation_points {
1129 let revocation_point_option =
1130 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1131 else if let Some(point) = revocation_points.2.as_ref() {
1132 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1134 if let Some(revocation_point) = revocation_point_option {
1135 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1136 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
1137 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1138 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1140 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1141 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1142 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1145 let a_htlc_key = match self.their_htlc_base_key {
1146 None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
1147 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1150 let mut total_value = 0;
1151 let mut values = Vec::new();
1152 let mut inputs = Vec::new();
1154 macro_rules! sign_input {
1155 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1157 let (sig, redeemscript) = match self.key_storage {
1158 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
1159 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1160 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1161 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1162 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1163 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1165 KeyStorage::SigsMode { .. } => {
1169 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1170 $input.witness[0].push(SigHashType::All as u8);
1171 $input.witness.push($preimage);
1172 $input.witness.push(redeemscript.into_bytes());
1177 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1178 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1180 previous_output: BitcoinOutPoint {
1181 txid: commitment_txid,
1182 vout: htlc.transaction_output_index,
1184 script_sig: Script::new(),
1185 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1186 witness: Vec::new(),
1188 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1190 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1191 total_value += htlc.amount_msat / 1000;
1193 let mut single_htlc_tx = Transaction {
1197 output: vec!(TxOut {
1198 script_pubkey: self.destination_script.clone(),
1199 value: htlc.amount_msat / 1000, //TODO: - fee
1202 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1203 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1204 txn_to_broadcast.push(single_htlc_tx);
1209 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
1211 let outputs = vec!(TxOut {
1212 script_pubkey: self.destination_script.clone(),
1213 value: total_value, //TODO: - fee
1215 let mut spend_tx = Transaction {
1222 let mut values_drain = values.drain(..);
1223 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1225 for input in spend_tx.input.iter_mut() {
1226 let value = values_drain.next().unwrap();
1227 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1230 txn_to_broadcast.push(spend_tx);
1235 (txn_to_broadcast, (commitment_txid, watch_outputs))
1238 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1239 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> Option<Transaction> {
1240 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1242 macro_rules! ignore_error {
1243 ( $thing : expr ) => {
1246 Err(_) => return None
1251 let secret = ignore_error!(self.get_secret(commitment_number));
1252 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1253 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1254 let revocation_pubkey = match self.key_storage {
1255 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1256 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1258 KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1259 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1262 let delayed_key = match self.their_delayed_payment_base_key {
1263 None => return None,
1264 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1266 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1267 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1269 let mut inputs = Vec::new();
1272 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1274 previous_output: BitcoinOutPoint {
1278 script_sig: Script::new(),
1279 sequence: 0xfffffffd,
1280 witness: Vec::new(),
1282 amount = tx.output[0].value;
1285 if !inputs.is_empty() {
1286 let outputs = vec!(TxOut {
1287 script_pubkey: self.destination_script.clone(),
1288 value: amount, //TODO: - fee
1291 let mut spend_tx = Transaction {
1298 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1300 let sig = match self.key_storage {
1301 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1302 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1303 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1304 self.secp_ctx.sign(&sighash, &revocation_key)
1306 KeyStorage::SigsMode { .. } => {
1310 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1311 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1312 spend_tx.input[0].witness.push(vec!(1));
1313 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1319 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
1320 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1322 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1324 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);
1326 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1328 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1329 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1330 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1331 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1333 htlc_timeout_tx.input[0].witness.push(Vec::new());
1334 htlc_timeout_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
1336 res.push(htlc_timeout_tx);
1338 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1339 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);
1341 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1343 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1344 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1345 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1346 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1348 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1349 htlc_success_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
1351 res.push(htlc_success_tx);
1359 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1360 /// revoked using data in local_claimable_outpoints.
1361 /// Should not be used if check_spend_revoked_transaction succeeds.
1362 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
1363 let commitment_txid = tx.txid();
1364 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1365 if local_tx.txid == commitment_txid {
1366 return self.broadcast_by_local_state(local_tx);
1369 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1370 if local_tx.txid == commitment_txid {
1371 return self.broadcast_by_local_state(local_tx);
1377 fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface)-> Vec<(Sha256dHash, Vec<TxOut>)> {
1378 let mut watch_outputs = Vec::new();
1379 for tx in txn_matched {
1380 if tx.input.len() == 1 {
1381 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1382 // commitment transactions and HTLC transactions will all only ever have one input,
1383 // which is an easy way to filter out any potential non-matching txn for lazy
1385 let prevout = &tx.input[0].previous_output;
1386 let mut txn: Vec<Transaction> = Vec::new();
1387 if self.funding_txo.is_none() || (prevout.txid == self.funding_txo.as_ref().unwrap().0.txid && prevout.vout == self.funding_txo.as_ref().unwrap().0.index as u32) {
1388 let (remote_txn, new_outputs) = self.check_spend_remote_transaction(tx, height);
1390 if !new_outputs.1.is_empty() {
1391 watch_outputs.push(new_outputs);
1394 txn = self.check_spend_local_transaction(tx, height);
1397 let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
1398 if let Some(commitment_number) = remote_commitment_txn_on_chain.get(&prevout.txid) {
1399 if let Some(tx) = self.check_spend_remote_htlc(tx, *commitment_number) {
1404 for tx in txn.iter() {
1405 broadcaster.broadcast_transaction(tx);
1409 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1410 let mut needs_broadcast = false;
1411 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1412 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1413 if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1414 needs_broadcast = true;
1419 if needs_broadcast {
1420 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1421 for tx in self.broadcast_by_local_state(&cur_local_tx) {
1422 broadcaster.broadcast_transaction(&tx);
1429 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1430 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1431 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1432 if htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER {
1433 if htlc.offered || self.payment_preimages.contains_key(&htlc.payment_hash) {
1445 use bitcoin::blockdata::script::Script;
1446 use bitcoin::blockdata::transaction::Transaction;
1447 use crypto::digest::Digest;
1449 use ln::channelmonitor::ChannelMonitor;
1450 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1451 use util::sha2::Sha256;
1452 use secp256k1::key::{SecretKey,PublicKey};
1453 use secp256k1::{Secp256k1, Signature};
1454 use rand::{thread_rng,Rng};
1457 fn test_per_commitment_storage() {
1458 // Test vectors from BOLT 3:
1459 let mut secrets: Vec<[u8; 32]> = Vec::new();
1460 let mut monitor: ChannelMonitor;
1461 let secp_ctx = Secp256k1::new();
1463 macro_rules! test_secrets {
1465 let mut idx = 281474976710655;
1466 for secret in secrets.iter() {
1467 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1470 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1471 assert!(monitor.get_secret(idx).is_err());
1475 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1478 // insert_secret correct sequence
1479 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1482 secrets.push([0; 32]);
1483 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1484 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1487 secrets.push([0; 32]);
1488 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1489 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1492 secrets.push([0; 32]);
1493 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1494 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1497 secrets.push([0; 32]);
1498 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1499 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1502 secrets.push([0; 32]);
1503 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1504 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1507 secrets.push([0; 32]);
1508 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1509 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1512 secrets.push([0; 32]);
1513 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1514 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1517 secrets.push([0; 32]);
1518 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1519 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1524 // insert_secret #1 incorrect
1525 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1528 secrets.push([0; 32]);
1529 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1530 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1533 secrets.push([0; 32]);
1534 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1535 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1536 "Previous secret did not match new one");
1540 // insert_secret #2 incorrect (#1 derived from incorrect)
1541 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1544 secrets.push([0; 32]);
1545 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1546 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1549 secrets.push([0; 32]);
1550 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1551 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1554 secrets.push([0; 32]);
1555 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1556 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1559 secrets.push([0; 32]);
1560 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1561 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1562 "Previous secret did not match new one");
1566 // insert_secret #3 incorrect
1567 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1570 secrets.push([0; 32]);
1571 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1572 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1575 secrets.push([0; 32]);
1576 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1577 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1580 secrets.push([0; 32]);
1581 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1582 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1585 secrets.push([0; 32]);
1586 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1587 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1588 "Previous secret did not match new one");
1592 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1593 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1596 secrets.push([0; 32]);
1597 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1598 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1601 secrets.push([0; 32]);
1602 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1603 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1606 secrets.push([0; 32]);
1607 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1608 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1611 secrets.push([0; 32]);
1612 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1613 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1616 secrets.push([0; 32]);
1617 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1618 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1621 secrets.push([0; 32]);
1622 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1623 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1626 secrets.push([0; 32]);
1627 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1628 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1631 secrets.push([0; 32]);
1632 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1633 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1634 "Previous secret did not match new one");
1638 // insert_secret #5 incorrect
1639 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1642 secrets.push([0; 32]);
1643 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1644 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1647 secrets.push([0; 32]);
1648 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1649 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1652 secrets.push([0; 32]);
1653 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1654 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1657 secrets.push([0; 32]);
1658 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1659 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1662 secrets.push([0; 32]);
1663 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1664 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1667 secrets.push([0; 32]);
1668 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1669 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1670 "Previous secret did not match new one");
1674 // insert_secret #6 incorrect (5 derived from incorrect)
1675 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1678 secrets.push([0; 32]);
1679 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1680 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1683 secrets.push([0; 32]);
1684 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1685 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1688 secrets.push([0; 32]);
1689 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1690 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1693 secrets.push([0; 32]);
1694 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1695 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1698 secrets.push([0; 32]);
1699 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1700 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1703 secrets.push([0; 32]);
1704 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1705 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1708 secrets.push([0; 32]);
1709 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1710 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1713 secrets.push([0; 32]);
1714 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1715 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1716 "Previous secret did not match new one");
1720 // insert_secret #7 incorrect
1721 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1724 secrets.push([0; 32]);
1725 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1726 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1729 secrets.push([0; 32]);
1730 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1731 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1734 secrets.push([0; 32]);
1735 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1736 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1739 secrets.push([0; 32]);
1740 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1741 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1744 secrets.push([0; 32]);
1745 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1746 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1749 secrets.push([0; 32]);
1750 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1751 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1754 secrets.push([0; 32]);
1755 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1756 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1759 secrets.push([0; 32]);
1760 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1761 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1762 "Previous secret did not match new one");
1766 // insert_secret #8 incorrect
1767 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1770 secrets.push([0; 32]);
1771 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1772 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1775 secrets.push([0; 32]);
1776 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1777 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1780 secrets.push([0; 32]);
1781 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1782 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1785 secrets.push([0; 32]);
1786 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1787 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1790 secrets.push([0; 32]);
1791 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1792 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1795 secrets.push([0; 32]);
1796 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1797 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1800 secrets.push([0; 32]);
1801 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1802 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1805 secrets.push([0; 32]);
1806 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1807 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1808 "Previous secret did not match new one");
1813 fn test_prune_preimages() {
1814 let secp_ctx = Secp256k1::new();
1815 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
1817 macro_rules! dummy_keys {
1820 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1822 per_commitment_point: dummy_key.clone(),
1823 revocation_key: dummy_key.clone(),
1824 a_htlc_key: dummy_key.clone(),
1825 b_htlc_key: dummy_key.clone(),
1826 a_delayed_payment_key: dummy_key.clone(),
1827 b_payment_key: dummy_key.clone(),
1832 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
1834 let mut preimages = Vec::new();
1836 let mut rng = thread_rng();
1838 let mut preimage = [0; 32];
1839 rng.fill_bytes(&mut preimage);
1840 let mut sha = Sha256::new();
1841 sha.input(&preimage);
1842 let mut hash = [0; 32];
1843 sha.result(&mut hash);
1844 preimages.push((preimage, hash));
1848 macro_rules! preimages_slice_to_htlc_outputs {
1849 ($preimages_slice: expr) => {
1851 let mut res = Vec::new();
1852 for (idx, preimage) in $preimages_slice.iter().enumerate() {
1853 res.push(HTLCOutputInCommitment {
1857 payment_hash: preimage.1.clone(),
1858 transaction_output_index: idx as u32,
1865 macro_rules! preimages_to_local_htlcs {
1866 ($preimages_slice: expr) => {
1868 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
1869 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
1875 macro_rules! test_preimages_exist {
1876 ($preimages_slice: expr, $monitor: expr) => {
1877 for preimage in $preimages_slice {
1878 assert!($monitor.payment_preimages.contains_key(&preimage.1));
1883 // Prune with one old state and a local commitment tx holding a few overlaps with the
1885 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1886 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1887 monitor.set_their_to_self_delay(10);
1889 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
1890 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
1891 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
1892 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
1893 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
1894 for &(ref preimage, ref hash) in preimages.iter() {
1895 monitor.provide_payment_preimage(hash, preimage);
1898 // Now provide a secret, pruning preimages 10-15
1899 let mut secret = [0; 32];
1900 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1901 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
1902 assert_eq!(monitor.payment_preimages.len(), 15);
1903 test_preimages_exist!(&preimages[0..10], monitor);
1904 test_preimages_exist!(&preimages[15..20], monitor);
1906 // Now provide a further secret, pruning preimages 15-17
1907 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1908 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
1909 assert_eq!(monitor.payment_preimages.len(), 13);
1910 test_preimages_exist!(&preimages[0..10], monitor);
1911 test_preimages_exist!(&preimages[17..20], monitor);
1913 // Now update local commitment tx info, pruning only element 18 as we still care about the
1914 // previous commitment tx's preimages too
1915 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
1916 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1917 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
1918 assert_eq!(monitor.payment_preimages.len(), 12);
1919 test_preimages_exist!(&preimages[0..10], monitor);
1920 test_preimages_exist!(&preimages[18..20], monitor);
1922 // But if we do it again, we'll prune 5-10
1923 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
1924 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1925 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
1926 assert_eq!(monitor.payment_preimages.len(), 5);
1927 test_preimages_exist!(&preimages[0..5], monitor);
1930 // Further testing is done in the ChannelManager integration tests.