1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode::{self, Decodable, Encodable};
20 use bitcoin::util::hash::{Hash160, BitcoinHash,Sha256dHash};
21 use bitcoin::util::bip143;
23 use crypto::digest::Digest;
25 use secp256k1::{Secp256k1,Message,Signature};
26 use secp256k1::key::{SecretKey,PublicKey};
29 use ln::msgs::DecodeError;
31 use ln::chan_utils::HTLCOutputInCommitment;
32 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
33 use chain::transaction::OutPoint;
34 use chain::keysinterface::SpendableOutputDescriptor;
35 use util::logger::Logger;
36 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
37 use util::sha2::Sha256;
38 use util::{byte_utils, events};
40 use std::collections::HashMap;
41 use std::sync::{Arc,Mutex};
42 use std::{hash,cmp, mem};
44 /// An error enum representing a failure to persist a channel monitor update.
46 pub enum ChannelMonitorUpdateErr {
47 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
48 /// to succeed at some point in the future).
50 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
51 /// submitting new commitment transactions to the remote party.
52 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
53 /// the channel to an operational state.
55 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
56 /// persisted is unsafe - if you failed to store the update on your own local disk you should
57 /// instead return PermanentFailure to force closure of the channel ASAP.
59 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
60 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
61 /// to claim it on this channel) and those updates must be applied wherever they can be. At
62 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
63 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
64 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
67 /// Note that even if updates made after TemporaryFailure succeed you must still call
68 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
69 /// channel operation.
71 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
72 /// different watchtower and cannot update with all watchtowers that were previously informed
73 /// of this channel). This will force-close the channel in question.
75 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
79 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
80 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
81 /// means you tried to merge two monitors for different channels or for a channel which was
82 /// restored from a backup and then generated new commitment updates.
83 /// Contains a human-readable error message.
85 pub struct MonitorUpdateError(pub &'static str);
87 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
88 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
89 /// events to it, while also taking any add_update_monitor events and passing them to some remote
92 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
93 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
94 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
95 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
96 pub trait ManyChannelMonitor: Send + Sync {
97 /// Adds or updates a monitor for the given `funding_txo`.
99 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
100 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
101 /// any spends of it.
102 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
105 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
106 /// watchtower or watch our own channels.
108 /// Note that you must provide your own key by which to refer to channels.
110 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
111 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
112 /// index by a PublicKey which is required to sign any updates.
114 /// If you're using this for local monitoring of your own channels, you probably want to use
115 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
116 pub struct SimpleManyChannelMonitor<Key> {
117 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
118 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
120 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
121 chain_monitor: Arc<ChainWatchInterface>,
122 broadcaster: Arc<BroadcasterInterface>,
123 pending_events: Mutex<Vec<events::Event>>,
127 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
128 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
129 let block_hash = header.bitcoin_hash();
130 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
132 let mut monitors = self.monitors.lock().unwrap();
133 for monitor in monitors.values_mut() {
134 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
135 if spendable_outputs.len() > 0 {
136 new_events.push(events::Event::SpendableOutputs {
137 outputs: spendable_outputs,
140 for (ref txid, ref outputs) in txn_outputs {
141 for (idx, output) in outputs.iter().enumerate() {
142 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
147 let mut pending_events = self.pending_events.lock().unwrap();
148 pending_events.append(&mut new_events);
151 fn block_disconnected(&self, _: &BlockHeader) { }
154 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
155 /// Creates a new object which can be used to monitor several channels given the chain
156 /// interface with which to register to receive notifications.
157 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
158 let res = Arc::new(SimpleManyChannelMonitor {
159 monitors: Mutex::new(HashMap::new()),
162 pending_events: Mutex::new(Vec::new()),
165 let weak_res = Arc::downgrade(&res);
166 res.chain_monitor.register_listener(weak_res);
170 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
171 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
172 let mut monitors = self.monitors.lock().unwrap();
173 match monitors.get_mut(&key) {
174 Some(orig_monitor) => {
175 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
176 return orig_monitor.insert_combine(monitor);
180 match monitor.key_storage {
181 Storage::Local { ref funding_info, .. } => {
184 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
186 &Some((ref outpoint, ref script)) => {
187 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
188 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
189 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
193 Storage::Watchtower { .. } => {
194 self.chain_monitor.watch_all_txn();
197 monitors.insert(key, monitor);
202 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
203 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
204 match self.add_update_monitor_by_key(funding_txo, monitor) {
206 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
211 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
212 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
213 let mut pending_events = self.pending_events.lock().unwrap();
214 let mut ret = Vec::new();
215 mem::swap(&mut ret, &mut *pending_events);
220 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
221 /// instead claiming it in its own individual transaction.
222 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
223 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
224 /// HTLC-Success transaction.
225 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
226 /// transaction confirmed (and we use it in a few more, equivalent, places).
227 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
228 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
229 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
230 /// copies of ChannelMonitors, including watchtowers).
231 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
233 #[derive(Clone, PartialEq)]
236 revocation_base_key: SecretKey,
237 htlc_base_key: SecretKey,
238 delayed_payment_base_key: SecretKey,
239 payment_base_key: SecretKey,
240 shutdown_pubkey: PublicKey,
241 prev_latest_per_commitment_point: Option<PublicKey>,
242 latest_per_commitment_point: Option<PublicKey>,
243 funding_info: Option<(OutPoint, Script)>,
246 revocation_base_key: PublicKey,
247 htlc_base_key: PublicKey,
251 #[derive(Clone, PartialEq)]
252 struct LocalSignedTx {
253 /// txid of the transaction in tx, just used to make comparison faster
256 revocation_key: PublicKey,
257 a_htlc_key: PublicKey,
258 b_htlc_key: PublicKey,
259 delayed_payment_key: PublicKey,
261 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
264 const SERIALIZATION_VERSION: u8 = 1;
265 const MIN_SERIALIZATION_VERSION: u8 = 1;
267 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
268 /// on-chain transactions to ensure no loss of funds occurs.
270 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
271 /// information and are actively monitoring the chain.
273 pub struct ChannelMonitor {
274 commitment_transaction_number_obscure_factor: u64,
276 key_storage: Storage,
277 their_htlc_base_key: Option<PublicKey>,
278 their_delayed_payment_base_key: Option<PublicKey>,
279 // first is the idx of the first of the two revocation points
280 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
282 our_to_self_delay: u16,
283 their_to_self_delay: Option<u16>,
285 old_secrets: [([u8; 32], u64); 49],
286 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
287 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
288 /// Nor can we figure out their commitment numbers without the commitment transaction they are
289 /// spending. Thus, in order to claim them via revocation key, we track all the remote
290 /// commitment transactions which we find on-chain, mapping them to the commitment number which
291 /// can be used to derive the revocation key and claim the transactions.
292 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
293 /// Cache used to make pruning of payment_preimages faster.
294 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
295 /// remote transactions (ie should remain pretty small).
296 /// Serialized to disk but should generally not be sent to Watchtowers.
297 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
299 // We store two local commitment transactions to avoid any race conditions where we may update
300 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
301 // various monitors for one channel being out of sync, and us broadcasting a local
302 // transaction for which we have deleted claim information on some watchtowers.
303 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
304 current_local_signed_commitment_tx: Option<LocalSignedTx>,
306 // Used just for ChannelManager to make sure it has the latest channel data during
308 current_remote_commitment_number: u64,
310 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
312 destination_script: Script,
314 // We simply modify last_block_hash in Channel's block_connected so that serialization is
315 // consistent but hopefully the users' copy handles block_connected in a consistent way.
316 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
317 // their last_block_hash from its state and not based on updated copies that didn't run through
318 // the full block_connected).
319 pub(crate) last_block_hash: Sha256dHash,
320 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
324 #[cfg(any(test, feature = "fuzztarget"))]
325 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
326 /// underlying object
327 impl PartialEq for ChannelMonitor {
328 fn eq(&self, other: &Self) -> bool {
329 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
330 self.key_storage != other.key_storage ||
331 self.their_htlc_base_key != other.their_htlc_base_key ||
332 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
333 self.their_cur_revocation_points != other.their_cur_revocation_points ||
334 self.our_to_self_delay != other.our_to_self_delay ||
335 self.their_to_self_delay != other.their_to_self_delay ||
336 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
337 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
338 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
339 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
340 self.current_remote_commitment_number != other.current_remote_commitment_number ||
341 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
342 self.payment_preimages != other.payment_preimages ||
343 self.destination_script != other.destination_script
347 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
348 if secret != o_secret || idx != o_idx {
357 impl ChannelMonitor {
358 pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
360 commitment_transaction_number_obscure_factor: 0,
362 key_storage: Storage::Local {
363 revocation_base_key: revocation_base_key.clone(),
364 htlc_base_key: htlc_base_key.clone(),
365 delayed_payment_base_key: delayed_payment_base_key.clone(),
366 payment_base_key: payment_base_key.clone(),
367 shutdown_pubkey: shutdown_pubkey.clone(),
368 prev_latest_per_commitment_point: None,
369 latest_per_commitment_point: None,
372 their_htlc_base_key: None,
373 their_delayed_payment_base_key: None,
374 their_cur_revocation_points: None,
376 our_to_self_delay: our_to_self_delay,
377 their_to_self_delay: None,
379 old_secrets: [([0; 32], 1 << 48); 49],
380 remote_claimable_outpoints: HashMap::new(),
381 remote_commitment_txn_on_chain: HashMap::new(),
382 remote_hash_commitment_number: HashMap::new(),
384 prev_local_signed_commitment_tx: None,
385 current_local_signed_commitment_tx: None,
386 current_remote_commitment_number: 1 << 48,
388 payment_preimages: HashMap::new(),
389 destination_script: destination_script,
391 last_block_hash: Default::default(),
392 secp_ctx: Secp256k1::new(),
398 fn place_secret(idx: u64) -> u8 {
400 if idx & (1 << i) == (1 << i) {
408 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
409 let mut res: [u8; 32] = secret;
411 let bitpos = bits - 1 - i;
412 if idx & (1 << bitpos) == (1 << bitpos) {
413 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
414 let mut sha = Sha256::new();
416 sha.result(&mut res);
422 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
423 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
424 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
425 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
426 let pos = ChannelMonitor::place_secret(idx);
428 let (old_secret, old_idx) = self.old_secrets[i as usize];
429 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
430 return Err(MonitorUpdateError("Previous secret did not match new one"));
433 self.old_secrets[pos as usize] = (secret, idx);
435 if !self.payment_preimages.is_empty() {
436 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
437 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
438 let min_idx = self.get_min_seen_secret();
439 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
441 self.payment_preimages.retain(|&k, _| {
442 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
443 if k == htlc.payment_hash {
447 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
448 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
449 if k == htlc.payment_hash {
454 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
461 remote_hash_commitment_number.remove(&k);
470 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
471 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
472 /// possibly future revocation/preimage information) to claim outputs where possible.
473 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
474 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64, their_revocation_point: PublicKey) {
475 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
476 // so that a remote monitor doesn't learn anything unless there is a malicious close.
477 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
479 for htlc in &htlc_outputs {
480 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
482 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
483 self.current_remote_commitment_number = commitment_number;
484 //TODO: Merge this into the other per-remote-transaction output storage stuff
485 match self.their_cur_revocation_points {
486 Some(old_points) => {
487 if old_points.0 == commitment_number + 1 {
488 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
489 } else if old_points.0 == commitment_number + 2 {
490 if let Some(old_second_point) = old_points.2 {
491 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
493 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
496 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
500 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
505 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
506 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
507 /// is important that any clones of this channel monitor (including remote clones) by kept
508 /// up-to-date as our local commitment transaction is updated.
509 /// Panics if set_their_to_self_delay has never been called.
510 /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
511 /// case of onchain HTLC tx
512 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)>) {
513 assert!(self.their_to_self_delay.is_some());
514 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
515 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
516 txid: signed_commitment_tx.txid(),
517 tx: signed_commitment_tx,
518 revocation_key: local_keys.revocation_key,
519 a_htlc_key: local_keys.a_htlc_key,
520 b_htlc_key: local_keys.b_htlc_key,
521 delayed_payment_key: local_keys.a_delayed_payment_key,
526 if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
527 *latest_per_commitment_point = Some(local_keys.per_commitment_point);
529 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
533 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
534 /// commitment_tx_infos which contain the payment hash have been revoked.
535 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
536 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
539 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
540 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
541 /// chain for new blocks/transactions.
542 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
543 match self.key_storage {
544 Storage::Local { ref funding_info, .. } => {
545 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
546 let our_funding_info = funding_info;
547 if let Storage::Local { ref funding_info, .. } = other.key_storage {
548 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
549 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
550 // easy to collide the funding_txo hash and have a different scriptPubKey.
551 if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
552 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
555 return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
558 Storage::Watchtower { .. } => {
559 if let Storage::Watchtower { .. } = other.key_storage {
562 return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
566 let other_min_secret = other.get_min_seen_secret();
567 let our_min_secret = self.get_min_seen_secret();
568 if our_min_secret > other_min_secret {
569 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
571 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
572 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
573 let our_commitment_number = 0xffffffffffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
574 let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
575 if our_commitment_number >= other_commitment_number {
576 self.key_storage = other.key_storage;
580 // TODO: We should use current_remote_commitment_number and the commitment number out of
581 // local transactions to decide how to merge
582 if our_min_secret >= other_min_secret {
583 self.their_cur_revocation_points = other.their_cur_revocation_points;
584 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
585 self.remote_claimable_outpoints.insert(txid, htlcs);
587 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
588 self.prev_local_signed_commitment_tx = Some(local_tx);
590 if let Some(local_tx) = other.current_local_signed_commitment_tx {
591 self.current_local_signed_commitment_tx = Some(local_tx);
593 self.payment_preimages = other.payment_preimages;
596 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
600 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
601 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
602 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
603 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
606 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
607 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
608 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
609 /// provides slightly better privacy.
610 /// It's the responsibility of the caller to register outpoint and script with passing the former
611 /// value as key to add_update_monitor.
612 pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
613 match self.key_storage {
614 Storage::Local { ref mut funding_info, .. } => {
615 *funding_info = Some(new_funding_info);
617 Storage::Watchtower { .. } => {
618 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
623 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
624 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
625 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
626 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
629 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
630 self.their_to_self_delay = Some(their_to_self_delay);
633 pub(super) fn unset_funding_info(&mut self) {
634 match self.key_storage {
635 Storage::Local { ref mut funding_info, .. } => {
636 *funding_info = None;
638 Storage::Watchtower { .. } => {
639 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
644 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
645 pub fn get_funding_txo(&self) -> Option<OutPoint> {
646 match self.key_storage {
647 Storage::Local { ref funding_info, .. } => {
649 &Some((outpoint, _)) => Some(outpoint),
653 Storage::Watchtower { .. } => {
659 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
660 /// Generally useful when deserializing as during normal operation the return values of
661 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
662 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
663 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
664 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
665 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
666 for (idx, output) in outputs.iter().enumerate() {
667 res.push(((*txid).clone(), idx as u32, output));
673 /// Serializes into a vec, with various modes for the exposed pub fns
674 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
675 //TODO: We still write out all the serialization here manually instead of using the fancy
676 //serialization framework we have, we should migrate things over to it.
677 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
678 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
680 // Set in initial Channel-object creation, so should always be set by now:
681 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
683 match self.key_storage {
684 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info } => {
685 writer.write_all(&[0; 1])?;
686 writer.write_all(&revocation_base_key[..])?;
687 writer.write_all(&htlc_base_key[..])?;
688 writer.write_all(&delayed_payment_base_key[..])?;
689 writer.write_all(&payment_base_key[..])?;
690 writer.write_all(&shutdown_pubkey.serialize())?;
691 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
692 writer.write_all(&[1; 1])?;
693 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
695 writer.write_all(&[0; 1])?;
697 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
698 writer.write_all(&[1; 1])?;
699 writer.write_all(&latest_per_commitment_point.serialize())?;
701 writer.write_all(&[0; 1])?;
704 &Some((ref outpoint, ref script)) => {
705 writer.write_all(&outpoint.txid[..])?;
706 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
707 script.write(writer)?;
710 debug_assert!(false, "Try to serialize a useless Local monitor !");
714 Storage::Watchtower { .. } => unimplemented!(),
717 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
718 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
720 match self.their_cur_revocation_points {
721 Some((idx, pubkey, second_option)) => {
722 writer.write_all(&byte_utils::be48_to_array(idx))?;
723 writer.write_all(&pubkey.serialize())?;
724 match second_option {
725 Some(second_pubkey) => {
726 writer.write_all(&second_pubkey.serialize())?;
729 writer.write_all(&[0; 33])?;
734 writer.write_all(&byte_utils::be48_to_array(0))?;
738 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
739 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
741 for &(ref secret, ref idx) in self.old_secrets.iter() {
742 writer.write_all(secret)?;
743 writer.write_all(&byte_utils::be64_to_array(*idx))?;
746 macro_rules! serialize_htlc_in_commitment {
747 ($htlc_output: expr) => {
748 writer.write_all(&[$htlc_output.offered as u8; 1])?;
749 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
750 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
751 writer.write_all(&$htlc_output.payment_hash)?;
752 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
756 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
757 for (ref txid, ref htlc_outputs) in self.remote_claimable_outpoints.iter() {
758 writer.write_all(&txid[..])?;
759 writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
760 for htlc_output in htlc_outputs.iter() {
761 serialize_htlc_in_commitment!(htlc_output);
765 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
766 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
767 writer.write_all(&txid[..])?;
768 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
769 (txouts.len() as u64).write(writer)?;
770 for script in txouts.iter() {
771 script.write(writer)?;
775 if for_local_storage {
776 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
777 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
778 writer.write_all(*payment_hash)?;
779 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
782 writer.write_all(&byte_utils::be64_to_array(0))?;
785 macro_rules! serialize_local_tx {
786 ($local_tx: expr) => {
787 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
789 encode::Error::Io(e) => return Err(e),
790 _ => panic!("local tx must have been well-formed!"),
794 writer.write_all(&$local_tx.revocation_key.serialize())?;
795 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
796 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
797 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
799 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
800 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
801 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
802 serialize_htlc_in_commitment!(htlc_output);
803 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
804 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
809 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
810 writer.write_all(&[1; 1])?;
811 serialize_local_tx!(prev_local_tx);
813 writer.write_all(&[0; 1])?;
816 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
817 writer.write_all(&[1; 1])?;
818 serialize_local_tx!(cur_local_tx);
820 writer.write_all(&[0; 1])?;
823 if for_local_storage {
824 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
826 writer.write_all(&byte_utils::be48_to_array(0))?;
829 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
830 for payment_preimage in self.payment_preimages.values() {
831 writer.write_all(payment_preimage)?;
834 self.last_block_hash.write(writer)?;
835 self.destination_script.write(writer)?;
840 /// Writes this monitor into the given writer, suitable for writing to disk.
842 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
843 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
844 /// the "reorg path" (ie not just starting at the same height but starting at the highest
845 /// common block that appears on your best chain as well as on the chain which contains the
846 /// last block hash returned) upon deserializing the object!
847 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
848 self.write(writer, true)
851 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
853 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
854 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
855 /// the "reorg path" (ie not just starting at the same height but starting at the highest
856 /// common block that appears on your best chain as well as on the chain which contains the
857 /// last block hash returned) upon deserializing the object!
858 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
859 self.write(writer, false)
862 //TODO: Functions to serialize/deserialize (with different forms depending on which information
863 //we want to leave out (eg funding_txo, etc).
865 /// Can only fail if idx is < get_min_seen_secret
866 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
867 for i in 0..self.old_secrets.len() {
868 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
869 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
872 assert!(idx < self.get_min_seen_secret());
876 pub(super) fn get_min_seen_secret(&self) -> u64 {
877 //TODO This can be optimized?
878 let mut min = 1 << 48;
879 for &(_, idx) in self.old_secrets.iter() {
887 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
888 self.current_remote_commitment_number
891 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
892 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
893 0xffff_ffff_ffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor)
894 } else { 0xffff_ffff_ffff }
897 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
898 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
899 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
900 /// HTLC-Success/HTLC-Timeout transactions.
901 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
902 // Most secp and related errors trying to create keys means we have no hope of constructing
903 // a spend transaction...so we return no transactions to broadcast
904 let mut txn_to_broadcast = Vec::new();
905 let mut watch_outputs = Vec::new();
906 let mut spendable_outputs = Vec::new();
908 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
909 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
911 macro_rules! ignore_error {
912 ( $thing : expr ) => {
915 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
920 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);
921 if commitment_number >= self.get_min_seen_secret() {
922 let secret = self.get_secret(commitment_number).unwrap();
923 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
924 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
925 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
926 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
927 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
928 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
929 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
931 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
932 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
933 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
934 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
938 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key.unwrap()));
939 let a_htlc_key = match self.their_htlc_base_key {
940 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
941 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)),
944 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
945 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
947 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
948 // Note that the Network here is ignored as we immediately drop the address for the
949 // script_pubkey version.
950 let payment_hash160 = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
951 Some(Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
954 let mut total_value = 0;
955 let mut values = Vec::new();
956 let mut inputs = Vec::new();
957 let mut htlc_idxs = Vec::new();
959 for (idx, outp) in tx.output.iter().enumerate() {
960 if outp.script_pubkey == revokeable_p2wsh {
962 previous_output: BitcoinOutPoint {
963 txid: commitment_txid,
966 script_sig: Script::new(),
967 sequence: 0xfffffffd,
970 htlc_idxs.push(None);
971 values.push(outp.value);
972 total_value += outp.value;
973 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
974 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
975 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
976 key: local_payment_key.unwrap(),
977 output: outp.clone(),
982 macro_rules! sign_input {
983 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
985 let (sig, redeemscript) = match self.key_storage {
986 Storage::Local { ref revocation_base_key, .. } => {
987 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
988 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
989 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
991 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
992 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
993 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
995 Storage::Watchtower { .. } => {
999 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1000 $input.witness[0].push(SigHashType::All as u8);
1001 if $htlc_idx.is_none() {
1002 $input.witness.push(vec!(1));
1004 $input.witness.push(revocation_pubkey.serialize().to_vec());
1006 $input.witness.push(redeemscript.into_bytes());
1011 if let Some(per_commitment_data) = per_commitment_option {
1012 inputs.reserve_exact(per_commitment_data.len());
1014 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1015 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1016 if htlc.transaction_output_index as usize >= tx.output.len() ||
1017 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1018 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1019 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1022 previous_output: BitcoinOutPoint {
1023 txid: commitment_txid,
1024 vout: htlc.transaction_output_index,
1026 script_sig: Script::new(),
1027 sequence: 0xfffffffd,
1028 witness: Vec::new(),
1030 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1032 htlc_idxs.push(Some(idx));
1033 values.push(tx.output[htlc.transaction_output_index as usize].value);
1034 total_value += htlc.amount_msat / 1000;
1036 let mut single_htlc_tx = Transaction {
1040 output: vec!(TxOut {
1041 script_pubkey: self.destination_script.clone(),
1042 value: htlc.amount_msat / 1000, //TODO: - fee
1045 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1046 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1047 txn_to_broadcast.push(single_htlc_tx);
1052 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1053 // We're definitely a remote commitment transaction!
1054 watch_outputs.append(&mut tx.output.clone());
1055 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1057 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1059 let outputs = vec!(TxOut {
1060 script_pubkey: self.destination_script.clone(),
1061 value: total_value, //TODO: - fee
1063 let mut spend_tx = Transaction {
1070 let mut values_drain = values.drain(..);
1071 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1073 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1074 let value = values_drain.next().unwrap();
1075 sign_input!(sighash_parts, input, htlc_idx, value);
1078 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1079 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1080 output: spend_tx.output[0].clone(),
1082 txn_to_broadcast.push(spend_tx);
1083 } else if let Some(per_commitment_data) = per_commitment_option {
1084 // While this isn't useful yet, there is a potential race where if a counterparty
1085 // revokes a state at the same time as the commitment transaction for that state is
1086 // confirmed, and the watchtower receives the block before the user, the user could
1087 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1088 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1089 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1091 watch_outputs.append(&mut tx.output.clone());
1092 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1094 if let Some(revocation_points) = self.their_cur_revocation_points {
1095 let revocation_point_option =
1096 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1097 else if let Some(point) = revocation_points.2.as_ref() {
1098 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1100 if let Some(revocation_point) = revocation_point_option {
1101 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1102 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1103 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1104 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1106 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1107 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1108 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1111 let a_htlc_key = match self.their_htlc_base_key {
1112 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1113 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1116 for (idx, outp) in tx.output.iter().enumerate() {
1117 if outp.script_pubkey.is_v0_p2wpkh() {
1118 match self.key_storage {
1119 Storage::Local { ref payment_base_key, .. } => {
1120 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1121 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1122 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1124 output: outp.clone(),
1128 Storage::Watchtower { .. } => {}
1130 break; // Only to_remote ouput is claimable
1134 let mut total_value = 0;
1135 let mut values = Vec::new();
1136 let mut inputs = Vec::new();
1138 macro_rules! sign_input {
1139 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1141 let (sig, redeemscript) = match self.key_storage {
1142 Storage::Local { ref htlc_base_key, .. } => {
1143 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1144 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1145 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1146 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1147 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1149 Storage::Watchtower { .. } => {
1153 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1154 $input.witness[0].push(SigHashType::All as u8);
1155 $input.witness.push($preimage);
1156 $input.witness.push(redeemscript.into_bytes());
1161 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1162 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1163 if htlc.transaction_output_index as usize >= tx.output.len() ||
1164 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1165 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1166 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1168 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1170 previous_output: BitcoinOutPoint {
1171 txid: commitment_txid,
1172 vout: htlc.transaction_output_index,
1174 script_sig: Script::new(),
1175 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1176 witness: Vec::new(),
1178 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1180 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1181 total_value += htlc.amount_msat / 1000;
1183 let mut single_htlc_tx = Transaction {
1187 output: vec!(TxOut {
1188 script_pubkey: self.destination_script.clone(),
1189 value: htlc.amount_msat / 1000, //TODO: - fee
1192 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1193 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1194 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1195 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1196 output: single_htlc_tx.output[0].clone(),
1198 txn_to_broadcast.push(single_htlc_tx);
1203 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1205 let outputs = vec!(TxOut {
1206 script_pubkey: self.destination_script.clone(),
1207 value: total_value, //TODO: - fee
1209 let mut spend_tx = Transaction {
1216 let mut values_drain = values.drain(..);
1217 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1219 for input in spend_tx.input.iter_mut() {
1220 let value = values_drain.next().unwrap();
1221 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1224 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1225 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1226 output: spend_tx.output[0].clone(),
1228 txn_to_broadcast.push(spend_tx);
1233 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1236 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1237 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1238 if tx.input.len() != 1 || tx.output.len() != 1 {
1242 macro_rules! ignore_error {
1243 ( $thing : expr ) => {
1246 Err(_) => return (None, None)
1251 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
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 Storage::Local { 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 Storage::Watchtower { 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, 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();
1268 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1270 let mut inputs = Vec::new();
1273 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1275 previous_output: BitcoinOutPoint {
1279 script_sig: Script::new(),
1280 sequence: 0xfffffffd,
1281 witness: Vec::new(),
1283 amount = tx.output[0].value;
1286 if !inputs.is_empty() {
1287 let outputs = vec!(TxOut {
1288 script_pubkey: self.destination_script.clone(),
1289 value: amount, //TODO: - fee
1292 let mut spend_tx = Transaction {
1299 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1301 let sig = match self.key_storage {
1302 Storage::Local { ref revocation_base_key, .. } => {
1303 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1304 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1305 self.secp_ctx.sign(&sighash, &revocation_key)
1307 Storage::Watchtower { .. } => {
1311 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1312 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1313 spend_tx.input[0].witness.push(vec!(1));
1314 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1316 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1317 let output = spend_tx.output[0].clone();
1318 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1319 } else { (None, None) }
1322 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1323 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1324 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1326 macro_rules! add_dynamic_output {
1327 ($father_tx: expr, $vout: expr) => {
1328 if let Some(ref per_commitment_point) = *per_commitment_point {
1329 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1330 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1331 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1332 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1333 key: local_delayedkey,
1334 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1335 to_self_delay: self.our_to_self_delay,
1336 output: $father_tx.output[$vout as usize].clone(),
1345 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1346 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1347 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1348 if output.script_pubkey == revokeable_p2wsh {
1349 add_dynamic_output!(local_tx.tx, idx as u32);
1354 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1356 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);
1358 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1360 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1361 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1362 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1363 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1365 htlc_timeout_tx.input[0].witness.push(Vec::new());
1366 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());
1368 add_dynamic_output!(htlc_timeout_tx, 0);
1369 res.push(htlc_timeout_tx);
1371 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1372 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);
1374 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1376 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1377 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1378 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1379 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1381 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1382 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());
1384 add_dynamic_output!(htlc_success_tx, 0);
1385 res.push(htlc_success_tx);
1390 (res, spendable_outputs)
1393 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1394 /// revoked using data in local_claimable_outpoints.
1395 /// Should not be used if check_spend_revoked_transaction succeeds.
1396 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1397 let commitment_txid = tx.txid();
1398 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1399 if local_tx.txid == commitment_txid {
1400 match self.key_storage {
1401 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1402 return self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1404 Storage::Watchtower { .. } => {
1405 return self.broadcast_by_local_state(local_tx, &None, &None);
1410 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1411 if local_tx.txid == commitment_txid {
1412 match self.key_storage {
1413 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1414 return self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1416 Storage::Watchtower { .. } => {
1417 return self.broadcast_by_local_state(local_tx, &None, &None);
1422 (Vec::new(), Vec::new())
1425 /// Generate a spendable output event when closing_transaction get registered onchain.
1426 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1427 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1428 match self.key_storage {
1429 Storage::Local { ref shutdown_pubkey, .. } => {
1430 let our_channel_close_key_hash = Hash160::from_data(&shutdown_pubkey.serialize());
1431 let shutdown_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1432 for (idx, output) in tx.output.iter().enumerate() {
1433 if shutdown_script == output.script_pubkey {
1434 return Some(SpendableOutputDescriptor::StaticOutput {
1435 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1436 output: output.clone(),
1441 Storage::Watchtower { .. } => {
1442 //TODO: we need to ensure an offline client will generate the event when it
1443 // cames back online after only the watchtower saw the transaction
1450 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1451 /// the Channel was out-of-date.
1452 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1453 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1454 let mut res = vec![local_tx.tx.clone()];
1455 match self.key_storage {
1456 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1457 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1459 _ => panic!("Can only broadcast by local channelmonitor"),
1467 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>) {
1468 let mut watch_outputs = Vec::new();
1469 let mut spendable_outputs = Vec::new();
1470 for tx in txn_matched {
1471 if tx.input.len() == 1 {
1472 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1473 // commitment transactions and HTLC transactions will all only ever have one input,
1474 // which is an easy way to filter out any potential non-matching txn for lazy
1476 let prevout = &tx.input[0].previous_output;
1477 let mut txn: Vec<Transaction> = Vec::new();
1478 let funding_txo = match self.key_storage {
1479 Storage::Local { ref funding_info, .. } => {
1480 funding_info.clone()
1482 Storage::Watchtower { .. } => {
1486 if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
1487 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height);
1489 spendable_outputs.append(&mut spendable_output);
1490 if !new_outputs.1.is_empty() {
1491 watch_outputs.push(new_outputs);
1494 let (remote_txn, mut outputs) = self.check_spend_local_transaction(tx, height);
1495 spendable_outputs.append(&mut outputs);
1498 if !funding_txo.is_none() && txn.is_empty() {
1499 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1500 spendable_outputs.push(spendable_output);
1504 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1505 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1506 if let Some(tx) = tx {
1509 if let Some(spendable_output) = spendable_output {
1510 spendable_outputs.push(spendable_output);
1514 for tx in txn.iter() {
1515 broadcaster.broadcast_transaction(tx);
1519 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1520 if self.would_broadcast_at_height(height) {
1521 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1522 match self.key_storage {
1523 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1524 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1525 spendable_outputs.append(&mut outputs);
1527 broadcaster.broadcast_transaction(&tx);
1530 Storage::Watchtower { .. } => {
1531 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1532 spendable_outputs.append(&mut outputs);
1534 broadcaster.broadcast_transaction(&tx);
1540 self.last_block_hash = block_hash.clone();
1541 (watch_outputs, spendable_outputs)
1544 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1545 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1546 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1547 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1548 // chain with enough room to claim the HTLC without our counterparty being able to
1549 // time out the HTLC first.
1550 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1551 // concern is being able to claim the corresponding inbound HTLC (on another
1552 // channel) before it expires. In fact, we don't even really care if our
1553 // counterparty here claims such an outbound HTLC after it expired as long as we
1554 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1555 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1556 // we give ourselves a few blocks of headroom after expiration before going
1557 // on-chain for an expired HTLC.
1558 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1559 // from us until we've reached the point where we go on-chain with the
1560 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1561 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1562 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1563 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1564 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1565 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1566 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1567 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1568 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1577 const MAX_ALLOC_SIZE: usize = 64*1024;
1579 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1580 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1581 let secp_ctx = Secp256k1::new();
1582 macro_rules! unwrap_obj {
1586 Err(_) => return Err(DecodeError::InvalidValue),
1591 let _ver: u8 = Readable::read(reader)?;
1592 let min_ver: u8 = Readable::read(reader)?;
1593 if min_ver > SERIALIZATION_VERSION {
1594 return Err(DecodeError::UnknownVersion);
1597 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1599 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1601 let revocation_base_key = Readable::read(reader)?;
1602 let htlc_base_key = Readable::read(reader)?;
1603 let delayed_payment_base_key = Readable::read(reader)?;
1604 let payment_base_key = Readable::read(reader)?;
1605 let shutdown_pubkey = Readable::read(reader)?;
1606 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1608 1 => Some(Readable::read(reader)?),
1609 _ => return Err(DecodeError::InvalidValue),
1611 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1613 1 => Some(Readable::read(reader)?),
1614 _ => return Err(DecodeError::InvalidValue),
1616 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1617 // barely-init'd ChannelMonitors that we can't do anything with.
1618 let outpoint = OutPoint {
1619 txid: Readable::read(reader)?,
1620 index: Readable::read(reader)?,
1622 let funding_info = Some((outpoint, Readable::read(reader)?));
1624 revocation_base_key,
1626 delayed_payment_base_key,
1629 prev_latest_per_commitment_point,
1630 latest_per_commitment_point,
1634 _ => return Err(DecodeError::InvalidValue),
1637 let their_htlc_base_key = Some(Readable::read(reader)?);
1638 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1640 let their_cur_revocation_points = {
1641 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1645 let first_point = Readable::read(reader)?;
1646 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1647 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1648 Some((first_idx, first_point, None))
1650 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1655 let our_to_self_delay: u16 = Readable::read(reader)?;
1656 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1658 let mut old_secrets = [([0; 32], 1 << 48); 49];
1659 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1660 *secret = Readable::read(reader)?;
1661 *idx = Readable::read(reader)?;
1664 macro_rules! read_htlc_in_commitment {
1667 let offered: bool = Readable::read(reader)?;
1668 let amount_msat: u64 = Readable::read(reader)?;
1669 let cltv_expiry: u32 = Readable::read(reader)?;
1670 let payment_hash: [u8; 32] = Readable::read(reader)?;
1671 let transaction_output_index: u32 = Readable::read(reader)?;
1673 HTLCOutputInCommitment {
1674 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1680 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1681 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1682 for _ in 0..remote_claimable_outpoints_len {
1683 let txid: Sha256dHash = Readable::read(reader)?;
1684 let outputs_count: u64 = Readable::read(reader)?;
1685 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1686 for _ in 0..outputs_count {
1687 outputs.push(read_htlc_in_commitment!());
1689 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1690 return Err(DecodeError::InvalidValue);
1694 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
1695 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
1696 for _ in 0..remote_commitment_txn_on_chain_len {
1697 let txid: Sha256dHash = Readable::read(reader)?;
1698 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1699 let outputs_count = <u64 as Readable<R>>::read(reader)?;
1700 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
1701 for _ in 0..outputs_count {
1702 outputs.push(Readable::read(reader)?);
1704 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
1705 return Err(DecodeError::InvalidValue);
1709 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
1710 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
1711 for _ in 0..remote_hash_commitment_number_len {
1712 let txid: [u8; 32] = Readable::read(reader)?;
1713 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1714 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1715 return Err(DecodeError::InvalidValue);
1719 macro_rules! read_local_tx {
1722 let tx = match Transaction::consensus_decode(reader.by_ref()) {
1725 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
1726 _ => return Err(DecodeError::InvalidValue),
1730 if tx.input.is_empty() {
1731 // Ensure tx didn't hit the 0-input ambiguity case.
1732 return Err(DecodeError::InvalidValue);
1735 let revocation_key = Readable::read(reader)?;
1736 let a_htlc_key = Readable::read(reader)?;
1737 let b_htlc_key = Readable::read(reader)?;
1738 let delayed_payment_key = Readable::read(reader)?;
1739 let feerate_per_kw: u64 = Readable::read(reader)?;
1741 let htlc_outputs_len: u64 = Readable::read(reader)?;
1742 let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
1743 for _ in 0..htlc_outputs_len {
1744 htlc_outputs.push((read_htlc_in_commitment!(), Readable::read(reader)?, Readable::read(reader)?));
1749 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1755 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1758 Some(read_local_tx!())
1760 _ => return Err(DecodeError::InvalidValue),
1763 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1766 Some(read_local_tx!())
1768 _ => return Err(DecodeError::InvalidValue),
1771 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1773 let payment_preimages_len: u64 = Readable::read(reader)?;
1774 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
1775 let mut sha = Sha256::new();
1776 for _ in 0..payment_preimages_len {
1777 let preimage: [u8; 32] = Readable::read(reader)?;
1779 sha.input(&preimage);
1780 let mut hash = [0; 32];
1781 sha.result(&mut hash);
1782 if let Some(_) = payment_preimages.insert(hash, preimage) {
1783 return Err(DecodeError::InvalidValue);
1787 let last_block_hash: Sha256dHash = Readable::read(reader)?;
1788 let destination_script = Readable::read(reader)?;
1790 Ok((last_block_hash.clone(), ChannelMonitor {
1791 commitment_transaction_number_obscure_factor,
1794 their_htlc_base_key,
1795 their_delayed_payment_base_key,
1796 their_cur_revocation_points,
1799 their_to_self_delay,
1802 remote_claimable_outpoints,
1803 remote_commitment_txn_on_chain,
1804 remote_hash_commitment_number,
1806 prev_local_signed_commitment_tx,
1807 current_local_signed_commitment_tx,
1808 current_remote_commitment_number,
1823 use bitcoin::blockdata::script::Script;
1824 use bitcoin::blockdata::transaction::Transaction;
1825 use crypto::digest::Digest;
1827 use ln::channelmonitor::ChannelMonitor;
1828 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1829 use util::sha2::Sha256;
1830 use util::test_utils::TestLogger;
1831 use secp256k1::key::{SecretKey,PublicKey};
1832 use secp256k1::{Secp256k1, Signature};
1833 use rand::{thread_rng,Rng};
1837 fn test_per_commitment_storage() {
1838 // Test vectors from BOLT 3:
1839 let mut secrets: Vec<[u8; 32]> = Vec::new();
1840 let mut monitor: ChannelMonitor;
1841 let secp_ctx = Secp256k1::new();
1842 let logger = Arc::new(TestLogger::new());
1844 macro_rules! test_secrets {
1846 let mut idx = 281474976710655;
1847 for secret in secrets.iter() {
1848 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1851 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1852 assert!(monitor.get_secret(idx).is_none());
1857 // insert_secret correct sequence
1858 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1861 secrets.push([0; 32]);
1862 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1863 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1866 secrets.push([0; 32]);
1867 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1868 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1871 secrets.push([0; 32]);
1872 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1873 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1876 secrets.push([0; 32]);
1877 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1878 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1881 secrets.push([0; 32]);
1882 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1883 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1886 secrets.push([0; 32]);
1887 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1888 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1891 secrets.push([0; 32]);
1892 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1893 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1896 secrets.push([0; 32]);
1897 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1898 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1903 // insert_secret #1 incorrect
1904 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1907 secrets.push([0; 32]);
1908 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1909 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1912 secrets.push([0; 32]);
1913 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1914 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
1915 "Previous secret did not match new one");
1919 // insert_secret #2 incorrect (#1 derived from incorrect)
1920 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1923 secrets.push([0; 32]);
1924 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1925 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1928 secrets.push([0; 32]);
1929 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1930 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1933 secrets.push([0; 32]);
1934 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1935 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1938 secrets.push([0; 32]);
1939 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1940 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
1941 "Previous secret did not match new one");
1945 // insert_secret #3 incorrect
1946 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1949 secrets.push([0; 32]);
1950 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1951 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1954 secrets.push([0; 32]);
1955 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1956 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1959 secrets.push([0; 32]);
1960 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1961 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1964 secrets.push([0; 32]);
1965 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1966 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
1967 "Previous secret did not match new one");
1971 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1972 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1975 secrets.push([0; 32]);
1976 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1977 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1980 secrets.push([0; 32]);
1981 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1982 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1985 secrets.push([0; 32]);
1986 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1987 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1990 secrets.push([0; 32]);
1991 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1992 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1995 secrets.push([0; 32]);
1996 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1997 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2000 secrets.push([0; 32]);
2001 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2002 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2005 secrets.push([0; 32]);
2006 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2007 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2010 secrets.push([0; 32]);
2011 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2012 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2013 "Previous secret did not match new one");
2017 // insert_secret #5 incorrect
2018 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2021 secrets.push([0; 32]);
2022 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2023 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2026 secrets.push([0; 32]);
2027 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2028 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2031 secrets.push([0; 32]);
2032 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2033 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2036 secrets.push([0; 32]);
2037 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2038 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2041 secrets.push([0; 32]);
2042 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2043 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2046 secrets.push([0; 32]);
2047 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2048 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2049 "Previous secret did not match new one");
2053 // insert_secret #6 incorrect (5 derived from incorrect)
2054 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2057 secrets.push([0; 32]);
2058 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2059 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2062 secrets.push([0; 32]);
2063 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2064 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2067 secrets.push([0; 32]);
2068 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2069 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2072 secrets.push([0; 32]);
2073 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2074 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2077 secrets.push([0; 32]);
2078 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2079 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2082 secrets.push([0; 32]);
2083 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2084 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2087 secrets.push([0; 32]);
2088 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2089 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2092 secrets.push([0; 32]);
2093 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2094 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2095 "Previous secret did not match new one");
2099 // insert_secret #7 incorrect
2100 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2103 secrets.push([0; 32]);
2104 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2105 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2108 secrets.push([0; 32]);
2109 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2110 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2113 secrets.push([0; 32]);
2114 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2115 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2118 secrets.push([0; 32]);
2119 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2120 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2123 secrets.push([0; 32]);
2124 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2125 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2128 secrets.push([0; 32]);
2129 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2130 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2133 secrets.push([0; 32]);
2134 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2135 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2138 secrets.push([0; 32]);
2139 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2140 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2141 "Previous secret did not match new one");
2145 // insert_secret #8 incorrect
2146 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2149 secrets.push([0; 32]);
2150 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2151 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2154 secrets.push([0; 32]);
2155 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2156 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2159 secrets.push([0; 32]);
2160 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2161 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2164 secrets.push([0; 32]);
2165 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2166 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2169 secrets.push([0; 32]);
2170 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2171 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2174 secrets.push([0; 32]);
2175 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2176 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2179 secrets.push([0; 32]);
2180 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2181 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2184 secrets.push([0; 32]);
2185 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2186 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2187 "Previous secret did not match new one");
2192 fn test_prune_preimages() {
2193 let secp_ctx = Secp256k1::new();
2194 let logger = Arc::new(TestLogger::new());
2195 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2197 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2198 macro_rules! dummy_keys {
2202 per_commitment_point: dummy_key.clone(),
2203 revocation_key: dummy_key.clone(),
2204 a_htlc_key: dummy_key.clone(),
2205 b_htlc_key: dummy_key.clone(),
2206 a_delayed_payment_key: dummy_key.clone(),
2207 b_payment_key: dummy_key.clone(),
2212 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2214 let mut preimages = Vec::new();
2216 let mut rng = thread_rng();
2218 let mut preimage = [0; 32];
2219 rng.fill_bytes(&mut preimage);
2220 let mut sha = Sha256::new();
2221 sha.input(&preimage);
2222 let mut hash = [0; 32];
2223 sha.result(&mut hash);
2224 preimages.push((preimage, hash));
2228 macro_rules! preimages_slice_to_htlc_outputs {
2229 ($preimages_slice: expr) => {
2231 let mut res = Vec::new();
2232 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2233 res.push(HTLCOutputInCommitment {
2237 payment_hash: preimage.1.clone(),
2238 transaction_output_index: idx as u32,
2245 macro_rules! preimages_to_local_htlcs {
2246 ($preimages_slice: expr) => {
2248 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2249 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2255 macro_rules! test_preimages_exist {
2256 ($preimages_slice: expr, $monitor: expr) => {
2257 for preimage in $preimages_slice {
2258 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2263 // Prune with one old state and a local commitment tx holding a few overlaps with the
2265 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2266 monitor.set_their_to_self_delay(10);
2268 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2269 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2270 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2271 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2272 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2273 for &(ref preimage, ref hash) in preimages.iter() {
2274 monitor.provide_payment_preimage(hash, preimage);
2277 // Now provide a secret, pruning preimages 10-15
2278 let mut secret = [0; 32];
2279 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2280 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2281 assert_eq!(monitor.payment_preimages.len(), 15);
2282 test_preimages_exist!(&preimages[0..10], monitor);
2283 test_preimages_exist!(&preimages[15..20], monitor);
2285 // Now provide a further secret, pruning preimages 15-17
2286 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2287 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2288 assert_eq!(monitor.payment_preimages.len(), 13);
2289 test_preimages_exist!(&preimages[0..10], monitor);
2290 test_preimages_exist!(&preimages[17..20], monitor);
2292 // Now update local commitment tx info, pruning only element 18 as we still care about the
2293 // previous commitment tx's preimages too
2294 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2295 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2296 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2297 assert_eq!(monitor.payment_preimages.len(), 12);
2298 test_preimages_exist!(&preimages[0..10], monitor);
2299 test_preimages_exist!(&preimages[18..20], monitor);
2301 // But if we do it again, we'll prune 5-10
2302 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2303 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2304 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2305 assert_eq!(monitor.payment_preimages.len(), 5);
2306 test_preimages_exist!(&preimages[0..5], monitor);
2309 // Further testing is done in the ChannelManager integration tests.