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;
18 use bitcoin::network::serialize;
19 use bitcoin::network::serialize::BitcoinHash;
20 use bitcoin::network::encodable::{ConsensusDecodable, ConsensusEncodable};
21 use bitcoin::util::hash::Sha256dHash;
22 use bitcoin::util::bip143;
24 use crypto::digest::Digest;
26 use secp256k1::{Secp256k1,Message,Signature};
27 use secp256k1::key::{SecretKey,PublicKey};
30 use ln::msgs::{DecodeError, HandleError};
32 use ln::chan_utils::HTLCOutputInCommitment;
33 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
34 use chain::transaction::OutPoint;
35 use chain::keysinterface::SpendableOutputDescriptor;
36 use util::logger::Logger;
37 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
38 use util::sha2::Sha256;
39 use util::{byte_utils, events};
41 use std::collections::HashMap;
42 use std::sync::{Arc,Mutex};
43 use std::{hash,cmp, mem};
45 /// An error enum representing a failure to persist a channel monitor update.
47 pub enum ChannelMonitorUpdateErr {
48 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
49 /// to succeed at some point in the future).
51 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
52 /// submitting new commitment transactions to the remote party.
53 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
54 /// the channel to an operational state.
56 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
57 /// persisted is unsafe - if you failed to store the update on your own local disk you should
58 /// instead return PermanentFailure to force closure of the channel ASAP.
60 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
61 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
62 /// to claim it on this channel) and those updates must be applied wherever they can be. At
63 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
64 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
65 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
68 /// Note that even if updates made after TemporaryFailure succeed you must still call
69 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
70 /// channel operation.
72 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
73 /// different watchtower and cannot update with all watchtowers that were previously informed
74 /// of this channel). This will force-close the channel in question.
78 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
79 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
80 /// events to it, while also taking any add_update_monitor events and passing them to some remote
83 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
84 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
85 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
86 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
87 pub trait ManyChannelMonitor: Send + Sync {
88 /// Adds or updates a monitor for the given `funding_txo`.
90 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
91 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
93 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
96 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
97 /// watchtower or watch our own channels.
99 /// Note that you must provide your own key by which to refer to channels.
101 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
102 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
103 /// index by a PublicKey which is required to sign any updates.
105 /// If you're using this for local monitoring of your own channels, you probably want to use
106 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
107 pub struct SimpleManyChannelMonitor<Key> {
108 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
109 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
111 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
112 chain_monitor: Arc<ChainWatchInterface>,
113 broadcaster: Arc<BroadcasterInterface>,
114 pending_events: Mutex<Vec<events::Event>>,
118 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
119 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
120 let block_hash = header.bitcoin_hash();
121 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
123 let mut monitors = self.monitors.lock().unwrap();
124 for monitor in monitors.values_mut() {
125 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
126 if spendable_outputs.len() > 0 {
127 new_events.push(events::Event::SpendableOutputs {
128 outputs: spendable_outputs,
131 for (ref txid, ref outputs) in txn_outputs {
132 for (idx, output) in outputs.iter().enumerate() {
133 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
138 let mut pending_events = self.pending_events.lock().unwrap();
139 pending_events.append(&mut new_events);
142 fn block_disconnected(&self, _: &BlockHeader) { }
145 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
146 /// Creates a new object which can be used to monitor several channels given the chain
147 /// interface with which to register to receive notifications.
148 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
149 let res = Arc::new(SimpleManyChannelMonitor {
150 monitors: Mutex::new(HashMap::new()),
153 pending_events: Mutex::new(Vec::new()),
156 let weak_res = Arc::downgrade(&res);
157 res.chain_monitor.register_listener(weak_res);
161 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
162 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
163 let mut monitors = self.monitors.lock().unwrap();
164 match monitors.get_mut(&key) {
165 Some(orig_monitor) => {
166 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_option!(monitor.funding_txo));
167 return orig_monitor.insert_combine(monitor);
171 match &monitor.funding_txo {
173 log_trace!(self, "Got new Channel Monitor for no-funding-set channel (monitoring all txn!)");
174 self.chain_monitor.watch_all_txn()
176 &Some((ref outpoint, ref script)) => {
177 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
178 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
179 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
182 monitors.insert(key, monitor);
187 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
188 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
189 match self.add_update_monitor_by_key(funding_txo, monitor) {
191 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
196 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
197 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
198 let mut pending_events = self.pending_events.lock().unwrap();
199 let mut ret = Vec::new();
200 mem::swap(&mut ret, &mut *pending_events);
205 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
206 /// instead claiming it in its own individual transaction.
207 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
208 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
209 /// HTLC-Success transaction.
210 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
211 /// transaction confirmed (and we use it in a few more, equivalent, places).
212 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
213 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
214 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
215 /// copies of ChannelMonitors, including watchtowers).
216 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
218 #[derive(Clone, PartialEq)]
221 revocation_base_key: SecretKey,
222 htlc_base_key: SecretKey,
223 delayed_payment_base_key: SecretKey,
224 prev_latest_per_commitment_point: Option<PublicKey>,
225 latest_per_commitment_point: Option<PublicKey>,
228 revocation_base_key: PublicKey,
229 htlc_base_key: PublicKey,
230 sigs: HashMap<Sha256dHash, Signature>,
234 #[derive(Clone, PartialEq)]
235 struct LocalSignedTx {
236 /// txid of the transaction in tx, just used to make comparison faster
239 revocation_key: PublicKey,
240 a_htlc_key: PublicKey,
241 b_htlc_key: PublicKey,
242 delayed_payment_key: PublicKey,
244 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
247 const SERIALIZATION_VERSION: u8 = 1;
248 const MIN_SERIALIZATION_VERSION: u8 = 1;
250 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
251 /// on-chain transactions to ensure no loss of funds occurs.
253 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
254 /// information and are actively monitoring the chain.
256 pub struct ChannelMonitor {
257 funding_txo: Option<(OutPoint, Script)>,
258 commitment_transaction_number_obscure_factor: u64,
260 key_storage: KeyStorage,
261 their_htlc_base_key: Option<PublicKey>,
262 their_delayed_payment_base_key: Option<PublicKey>,
263 // first is the idx of the first of the two revocation points
264 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
266 our_to_self_delay: u16,
267 their_to_self_delay: Option<u16>,
269 old_secrets: [([u8; 32], u64); 49],
270 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
271 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
272 /// Nor can we figure out their commitment numbers without the commitment transaction they are
273 /// spending. Thus, in order to claim them via revocation key, we track all the remote
274 /// commitment transactions which we find on-chain, mapping them to the commitment number which
275 /// can be used to derive the revocation key and claim the transactions.
276 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
277 /// Cache used to make pruning of payment_preimages faster.
278 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
279 /// remote transactions (ie should remain pretty small).
280 /// Serialized to disk but should generally not be sent to Watchtowers.
281 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
283 // We store two local commitment transactions to avoid any race conditions where we may update
284 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
285 // various monitors for one channel being out of sync, and us broadcasting a local
286 // transaction for which we have deleted claim information on some watchtowers.
287 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
288 current_local_signed_commitment_tx: Option<LocalSignedTx>,
290 // Used just for ChannelManager to make sure it has the latest channel data during
292 current_remote_commitment_number: u64,
294 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
296 destination_script: Script,
298 // We simply modify last_block_hash in Channel's block_connected so that serialization is
299 // consistent but hopefully the users' copy handles block_connected in a consistent way.
300 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
301 // their last_block_hash from its state and not based on updated copies that didn't run through
302 // the full block_connected).
303 pub(crate) last_block_hash: Sha256dHash,
304 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
308 #[cfg(any(test, feature = "fuzztarget"))]
309 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
310 /// underlying object
311 impl PartialEq for ChannelMonitor {
312 fn eq(&self, other: &Self) -> bool {
313 if self.funding_txo != other.funding_txo ||
314 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
315 self.key_storage != other.key_storage ||
316 self.their_htlc_base_key != other.their_htlc_base_key ||
317 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
318 self.their_cur_revocation_points != other.their_cur_revocation_points ||
319 self.our_to_self_delay != other.our_to_self_delay ||
320 self.their_to_self_delay != other.their_to_self_delay ||
321 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
322 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
323 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
324 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
325 self.current_remote_commitment_number != other.current_remote_commitment_number ||
326 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
327 self.payment_preimages != other.payment_preimages ||
328 self.destination_script != other.destination_script
332 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
333 if secret != o_secret || idx != o_idx {
342 impl ChannelMonitor {
343 pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
346 commitment_transaction_number_obscure_factor: 0,
348 key_storage: KeyStorage::PrivMode {
349 revocation_base_key: revocation_base_key.clone(),
350 htlc_base_key: htlc_base_key.clone(),
351 delayed_payment_base_key: delayed_payment_base_key.clone(),
352 prev_latest_per_commitment_point: None,
353 latest_per_commitment_point: None,
355 their_htlc_base_key: None,
356 their_delayed_payment_base_key: None,
357 their_cur_revocation_points: None,
359 our_to_self_delay: our_to_self_delay,
360 their_to_self_delay: None,
362 old_secrets: [([0; 32], 1 << 48); 49],
363 remote_claimable_outpoints: HashMap::new(),
364 remote_commitment_txn_on_chain: HashMap::new(),
365 remote_hash_commitment_number: HashMap::new(),
367 prev_local_signed_commitment_tx: None,
368 current_local_signed_commitment_tx: None,
369 current_remote_commitment_number: 1 << 48,
371 payment_preimages: HashMap::new(),
372 destination_script: destination_script,
374 last_block_hash: Default::default(),
375 secp_ctx: Secp256k1::new(),
381 fn place_secret(idx: u64) -> u8 {
383 if idx & (1 << i) == (1 << i) {
391 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
392 let mut res: [u8; 32] = secret;
394 let bitpos = bits - 1 - i;
395 if idx & (1 << bitpos) == (1 << bitpos) {
396 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
397 let mut sha = Sha256::new();
399 sha.result(&mut res);
405 /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
406 /// revocation point which may be required to claim HTLC outputs which we know the preimage of
407 /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
408 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
409 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
410 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
411 let pos = ChannelMonitor::place_secret(idx);
413 let (old_secret, old_idx) = self.old_secrets[i as usize];
414 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
415 return Err(HandleError{err: "Previous secret did not match new one", action: None})
418 self.old_secrets[pos as usize] = (secret, idx);
420 if let Some(new_revocation_point) = their_next_revocation_point {
421 match self.their_cur_revocation_points {
422 Some(old_points) => {
423 if old_points.0 == new_revocation_point.0 + 1 {
424 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
425 } else if old_points.0 == new_revocation_point.0 + 2 {
426 if let Some(old_second_point) = old_points.2 {
427 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
429 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
432 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
436 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
441 if !self.payment_preimages.is_empty() {
442 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
443 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
444 let min_idx = self.get_min_seen_secret();
445 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
447 self.payment_preimages.retain(|&k, _| {
448 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
449 if k == htlc.payment_hash {
453 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
454 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
455 if k == htlc.payment_hash {
460 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
467 remote_hash_commitment_number.remove(&k);
476 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
477 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
478 /// possibly future revocation/preimage information) to claim outputs where possible.
479 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
480 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
481 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
482 // so that a remote monitor doesn't learn anything unless there is a malicious close.
483 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
485 for htlc in &htlc_outputs {
486 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
488 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
489 self.current_remote_commitment_number = commitment_number;
492 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
493 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
494 /// is important that any clones of this channel monitor (including remote clones) by kept
495 /// up-to-date as our local commitment transaction is updated.
496 /// Panics if set_their_to_self_delay has never been called.
497 /// Also update KeyStorage with latest local per_commitment_point to derive local_delayedkey in
498 /// case of onchain HTLC tx
499 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)>) {
500 assert!(self.their_to_self_delay.is_some());
501 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
502 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
503 txid: signed_commitment_tx.txid(),
504 tx: signed_commitment_tx,
505 revocation_key: local_keys.revocation_key,
506 a_htlc_key: local_keys.a_htlc_key,
507 b_htlc_key: local_keys.b_htlc_key,
508 delayed_payment_key: local_keys.a_delayed_payment_key,
512 self.key_storage = if let KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } = self.key_storage {
513 KeyStorage::PrivMode {
514 revocation_base_key: *revocation_base_key,
515 htlc_base_key: *htlc_base_key,
516 delayed_payment_base_key: *delayed_payment_base_key,
517 prev_latest_per_commitment_point: *latest_per_commitment_point,
518 latest_per_commitment_point: Some(local_keys.per_commitment_point),
520 } else { unimplemented!(); };
523 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
524 /// commitment_tx_infos which contain the payment hash have been revoked.
525 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
526 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
529 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
530 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
531 /// chain for new blocks/transactions.
532 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
533 if self.funding_txo.is_some() {
534 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
535 // easy to collide the funding_txo hash and have a different scriptPubKey.
536 if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
537 return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
540 self.funding_txo = other.funding_txo.take();
542 let other_min_secret = other.get_min_seen_secret();
543 let our_min_secret = self.get_min_seen_secret();
544 if our_min_secret > other_min_secret {
545 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
547 // TODO: We should use current_remote_commitment_number and the commitment number out of
548 // local transactions to decide how to merge
549 if our_min_secret >= other_min_secret {
550 self.their_cur_revocation_points = other.their_cur_revocation_points;
551 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
552 self.remote_claimable_outpoints.insert(txid, htlcs);
554 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
555 self.prev_local_signed_commitment_tx = Some(local_tx);
557 if let Some(local_tx) = other.current_local_signed_commitment_tx {
558 self.current_local_signed_commitment_tx = Some(local_tx);
560 self.payment_preimages = other.payment_preimages;
562 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
566 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
567 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
568 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
569 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
572 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
573 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
574 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
575 /// provides slightly better privacy.
576 /// It's the responsibility of the caller to register outpoint and script with passing the former
577 /// value as key to add_update_monitor.
578 pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
579 self.funding_txo = Some(funding_info);
582 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
583 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
584 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
585 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
588 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
589 self.their_to_self_delay = Some(their_to_self_delay);
592 pub(super) fn unset_funding_info(&mut self) {
593 self.funding_txo = None;
596 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
597 pub fn get_funding_txo(&self) -> Option<OutPoint> {
598 match self.funding_txo {
599 Some((outpoint, _)) => Some(outpoint),
604 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
605 /// Generally useful when deserializing as during normal operation the return values of
606 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
607 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
608 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
609 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
610 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
611 for (idx, output) in outputs.iter().enumerate() {
612 res.push(((*txid).clone(), idx as u32, output));
618 /// Serializes into a vec, with various modes for the exposed pub fns
619 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
620 //TODO: We still write out all the serialization here manually instead of using the fancy
621 //serialization framework we have, we should migrate things over to it.
622 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
623 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
625 match &self.funding_txo {
626 &Some((ref outpoint, ref script)) => {
627 writer.write_all(&outpoint.txid[..])?;
628 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
629 script.write(writer)?;
632 // We haven't even been initialized...not sure why anyone is serializing us, but
633 // not much to give them.
638 // Set in initial Channel-object creation, so should always be set by now:
639 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
641 match self.key_storage {
642 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref prev_latest_per_commitment_point, ref latest_per_commitment_point } => {
643 writer.write_all(&[0; 1])?;
644 writer.write_all(&revocation_base_key[..])?;
645 writer.write_all(&htlc_base_key[..])?;
646 writer.write_all(&delayed_payment_base_key[..])?;
647 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
648 writer.write_all(&[1; 1])?;
649 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
651 writer.write_all(&[0; 1])?;
653 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
654 writer.write_all(&[1; 1])?;
655 writer.write_all(&latest_per_commitment_point.serialize())?;
657 writer.write_all(&[0; 1])?;
661 KeyStorage::SigsMode { .. } => unimplemented!(),
664 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
665 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
667 match self.their_cur_revocation_points {
668 Some((idx, pubkey, second_option)) => {
669 writer.write_all(&byte_utils::be48_to_array(idx))?;
670 writer.write_all(&pubkey.serialize())?;
671 match second_option {
672 Some(second_pubkey) => {
673 writer.write_all(&second_pubkey.serialize())?;
676 writer.write_all(&[0; 33])?;
681 writer.write_all(&byte_utils::be48_to_array(0))?;
685 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
686 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
688 for &(ref secret, ref idx) in self.old_secrets.iter() {
689 writer.write_all(secret)?;
690 writer.write_all(&byte_utils::be64_to_array(*idx))?;
693 macro_rules! serialize_htlc_in_commitment {
694 ($htlc_output: expr) => {
695 writer.write_all(&[$htlc_output.offered as u8; 1])?;
696 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
697 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
698 writer.write_all(&$htlc_output.payment_hash)?;
699 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
703 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
704 for (ref txid, ref htlc_outputs) in self.remote_claimable_outpoints.iter() {
705 writer.write_all(&txid[..])?;
706 writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
707 for htlc_output in htlc_outputs.iter() {
708 serialize_htlc_in_commitment!(htlc_output);
712 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
713 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
714 writer.write_all(&txid[..])?;
715 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
716 (txouts.len() as u64).write(writer)?;
717 for script in txouts.iter() {
718 script.write(writer)?;
722 if for_local_storage {
723 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
724 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
725 writer.write_all(*payment_hash)?;
726 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
729 writer.write_all(&byte_utils::be64_to_array(0))?;
732 macro_rules! serialize_local_tx {
733 ($local_tx: expr) => {
734 if let Err(e) = $local_tx.tx.consensus_encode(&mut serialize::RawEncoder::new(WriterWriteAdaptor(writer))) {
736 serialize::Error::Io(e) => return Err(e),
737 _ => panic!("local tx must have been well-formed!"),
741 writer.write_all(&$local_tx.revocation_key.serialize())?;
742 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
743 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
744 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
746 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
747 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
748 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
749 serialize_htlc_in_commitment!(htlc_output);
750 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
751 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
756 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
757 writer.write_all(&[1; 1])?;
758 serialize_local_tx!(prev_local_tx);
760 writer.write_all(&[0; 1])?;
763 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
764 writer.write_all(&[1; 1])?;
765 serialize_local_tx!(cur_local_tx);
767 writer.write_all(&[0; 1])?;
770 if for_local_storage {
771 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
773 writer.write_all(&byte_utils::be48_to_array(0))?;
776 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
777 for payment_preimage in self.payment_preimages.values() {
778 writer.write_all(payment_preimage)?;
781 self.last_block_hash.write(writer)?;
782 self.destination_script.write(writer)?;
787 /// Writes this monitor into the given writer, suitable for writing to disk.
789 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
790 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
791 /// the "reorg path" (ie not just starting at the same height but starting at the highest
792 /// common block that appears on your best chain as well as on the chain which contains the
793 /// last block hash returned) upon deserializing the object!
794 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
795 self.write(writer, true)
798 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
800 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
801 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
802 /// the "reorg path" (ie not just starting at the same height but starting at the highest
803 /// common block that appears on your best chain as well as on the chain which contains the
804 /// last block hash returned) upon deserializing the object!
805 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
806 self.write(writer, false)
809 //TODO: Functions to serialize/deserialize (with different forms depending on which information
810 //we want to leave out (eg funding_txo, etc).
812 /// Can only fail if idx is < get_min_seen_secret
813 pub(super) fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
814 for i in 0..self.old_secrets.len() {
815 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
816 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
819 assert!(idx < self.get_min_seen_secret());
820 Err(HandleError{err: "idx too low", action: None})
823 pub(super) fn get_min_seen_secret(&self) -> u64 {
824 //TODO This can be optimized?
825 let mut min = 1 << 48;
826 for &(_, idx) in self.old_secrets.iter() {
834 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
835 self.current_remote_commitment_number
838 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
839 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
840 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)
841 } else { 0xffff_ffff_ffff }
844 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
845 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
846 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
847 /// HTLC-Success/HTLC-Timeout transactions.
848 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
849 // Most secp and related errors trying to create keys means we have no hope of constructing
850 // a spend transaction...so we return no transactions to broadcast
851 let mut txn_to_broadcast = Vec::new();
852 let mut watch_outputs = Vec::new();
853 let mut spendable_outputs = Vec::new();
855 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
856 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
858 macro_rules! ignore_error {
859 ( $thing : expr ) => {
862 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
867 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);
868 if commitment_number >= self.get_min_seen_secret() {
869 let secret = self.get_secret(commitment_number).unwrap();
870 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
871 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
872 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
873 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
874 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
875 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
877 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
878 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
879 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
880 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
883 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()));
884 let a_htlc_key = match self.their_htlc_base_key {
885 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
886 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)),
889 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
890 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
892 let mut total_value = 0;
893 let mut values = Vec::new();
894 let mut inputs = Vec::new();
895 let mut htlc_idxs = Vec::new();
897 for (idx, outp) in tx.output.iter().enumerate() {
898 if outp.script_pubkey == revokeable_p2wsh {
900 previous_output: BitcoinOutPoint {
901 txid: commitment_txid,
904 script_sig: Script::new(),
905 sequence: 0xfffffffd,
908 htlc_idxs.push(None);
909 values.push(outp.value);
910 total_value += outp.value;
911 break; // There can only be one of these
915 macro_rules! sign_input {
916 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
918 let (sig, redeemscript) = match self.key_storage {
919 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
920 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
921 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
922 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
924 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
925 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
926 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
928 KeyStorage::SigsMode { .. } => {
932 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
933 $input.witness[0].push(SigHashType::All as u8);
934 if $htlc_idx.is_none() {
935 $input.witness.push(vec!(1));
937 $input.witness.push(revocation_pubkey.serialize().to_vec());
939 $input.witness.push(redeemscript.into_bytes());
944 if let Some(per_commitment_data) = per_commitment_option {
945 inputs.reserve_exact(per_commitment_data.len());
947 for (idx, htlc) in per_commitment_data.iter().enumerate() {
948 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
949 if htlc.transaction_output_index as usize >= tx.output.len() ||
950 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
951 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
952 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
955 previous_output: BitcoinOutPoint {
956 txid: commitment_txid,
957 vout: htlc.transaction_output_index,
959 script_sig: Script::new(),
960 sequence: 0xfffffffd,
963 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
965 htlc_idxs.push(Some(idx));
966 values.push(tx.output[htlc.transaction_output_index as usize].value);
967 total_value += htlc.amount_msat / 1000;
969 let mut single_htlc_tx = Transaction {
974 script_pubkey: self.destination_script.clone(),
975 value: htlc.amount_msat / 1000, //TODO: - fee
978 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
979 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
980 txn_to_broadcast.push(single_htlc_tx);
985 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
986 // We're definitely a remote commitment transaction!
987 watch_outputs.append(&mut tx.output.clone());
988 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
990 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
992 let outputs = vec!(TxOut {
993 script_pubkey: self.destination_script.clone(),
994 value: total_value, //TODO: - fee
996 let mut spend_tx = Transaction {
1003 let mut values_drain = values.drain(..);
1004 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1006 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1007 let value = values_drain.next().unwrap();
1008 sign_input!(sighash_parts, input, htlc_idx, value);
1011 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1012 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1013 output: spend_tx.output[0].clone(),
1015 txn_to_broadcast.push(spend_tx);
1016 } else if let Some(per_commitment_data) = per_commitment_option {
1017 // While this isn't useful yet, there is a potential race where if a counterparty
1018 // revokes a state at the same time as the commitment transaction for that state is
1019 // confirmed, and the watchtower receives the block before the user, the user could
1020 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1021 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1022 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1024 watch_outputs.append(&mut tx.output.clone());
1025 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1027 if let Some(revocation_points) = self.their_cur_revocation_points {
1028 let revocation_point_option =
1029 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1030 else if let Some(point) = revocation_points.2.as_ref() {
1031 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1033 if let Some(revocation_point) = revocation_point_option {
1034 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1035 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1036 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1037 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1039 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1040 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1041 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1044 let a_htlc_key = match self.their_htlc_base_key {
1045 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1046 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1049 let mut total_value = 0;
1050 let mut values = Vec::new();
1051 let mut inputs = Vec::new();
1053 macro_rules! sign_input {
1054 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1056 let (sig, redeemscript) = match self.key_storage {
1057 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
1058 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1059 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1060 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1061 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1062 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1064 KeyStorage::SigsMode { .. } => {
1068 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1069 $input.witness[0].push(SigHashType::All as u8);
1070 $input.witness.push($preimage);
1071 $input.witness.push(redeemscript.into_bytes());
1076 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1077 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1079 previous_output: BitcoinOutPoint {
1080 txid: commitment_txid,
1081 vout: htlc.transaction_output_index,
1083 script_sig: Script::new(),
1084 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1085 witness: Vec::new(),
1087 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1089 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1090 total_value += htlc.amount_msat / 1000;
1092 let mut single_htlc_tx = Transaction {
1096 output: vec!(TxOut {
1097 script_pubkey: self.destination_script.clone(),
1098 value: htlc.amount_msat / 1000, //TODO: - fee
1101 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1102 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1103 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1104 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1105 output: single_htlc_tx.output[0].clone(),
1107 txn_to_broadcast.push(single_htlc_tx);
1112 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1114 let outputs = vec!(TxOut {
1115 script_pubkey: self.destination_script.clone(),
1116 value: total_value, //TODO: - fee
1118 let mut spend_tx = Transaction {
1125 let mut values_drain = values.drain(..);
1126 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1128 for input in spend_tx.input.iter_mut() {
1129 let value = values_drain.next().unwrap();
1130 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1133 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1134 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1135 output: spend_tx.output[0].clone(),
1137 txn_to_broadcast.push(spend_tx);
1142 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1145 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1146 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1147 if tx.input.len() != 1 || tx.output.len() != 1 {
1151 macro_rules! ignore_error {
1152 ( $thing : expr ) => {
1155 Err(_) => return (None, None)
1160 let secret = ignore_error!(self.get_secret(commitment_number));
1161 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1162 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1163 let revocation_pubkey = match self.key_storage {
1164 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1165 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1167 KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1168 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1171 let delayed_key = match self.their_delayed_payment_base_key {
1172 None => return (None, None),
1173 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1175 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1176 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1177 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1179 let mut inputs = Vec::new();
1182 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1184 previous_output: BitcoinOutPoint {
1188 script_sig: Script::new(),
1189 sequence: 0xfffffffd,
1190 witness: Vec::new(),
1192 amount = tx.output[0].value;
1195 if !inputs.is_empty() {
1196 let outputs = vec!(TxOut {
1197 script_pubkey: self.destination_script.clone(),
1198 value: amount, //TODO: - fee
1201 let mut spend_tx = Transaction {
1208 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1210 let sig = match self.key_storage {
1211 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1212 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1213 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1214 self.secp_ctx.sign(&sighash, &revocation_key)
1216 KeyStorage::SigsMode { .. } => {
1220 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1221 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1222 spend_tx.input[0].witness.push(vec!(1));
1223 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1225 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1226 let output = spend_tx.output[0].clone();
1227 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1228 } else { (None, None) }
1231 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1232 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1233 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1235 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1237 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);
1239 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1241 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1242 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1243 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1244 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1246 htlc_timeout_tx.input[0].witness.push(Vec::new());
1247 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());
1249 if let Some(ref per_commitment_point) = *per_commitment_point {
1250 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1251 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1252 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutput {
1253 outpoint: BitcoinOutPoint { txid: htlc_timeout_tx.txid(), vout: 0 },
1255 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1256 to_self_delay: self.our_to_self_delay
1261 res.push(htlc_timeout_tx);
1263 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1264 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);
1266 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1268 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1269 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1270 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1271 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1273 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1274 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());
1276 if let Some(ref per_commitment_point) = *per_commitment_point {
1277 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1278 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1279 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutput {
1280 outpoint: BitcoinOutPoint { txid: htlc_success_tx.txid(), vout: 0 },
1282 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1283 to_self_delay: self.our_to_self_delay
1288 res.push(htlc_success_tx);
1293 (res, spendable_outputs)
1296 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1297 /// revoked using data in local_claimable_outpoints.
1298 /// Should not be used if check_spend_revoked_transaction succeeds.
1299 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1300 let commitment_txid = tx.txid();
1301 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1302 if local_tx.txid == commitment_txid {
1303 match self.key_storage {
1304 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
1305 return self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1307 KeyStorage::SigsMode { .. } => {
1308 return self.broadcast_by_local_state(local_tx, &None, &None);
1313 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1314 if local_tx.txid == commitment_txid {
1315 match self.key_storage {
1316 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1317 return self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1319 KeyStorage::SigsMode { .. } => {
1320 return self.broadcast_by_local_state(local_tx, &None, &None);
1325 (Vec::new(), Vec::new())
1328 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1329 /// the Channel was out-of-date.
1330 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1331 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1332 let mut res = vec![local_tx.tx.clone()];
1333 match self.key_storage {
1334 KeyStorage::PrivMode { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1335 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1337 _ => panic!("Can only broadcast by local channelmonitor"),
1345 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>) {
1346 let mut watch_outputs = Vec::new();
1347 let mut spendable_outputs = Vec::new();
1348 for tx in txn_matched {
1349 if tx.input.len() == 1 {
1350 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1351 // commitment transactions and HTLC transactions will all only ever have one input,
1352 // which is an easy way to filter out any potential non-matching txn for lazy
1354 let prevout = &tx.input[0].previous_output;
1355 let mut txn: Vec<Transaction> = Vec::new();
1356 if self.funding_txo.is_none() || (prevout.txid == self.funding_txo.as_ref().unwrap().0.txid && prevout.vout == self.funding_txo.as_ref().unwrap().0.index as u32) {
1357 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height);
1359 spendable_outputs.append(&mut spendable_output);
1360 if !new_outputs.1.is_empty() {
1361 watch_outputs.push(new_outputs);
1364 let (remote_txn, mut outputs) = self.check_spend_local_transaction(tx, height);
1365 spendable_outputs.append(&mut outputs);
1369 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1370 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1371 if let Some(tx) = tx {
1374 if let Some(spendable_output) = spendable_output {
1375 spendable_outputs.push(spendable_output);
1379 for tx in txn.iter() {
1380 broadcaster.broadcast_transaction(tx);
1384 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1385 if self.would_broadcast_at_height(height) {
1386 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1387 match self.key_storage {
1388 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
1389 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1390 spendable_outputs.append(&mut outputs);
1392 broadcaster.broadcast_transaction(&tx);
1395 KeyStorage::SigsMode { .. } => {
1396 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1397 spendable_outputs.append(&mut outputs);
1399 broadcaster.broadcast_transaction(&tx);
1405 self.last_block_hash = block_hash.clone();
1406 (watch_outputs, spendable_outputs)
1409 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1410 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1411 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1412 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1413 // chain with enough room to claim the HTLC without our counterparty being able to
1414 // time out the HTLC first.
1415 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1416 // concern is being able to claim the corresponding inbound HTLC (on another
1417 // channel) before it expires. In fact, we don't even really care if our
1418 // counterparty here claims such an outbound HTLC after it expired as long as we
1419 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1420 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1421 // we give ourselves a few blocks of headroom after expiration before going
1422 // on-chain for an expired HTLC.
1423 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1424 // from us until we've reached the point where we go on-chain with the
1425 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1426 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1427 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1428 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1429 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1430 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1431 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1432 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1433 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1442 const MAX_ALLOC_SIZE: usize = 64*1024;
1444 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1445 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1446 let secp_ctx = Secp256k1::new();
1447 macro_rules! unwrap_obj {
1451 Err(_) => return Err(DecodeError::InvalidValue),
1456 let _ver: u8 = Readable::read(reader)?;
1457 let min_ver: u8 = Readable::read(reader)?;
1458 if min_ver > SERIALIZATION_VERSION {
1459 return Err(DecodeError::UnknownVersion);
1462 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1463 // barely-init'd ChannelMonitors that we can't do anything with.
1464 let outpoint = OutPoint {
1465 txid: Readable::read(reader)?,
1466 index: Readable::read(reader)?,
1468 let funding_txo = Some((outpoint, Readable::read(reader)?));
1469 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1471 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1473 let revocation_base_key = Readable::read(reader)?;
1474 let htlc_base_key = Readable::read(reader)?;
1475 let delayed_payment_base_key = Readable::read(reader)?;
1476 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1478 1 => Some(Readable::read(reader)?),
1479 _ => return Err(DecodeError::InvalidValue),
1481 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1483 1 => Some(Readable::read(reader)?),
1484 _ => return Err(DecodeError::InvalidValue),
1486 KeyStorage::PrivMode {
1487 revocation_base_key,
1489 delayed_payment_base_key,
1490 prev_latest_per_commitment_point,
1491 latest_per_commitment_point,
1494 _ => return Err(DecodeError::InvalidValue),
1497 let their_htlc_base_key = Some(Readable::read(reader)?);
1498 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1500 let their_cur_revocation_points = {
1501 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1505 let first_point = Readable::read(reader)?;
1506 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1507 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1508 Some((first_idx, first_point, None))
1510 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1515 let our_to_self_delay: u16 = Readable::read(reader)?;
1516 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1518 let mut old_secrets = [([0; 32], 1 << 48); 49];
1519 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1520 *secret = Readable::read(reader)?;
1521 *idx = Readable::read(reader)?;
1524 macro_rules! read_htlc_in_commitment {
1527 let offered: bool = Readable::read(reader)?;
1528 let amount_msat: u64 = Readable::read(reader)?;
1529 let cltv_expiry: u32 = Readable::read(reader)?;
1530 let payment_hash: [u8; 32] = Readable::read(reader)?;
1531 let transaction_output_index: u32 = Readable::read(reader)?;
1533 HTLCOutputInCommitment {
1534 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1540 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1541 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1542 for _ in 0..remote_claimable_outpoints_len {
1543 let txid: Sha256dHash = Readable::read(reader)?;
1544 let outputs_count: u64 = Readable::read(reader)?;
1545 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1546 for _ in 0..outputs_count {
1547 outputs.push(read_htlc_in_commitment!());
1549 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1550 return Err(DecodeError::InvalidValue);
1554 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
1555 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
1556 for _ in 0..remote_commitment_txn_on_chain_len {
1557 let txid: Sha256dHash = Readable::read(reader)?;
1558 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1559 let outputs_count = <u64 as Readable<R>>::read(reader)?;
1560 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
1561 for _ in 0..outputs_count {
1562 outputs.push(Readable::read(reader)?);
1564 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
1565 return Err(DecodeError::InvalidValue);
1569 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
1570 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
1571 for _ in 0..remote_hash_commitment_number_len {
1572 let txid: [u8; 32] = Readable::read(reader)?;
1573 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1574 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1575 return Err(DecodeError::InvalidValue);
1579 macro_rules! read_local_tx {
1582 let tx = match Transaction::consensus_decode(&mut serialize::RawDecoder::new(reader.by_ref())) {
1585 serialize::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
1586 _ => return Err(DecodeError::InvalidValue),
1590 if tx.input.is_empty() {
1591 // Ensure tx didn't hit the 0-input ambiguity case.
1592 return Err(DecodeError::InvalidValue);
1595 let revocation_key = Readable::read(reader)?;
1596 let a_htlc_key = Readable::read(reader)?;
1597 let b_htlc_key = Readable::read(reader)?;
1598 let delayed_payment_key = Readable::read(reader)?;
1599 let feerate_per_kw: u64 = Readable::read(reader)?;
1601 let htlc_outputs_len: u64 = Readable::read(reader)?;
1602 let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
1603 for _ in 0..htlc_outputs_len {
1604 htlc_outputs.push((read_htlc_in_commitment!(), Readable::read(reader)?, Readable::read(reader)?));
1609 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1615 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1618 Some(read_local_tx!())
1620 _ => return Err(DecodeError::InvalidValue),
1623 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1626 Some(read_local_tx!())
1628 _ => return Err(DecodeError::InvalidValue),
1631 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1633 let payment_preimages_len: u64 = Readable::read(reader)?;
1634 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
1635 let mut sha = Sha256::new();
1636 for _ in 0..payment_preimages_len {
1637 let preimage: [u8; 32] = Readable::read(reader)?;
1639 sha.input(&preimage);
1640 let mut hash = [0; 32];
1641 sha.result(&mut hash);
1642 if let Some(_) = payment_preimages.insert(hash, preimage) {
1643 return Err(DecodeError::InvalidValue);
1647 let last_block_hash: Sha256dHash = Readable::read(reader)?;
1648 let destination_script = Readable::read(reader)?;
1650 Ok((last_block_hash.clone(), ChannelMonitor {
1652 commitment_transaction_number_obscure_factor,
1655 their_htlc_base_key,
1656 their_delayed_payment_base_key,
1657 their_cur_revocation_points,
1660 their_to_self_delay,
1663 remote_claimable_outpoints,
1664 remote_commitment_txn_on_chain,
1665 remote_hash_commitment_number,
1667 prev_local_signed_commitment_tx,
1668 current_local_signed_commitment_tx,
1669 current_remote_commitment_number,
1684 use bitcoin::blockdata::script::Script;
1685 use bitcoin::blockdata::transaction::Transaction;
1686 use crypto::digest::Digest;
1688 use ln::channelmonitor::ChannelMonitor;
1689 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1690 use util::sha2::Sha256;
1691 use util::test_utils::TestLogger;
1692 use secp256k1::key::{SecretKey,PublicKey};
1693 use secp256k1::{Secp256k1, Signature};
1694 use rand::{thread_rng,Rng};
1698 fn test_per_commitment_storage() {
1699 // Test vectors from BOLT 3:
1700 let mut secrets: Vec<[u8; 32]> = Vec::new();
1701 let mut monitor: ChannelMonitor;
1702 let secp_ctx = Secp256k1::new();
1703 let logger = Arc::new(TestLogger::new());
1705 macro_rules! test_secrets {
1707 let mut idx = 281474976710655;
1708 for secret in secrets.iter() {
1709 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1712 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1713 assert!(monitor.get_secret(idx).is_err());
1718 // insert_secret correct sequence
1719 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(), 0, Script::new(), logger.clone());
1722 secrets.push([0; 32]);
1723 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1724 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1727 secrets.push([0; 32]);
1728 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1729 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1732 secrets.push([0; 32]);
1733 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1734 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1737 secrets.push([0; 32]);
1738 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1739 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1742 secrets.push([0; 32]);
1743 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1744 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1747 secrets.push([0; 32]);
1748 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1749 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1752 secrets.push([0; 32]);
1753 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1754 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1757 secrets.push([0; 32]);
1758 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1759 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1764 // insert_secret #1 incorrect
1765 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(), 0, Script::new(), logger.clone());
1768 secrets.push([0; 32]);
1769 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1770 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1773 secrets.push([0; 32]);
1774 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1775 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1776 "Previous secret did not match new one");
1780 // insert_secret #2 incorrect (#1 derived from incorrect)
1781 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(), 0, Script::new(), logger.clone());
1784 secrets.push([0; 32]);
1785 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1786 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1789 secrets.push([0; 32]);
1790 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1791 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1794 secrets.push([0; 32]);
1795 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1796 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1799 secrets.push([0; 32]);
1800 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1801 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1802 "Previous secret did not match new one");
1806 // insert_secret #3 incorrect
1807 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(), 0, Script::new(), logger.clone());
1810 secrets.push([0; 32]);
1811 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1812 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1815 secrets.push([0; 32]);
1816 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1817 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1820 secrets.push([0; 32]);
1821 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1822 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1825 secrets.push([0; 32]);
1826 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1827 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1828 "Previous secret did not match new one");
1832 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1833 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(), 0, Script::new(), logger.clone());
1836 secrets.push([0; 32]);
1837 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1838 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1841 secrets.push([0; 32]);
1842 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1843 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1846 secrets.push([0; 32]);
1847 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1848 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1851 secrets.push([0; 32]);
1852 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1853 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1856 secrets.push([0; 32]);
1857 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1858 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1861 secrets.push([0; 32]);
1862 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1863 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1866 secrets.push([0; 32]);
1867 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1868 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1871 secrets.push([0; 32]);
1872 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1873 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1874 "Previous secret did not match new one");
1878 // insert_secret #5 incorrect
1879 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(), 0, Script::new(), logger.clone());
1882 secrets.push([0; 32]);
1883 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1884 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1887 secrets.push([0; 32]);
1888 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1889 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1892 secrets.push([0; 32]);
1893 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1894 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1897 secrets.push([0; 32]);
1898 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1899 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1902 secrets.push([0; 32]);
1903 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1904 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1907 secrets.push([0; 32]);
1908 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1909 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1910 "Previous secret did not match new one");
1914 // insert_secret #6 incorrect (5 derived from incorrect)
1915 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(), 0, Script::new(), logger.clone());
1918 secrets.push([0; 32]);
1919 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1920 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1923 secrets.push([0; 32]);
1924 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1925 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1928 secrets.push([0; 32]);
1929 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1930 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1933 secrets.push([0; 32]);
1934 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1935 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1938 secrets.push([0; 32]);
1939 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1940 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1943 secrets.push([0; 32]);
1944 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1945 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1948 secrets.push([0; 32]);
1949 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1950 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1953 secrets.push([0; 32]);
1954 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1955 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1956 "Previous secret did not match new one");
1960 // insert_secret #7 incorrect
1961 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(), 0, Script::new(), logger.clone());
1964 secrets.push([0; 32]);
1965 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1966 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1969 secrets.push([0; 32]);
1970 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1971 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1974 secrets.push([0; 32]);
1975 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1976 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1979 secrets.push([0; 32]);
1980 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1981 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1984 secrets.push([0; 32]);
1985 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1986 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1989 secrets.push([0; 32]);
1990 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1991 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1994 secrets.push([0; 32]);
1995 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1996 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1999 secrets.push([0; 32]);
2000 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2001 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
2002 "Previous secret did not match new one");
2006 // insert_secret #8 incorrect
2007 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(), 0, Script::new(), logger.clone());
2010 secrets.push([0; 32]);
2011 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2012 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
2015 secrets.push([0; 32]);
2016 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2017 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
2020 secrets.push([0; 32]);
2021 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2022 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
2025 secrets.push([0; 32]);
2026 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2027 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
2030 secrets.push([0; 32]);
2031 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2032 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
2035 secrets.push([0; 32]);
2036 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2037 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
2040 secrets.push([0; 32]);
2041 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2042 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
2045 secrets.push([0; 32]);
2046 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2047 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
2048 "Previous secret did not match new one");
2053 fn test_prune_preimages() {
2054 let secp_ctx = Secp256k1::new();
2055 let logger = Arc::new(TestLogger::new());
2056 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2058 macro_rules! dummy_keys {
2061 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2063 per_commitment_point: dummy_key.clone(),
2064 revocation_key: dummy_key.clone(),
2065 a_htlc_key: dummy_key.clone(),
2066 b_htlc_key: dummy_key.clone(),
2067 a_delayed_payment_key: dummy_key.clone(),
2068 b_payment_key: dummy_key.clone(),
2073 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2075 let mut preimages = Vec::new();
2077 let mut rng = thread_rng();
2079 let mut preimage = [0; 32];
2080 rng.fill_bytes(&mut preimage);
2081 let mut sha = Sha256::new();
2082 sha.input(&preimage);
2083 let mut hash = [0; 32];
2084 sha.result(&mut hash);
2085 preimages.push((preimage, hash));
2089 macro_rules! preimages_slice_to_htlc_outputs {
2090 ($preimages_slice: expr) => {
2092 let mut res = Vec::new();
2093 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2094 res.push(HTLCOutputInCommitment {
2098 payment_hash: preimage.1.clone(),
2099 transaction_output_index: idx as u32,
2106 macro_rules! preimages_to_local_htlcs {
2107 ($preimages_slice: expr) => {
2109 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2110 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2116 macro_rules! test_preimages_exist {
2117 ($preimages_slice: expr, $monitor: expr) => {
2118 for preimage in $preimages_slice {
2119 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2124 // Prune with one old state and a local commitment tx holding a few overlaps with the
2126 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(), 0, Script::new(), logger.clone());
2127 monitor.set_their_to_self_delay(10);
2129 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2130 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
2131 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
2132 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
2133 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
2134 for &(ref preimage, ref hash) in preimages.iter() {
2135 monitor.provide_payment_preimage(hash, preimage);
2138 // Now provide a secret, pruning preimages 10-15
2139 let mut secret = [0; 32];
2140 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2141 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
2142 assert_eq!(monitor.payment_preimages.len(), 15);
2143 test_preimages_exist!(&preimages[0..10], monitor);
2144 test_preimages_exist!(&preimages[15..20], monitor);
2146 // Now provide a further secret, pruning preimages 15-17
2147 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2148 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
2149 assert_eq!(monitor.payment_preimages.len(), 13);
2150 test_preimages_exist!(&preimages[0..10], monitor);
2151 test_preimages_exist!(&preimages[17..20], monitor);
2153 // Now update local commitment tx info, pruning only element 18 as we still care about the
2154 // previous commitment tx's preimages too
2155 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2156 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2157 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
2158 assert_eq!(monitor.payment_preimages.len(), 12);
2159 test_preimages_exist!(&preimages[0..10], monitor);
2160 test_preimages_exist!(&preimages[18..20], monitor);
2162 // But if we do it again, we'll prune 5-10
2163 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2164 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2165 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
2166 assert_eq!(monitor.payment_preimages.len(), 5);
2167 test_preimages_exist!(&preimages[0..5], monitor);
2170 // Further testing is done in the ChannelManager integration tests.