1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode::{self, Decodable, Encodable};
20 use bitcoin::util::hash::{Hash160, BitcoinHash,Sha256dHash};
21 use bitcoin::util::bip143;
23 use crypto::digest::Digest;
25 use secp256k1::{Secp256k1,Message,Signature};
26 use secp256k1::key::{SecretKey,PublicKey};
29 use ln::msgs::DecodeError;
31 use ln::chan_utils::HTLCOutputInCommitment;
32 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
33 use chain::transaction::OutPoint;
34 use chain::keysinterface::SpendableOutputDescriptor;
35 use util::logger::Logger;
36 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
37 use util::sha2::Sha256;
38 use util::{byte_utils, events};
40 use std::collections::HashMap;
41 use std::sync::{Arc,Mutex};
42 use std::{hash,cmp, mem};
44 /// An error enum representing a failure to persist a channel monitor update.
46 pub enum ChannelMonitorUpdateErr {
47 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
48 /// to succeed at some point in the future).
50 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
51 /// submitting new commitment transactions to the remote party.
52 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
53 /// the channel to an operational state.
55 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
56 /// persisted is unsafe - if you failed to store the update on your own local disk you should
57 /// instead return PermanentFailure to force closure of the channel ASAP.
59 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
60 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
61 /// to claim it on this channel) and those updates must be applied wherever they can be. At
62 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
63 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
64 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
67 /// Note that even if updates made after TemporaryFailure succeed you must still call
68 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
69 /// channel operation.
71 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
72 /// different watchtower and cannot update with all watchtowers that were previously informed
73 /// of this channel). This will force-close the channel in question.
77 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
78 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
79 /// means you tried to merge two monitors for different channels or for a channel which was
80 /// restored from a backup and then generated new commitment updates.
81 /// Contains a human-readable error message.
83 pub struct MonitorUpdateError(pub &'static str);
85 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
86 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
87 /// events to it, while also taking any add_update_monitor events and passing them to some remote
90 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
91 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
92 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
93 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
94 pub trait ManyChannelMonitor: Send + Sync {
95 /// Adds or updates a monitor for the given `funding_txo`.
97 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
98 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
100 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
103 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
104 /// watchtower or watch our own channels.
106 /// Note that you must provide your own key by which to refer to channels.
108 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
109 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
110 /// index by a PublicKey which is required to sign any updates.
112 /// If you're using this for local monitoring of your own channels, you probably want to use
113 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
114 pub struct SimpleManyChannelMonitor<Key> {
115 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
116 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
118 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
119 chain_monitor: Arc<ChainWatchInterface>,
120 broadcaster: Arc<BroadcasterInterface>,
121 pending_events: Mutex<Vec<events::Event>>,
125 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
126 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
127 let block_hash = header.bitcoin_hash();
128 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
130 let mut monitors = self.monitors.lock().unwrap();
131 for monitor in monitors.values_mut() {
132 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
133 if spendable_outputs.len() > 0 {
134 new_events.push(events::Event::SpendableOutputs {
135 outputs: spendable_outputs,
138 for (ref txid, ref outputs) in txn_outputs {
139 for (idx, output) in outputs.iter().enumerate() {
140 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
145 let mut pending_events = self.pending_events.lock().unwrap();
146 pending_events.append(&mut new_events);
149 fn block_disconnected(&self, _: &BlockHeader) { }
152 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
153 /// Creates a new object which can be used to monitor several channels given the chain
154 /// interface with which to register to receive notifications.
155 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
156 let res = Arc::new(SimpleManyChannelMonitor {
157 monitors: Mutex::new(HashMap::new()),
160 pending_events: Mutex::new(Vec::new()),
163 let weak_res = Arc::downgrade(&res);
164 res.chain_monitor.register_listener(weak_res);
168 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
169 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
170 let mut monitors = self.monitors.lock().unwrap();
171 match monitors.get_mut(&key) {
172 Some(orig_monitor) => {
173 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_option!(monitor.funding_txo));
174 return orig_monitor.insert_combine(monitor);
178 match &monitor.funding_txo {
180 log_trace!(self, "Got new Channel Monitor for no-funding-set channel (monitoring all txn!)");
181 self.chain_monitor.watch_all_txn()
183 &Some((ref outpoint, ref script)) => {
184 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
185 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
186 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
189 monitors.insert(key, monitor);
194 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
195 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
196 match self.add_update_monitor_by_key(funding_txo, monitor) {
198 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
203 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
204 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
205 let mut pending_events = self.pending_events.lock().unwrap();
206 let mut ret = Vec::new();
207 mem::swap(&mut ret, &mut *pending_events);
212 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
213 /// instead claiming it in its own individual transaction.
214 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
215 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
216 /// HTLC-Success transaction.
217 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
218 /// transaction confirmed (and we use it in a few more, equivalent, places).
219 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
220 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
221 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
222 /// copies of ChannelMonitors, including watchtowers).
223 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
225 #[derive(Clone, PartialEq)]
228 revocation_base_key: SecretKey,
229 htlc_base_key: SecretKey,
230 delayed_payment_base_key: SecretKey,
231 payment_base_key: SecretKey,
232 shutdown_pubkey: PublicKey,
233 prev_latest_per_commitment_point: Option<PublicKey>,
234 latest_per_commitment_point: Option<PublicKey>,
237 revocation_base_key: PublicKey,
238 htlc_base_key: PublicKey,
239 sigs: HashMap<Sha256dHash, Signature>,
243 #[derive(Clone, PartialEq)]
244 struct LocalSignedTx {
245 /// txid of the transaction in tx, just used to make comparison faster
248 revocation_key: PublicKey,
249 a_htlc_key: PublicKey,
250 b_htlc_key: PublicKey,
251 delayed_payment_key: PublicKey,
253 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
256 const SERIALIZATION_VERSION: u8 = 1;
257 const MIN_SERIALIZATION_VERSION: u8 = 1;
259 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
260 /// on-chain transactions to ensure no loss of funds occurs.
262 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
263 /// information and are actively monitoring the chain.
265 pub struct ChannelMonitor {
266 funding_txo: Option<(OutPoint, Script)>,
267 commitment_transaction_number_obscure_factor: u64,
269 key_storage: KeyStorage,
270 their_htlc_base_key: Option<PublicKey>,
271 their_delayed_payment_base_key: Option<PublicKey>,
272 // first is the idx of the first of the two revocation points
273 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
275 our_to_self_delay: u16,
276 their_to_self_delay: Option<u16>,
278 old_secrets: [([u8; 32], u64); 49],
279 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
280 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
281 /// Nor can we figure out their commitment numbers without the commitment transaction they are
282 /// spending. Thus, in order to claim them via revocation key, we track all the remote
283 /// commitment transactions which we find on-chain, mapping them to the commitment number which
284 /// can be used to derive the revocation key and claim the transactions.
285 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
286 /// Cache used to make pruning of payment_preimages faster.
287 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
288 /// remote transactions (ie should remain pretty small).
289 /// Serialized to disk but should generally not be sent to Watchtowers.
290 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
292 // We store two local commitment transactions to avoid any race conditions where we may update
293 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
294 // various monitors for one channel being out of sync, and us broadcasting a local
295 // transaction for which we have deleted claim information on some watchtowers.
296 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
297 current_local_signed_commitment_tx: Option<LocalSignedTx>,
299 // Used just for ChannelManager to make sure it has the latest channel data during
301 current_remote_commitment_number: u64,
303 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
305 destination_script: Script,
307 // We simply modify last_block_hash in Channel's block_connected so that serialization is
308 // consistent but hopefully the users' copy handles block_connected in a consistent way.
309 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
310 // their last_block_hash from its state and not based on updated copies that didn't run through
311 // the full block_connected).
312 pub(crate) last_block_hash: Sha256dHash,
313 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
317 #[cfg(any(test, feature = "fuzztarget"))]
318 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
319 /// underlying object
320 impl PartialEq for ChannelMonitor {
321 fn eq(&self, other: &Self) -> bool {
322 if self.funding_txo != other.funding_txo ||
323 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
324 self.key_storage != other.key_storage ||
325 self.their_htlc_base_key != other.their_htlc_base_key ||
326 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
327 self.their_cur_revocation_points != other.their_cur_revocation_points ||
328 self.our_to_self_delay != other.our_to_self_delay ||
329 self.their_to_self_delay != other.their_to_self_delay ||
330 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
331 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
332 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
333 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
334 self.current_remote_commitment_number != other.current_remote_commitment_number ||
335 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
336 self.payment_preimages != other.payment_preimages ||
337 self.destination_script != other.destination_script
341 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
342 if secret != o_secret || idx != o_idx {
351 impl ChannelMonitor {
352 pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
355 commitment_transaction_number_obscure_factor: 0,
357 key_storage: KeyStorage::PrivMode {
358 revocation_base_key: revocation_base_key.clone(),
359 htlc_base_key: htlc_base_key.clone(),
360 delayed_payment_base_key: delayed_payment_base_key.clone(),
361 payment_base_key: payment_base_key.clone(),
362 shutdown_pubkey: shutdown_pubkey.clone(),
363 prev_latest_per_commitment_point: None,
364 latest_per_commitment_point: None,
366 their_htlc_base_key: None,
367 their_delayed_payment_base_key: None,
368 their_cur_revocation_points: None,
370 our_to_self_delay: our_to_self_delay,
371 their_to_self_delay: None,
373 old_secrets: [([0; 32], 1 << 48); 49],
374 remote_claimable_outpoints: HashMap::new(),
375 remote_commitment_txn_on_chain: HashMap::new(),
376 remote_hash_commitment_number: HashMap::new(),
378 prev_local_signed_commitment_tx: None,
379 current_local_signed_commitment_tx: None,
380 current_remote_commitment_number: 1 << 48,
382 payment_preimages: HashMap::new(),
383 destination_script: destination_script,
385 last_block_hash: Default::default(),
386 secp_ctx: Secp256k1::new(),
392 fn place_secret(idx: u64) -> u8 {
394 if idx & (1 << i) == (1 << i) {
402 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
403 let mut res: [u8; 32] = secret;
405 let bitpos = bits - 1 - i;
406 if idx & (1 << bitpos) == (1 << bitpos) {
407 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
408 let mut sha = Sha256::new();
410 sha.result(&mut res);
416 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
417 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
418 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
419 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
420 let pos = ChannelMonitor::place_secret(idx);
422 let (old_secret, old_idx) = self.old_secrets[i as usize];
423 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
424 return Err(MonitorUpdateError("Previous secret did not match new one"));
427 self.old_secrets[pos as usize] = (secret, idx);
429 if !self.payment_preimages.is_empty() {
430 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
431 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
432 let min_idx = self.get_min_seen_secret();
433 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
435 self.payment_preimages.retain(|&k, _| {
436 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
437 if k == htlc.payment_hash {
441 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
442 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
443 if k == htlc.payment_hash {
448 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
455 remote_hash_commitment_number.remove(&k);
464 /// Tracks the next revocation point which may be required to claim HTLC outputs which we know
465 /// the preimage of in case the remote end force-closes using their latest state. When called at
466 /// channel opening revocation point is the CURRENT one used for first commitment tx. Needed in case of sizeable push_msat.
467 pub(super) fn provide_their_next_revocation_point(&mut self, their_next_revocation_point: Option<(u64, PublicKey)>) {
468 if let Some(new_revocation_point) = their_next_revocation_point {
469 match self.their_cur_revocation_points {
470 Some(old_points) => {
471 if old_points.0 == new_revocation_point.0 + 1 {
472 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
473 } else if old_points.0 == new_revocation_point.0 + 2 {
474 if let Some(old_second_point) = old_points.2 {
475 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
477 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
480 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
484 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
490 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
491 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
492 /// possibly future revocation/preimage information) to claim outputs where possible.
493 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
494 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
495 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
496 // so that a remote monitor doesn't learn anything unless there is a malicious close.
497 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
499 for htlc in &htlc_outputs {
500 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
502 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
503 self.current_remote_commitment_number = commitment_number;
506 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
507 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
508 /// is important that any clones of this channel monitor (including remote clones) by kept
509 /// up-to-date as our local commitment transaction is updated.
510 /// Panics if set_their_to_self_delay has never been called.
511 /// Also update KeyStorage with latest local per_commitment_point to derive local_delayedkey in
512 /// case of onchain HTLC tx
513 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)>) {
514 assert!(self.their_to_self_delay.is_some());
515 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
516 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
517 txid: signed_commitment_tx.txid(),
518 tx: signed_commitment_tx,
519 revocation_key: local_keys.revocation_key,
520 a_htlc_key: local_keys.a_htlc_key,
521 b_htlc_key: local_keys.b_htlc_key,
522 delayed_payment_key: local_keys.a_delayed_payment_key,
526 self.key_storage = if let KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref latest_per_commitment_point, .. } = self.key_storage {
527 KeyStorage::PrivMode {
528 revocation_base_key: *revocation_base_key,
529 htlc_base_key: *htlc_base_key,
530 delayed_payment_base_key: *delayed_payment_base_key,
531 payment_base_key: *payment_base_key,
532 shutdown_pubkey: *shutdown_pubkey,
533 prev_latest_per_commitment_point: *latest_per_commitment_point,
534 latest_per_commitment_point: Some(local_keys.per_commitment_point),
536 } else { unimplemented!(); };
539 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
540 /// commitment_tx_infos which contain the payment hash have been revoked.
541 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
542 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
545 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
546 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
547 /// chain for new blocks/transactions.
548 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
549 if self.funding_txo.is_some() {
550 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
551 // easy to collide the funding_txo hash and have a different scriptPubKey.
552 if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
553 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
556 self.funding_txo = other.funding_txo.take();
558 let other_min_secret = other.get_min_seen_secret();
559 let our_min_secret = self.get_min_seen_secret();
560 if our_min_secret > other_min_secret {
561 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
563 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
564 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
565 let our_commitment_number = 0xffffffffffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
566 let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
567 if our_commitment_number >= other_commitment_number {
568 self.key_storage = other.key_storage;
572 // TODO: We should use current_remote_commitment_number and the commitment number out of
573 // local transactions to decide how to merge
574 if our_min_secret >= other_min_secret {
575 self.their_cur_revocation_points = other.their_cur_revocation_points;
576 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
577 self.remote_claimable_outpoints.insert(txid, htlcs);
579 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
580 self.prev_local_signed_commitment_tx = Some(local_tx);
582 if let Some(local_tx) = other.current_local_signed_commitment_tx {
583 self.current_local_signed_commitment_tx = Some(local_tx);
585 self.payment_preimages = other.payment_preimages;
588 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
592 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
593 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
594 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
595 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
598 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
599 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
600 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
601 /// provides slightly better privacy.
602 /// It's the responsibility of the caller to register outpoint and script with passing the former
603 /// value as key to add_update_monitor.
604 pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
605 self.funding_txo = Some(funding_info);
608 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
609 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
610 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
611 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
614 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
615 self.their_to_self_delay = Some(their_to_self_delay);
618 pub(super) fn unset_funding_info(&mut self) {
619 self.funding_txo = None;
622 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
623 pub fn get_funding_txo(&self) -> Option<OutPoint> {
624 match self.funding_txo {
625 Some((outpoint, _)) => Some(outpoint),
630 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
631 /// Generally useful when deserializing as during normal operation the return values of
632 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
633 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
634 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
635 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
636 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
637 for (idx, output) in outputs.iter().enumerate() {
638 res.push(((*txid).clone(), idx as u32, output));
644 /// Serializes into a vec, with various modes for the exposed pub fns
645 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
646 //TODO: We still write out all the serialization here manually instead of using the fancy
647 //serialization framework we have, we should migrate things over to it.
648 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
649 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
651 match &self.funding_txo {
652 &Some((ref outpoint, ref script)) => {
653 writer.write_all(&outpoint.txid[..])?;
654 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
655 script.write(writer)?;
658 // We haven't even been initialized...not sure why anyone is serializing us, but
659 // not much to give them.
664 // Set in initial Channel-object creation, so should always be set by now:
665 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
667 match self.key_storage {
668 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point } => {
669 writer.write_all(&[0; 1])?;
670 writer.write_all(&revocation_base_key[..])?;
671 writer.write_all(&htlc_base_key[..])?;
672 writer.write_all(&delayed_payment_base_key[..])?;
673 writer.write_all(&payment_base_key[..])?;
674 writer.write_all(&shutdown_pubkey.serialize())?;
675 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
676 writer.write_all(&[1; 1])?;
677 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
679 writer.write_all(&[0; 1])?;
681 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
682 writer.write_all(&[1; 1])?;
683 writer.write_all(&latest_per_commitment_point.serialize())?;
685 writer.write_all(&[0; 1])?;
689 KeyStorage::SigsMode { .. } => unimplemented!(),
692 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
693 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
695 match self.their_cur_revocation_points {
696 Some((idx, pubkey, second_option)) => {
697 writer.write_all(&byte_utils::be48_to_array(idx))?;
698 writer.write_all(&pubkey.serialize())?;
699 match second_option {
700 Some(second_pubkey) => {
701 writer.write_all(&second_pubkey.serialize())?;
704 writer.write_all(&[0; 33])?;
709 writer.write_all(&byte_utils::be48_to_array(0))?;
713 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
714 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
716 for &(ref secret, ref idx) in self.old_secrets.iter() {
717 writer.write_all(secret)?;
718 writer.write_all(&byte_utils::be64_to_array(*idx))?;
721 macro_rules! serialize_htlc_in_commitment {
722 ($htlc_output: expr) => {
723 writer.write_all(&[$htlc_output.offered as u8; 1])?;
724 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
725 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
726 writer.write_all(&$htlc_output.payment_hash)?;
727 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
731 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
732 for (ref txid, ref htlc_outputs) in self.remote_claimable_outpoints.iter() {
733 writer.write_all(&txid[..])?;
734 writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
735 for htlc_output in htlc_outputs.iter() {
736 serialize_htlc_in_commitment!(htlc_output);
740 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
741 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
742 writer.write_all(&txid[..])?;
743 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
744 (txouts.len() as u64).write(writer)?;
745 for script in txouts.iter() {
746 script.write(writer)?;
750 if for_local_storage {
751 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
752 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
753 writer.write_all(*payment_hash)?;
754 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
757 writer.write_all(&byte_utils::be64_to_array(0))?;
760 macro_rules! serialize_local_tx {
761 ($local_tx: expr) => {
762 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
764 encode::Error::Io(e) => return Err(e),
765 _ => panic!("local tx must have been well-formed!"),
769 writer.write_all(&$local_tx.revocation_key.serialize())?;
770 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
771 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
772 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
774 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
775 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
776 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
777 serialize_htlc_in_commitment!(htlc_output);
778 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
779 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
784 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
785 writer.write_all(&[1; 1])?;
786 serialize_local_tx!(prev_local_tx);
788 writer.write_all(&[0; 1])?;
791 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
792 writer.write_all(&[1; 1])?;
793 serialize_local_tx!(cur_local_tx);
795 writer.write_all(&[0; 1])?;
798 if for_local_storage {
799 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
801 writer.write_all(&byte_utils::be48_to_array(0))?;
804 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
805 for payment_preimage in self.payment_preimages.values() {
806 writer.write_all(payment_preimage)?;
809 self.last_block_hash.write(writer)?;
810 self.destination_script.write(writer)?;
815 /// Writes this monitor into the given writer, suitable for writing to disk.
817 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
818 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
819 /// the "reorg path" (ie not just starting at the same height but starting at the highest
820 /// common block that appears on your best chain as well as on the chain which contains the
821 /// last block hash returned) upon deserializing the object!
822 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
823 self.write(writer, true)
826 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
828 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
829 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
830 /// the "reorg path" (ie not just starting at the same height but starting at the highest
831 /// common block that appears on your best chain as well as on the chain which contains the
832 /// last block hash returned) upon deserializing the object!
833 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
834 self.write(writer, false)
837 //TODO: Functions to serialize/deserialize (with different forms depending on which information
838 //we want to leave out (eg funding_txo, etc).
840 /// Can only fail if idx is < get_min_seen_secret
841 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
842 for i in 0..self.old_secrets.len() {
843 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
844 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
847 assert!(idx < self.get_min_seen_secret());
851 pub(super) fn get_min_seen_secret(&self) -> u64 {
852 //TODO This can be optimized?
853 let mut min = 1 << 48;
854 for &(_, idx) in self.old_secrets.iter() {
862 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
863 self.current_remote_commitment_number
866 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
867 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
868 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)
869 } else { 0xffff_ffff_ffff }
872 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
873 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
874 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
875 /// HTLC-Success/HTLC-Timeout transactions.
876 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
877 // Most secp and related errors trying to create keys means we have no hope of constructing
878 // a spend transaction...so we return no transactions to broadcast
879 let mut txn_to_broadcast = Vec::new();
880 let mut watch_outputs = Vec::new();
881 let mut spendable_outputs = Vec::new();
883 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
884 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
886 macro_rules! ignore_error {
887 ( $thing : expr ) => {
890 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
895 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);
896 if commitment_number >= self.get_min_seen_secret() {
897 let secret = self.get_secret(commitment_number).unwrap();
898 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
899 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
900 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
901 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
902 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
903 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
905 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
906 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
907 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
908 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
911 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()));
912 let a_htlc_key = match self.their_htlc_base_key {
913 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
914 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)),
917 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
918 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
920 let mut total_value = 0;
921 let mut values = Vec::new();
922 let mut inputs = Vec::new();
923 let mut htlc_idxs = Vec::new();
925 for (idx, outp) in tx.output.iter().enumerate() {
926 if outp.script_pubkey == revokeable_p2wsh {
928 previous_output: BitcoinOutPoint {
929 txid: commitment_txid,
932 script_sig: Script::new(),
933 sequence: 0xfffffffd,
936 htlc_idxs.push(None);
937 values.push(outp.value);
938 total_value += outp.value;
939 } else if outp.script_pubkey.is_v0_p2wpkh() {
940 match self.key_storage {
941 KeyStorage::PrivMode { ref payment_base_key, .. } => {
942 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
943 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key) {
944 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
945 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
947 output: outp.clone(),
951 KeyStorage::SigsMode { .. } => {
952 //TODO: we need to ensure an offline client will generate the event when it
953 // cames back online after only the watchtower saw the transaction
959 macro_rules! sign_input {
960 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
962 let (sig, redeemscript) = match self.key_storage {
963 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
964 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
965 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
966 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
968 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
969 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
970 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
972 KeyStorage::SigsMode { .. } => {
976 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
977 $input.witness[0].push(SigHashType::All as u8);
978 if $htlc_idx.is_none() {
979 $input.witness.push(vec!(1));
981 $input.witness.push(revocation_pubkey.serialize().to_vec());
983 $input.witness.push(redeemscript.into_bytes());
988 if let Some(per_commitment_data) = per_commitment_option {
989 inputs.reserve_exact(per_commitment_data.len());
991 for (idx, htlc) in per_commitment_data.iter().enumerate() {
992 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
993 if htlc.transaction_output_index as usize >= tx.output.len() ||
994 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
995 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
996 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
999 previous_output: BitcoinOutPoint {
1000 txid: commitment_txid,
1001 vout: htlc.transaction_output_index,
1003 script_sig: Script::new(),
1004 sequence: 0xfffffffd,
1005 witness: Vec::new(),
1007 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1009 htlc_idxs.push(Some(idx));
1010 values.push(tx.output[htlc.transaction_output_index as usize].value);
1011 total_value += htlc.amount_msat / 1000;
1013 let mut single_htlc_tx = Transaction {
1017 output: vec!(TxOut {
1018 script_pubkey: self.destination_script.clone(),
1019 value: htlc.amount_msat / 1000, //TODO: - fee
1022 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1023 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1024 txn_to_broadcast.push(single_htlc_tx);
1029 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1030 // We're definitely a remote commitment transaction!
1031 watch_outputs.append(&mut tx.output.clone());
1032 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1034 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1036 let outputs = vec!(TxOut {
1037 script_pubkey: self.destination_script.clone(),
1038 value: total_value, //TODO: - fee
1040 let mut spend_tx = Transaction {
1047 let mut values_drain = values.drain(..);
1048 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1050 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1051 let value = values_drain.next().unwrap();
1052 sign_input!(sighash_parts, input, htlc_idx, value);
1055 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1056 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1057 output: spend_tx.output[0].clone(),
1059 txn_to_broadcast.push(spend_tx);
1060 } else if let Some(per_commitment_data) = per_commitment_option {
1061 // While this isn't useful yet, there is a potential race where if a counterparty
1062 // revokes a state at the same time as the commitment transaction for that state is
1063 // confirmed, and the watchtower receives the block before the user, the user could
1064 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1065 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1066 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1068 watch_outputs.append(&mut tx.output.clone());
1069 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1071 if let Some(revocation_points) = self.their_cur_revocation_points {
1072 let revocation_point_option =
1073 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1074 else if let Some(point) = revocation_points.2.as_ref() {
1075 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1077 if let Some(revocation_point) = revocation_point_option {
1078 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1079 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1080 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1081 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1083 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
1084 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1085 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1088 let a_htlc_key = match self.their_htlc_base_key {
1089 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1090 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1094 for (idx, outp) in tx.output.iter().enumerate() {
1095 if outp.script_pubkey.is_v0_p2wpkh() {
1096 match self.key_storage {
1097 KeyStorage::PrivMode { ref payment_base_key, .. } => {
1098 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1099 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1100 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1102 output: outp.clone(),
1106 KeyStorage::SigsMode { .. } => {
1107 //TODO: we need to ensure an offline client will generate the event when it
1108 // cames back online after only the watchtower saw the transaction
1111 break; // Only to_remote ouput is claimable
1115 let mut total_value = 0;
1116 let mut values = Vec::new();
1117 let mut inputs = Vec::new();
1119 macro_rules! sign_input {
1120 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1122 let (sig, redeemscript) = match self.key_storage {
1123 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
1124 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
1125 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1126 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1127 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1128 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1130 KeyStorage::SigsMode { .. } => {
1134 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1135 $input.witness[0].push(SigHashType::All as u8);
1136 $input.witness.push($preimage);
1137 $input.witness.push(redeemscript.into_bytes());
1142 for (idx, htlc) in per_commitment_data.iter().enumerate() {
1143 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1145 previous_output: BitcoinOutPoint {
1146 txid: commitment_txid,
1147 vout: htlc.transaction_output_index,
1149 script_sig: Script::new(),
1150 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1151 witness: Vec::new(),
1153 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1155 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1156 total_value += htlc.amount_msat / 1000;
1158 let mut single_htlc_tx = Transaction {
1162 output: vec!(TxOut {
1163 script_pubkey: self.destination_script.clone(),
1164 value: htlc.amount_msat / 1000, //TODO: - fee
1167 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1168 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1169 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1170 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1171 output: single_htlc_tx.output[0].clone(),
1173 txn_to_broadcast.push(single_htlc_tx);
1178 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1180 let outputs = vec!(TxOut {
1181 script_pubkey: self.destination_script.clone(),
1182 value: total_value, //TODO: - fee
1184 let mut spend_tx = Transaction {
1191 let mut values_drain = values.drain(..);
1192 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1194 for input in spend_tx.input.iter_mut() {
1195 let value = values_drain.next().unwrap();
1196 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1199 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1200 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1201 output: spend_tx.output[0].clone(),
1203 txn_to_broadcast.push(spend_tx);
1208 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1211 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1212 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1213 if tx.input.len() != 1 || tx.output.len() != 1 {
1217 macro_rules! ignore_error {
1218 ( $thing : expr ) => {
1221 Err(_) => return (None, None)
1226 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1227 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1228 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1229 let revocation_pubkey = match self.key_storage {
1230 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1231 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1233 KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1234 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1237 let delayed_key = match self.their_delayed_payment_base_key {
1238 None => return (None, None),
1239 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1241 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1242 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1243 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1245 let mut inputs = Vec::new();
1248 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1250 previous_output: BitcoinOutPoint {
1254 script_sig: Script::new(),
1255 sequence: 0xfffffffd,
1256 witness: Vec::new(),
1258 amount = tx.output[0].value;
1261 if !inputs.is_empty() {
1262 let outputs = vec!(TxOut {
1263 script_pubkey: self.destination_script.clone(),
1264 value: amount, //TODO: - fee
1267 let mut spend_tx = Transaction {
1274 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1276 let sig = match self.key_storage {
1277 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1278 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1279 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1280 self.secp_ctx.sign(&sighash, &revocation_key)
1282 KeyStorage::SigsMode { .. } => {
1286 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1287 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1288 spend_tx.input[0].witness.push(vec!(1));
1289 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1291 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1292 let output = spend_tx.output[0].clone();
1293 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1294 } else { (None, None) }
1297 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1298 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1299 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1301 macro_rules! add_dynamic_output {
1302 ($father_tx: expr, $vout: expr) => {
1303 if let Some(ref per_commitment_point) = *per_commitment_point {
1304 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1305 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1306 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1307 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1308 key: local_delayedkey,
1309 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1310 to_self_delay: self.our_to_self_delay,
1311 output: $father_tx.output[$vout as usize].clone(),
1320 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1321 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1322 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1323 if output.script_pubkey == revokeable_p2wsh {
1324 add_dynamic_output!(local_tx.tx, idx as u32);
1329 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1331 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);
1333 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1335 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1336 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1337 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1338 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1340 htlc_timeout_tx.input[0].witness.push(Vec::new());
1341 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());
1343 add_dynamic_output!(htlc_timeout_tx, 0);
1344 res.push(htlc_timeout_tx);
1346 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1347 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);
1349 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1351 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1352 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1353 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1354 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1356 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1357 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());
1359 add_dynamic_output!(htlc_success_tx, 0);
1360 res.push(htlc_success_tx);
1365 (res, spendable_outputs)
1368 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1369 /// revoked using data in local_claimable_outpoints.
1370 /// Should not be used if check_spend_revoked_transaction succeeds.
1371 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>) {
1372 let commitment_txid = tx.txid();
1373 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1374 if local_tx.txid == commitment_txid {
1375 match self.key_storage {
1376 KeyStorage::PrivMode { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1377 return self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1379 KeyStorage::SigsMode { .. } => {
1380 return self.broadcast_by_local_state(local_tx, &None, &None);
1385 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1386 if local_tx.txid == commitment_txid {
1387 match self.key_storage {
1388 KeyStorage::PrivMode { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1389 return self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1391 KeyStorage::SigsMode { .. } => {
1392 return self.broadcast_by_local_state(local_tx, &None, &None);
1397 (Vec::new(), Vec::new())
1400 /// Generate a spendable output event when closing_transaction get registered onchain.
1401 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1402 if tx.input[0].sequence == 0xFFFFFFFF && tx.input[0].witness.last().unwrap().len() == 71 {
1403 match self.key_storage {
1404 KeyStorage::PrivMode { ref shutdown_pubkey, .. } => {
1405 let our_channel_close_key_hash = Hash160::from_data(&shutdown_pubkey.serialize());
1406 let shutdown_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1407 for (idx, output) in tx.output.iter().enumerate() {
1408 if shutdown_script == output.script_pubkey {
1409 return Some(SpendableOutputDescriptor::StaticOutput {
1410 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1411 output: output.clone(),
1416 KeyStorage::SigsMode { .. } => {
1417 //TODO: we need to ensure an offline client will generate the event when it
1418 // cames back online after only the watchtower saw the transaction
1425 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1426 /// the Channel was out-of-date.
1427 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1428 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1429 let mut res = vec![local_tx.tx.clone()];
1430 match self.key_storage {
1431 KeyStorage::PrivMode { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1432 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1434 _ => panic!("Can only broadcast by local channelmonitor"),
1442 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>) {
1443 let mut watch_outputs = Vec::new();
1444 let mut spendable_outputs = Vec::new();
1445 for tx in txn_matched {
1446 if tx.input.len() == 1 {
1447 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1448 // commitment transactions and HTLC transactions will all only ever have one input,
1449 // which is an easy way to filter out any potential non-matching txn for lazy
1451 let prevout = &tx.input[0].previous_output;
1452 let mut txn: Vec<Transaction> = Vec::new();
1453 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) {
1454 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height);
1456 spendable_outputs.append(&mut spendable_output);
1457 if !new_outputs.1.is_empty() {
1458 watch_outputs.push(new_outputs);
1461 let (remote_txn, mut outputs) = self.check_spend_local_transaction(tx, height);
1462 spendable_outputs.append(&mut outputs);
1465 if !self.funding_txo.is_none() && txn.is_empty() {
1466 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1467 spendable_outputs.push(spendable_output);
1471 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1472 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1473 if let Some(tx) = tx {
1476 if let Some(spendable_output) = spendable_output {
1477 spendable_outputs.push(spendable_output);
1481 for tx in txn.iter() {
1482 broadcaster.broadcast_transaction(tx);
1486 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1487 if self.would_broadcast_at_height(height) {
1488 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1489 match self.key_storage {
1490 KeyStorage::PrivMode { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1491 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1492 spendable_outputs.append(&mut outputs);
1494 broadcaster.broadcast_transaction(&tx);
1497 KeyStorage::SigsMode { .. } => {
1498 let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1499 spendable_outputs.append(&mut outputs);
1501 broadcaster.broadcast_transaction(&tx);
1507 self.last_block_hash = block_hash.clone();
1508 (watch_outputs, spendable_outputs)
1511 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1512 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1513 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1514 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1515 // chain with enough room to claim the HTLC without our counterparty being able to
1516 // time out the HTLC first.
1517 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1518 // concern is being able to claim the corresponding inbound HTLC (on another
1519 // channel) before it expires. In fact, we don't even really care if our
1520 // counterparty here claims such an outbound HTLC after it expired as long as we
1521 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1522 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1523 // we give ourselves a few blocks of headroom after expiration before going
1524 // on-chain for an expired HTLC.
1525 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1526 // from us until we've reached the point where we go on-chain with the
1527 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1528 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1529 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1530 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1531 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1532 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1533 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1534 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1535 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1544 const MAX_ALLOC_SIZE: usize = 64*1024;
1546 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1547 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1548 let secp_ctx = Secp256k1::new();
1549 macro_rules! unwrap_obj {
1553 Err(_) => return Err(DecodeError::InvalidValue),
1558 let _ver: u8 = Readable::read(reader)?;
1559 let min_ver: u8 = Readable::read(reader)?;
1560 if min_ver > SERIALIZATION_VERSION {
1561 return Err(DecodeError::UnknownVersion);
1564 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1565 // barely-init'd ChannelMonitors that we can't do anything with.
1566 let outpoint = OutPoint {
1567 txid: Readable::read(reader)?,
1568 index: Readable::read(reader)?,
1570 let funding_txo = Some((outpoint, Readable::read(reader)?));
1571 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1573 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1575 let revocation_base_key = Readable::read(reader)?;
1576 let htlc_base_key = Readable::read(reader)?;
1577 let delayed_payment_base_key = Readable::read(reader)?;
1578 let payment_base_key = Readable::read(reader)?;
1579 let shutdown_pubkey = Readable::read(reader)?;
1580 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1582 1 => Some(Readable::read(reader)?),
1583 _ => return Err(DecodeError::InvalidValue),
1585 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1587 1 => Some(Readable::read(reader)?),
1588 _ => return Err(DecodeError::InvalidValue),
1590 KeyStorage::PrivMode {
1591 revocation_base_key,
1593 delayed_payment_base_key,
1596 prev_latest_per_commitment_point,
1597 latest_per_commitment_point,
1600 _ => return Err(DecodeError::InvalidValue),
1603 let their_htlc_base_key = Some(Readable::read(reader)?);
1604 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1606 let their_cur_revocation_points = {
1607 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1611 let first_point = Readable::read(reader)?;
1612 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1613 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1614 Some((first_idx, first_point, None))
1616 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1621 let our_to_self_delay: u16 = Readable::read(reader)?;
1622 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1624 let mut old_secrets = [([0; 32], 1 << 48); 49];
1625 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1626 *secret = Readable::read(reader)?;
1627 *idx = Readable::read(reader)?;
1630 macro_rules! read_htlc_in_commitment {
1633 let offered: bool = Readable::read(reader)?;
1634 let amount_msat: u64 = Readable::read(reader)?;
1635 let cltv_expiry: u32 = Readable::read(reader)?;
1636 let payment_hash: [u8; 32] = Readable::read(reader)?;
1637 let transaction_output_index: u32 = Readable::read(reader)?;
1639 HTLCOutputInCommitment {
1640 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1646 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1647 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1648 for _ in 0..remote_claimable_outpoints_len {
1649 let txid: Sha256dHash = Readable::read(reader)?;
1650 let outputs_count: u64 = Readable::read(reader)?;
1651 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1652 for _ in 0..outputs_count {
1653 outputs.push(read_htlc_in_commitment!());
1655 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1656 return Err(DecodeError::InvalidValue);
1660 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
1661 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
1662 for _ in 0..remote_commitment_txn_on_chain_len {
1663 let txid: Sha256dHash = Readable::read(reader)?;
1664 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1665 let outputs_count = <u64 as Readable<R>>::read(reader)?;
1666 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
1667 for _ in 0..outputs_count {
1668 outputs.push(Readable::read(reader)?);
1670 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
1671 return Err(DecodeError::InvalidValue);
1675 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
1676 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
1677 for _ in 0..remote_hash_commitment_number_len {
1678 let txid: [u8; 32] = Readable::read(reader)?;
1679 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1680 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1681 return Err(DecodeError::InvalidValue);
1685 macro_rules! read_local_tx {
1688 let tx = match Transaction::consensus_decode(reader.by_ref()) {
1691 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
1692 _ => return Err(DecodeError::InvalidValue),
1696 if tx.input.is_empty() {
1697 // Ensure tx didn't hit the 0-input ambiguity case.
1698 return Err(DecodeError::InvalidValue);
1701 let revocation_key = Readable::read(reader)?;
1702 let a_htlc_key = Readable::read(reader)?;
1703 let b_htlc_key = Readable::read(reader)?;
1704 let delayed_payment_key = Readable::read(reader)?;
1705 let feerate_per_kw: u64 = Readable::read(reader)?;
1707 let htlc_outputs_len: u64 = Readable::read(reader)?;
1708 let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
1709 for _ in 0..htlc_outputs_len {
1710 htlc_outputs.push((read_htlc_in_commitment!(), Readable::read(reader)?, Readable::read(reader)?));
1715 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1721 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1724 Some(read_local_tx!())
1726 _ => return Err(DecodeError::InvalidValue),
1729 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
1732 Some(read_local_tx!())
1734 _ => return Err(DecodeError::InvalidValue),
1737 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
1739 let payment_preimages_len: u64 = Readable::read(reader)?;
1740 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
1741 let mut sha = Sha256::new();
1742 for _ in 0..payment_preimages_len {
1743 let preimage: [u8; 32] = Readable::read(reader)?;
1745 sha.input(&preimage);
1746 let mut hash = [0; 32];
1747 sha.result(&mut hash);
1748 if let Some(_) = payment_preimages.insert(hash, preimage) {
1749 return Err(DecodeError::InvalidValue);
1753 let last_block_hash: Sha256dHash = Readable::read(reader)?;
1754 let destination_script = Readable::read(reader)?;
1756 Ok((last_block_hash.clone(), ChannelMonitor {
1758 commitment_transaction_number_obscure_factor,
1761 their_htlc_base_key,
1762 their_delayed_payment_base_key,
1763 their_cur_revocation_points,
1766 their_to_self_delay,
1769 remote_claimable_outpoints,
1770 remote_commitment_txn_on_chain,
1771 remote_hash_commitment_number,
1773 prev_local_signed_commitment_tx,
1774 current_local_signed_commitment_tx,
1775 current_remote_commitment_number,
1790 use bitcoin::blockdata::script::Script;
1791 use bitcoin::blockdata::transaction::Transaction;
1792 use crypto::digest::Digest;
1794 use ln::channelmonitor::ChannelMonitor;
1795 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1796 use util::sha2::Sha256;
1797 use util::test_utils::TestLogger;
1798 use secp256k1::key::{SecretKey,PublicKey};
1799 use secp256k1::{Secp256k1, Signature};
1800 use rand::{thread_rng,Rng};
1804 fn test_per_commitment_storage() {
1805 // Test vectors from BOLT 3:
1806 let mut secrets: Vec<[u8; 32]> = Vec::new();
1807 let mut monitor: ChannelMonitor;
1808 let secp_ctx = Secp256k1::new();
1809 let logger = Arc::new(TestLogger::new());
1811 macro_rules! test_secrets {
1813 let mut idx = 281474976710655;
1814 for secret in secrets.iter() {
1815 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1818 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1819 assert!(monitor.get_secret(idx).is_none());
1824 // insert_secret correct sequence
1825 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1828 secrets.push([0; 32]);
1829 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1830 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1833 secrets.push([0; 32]);
1834 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1835 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1838 secrets.push([0; 32]);
1839 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1840 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1843 secrets.push([0; 32]);
1844 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1845 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1848 secrets.push([0; 32]);
1849 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1850 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1853 secrets.push([0; 32]);
1854 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1855 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1858 secrets.push([0; 32]);
1859 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1860 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1863 secrets.push([0; 32]);
1864 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1865 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1870 // insert_secret #1 incorrect
1871 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1874 secrets.push([0; 32]);
1875 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1876 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1879 secrets.push([0; 32]);
1880 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1881 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
1882 "Previous secret did not match new one");
1886 // insert_secret #2 incorrect (#1 derived from incorrect)
1887 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1890 secrets.push([0; 32]);
1891 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1892 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1895 secrets.push([0; 32]);
1896 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1897 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1900 secrets.push([0; 32]);
1901 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1902 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1905 secrets.push([0; 32]);
1906 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1907 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
1908 "Previous secret did not match new one");
1912 // insert_secret #3 incorrect
1913 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1916 secrets.push([0; 32]);
1917 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1918 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1921 secrets.push([0; 32]);
1922 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1923 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1926 secrets.push([0; 32]);
1927 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1928 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1931 secrets.push([0; 32]);
1932 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1933 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
1934 "Previous secret did not match new one");
1938 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1939 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1942 secrets.push([0; 32]);
1943 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1944 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1947 secrets.push([0; 32]);
1948 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1949 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1952 secrets.push([0; 32]);
1953 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1954 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1957 secrets.push([0; 32]);
1958 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1959 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1962 secrets.push([0; 32]);
1963 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1964 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1967 secrets.push([0; 32]);
1968 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1969 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1972 secrets.push([0; 32]);
1973 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1974 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1977 secrets.push([0; 32]);
1978 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1979 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
1980 "Previous secret did not match new one");
1984 // insert_secret #5 incorrect
1985 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
1988 secrets.push([0; 32]);
1989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1990 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1993 secrets.push([0; 32]);
1994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1995 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1998 secrets.push([0; 32]);
1999 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2000 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2003 secrets.push([0; 32]);
2004 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2005 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2008 secrets.push([0; 32]);
2009 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2010 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2013 secrets.push([0; 32]);
2014 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2015 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2016 "Previous secret did not match new one");
2020 // insert_secret #6 incorrect (5 derived from incorrect)
2021 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2024 secrets.push([0; 32]);
2025 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2026 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2029 secrets.push([0; 32]);
2030 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2031 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2034 secrets.push([0; 32]);
2035 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2036 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2039 secrets.push([0; 32]);
2040 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2041 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2044 secrets.push([0; 32]);
2045 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2046 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2049 secrets.push([0; 32]);
2050 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2051 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2054 secrets.push([0; 32]);
2055 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2056 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2059 secrets.push([0; 32]);
2060 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2061 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2062 "Previous secret did not match new one");
2066 // insert_secret #7 incorrect
2067 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2070 secrets.push([0; 32]);
2071 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2072 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2075 secrets.push([0; 32]);
2076 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2077 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2080 secrets.push([0; 32]);
2081 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2082 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2085 secrets.push([0; 32]);
2086 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2087 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2090 secrets.push([0; 32]);
2091 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2092 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2095 secrets.push([0; 32]);
2096 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2097 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2100 secrets.push([0; 32]);
2101 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2102 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2105 secrets.push([0; 32]);
2106 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2107 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2108 "Previous secret did not match new one");
2112 // insert_secret #8 incorrect
2113 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2116 secrets.push([0; 32]);
2117 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2118 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2121 secrets.push([0; 32]);
2122 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2123 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2126 secrets.push([0; 32]);
2127 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2128 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2131 secrets.push([0; 32]);
2132 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2133 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2136 secrets.push([0; 32]);
2137 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2138 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2141 secrets.push([0; 32]);
2142 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2143 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2146 secrets.push([0; 32]);
2147 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2148 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2151 secrets.push([0; 32]);
2152 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2153 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2154 "Previous secret did not match new one");
2159 fn test_prune_preimages() {
2160 let secp_ctx = Secp256k1::new();
2161 let logger = Arc::new(TestLogger::new());
2162 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2164 macro_rules! dummy_keys {
2167 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2169 per_commitment_point: dummy_key.clone(),
2170 revocation_key: dummy_key.clone(),
2171 a_htlc_key: dummy_key.clone(),
2172 b_htlc_key: dummy_key.clone(),
2173 a_delayed_payment_key: dummy_key.clone(),
2174 b_payment_key: dummy_key.clone(),
2179 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2181 let mut preimages = Vec::new();
2183 let mut rng = thread_rng();
2185 let mut preimage = [0; 32];
2186 rng.fill_bytes(&mut preimage);
2187 let mut sha = Sha256::new();
2188 sha.input(&preimage);
2189 let mut hash = [0; 32];
2190 sha.result(&mut hash);
2191 preimages.push((preimage, hash));
2195 macro_rules! preimages_slice_to_htlc_outputs {
2196 ($preimages_slice: expr) => {
2198 let mut res = Vec::new();
2199 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2200 res.push(HTLCOutputInCommitment {
2204 payment_hash: preimage.1.clone(),
2205 transaction_output_index: idx as u32,
2212 macro_rules! preimages_to_local_htlcs {
2213 ($preimages_slice: expr) => {
2215 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2216 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2222 macro_rules! test_preimages_exist {
2223 ($preimages_slice: expr, $monitor: expr) => {
2224 for preimage in $preimages_slice {
2225 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2230 // Prune with one old state and a local commitment tx holding a few overlaps with the
2232 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2233 monitor.set_their_to_self_delay(10);
2235 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2236 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
2237 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
2238 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
2239 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
2240 for &(ref preimage, ref hash) in preimages.iter() {
2241 monitor.provide_payment_preimage(hash, preimage);
2244 // Now provide a secret, pruning preimages 10-15
2245 let mut secret = [0; 32];
2246 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2247 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2248 assert_eq!(monitor.payment_preimages.len(), 15);
2249 test_preimages_exist!(&preimages[0..10], monitor);
2250 test_preimages_exist!(&preimages[15..20], monitor);
2252 // Now provide a further secret, pruning preimages 15-17
2253 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2254 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2255 assert_eq!(monitor.payment_preimages.len(), 13);
2256 test_preimages_exist!(&preimages[0..10], monitor);
2257 test_preimages_exist!(&preimages[17..20], monitor);
2259 // Now update local commitment tx info, pruning only element 18 as we still care about the
2260 // previous commitment tx's preimages too
2261 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2262 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2263 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2264 assert_eq!(monitor.payment_preimages.len(), 12);
2265 test_preimages_exist!(&preimages[0..10], monitor);
2266 test_preimages_exist!(&preimages[18..20], monitor);
2268 // But if we do it again, we'll prune 5-10
2269 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2270 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2271 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2272 assert_eq!(monitor.payment_preimages.len(), 5);
2273 test_preimages_exist!(&preimages[0..5], monitor);
2276 // Further testing is done in the ChannelManager integration tests.