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::consensus::encode::{self, Decodable, Encodable};
19 use bitcoin::util::hash::{BitcoinHash,Sha256dHash};
20 use bitcoin::util::bip143;
22 use crypto::digest::Digest;
24 use secp256k1::{Secp256k1,Message,Signature};
25 use secp256k1::key::{SecretKey,PublicKey};
28 use ln::msgs::{DecodeError, HandleError};
30 use ln::chan_utils::HTLCOutputInCommitment;
31 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
32 use chain::transaction::OutPoint;
33 use chain::keysinterface::SpendableOutputDescriptor;
34 use util::logger::Logger;
35 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
36 use util::sha2::Sha256;
37 use util::{byte_utils, events};
39 use std::collections::HashMap;
40 use std::sync::{Arc,Mutex};
41 use std::{hash,cmp, mem};
43 /// An error enum representing a failure to persist a channel monitor update.
45 pub enum ChannelMonitorUpdateErr {
46 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
47 /// to succeed at some point in the future).
49 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
50 /// submitting new commitment transactions to the remote party.
51 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
52 /// the channel to an operational state.
54 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
55 /// persisted is unsafe - if you failed to store the update on your own local disk you should
56 /// instead return PermanentFailure to force closure of the channel ASAP.
58 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
59 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
60 /// to claim it on this channel) and those updates must be applied wherever they can be. At
61 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
62 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
63 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
66 /// Note that even if updates made after TemporaryFailure succeed you must still call
67 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
68 /// channel operation.
70 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
71 /// different watchtower and cannot update with all watchtowers that were previously informed
72 /// of this channel). This will force-close the channel in question.
76 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
77 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
78 /// events to it, while also taking any add_update_monitor events and passing them to some remote
81 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
82 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
83 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
84 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
85 pub trait ManyChannelMonitor: Send + Sync {
86 /// Adds or updates a monitor for the given `funding_txo`.
88 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
89 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
91 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
94 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
95 /// watchtower or watch our own channels.
97 /// Note that you must provide your own key by which to refer to channels.
99 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
100 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
101 /// index by a PublicKey which is required to sign any updates.
103 /// If you're using this for local monitoring of your own channels, you probably want to use
104 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
105 pub struct SimpleManyChannelMonitor<Key> {
106 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
107 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
109 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
110 chain_monitor: Arc<ChainWatchInterface>,
111 broadcaster: Arc<BroadcasterInterface>,
112 pending_events: Mutex<Vec<events::Event>>,
116 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
117 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
118 let block_hash = header.bitcoin_hash();
119 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
121 let mut monitors = self.monitors.lock().unwrap();
122 for monitor in monitors.values_mut() {
123 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
124 if spendable_outputs.len() > 0 {
125 new_events.push(events::Event::SpendableOutputs {
126 outputs: spendable_outputs,
129 for (ref txid, ref outputs) in txn_outputs {
130 for (idx, output) in outputs.iter().enumerate() {
131 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
136 let mut pending_events = self.pending_events.lock().unwrap();
137 pending_events.append(&mut new_events);
140 fn block_disconnected(&self, _: &BlockHeader) { }
143 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
144 /// Creates a new object which can be used to monitor several channels given the chain
145 /// interface with which to register to receive notifications.
146 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
147 let res = Arc::new(SimpleManyChannelMonitor {
148 monitors: Mutex::new(HashMap::new()),
151 pending_events: Mutex::new(Vec::new()),
154 let weak_res = Arc::downgrade(&res);
155 res.chain_monitor.register_listener(weak_res);
159 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
160 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
161 let mut monitors = self.monitors.lock().unwrap();
162 match monitors.get_mut(&key) {
163 Some(orig_monitor) => {
164 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_option!(monitor.funding_txo));
165 return orig_monitor.insert_combine(monitor);
169 match &monitor.funding_txo {
171 log_trace!(self, "Got new Channel Monitor for no-funding-set channel (monitoring all txn!)");
172 self.chain_monitor.watch_all_txn()
174 &Some((ref outpoint, ref script)) => {
175 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
176 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
177 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
180 monitors.insert(key, monitor);
185 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
186 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
187 match self.add_update_monitor_by_key(funding_txo, monitor) {
189 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
194 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
195 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
196 let mut pending_events = self.pending_events.lock().unwrap();
197 let mut ret = Vec::new();
198 mem::swap(&mut ret, &mut *pending_events);
203 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
204 /// instead claiming it in its own individual transaction.
205 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
206 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
207 /// HTLC-Success transaction.
208 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
209 /// transaction confirmed (and we use it in a few more, equivalent, places).
210 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
211 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
212 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
213 /// copies of ChannelMonitors, including watchtowers).
214 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
216 #[derive(Clone, PartialEq)]
219 revocation_base_key: SecretKey,
220 htlc_base_key: SecretKey,
221 delayed_payment_base_key: SecretKey,
222 prev_latest_per_commitment_point: Option<PublicKey>,
223 latest_per_commitment_point: Option<PublicKey>,
226 revocation_base_key: PublicKey,
227 htlc_base_key: PublicKey,
228 sigs: HashMap<Sha256dHash, Signature>,
232 #[derive(Clone, PartialEq)]
233 struct LocalSignedTx {
234 /// txid of the transaction in tx, just used to make comparison faster
237 revocation_key: PublicKey,
238 a_htlc_key: PublicKey,
239 b_htlc_key: PublicKey,
240 delayed_payment_key: PublicKey,
242 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
245 const SERIALIZATION_VERSION: u8 = 1;
246 const MIN_SERIALIZATION_VERSION: u8 = 1;
248 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
249 /// on-chain transactions to ensure no loss of funds occurs.
251 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
252 /// information and are actively monitoring the chain.
254 pub struct ChannelMonitor {
255 funding_txo: Option<(OutPoint, Script)>,
256 commitment_transaction_number_obscure_factor: u64,
258 key_storage: KeyStorage,
259 their_htlc_base_key: Option<PublicKey>,
260 their_delayed_payment_base_key: Option<PublicKey>,
261 // first is the idx of the first of the two revocation points
262 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
264 our_to_self_delay: u16,
265 their_to_self_delay: Option<u16>,
267 old_secrets: [([u8; 32], u64); 49],
268 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
269 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
270 /// Nor can we figure out their commitment numbers without the commitment transaction they are
271 /// spending. Thus, in order to claim them via revocation key, we track all the remote
272 /// commitment transactions which we find on-chain, mapping them to the commitment number which
273 /// can be used to derive the revocation key and claim the transactions.
274 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
275 /// Cache used to make pruning of payment_preimages faster.
276 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
277 /// remote transactions (ie should remain pretty small).
278 /// Serialized to disk but should generally not be sent to Watchtowers.
279 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
281 // We store two local commitment transactions to avoid any race conditions where we may update
282 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
283 // various monitors for one channel being out of sync, and us broadcasting a local
284 // transaction for which we have deleted claim information on some watchtowers.
285 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
286 current_local_signed_commitment_tx: Option<LocalSignedTx>,
288 // Used just for ChannelManager to make sure it has the latest channel data during
290 current_remote_commitment_number: u64,
292 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
294 destination_script: Script,
296 // We simply modify last_block_hash in Channel's block_connected so that serialization is
297 // consistent but hopefully the users' copy handles block_connected in a consistent way.
298 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
299 // their last_block_hash from its state and not based on updated copies that didn't run through
300 // the full block_connected).
301 pub(crate) last_block_hash: Sha256dHash,
302 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
306 #[cfg(any(test, feature = "fuzztarget"))]
307 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
308 /// underlying object
309 impl PartialEq for ChannelMonitor {
310 fn eq(&self, other: &Self) -> bool {
311 if self.funding_txo != other.funding_txo ||
312 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
313 self.key_storage != other.key_storage ||
314 self.their_htlc_base_key != other.their_htlc_base_key ||
315 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
316 self.their_cur_revocation_points != other.their_cur_revocation_points ||
317 self.our_to_self_delay != other.our_to_self_delay ||
318 self.their_to_self_delay != other.their_to_self_delay ||
319 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
320 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
321 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
322 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
323 self.current_remote_commitment_number != other.current_remote_commitment_number ||
324 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
325 self.payment_preimages != other.payment_preimages ||
326 self.destination_script != other.destination_script
330 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
331 if secret != o_secret || idx != o_idx {
340 impl ChannelMonitor {
341 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 {
344 commitment_transaction_number_obscure_factor: 0,
346 key_storage: KeyStorage::PrivMode {
347 revocation_base_key: revocation_base_key.clone(),
348 htlc_base_key: htlc_base_key.clone(),
349 delayed_payment_base_key: delayed_payment_base_key.clone(),
350 prev_latest_per_commitment_point: None,
351 latest_per_commitment_point: None,
353 their_htlc_base_key: None,
354 their_delayed_payment_base_key: None,
355 their_cur_revocation_points: None,
357 our_to_self_delay: our_to_self_delay,
358 their_to_self_delay: None,
360 old_secrets: [([0; 32], 1 << 48); 49],
361 remote_claimable_outpoints: HashMap::new(),
362 remote_commitment_txn_on_chain: HashMap::new(),
363 remote_hash_commitment_number: HashMap::new(),
365 prev_local_signed_commitment_tx: None,
366 current_local_signed_commitment_tx: None,
367 current_remote_commitment_number: 1 << 48,
369 payment_preimages: HashMap::new(),
370 destination_script: destination_script,
372 last_block_hash: Default::default(),
373 secp_ctx: Secp256k1::new(),
379 fn place_secret(idx: u64) -> u8 {
381 if idx & (1 << i) == (1 << i) {
389 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
390 let mut res: [u8; 32] = secret;
392 let bitpos = bits - 1 - i;
393 if idx & (1 << bitpos) == (1 << bitpos) {
394 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
395 let mut sha = Sha256::new();
397 sha.result(&mut res);
403 /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
404 /// revocation point which may be required to claim HTLC outputs which we know the preimage of
405 /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
406 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
407 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
408 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
409 let pos = ChannelMonitor::place_secret(idx);
411 let (old_secret, old_idx) = self.old_secrets[i as usize];
412 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
413 return Err(HandleError{err: "Previous secret did not match new one", action: None})
416 self.old_secrets[pos as usize] = (secret, idx);
418 if let Some(new_revocation_point) = their_next_revocation_point {
419 match self.their_cur_revocation_points {
420 Some(old_points) => {
421 if old_points.0 == new_revocation_point.0 + 1 {
422 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
423 } else if old_points.0 == new_revocation_point.0 + 2 {
424 if let Some(old_second_point) = old_points.2 {
425 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
427 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
430 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
434 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
439 if !self.payment_preimages.is_empty() {
440 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
441 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
442 let min_idx = self.get_min_seen_secret();
443 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
445 self.payment_preimages.retain(|&k, _| {
446 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
447 if k == htlc.payment_hash {
451 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
452 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
453 if k == htlc.payment_hash {
458 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
465 remote_hash_commitment_number.remove(&k);
474 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
475 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
476 /// possibly future revocation/preimage information) to claim outputs where possible.
477 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
478 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
479 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
480 // so that a remote monitor doesn't learn anything unless there is a malicious close.
481 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
483 for htlc in &htlc_outputs {
484 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
486 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
487 self.current_remote_commitment_number = commitment_number;
490 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
491 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
492 /// is important that any clones of this channel monitor (including remote clones) by kept
493 /// up-to-date as our local commitment transaction is updated.
494 /// Panics if set_their_to_self_delay has never been called.
495 /// Also update KeyStorage with latest local per_commitment_point to derive local_delayedkey in
496 /// case of onchain HTLC tx
497 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)>) {
498 assert!(self.their_to_self_delay.is_some());
499 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
500 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
501 txid: signed_commitment_tx.txid(),
502 tx: signed_commitment_tx,
503 revocation_key: local_keys.revocation_key,
504 a_htlc_key: local_keys.a_htlc_key,
505 b_htlc_key: local_keys.b_htlc_key,
506 delayed_payment_key: local_keys.a_delayed_payment_key,
510 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 {
511 KeyStorage::PrivMode {
512 revocation_base_key: *revocation_base_key,
513 htlc_base_key: *htlc_base_key,
514 delayed_payment_base_key: *delayed_payment_base_key,
515 prev_latest_per_commitment_point: *latest_per_commitment_point,
516 latest_per_commitment_point: Some(local_keys.per_commitment_point),
518 } else { unimplemented!(); };
521 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
522 /// commitment_tx_infos which contain the payment hash have been revoked.
523 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
524 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
527 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
528 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
529 /// chain for new blocks/transactions.
530 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
531 if self.funding_txo.is_some() {
532 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
533 // easy to collide the funding_txo hash and have a different scriptPubKey.
534 if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
535 return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
538 self.funding_txo = other.funding_txo.take();
540 let other_min_secret = other.get_min_seen_secret();
541 let our_min_secret = self.get_min_seen_secret();
542 if our_min_secret > other_min_secret {
543 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
545 // TODO: We should use current_remote_commitment_number and the commitment number out of
546 // local transactions to decide how to merge
547 if our_min_secret >= other_min_secret {
548 self.their_cur_revocation_points = other.their_cur_revocation_points;
549 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
550 self.remote_claimable_outpoints.insert(txid, htlcs);
552 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
553 self.prev_local_signed_commitment_tx = Some(local_tx);
555 if let Some(local_tx) = other.current_local_signed_commitment_tx {
556 self.current_local_signed_commitment_tx = Some(local_tx);
558 self.payment_preimages = other.payment_preimages;
560 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
564 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
565 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
566 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
567 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
570 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
571 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
572 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
573 /// provides slightly better privacy.
574 /// It's the responsibility of the caller to register outpoint and script with passing the former
575 /// value as key to add_update_monitor.
576 pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
577 self.funding_txo = Some(funding_info);
580 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
581 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
582 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
583 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
586 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
587 self.their_to_self_delay = Some(their_to_self_delay);
590 pub(super) fn unset_funding_info(&mut self) {
591 self.funding_txo = None;
594 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
595 pub fn get_funding_txo(&self) -> Option<OutPoint> {
596 match self.funding_txo {
597 Some((outpoint, _)) => Some(outpoint),
602 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
603 /// Generally useful when deserializing as during normal operation the return values of
604 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
605 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
606 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
607 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
608 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
609 for (idx, output) in outputs.iter().enumerate() {
610 res.push(((*txid).clone(), idx as u32, output));
616 /// Serializes into a vec, with various modes for the exposed pub fns
617 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
618 //TODO: We still write out all the serialization here manually instead of using the fancy
619 //serialization framework we have, we should migrate things over to it.
620 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
621 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
623 match &self.funding_txo {
624 &Some((ref outpoint, ref script)) => {
625 writer.write_all(&outpoint.txid[..])?;
626 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
627 script.write(writer)?;
630 // We haven't even been initialized...not sure why anyone is serializing us, but
631 // not much to give them.
636 // Set in initial Channel-object creation, so should always be set by now:
637 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
639 match self.key_storage {
640 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 } => {
641 writer.write_all(&[0; 1])?;
642 writer.write_all(&revocation_base_key[..])?;
643 writer.write_all(&htlc_base_key[..])?;
644 writer.write_all(&delayed_payment_base_key[..])?;
645 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
646 writer.write_all(&[1; 1])?;
647 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
649 writer.write_all(&[0; 1])?;
651 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
652 writer.write_all(&[1; 1])?;
653 writer.write_all(&latest_per_commitment_point.serialize())?;
655 writer.write_all(&[0; 1])?;
659 KeyStorage::SigsMode { .. } => unimplemented!(),
662 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
663 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
665 match self.their_cur_revocation_points {
666 Some((idx, pubkey, second_option)) => {
667 writer.write_all(&byte_utils::be48_to_array(idx))?;
668 writer.write_all(&pubkey.serialize())?;
669 match second_option {
670 Some(second_pubkey) => {
671 writer.write_all(&second_pubkey.serialize())?;
674 writer.write_all(&[0; 33])?;
679 writer.write_all(&byte_utils::be48_to_array(0))?;
683 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
684 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
686 for &(ref secret, ref idx) in self.old_secrets.iter() {
687 writer.write_all(secret)?;
688 writer.write_all(&byte_utils::be64_to_array(*idx))?;
691 macro_rules! serialize_htlc_in_commitment {
692 ($htlc_output: expr) => {
693 writer.write_all(&[$htlc_output.offered as u8; 1])?;
694 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
695 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
696 writer.write_all(&$htlc_output.payment_hash)?;
697 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
701 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
702 for (ref txid, ref htlc_outputs) in self.remote_claimable_outpoints.iter() {
703 writer.write_all(&txid[..])?;
704 writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
705 for htlc_output in htlc_outputs.iter() {
706 serialize_htlc_in_commitment!(htlc_output);
710 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
711 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
712 writer.write_all(&txid[..])?;
713 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
714 (txouts.len() as u64).write(writer)?;
715 for script in txouts.iter() {
716 script.write(writer)?;
720 if for_local_storage {
721 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
722 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
723 writer.write_all(*payment_hash)?;
724 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
727 writer.write_all(&byte_utils::be64_to_array(0))?;
730 macro_rules! serialize_local_tx {
731 ($local_tx: expr) => {
732 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
734 encode::Error::Io(e) => return Err(e),
735 _ => panic!("local tx must have been well-formed!"),
739 writer.write_all(&$local_tx.revocation_key.serialize())?;
740 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
741 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
742 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
744 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
745 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
746 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
747 serialize_htlc_in_commitment!(htlc_output);
748 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
749 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
754 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
755 writer.write_all(&[1; 1])?;
756 serialize_local_tx!(prev_local_tx);
758 writer.write_all(&[0; 1])?;
761 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
762 writer.write_all(&[1; 1])?;
763 serialize_local_tx!(cur_local_tx);
765 writer.write_all(&[0; 1])?;
768 if for_local_storage {
769 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
771 writer.write_all(&byte_utils::be48_to_array(0))?;
774 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
775 for payment_preimage in self.payment_preimages.values() {
776 writer.write_all(payment_preimage)?;
779 self.last_block_hash.write(writer)?;
780 self.destination_script.write(writer)?;
785 /// Writes this monitor into the given writer, suitable for writing to disk.
787 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
788 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
789 /// the "reorg path" (ie not just starting at the same height but starting at the highest
790 /// common block that appears on your best chain as well as on the chain which contains the
791 /// last block hash returned) upon deserializing the object!
792 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
793 self.write(writer, true)
796 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
798 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
799 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
800 /// the "reorg path" (ie not just starting at the same height but starting at the highest
801 /// common block that appears on your best chain as well as on the chain which contains the
802 /// last block hash returned) upon deserializing the object!
803 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
804 self.write(writer, false)
807 //TODO: Functions to serialize/deserialize (with different forms depending on which information
808 //we want to leave out (eg funding_txo, etc).
810 /// Can only fail if idx is < get_min_seen_secret
811 pub(super) fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
812 for i in 0..self.old_secrets.len() {
813 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
814 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
817 assert!(idx < self.get_min_seen_secret());
818 Err(HandleError{err: "idx too low", action: None})
821 pub(super) fn get_min_seen_secret(&self) -> u64 {
822 //TODO This can be optimized?
823 let mut min = 1 << 48;
824 for &(_, idx) in self.old_secrets.iter() {
832 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
833 self.current_remote_commitment_number
836 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
837 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
838 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)
839 } else { 0xffff_ffff_ffff }
842 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
843 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
844 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
845 /// HTLC-Success/HTLC-Timeout transactions.
846 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
847 // Most secp and related errors trying to create keys means we have no hope of constructing
848 // a spend transaction...so we return no transactions to broadcast
849 let mut txn_to_broadcast = Vec::new();
850 let mut watch_outputs = Vec::new();
851 let mut spendable_outputs = Vec::new();
853 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
854 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
856 macro_rules! ignore_error {
857 ( $thing : expr ) => {
860 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
865 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);
866 if commitment_number >= self.get_min_seen_secret() {
867 let secret = self.get_secret(commitment_number).unwrap();
868 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
869 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
870 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
871 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
872 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
873 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
875 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
876 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
877 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
878 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
881 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()));
882 let a_htlc_key = match self.their_htlc_base_key {
883 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
884 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)),
887 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
888 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
890 let mut total_value = 0;
891 let mut values = Vec::new();
892 let mut inputs = Vec::new();
893 let mut htlc_idxs = Vec::new();
895 for (idx, outp) in tx.output.iter().enumerate() {
896 if outp.script_pubkey == revokeable_p2wsh {
898 previous_output: BitcoinOutPoint {
899 txid: commitment_txid,
902 script_sig: Script::new(),
903 sequence: 0xfffffffd,
906 htlc_idxs.push(None);
907 values.push(outp.value);
908 total_value += outp.value;
909 break; // There can only be one of these
913 macro_rules! sign_input {
914 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
916 let (sig, redeemscript) = match self.key_storage {
917 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
918 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
919 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
920 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
922 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
923 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
924 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
926 KeyStorage::SigsMode { .. } => {
930 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
931 $input.witness[0].push(SigHashType::All as u8);
932 if $htlc_idx.is_none() {
933 $input.witness.push(vec!(1));
935 $input.witness.push(revocation_pubkey.serialize().to_vec());
937 $input.witness.push(redeemscript.into_bytes());
942 if let Some(per_commitment_data) = per_commitment_option {
943 inputs.reserve_exact(per_commitment_data.len());
945 for (idx, htlc) in per_commitment_data.iter().enumerate() {
946 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
947 if htlc.transaction_output_index as usize >= tx.output.len() ||
948 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
949 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
950 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
953 previous_output: BitcoinOutPoint {
954 txid: commitment_txid,
955 vout: htlc.transaction_output_index,
957 script_sig: Script::new(),
958 sequence: 0xfffffffd,
961 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
963 htlc_idxs.push(Some(idx));
964 values.push(tx.output[htlc.transaction_output_index as usize].value);
965 total_value += htlc.amount_msat / 1000;
967 let mut single_htlc_tx = Transaction {
972 script_pubkey: self.destination_script.clone(),
973 value: htlc.amount_msat / 1000, //TODO: - fee
976 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
977 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
978 txn_to_broadcast.push(single_htlc_tx);
983 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
984 // We're definitely a remote commitment transaction!
985 watch_outputs.append(&mut tx.output.clone());
986 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
988 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
990 let outputs = vec!(TxOut {
991 script_pubkey: self.destination_script.clone(),
992 value: total_value, //TODO: - fee
994 let mut spend_tx = Transaction {
1001 let mut values_drain = values.drain(..);
1002 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1004 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1005 let value = values_drain.next().unwrap();
1006 sign_input!(sighash_parts, input, htlc_idx, value);
1009 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1010 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1011 output: spend_tx.output[0].clone(),
1013 txn_to_broadcast.push(spend_tx);
1014 } else if let Some(per_commitment_data) = per_commitment_option {
1015 // While this isn't useful yet, there is a potential race where if a counterparty
1016 // revokes a state at the same time as the commitment transaction for that state is
1017 // confirmed, and the watchtower receives the block before the user, the user could
1018 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1019 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1020 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1022 watch_outputs.append(&mut tx.output.clone());
1023 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1025 if let Some(revocation_points) = self.their_cur_revocation_points {
1026 let revocation_point_option =
1027 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1028 else if let Some(point) = revocation_points.2.as_ref() {
1029 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1031 if let Some(revocation_point) = revocation_point_option {
1032 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1033 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1034 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1035 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1037 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1038 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1039 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1042 let a_htlc_key = match self.their_htlc_base_key {
1043 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1044 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1047 let mut total_value = 0;
1048 let mut values = Vec::new();
1049 let mut inputs = Vec::new();
1051 macro_rules! sign_input {
1052 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1054 let (sig, redeemscript) = match self.key_storage {
1055 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
1056 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1057 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1058 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1059 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1060 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1062 KeyStorage::SigsMode { .. } => {
1066 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1067 $input.witness[0].push(SigHashType::All as u8);
1068 $input.witness.push($preimage);
1069 $input.witness.push(redeemscript.into_bytes());
1074 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1075 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1077 previous_output: BitcoinOutPoint {
1078 txid: commitment_txid,
1079 vout: htlc.transaction_output_index,
1081 script_sig: Script::new(),
1082 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1083 witness: Vec::new(),
1085 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1087 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1088 total_value += htlc.amount_msat / 1000;
1090 let mut single_htlc_tx = Transaction {
1094 output: vec!(TxOut {
1095 script_pubkey: self.destination_script.clone(),
1096 value: htlc.amount_msat / 1000, //TODO: - fee
1099 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1100 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1101 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1102 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1103 output: single_htlc_tx.output[0].clone(),
1105 txn_to_broadcast.push(single_htlc_tx);
1110 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1112 let outputs = vec!(TxOut {
1113 script_pubkey: self.destination_script.clone(),
1114 value: total_value, //TODO: - fee
1116 let mut spend_tx = Transaction {
1123 let mut values_drain = values.drain(..);
1124 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1126 for input in spend_tx.input.iter_mut() {
1127 let value = values_drain.next().unwrap();
1128 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1131 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1132 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1133 output: spend_tx.output[0].clone(),
1135 txn_to_broadcast.push(spend_tx);
1140 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1143 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1144 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1145 if tx.input.len() != 1 || tx.output.len() != 1 {
1149 macro_rules! ignore_error {
1150 ( $thing : expr ) => {
1153 Err(_) => return (None, None)
1158 let secret = ignore_error!(self.get_secret(commitment_number));
1159 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1160 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1161 let revocation_pubkey = match self.key_storage {
1162 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1163 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1165 KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1166 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1169 let delayed_key = match self.their_delayed_payment_base_key {
1170 None => return (None, None),
1171 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1173 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1174 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1175 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1177 let mut inputs = Vec::new();
1180 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1182 previous_output: BitcoinOutPoint {
1186 script_sig: Script::new(),
1187 sequence: 0xfffffffd,
1188 witness: Vec::new(),
1190 amount = tx.output[0].value;
1193 if !inputs.is_empty() {
1194 let outputs = vec!(TxOut {
1195 script_pubkey: self.destination_script.clone(),
1196 value: amount, //TODO: - fee
1199 let mut spend_tx = Transaction {
1206 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1208 let sig = match self.key_storage {
1209 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1210 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1211 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1212 self.secp_ctx.sign(&sighash, &revocation_key)
1214 KeyStorage::SigsMode { .. } => {
1218 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1219 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1220 spend_tx.input[0].witness.push(vec!(1));
1221 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1223 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1224 let output = spend_tx.output[0].clone();
1225 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1226 } else { (None, None) }
1229 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1230 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1231 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1233 macro_rules! add_dynamic_output {
1234 ($father_tx: expr, $vout: expr) => {
1235 if let Some(ref per_commitment_point) = *per_commitment_point {
1236 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1237 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1238 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutput {
1239 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1241 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1242 to_self_delay: self.our_to_self_delay
1251 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1252 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1253 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1254 if output.script_pubkey == revokeable_p2wsh {
1255 add_dynamic_output!(local_tx.tx, idx as u32);
1260 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1262 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);
1264 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1266 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1267 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1268 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1269 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1271 htlc_timeout_tx.input[0].witness.push(Vec::new());
1272 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());
1274 add_dynamic_output!(htlc_timeout_tx, 0);
1275 res.push(htlc_timeout_tx);
1277 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1278 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);
1280 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1282 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1283 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1284 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1285 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1287 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1288 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());
1290 add_dynamic_output!(htlc_success_tx, 0);
1291 res.push(htlc_success_tx);
1296 (res, spendable_outputs)
1299 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1300 /// revoked using data in local_claimable_outpoints.
1301 /// Should not be used if check_spend_revoked_transaction succeeds.
1302 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1303 let commitment_txid = tx.txid();
1304 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1305 if local_tx.txid == commitment_txid {
1306 match self.key_storage {
1307 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
1308 return self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1310 KeyStorage::SigsMode { .. } => {
1311 return self.broadcast_by_local_state(local_tx, &None, &None);
1316 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1317 if local_tx.txid == commitment_txid {
1318 match self.key_storage {
1319 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1320 return self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1322 KeyStorage::SigsMode { .. } => {
1323 return self.broadcast_by_local_state(local_tx, &None, &None);
1328 (Vec::new(), Vec::new())
1331 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1332 /// the Channel was out-of-date.
1333 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1334 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1335 let mut res = vec![local_tx.tx.clone()];
1336 match self.key_storage {
1337 KeyStorage::PrivMode { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1338 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1340 _ => panic!("Can only broadcast by local channelmonitor"),
1348 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>) {
1349 let mut watch_outputs = Vec::new();
1350 let mut spendable_outputs = Vec::new();
1351 for tx in txn_matched {
1352 if tx.input.len() == 1 {
1353 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1354 // commitment transactions and HTLC transactions will all only ever have one input,
1355 // which is an easy way to filter out any potential non-matching txn for lazy
1357 let prevout = &tx.input[0].previous_output;
1358 let mut txn: Vec<Transaction> = Vec::new();
1359 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) {
1360 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height);
1362 spendable_outputs.append(&mut spendable_output);
1363 if !new_outputs.1.is_empty() {
1364 watch_outputs.push(new_outputs);
1367 let (remote_txn, mut outputs) = self.check_spend_local_transaction(tx, height);
1368 spendable_outputs.append(&mut outputs);
1372 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1373 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1374 if let Some(tx) = tx {
1377 if let Some(spendable_output) = spendable_output {
1378 spendable_outputs.push(spendable_output);
1382 for tx in txn.iter() {
1383 broadcaster.broadcast_transaction(tx);
1387 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1388 if self.would_broadcast_at_height(height) {
1389 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1390 match self.key_storage {
1391 KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
1392 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1393 spendable_outputs.append(&mut outputs);
1395 broadcaster.broadcast_transaction(&tx);
1398 KeyStorage::SigsMode { .. } => {
1399 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1400 spendable_outputs.append(&mut outputs);
1402 broadcaster.broadcast_transaction(&tx);
1408 self.last_block_hash = block_hash.clone();
1409 (watch_outputs, spendable_outputs)
1412 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1413 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1414 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1415 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1416 // chain with enough room to claim the HTLC without our counterparty being able to
1417 // time out the HTLC first.
1418 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1419 // concern is being able to claim the corresponding inbound HTLC (on another
1420 // channel) before it expires. In fact, we don't even really care if our
1421 // counterparty here claims such an outbound HTLC after it expired as long as we
1422 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1423 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1424 // we give ourselves a few blocks of headroom after expiration before going
1425 // on-chain for an expired HTLC.
1426 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1427 // from us until we've reached the point where we go on-chain with the
1428 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1429 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1430 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1431 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1432 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1433 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1434 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1435 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1436 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1445 const MAX_ALLOC_SIZE: usize = 64*1024;
1447 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1448 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1449 let secp_ctx = Secp256k1::new();
1450 macro_rules! unwrap_obj {
1454 Err(_) => return Err(DecodeError::InvalidValue),
1459 let _ver: u8 = Readable::read(reader)?;
1460 let min_ver: u8 = Readable::read(reader)?;
1461 if min_ver > SERIALIZATION_VERSION {
1462 return Err(DecodeError::UnknownVersion);
1465 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1466 // barely-init'd ChannelMonitors that we can't do anything with.
1467 let outpoint = OutPoint {
1468 txid: Readable::read(reader)?,
1469 index: Readable::read(reader)?,
1471 let funding_txo = Some((outpoint, Readable::read(reader)?));
1472 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1474 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1476 let revocation_base_key = Readable::read(reader)?;
1477 let htlc_base_key = Readable::read(reader)?;
1478 let delayed_payment_base_key = Readable::read(reader)?;
1479 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1481 1 => Some(Readable::read(reader)?),
1482 _ => return Err(DecodeError::InvalidValue),
1484 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1486 1 => Some(Readable::read(reader)?),
1487 _ => return Err(DecodeError::InvalidValue),
1489 KeyStorage::PrivMode {
1490 revocation_base_key,
1492 delayed_payment_base_key,
1493 prev_latest_per_commitment_point,
1494 latest_per_commitment_point,
1497 _ => return Err(DecodeError::InvalidValue),
1500 let their_htlc_base_key = Some(Readable::read(reader)?);
1501 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1503 let their_cur_revocation_points = {
1504 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1508 let first_point = Readable::read(reader)?;
1509 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1510 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1511 Some((first_idx, first_point, None))
1513 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1518 let our_to_self_delay: u16 = Readable::read(reader)?;
1519 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1521 let mut old_secrets = [([0; 32], 1 << 48); 49];
1522 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1523 *secret = Readable::read(reader)?;
1524 *idx = Readable::read(reader)?;
1527 macro_rules! read_htlc_in_commitment {
1530 let offered: bool = Readable::read(reader)?;
1531 let amount_msat: u64 = Readable::read(reader)?;
1532 let cltv_expiry: u32 = Readable::read(reader)?;
1533 let payment_hash: [u8; 32] = Readable::read(reader)?;
1534 let transaction_output_index: u32 = Readable::read(reader)?;
1536 HTLCOutputInCommitment {
1537 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1543 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1544 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1545 for _ in 0..remote_claimable_outpoints_len {
1546 let txid: Sha256dHash = Readable::read(reader)?;
1547 let outputs_count: u64 = Readable::read(reader)?;
1548 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1549 for _ in 0..outputs_count {
1550 outputs.push(read_htlc_in_commitment!());
1552 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1553 return Err(DecodeError::InvalidValue);
1557 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
1558 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
1559 for _ in 0..remote_commitment_txn_on_chain_len {
1560 let txid: Sha256dHash = Readable::read(reader)?;
1561 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1562 let outputs_count = <u64 as Readable<R>>::read(reader)?;
1563 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
1564 for _ in 0..outputs_count {
1565 outputs.push(Readable::read(reader)?);
1567 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
1568 return Err(DecodeError::InvalidValue);
1572 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
1573 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
1574 for _ in 0..remote_hash_commitment_number_len {
1575 let txid: [u8; 32] = Readable::read(reader)?;
1576 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1577 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1578 return Err(DecodeError::InvalidValue);
1582 macro_rules! read_local_tx {
1585 let tx = match Transaction::consensus_decode(reader.by_ref()) {
1588 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
1589 _ => return Err(DecodeError::InvalidValue),
1593 if tx.input.is_empty() {
1594 // Ensure tx didn't hit the 0-input ambiguity case.
1595 return Err(DecodeError::InvalidValue);
1598 let revocation_key = Readable::read(reader)?;
1599 let a_htlc_key = Readable::read(reader)?;
1600 let b_htlc_key = Readable::read(reader)?;
1601 let delayed_payment_key = Readable::read(reader)?;
1602 let feerate_per_kw: u64 = Readable::read(reader)?;
1604 let htlc_outputs_len: u64 = Readable::read(reader)?;
1605 let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
1606 for _ in 0..htlc_outputs_len {
1607 htlc_outputs.push((read_htlc_in_commitment!(), Readable::read(reader)?, Readable::read(reader)?));
1612 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1618 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1621 Some(read_local_tx!())
1623 _ => return Err(DecodeError::InvalidValue),
1626 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1629 Some(read_local_tx!())
1631 _ => return Err(DecodeError::InvalidValue),
1634 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1636 let payment_preimages_len: u64 = Readable::read(reader)?;
1637 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
1638 let mut sha = Sha256::new();
1639 for _ in 0..payment_preimages_len {
1640 let preimage: [u8; 32] = Readable::read(reader)?;
1642 sha.input(&preimage);
1643 let mut hash = [0; 32];
1644 sha.result(&mut hash);
1645 if let Some(_) = payment_preimages.insert(hash, preimage) {
1646 return Err(DecodeError::InvalidValue);
1650 let last_block_hash: Sha256dHash = Readable::read(reader)?;
1651 let destination_script = Readable::read(reader)?;
1653 Ok((last_block_hash.clone(), ChannelMonitor {
1655 commitment_transaction_number_obscure_factor,
1658 their_htlc_base_key,
1659 their_delayed_payment_base_key,
1660 their_cur_revocation_points,
1663 their_to_self_delay,
1666 remote_claimable_outpoints,
1667 remote_commitment_txn_on_chain,
1668 remote_hash_commitment_number,
1670 prev_local_signed_commitment_tx,
1671 current_local_signed_commitment_tx,
1672 current_remote_commitment_number,
1687 use bitcoin::blockdata::script::Script;
1688 use bitcoin::blockdata::transaction::Transaction;
1689 use crypto::digest::Digest;
1691 use ln::channelmonitor::ChannelMonitor;
1692 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1693 use util::sha2::Sha256;
1694 use util::test_utils::TestLogger;
1695 use secp256k1::key::{SecretKey,PublicKey};
1696 use secp256k1::{Secp256k1, Signature};
1697 use rand::{thread_rng,Rng};
1701 fn test_per_commitment_storage() {
1702 // Test vectors from BOLT 3:
1703 let mut secrets: Vec<[u8; 32]> = Vec::new();
1704 let mut monitor: ChannelMonitor;
1705 let secp_ctx = Secp256k1::new();
1706 let logger = Arc::new(TestLogger::new());
1708 macro_rules! test_secrets {
1710 let mut idx = 281474976710655;
1711 for secret in secrets.iter() {
1712 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1715 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1716 assert!(monitor.get_secret(idx).is_err());
1721 // insert_secret correct sequence
1722 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());
1725 secrets.push([0; 32]);
1726 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1727 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1730 secrets.push([0; 32]);
1731 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1732 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1735 secrets.push([0; 32]);
1736 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1737 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1740 secrets.push([0; 32]);
1741 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1742 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1745 secrets.push([0; 32]);
1746 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1747 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1750 secrets.push([0; 32]);
1751 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1752 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1755 secrets.push([0; 32]);
1756 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1757 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1760 secrets.push([0; 32]);
1761 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1762 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1767 // insert_secret #1 incorrect
1768 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());
1771 secrets.push([0; 32]);
1772 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1773 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1776 secrets.push([0; 32]);
1777 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1778 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1779 "Previous secret did not match new one");
1783 // insert_secret #2 incorrect (#1 derived from incorrect)
1784 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());
1787 secrets.push([0; 32]);
1788 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1789 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1792 secrets.push([0; 32]);
1793 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1794 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1797 secrets.push([0; 32]);
1798 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1799 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1802 secrets.push([0; 32]);
1803 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1804 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1805 "Previous secret did not match new one");
1809 // insert_secret #3 incorrect
1810 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());
1813 secrets.push([0; 32]);
1814 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1815 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1818 secrets.push([0; 32]);
1819 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1820 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1823 secrets.push([0; 32]);
1824 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1825 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1828 secrets.push([0; 32]);
1829 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1830 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1831 "Previous secret did not match new one");
1835 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1836 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());
1839 secrets.push([0; 32]);
1840 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1841 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1844 secrets.push([0; 32]);
1845 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1846 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1849 secrets.push([0; 32]);
1850 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1851 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1854 secrets.push([0; 32]);
1855 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1856 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1859 secrets.push([0; 32]);
1860 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1861 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1864 secrets.push([0; 32]);
1865 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1866 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1869 secrets.push([0; 32]);
1870 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1871 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1874 secrets.push([0; 32]);
1875 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1876 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1877 "Previous secret did not match new one");
1881 // insert_secret #5 incorrect
1882 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());
1885 secrets.push([0; 32]);
1886 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1887 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1890 secrets.push([0; 32]);
1891 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1892 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1895 secrets.push([0; 32]);
1896 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1897 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1900 secrets.push([0; 32]);
1901 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1902 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1905 secrets.push([0; 32]);
1906 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1907 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1910 secrets.push([0; 32]);
1911 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1912 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1913 "Previous secret did not match new one");
1917 // insert_secret #6 incorrect (5 derived from incorrect)
1918 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());
1921 secrets.push([0; 32]);
1922 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1923 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1926 secrets.push([0; 32]);
1927 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1928 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1931 secrets.push([0; 32]);
1932 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1933 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1936 secrets.push([0; 32]);
1937 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1938 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1941 secrets.push([0; 32]);
1942 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1943 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1946 secrets.push([0; 32]);
1947 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1948 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1951 secrets.push([0; 32]);
1952 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1953 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1956 secrets.push([0; 32]);
1957 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1958 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1959 "Previous secret did not match new one");
1963 // insert_secret #7 incorrect
1964 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());
1967 secrets.push([0; 32]);
1968 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1969 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1972 secrets.push([0; 32]);
1973 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1974 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1977 secrets.push([0; 32]);
1978 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1979 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1982 secrets.push([0; 32]);
1983 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1984 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1987 secrets.push([0; 32]);
1988 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1989 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1992 secrets.push([0; 32]);
1993 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1994 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1997 secrets.push([0; 32]);
1998 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1999 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
2002 secrets.push([0; 32]);
2003 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2004 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
2005 "Previous secret did not match new one");
2009 // insert_secret #8 incorrect
2010 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());
2013 secrets.push([0; 32]);
2014 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2015 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
2018 secrets.push([0; 32]);
2019 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2020 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
2023 secrets.push([0; 32]);
2024 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2025 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
2028 secrets.push([0; 32]);
2029 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2030 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2035 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2040 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
2043 secrets.push([0; 32]);
2044 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2045 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2050 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
2051 "Previous secret did not match new one");
2056 fn test_prune_preimages() {
2057 let secp_ctx = Secp256k1::new();
2058 let logger = Arc::new(TestLogger::new());
2059 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2061 macro_rules! dummy_keys {
2064 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2066 per_commitment_point: dummy_key.clone(),
2067 revocation_key: dummy_key.clone(),
2068 a_htlc_key: dummy_key.clone(),
2069 b_htlc_key: dummy_key.clone(),
2070 a_delayed_payment_key: dummy_key.clone(),
2071 b_payment_key: dummy_key.clone(),
2076 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2078 let mut preimages = Vec::new();
2080 let mut rng = thread_rng();
2082 let mut preimage = [0; 32];
2083 rng.fill_bytes(&mut preimage);
2084 let mut sha = Sha256::new();
2085 sha.input(&preimage);
2086 let mut hash = [0; 32];
2087 sha.result(&mut hash);
2088 preimages.push((preimage, hash));
2092 macro_rules! preimages_slice_to_htlc_outputs {
2093 ($preimages_slice: expr) => {
2095 let mut res = Vec::new();
2096 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2097 res.push(HTLCOutputInCommitment {
2101 payment_hash: preimage.1.clone(),
2102 transaction_output_index: idx as u32,
2109 macro_rules! preimages_to_local_htlcs {
2110 ($preimages_slice: expr) => {
2112 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2113 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2119 macro_rules! test_preimages_exist {
2120 ($preimages_slice: expr, $monitor: expr) => {
2121 for preimage in $preimages_slice {
2122 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2127 // Prune with one old state and a local commitment tx holding a few overlaps with the
2129 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());
2130 monitor.set_their_to_self_delay(10);
2132 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2133 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
2134 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
2135 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
2136 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
2137 for &(ref preimage, ref hash) in preimages.iter() {
2138 monitor.provide_payment_preimage(hash, preimage);
2141 // Now provide a secret, pruning preimages 10-15
2142 let mut secret = [0; 32];
2143 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2144 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
2145 assert_eq!(monitor.payment_preimages.len(), 15);
2146 test_preimages_exist!(&preimages[0..10], monitor);
2147 test_preimages_exist!(&preimages[15..20], monitor);
2149 // Now provide a further secret, pruning preimages 15-17
2150 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2151 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
2152 assert_eq!(monitor.payment_preimages.len(), 13);
2153 test_preimages_exist!(&preimages[0..10], monitor);
2154 test_preimages_exist!(&preimages[17..20], monitor);
2156 // Now update local commitment tx info, pruning only element 18 as we still care about the
2157 // previous commitment tx's preimages too
2158 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2159 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2160 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
2161 assert_eq!(monitor.payment_preimages.len(), 12);
2162 test_preimages_exist!(&preimages[0..10], monitor);
2163 test_preimages_exist!(&preimages[18..20], monitor);
2165 // But if we do it again, we'll prune 5-10
2166 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2167 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2168 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
2169 assert_eq!(monitor.payment_preimages.len(), 5);
2170 test_preimages_exist!(&preimages[0..5], monitor);
2173 // Further testing is done in the ChannelManager integration tests.