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::BitcoinHash;
21 use bitcoin::util::bip143;
23 use bitcoin_hashes::Hash;
24 use bitcoin_hashes::sha256::Hash as Sha256;
25 use bitcoin_hashes::hash160::Hash as Hash160;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
28 use secp256k1::{Secp256k1,Signature};
29 use secp256k1::key::{SecretKey,PublicKey};
32 use ln::msgs::DecodeError;
34 use ln::chan_utils::HTLCOutputInCommitment;
35 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
36 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
37 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
38 use chain::transaction::OutPoint;
39 use chain::keysinterface::SpendableOutputDescriptor;
40 use util::logger::Logger;
41 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
42 use util::{byte_utils, events};
44 use std::collections::{HashMap, hash_map};
45 use std::sync::{Arc,Mutex};
46 use std::{hash,cmp, mem};
48 /// An error enum representing a failure to persist a channel monitor update.
50 pub enum ChannelMonitorUpdateErr {
51 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
52 /// to succeed at some point in the future).
54 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
55 /// submitting new commitment transactions to the remote party.
56 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
57 /// the channel to an operational state.
59 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
60 /// persisted is unsafe - if you failed to store the update on your own local disk you should
61 /// instead return PermanentFailure to force closure of the channel ASAP.
63 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
64 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
65 /// to claim it on this channel) and those updates must be applied wherever they can be. At
66 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
67 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
68 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
71 /// Note that even if updates made after TemporaryFailure succeed you must still call
72 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
73 /// channel operation.
75 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
76 /// different watchtower and cannot update with all watchtowers that were previously informed
77 /// of this channel). This will force-close the channel in question.
79 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
83 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
84 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
85 /// means you tried to merge two monitors for different channels or for a channel which was
86 /// restored from a backup and then generated new commitment updates.
87 /// Contains a human-readable error message.
89 pub struct MonitorUpdateError(pub &'static str);
91 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
92 /// forward channel and from which info are needed to update HTLC in a backward channel.
93 pub struct HTLCUpdate {
94 pub(super) payment_hash: PaymentHash,
95 pub(super) payment_preimage: Option<PaymentPreimage>,
96 pub(super) source: HTLCSource
99 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
100 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
101 /// events to it, while also taking any add_update_monitor events and passing them to some remote
104 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
105 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
106 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
107 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
108 pub trait ManyChannelMonitor: Send + Sync {
109 /// Adds or updates a monitor for the given `funding_txo`.
111 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
112 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
113 /// any spends of it.
114 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
116 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
117 /// with success or failure backward
118 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate>;
121 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
122 /// watchtower or watch our own channels.
124 /// Note that you must provide your own key by which to refer to channels.
126 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
127 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
128 /// index by a PublicKey which is required to sign any updates.
130 /// If you're using this for local monitoring of your own channels, you probably want to use
131 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
132 pub struct SimpleManyChannelMonitor<Key> {
133 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
134 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
136 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
137 chain_monitor: Arc<ChainWatchInterface>,
138 broadcaster: Arc<BroadcasterInterface>,
139 pending_events: Mutex<Vec<events::Event>>,
140 pending_htlc_updated: Mutex<HashMap<PaymentHash, Vec<(HTLCSource, Option<PaymentPreimage>)>>>,
144 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
145 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
146 let block_hash = header.bitcoin_hash();
147 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
148 let mut htlc_updated_infos = Vec::new();
150 let mut monitors = self.monitors.lock().unwrap();
151 for monitor in monitors.values_mut() {
152 let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
153 if spendable_outputs.len() > 0 {
154 new_events.push(events::Event::SpendableOutputs {
155 outputs: spendable_outputs,
159 for (ref txid, ref outputs) in txn_outputs {
160 for (idx, output) in outputs.iter().enumerate() {
161 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
164 htlc_updated_infos.append(&mut htlc_updated);
168 // ChannelManager will just need to fetch pending_htlc_updated and pass state backward
169 let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap();
170 for htlc in htlc_updated_infos.drain(..) {
171 match pending_htlc_updated.entry(htlc.2) {
172 hash_map::Entry::Occupied(mut e) => {
173 // In case of reorg we may have htlc outputs solved in a different way so
174 // we prefer to keep claims but don't store duplicate updates for a given
175 // (payment_hash, HTLCSource) pair.
176 // TODO: Note that we currently don't really use this as ChannelManager
177 // will fail/claim backwards after the first block. We really should delay
178 // a few blocks before failing backwards (but can claim backwards
179 // immediately) as long as we have a few blocks of headroom.
180 let mut existing_claim = false;
181 e.get_mut().retain(|htlc_data| {
182 if htlc.0 == htlc_data.0 {
183 if htlc_data.1.is_some() {
184 existing_claim = true;
190 e.get_mut().push((htlc.0, htlc.1));
193 hash_map::Entry::Vacant(e) => {
194 e.insert(vec![(htlc.0, htlc.1)]);
199 let mut pending_events = self.pending_events.lock().unwrap();
200 pending_events.append(&mut new_events);
203 fn block_disconnected(&self, _: &BlockHeader) { }
206 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
207 /// Creates a new object which can be used to monitor several channels given the chain
208 /// interface with which to register to receive notifications.
209 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
210 let res = Arc::new(SimpleManyChannelMonitor {
211 monitors: Mutex::new(HashMap::new()),
214 pending_events: Mutex::new(Vec::new()),
215 pending_htlc_updated: Mutex::new(HashMap::new()),
218 let weak_res = Arc::downgrade(&res);
219 res.chain_monitor.register_listener(weak_res);
223 /// Adds or updates the monitor which monitors the channel referred to by the given key.
224 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
225 let mut monitors = self.monitors.lock().unwrap();
226 match monitors.get_mut(&key) {
227 Some(orig_monitor) => {
228 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
229 return orig_monitor.insert_combine(monitor);
233 match monitor.key_storage {
234 Storage::Local { ref funding_info, .. } => {
237 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
239 &Some((ref outpoint, ref script)) => {
240 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
241 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
242 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
246 Storage::Watchtower { .. } => {
247 self.chain_monitor.watch_all_txn();
250 monitors.insert(key, monitor);
255 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
256 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
257 match self.add_update_monitor_by_key(funding_txo, monitor) {
259 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
263 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
264 let mut updated = self.pending_htlc_updated.lock().unwrap();
265 let mut pending_htlcs_updated = Vec::with_capacity(updated.len());
266 for (k, v) in updated.drain() {
268 pending_htlcs_updated.push(HTLCUpdate {
270 payment_preimage: htlc_data.1,
275 pending_htlcs_updated
279 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
280 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
281 let mut pending_events = self.pending_events.lock().unwrap();
282 let mut ret = Vec::new();
283 mem::swap(&mut ret, &mut *pending_events);
288 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
289 /// instead claiming it in its own individual transaction.
290 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
291 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
292 /// HTLC-Success transaction.
293 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
294 /// transaction confirmed (and we use it in a few more, equivalent, places).
295 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
296 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
297 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
298 /// copies of ChannelMonitors, including watchtowers).
299 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
300 /// Number of blocks we wait on seeing a confirmed HTLC-Timeout or previous revoked commitment
301 /// transaction before we fail corresponding inbound HTLCs. This prevents us from failing backwards
302 /// and then getting a reorg resulting in us losing money.
303 //TODO: We currently don't actually use this...we should
304 pub(crate) const HTLC_FAIL_ANTI_REORG_DELAY: u32 = 6;
306 #[derive(Clone, PartialEq)]
309 revocation_base_key: SecretKey,
310 htlc_base_key: SecretKey,
311 delayed_payment_base_key: SecretKey,
312 payment_base_key: SecretKey,
313 shutdown_pubkey: PublicKey,
314 prev_latest_per_commitment_point: Option<PublicKey>,
315 latest_per_commitment_point: Option<PublicKey>,
316 funding_info: Option<(OutPoint, Script)>,
317 current_remote_commitment_txid: Option<Sha256dHash>,
318 prev_remote_commitment_txid: Option<Sha256dHash>,
321 revocation_base_key: PublicKey,
322 htlc_base_key: PublicKey,
326 #[derive(Clone, PartialEq)]
327 struct LocalSignedTx {
328 /// txid of the transaction in tx, just used to make comparison faster
331 revocation_key: PublicKey,
332 a_htlc_key: PublicKey,
333 b_htlc_key: PublicKey,
334 delayed_payment_key: PublicKey,
336 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option<HTLCSource>)>,
339 const SERIALIZATION_VERSION: u8 = 1;
340 const MIN_SERIALIZATION_VERSION: u8 = 1;
342 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
343 /// on-chain transactions to ensure no loss of funds occurs.
345 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
346 /// information and are actively monitoring the chain.
348 pub struct ChannelMonitor {
349 commitment_transaction_number_obscure_factor: u64,
351 key_storage: Storage,
352 their_htlc_base_key: Option<PublicKey>,
353 their_delayed_payment_base_key: Option<PublicKey>,
354 // first is the idx of the first of the two revocation points
355 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
357 our_to_self_delay: u16,
358 their_to_self_delay: Option<u16>,
360 old_secrets: [([u8; 32], u64); 49],
361 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
362 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
363 /// Nor can we figure out their commitment numbers without the commitment transaction they are
364 /// spending. Thus, in order to claim them via revocation key, we track all the remote
365 /// commitment transactions which we find on-chain, mapping them to the commitment number which
366 /// can be used to derive the revocation key and claim the transactions.
367 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
368 /// Cache used to make pruning of payment_preimages faster.
369 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
370 /// remote transactions (ie should remain pretty small).
371 /// Serialized to disk but should generally not be sent to Watchtowers.
372 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
374 // We store two local commitment transactions to avoid any race conditions where we may update
375 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
376 // various monitors for one channel being out of sync, and us broadcasting a local
377 // transaction for which we have deleted claim information on some watchtowers.
378 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
379 current_local_signed_commitment_tx: Option<LocalSignedTx>,
381 // Used just for ChannelManager to make sure it has the latest channel data during
383 current_remote_commitment_number: u64,
385 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
387 destination_script: Script,
389 // We simply modify last_block_hash in Channel's block_connected so that serialization is
390 // consistent but hopefully the users' copy handles block_connected in a consistent way.
391 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
392 // their last_block_hash from its state and not based on updated copies that didn't run through
393 // the full block_connected).
394 pub(crate) last_block_hash: Sha256dHash,
395 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
399 #[cfg(any(test, feature = "fuzztarget"))]
400 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
401 /// underlying object
402 impl PartialEq for ChannelMonitor {
403 fn eq(&self, other: &Self) -> bool {
404 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
405 self.key_storage != other.key_storage ||
406 self.their_htlc_base_key != other.their_htlc_base_key ||
407 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
408 self.their_cur_revocation_points != other.their_cur_revocation_points ||
409 self.our_to_self_delay != other.our_to_self_delay ||
410 self.their_to_self_delay != other.their_to_self_delay ||
411 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
412 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
413 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
414 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
415 self.current_remote_commitment_number != other.current_remote_commitment_number ||
416 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
417 self.payment_preimages != other.payment_preimages ||
418 self.destination_script != other.destination_script
422 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
423 if secret != o_secret || idx != o_idx {
432 impl ChannelMonitor {
433 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 {
435 commitment_transaction_number_obscure_factor: 0,
437 key_storage: Storage::Local {
438 revocation_base_key: revocation_base_key.clone(),
439 htlc_base_key: htlc_base_key.clone(),
440 delayed_payment_base_key: delayed_payment_base_key.clone(),
441 payment_base_key: payment_base_key.clone(),
442 shutdown_pubkey: shutdown_pubkey.clone(),
443 prev_latest_per_commitment_point: None,
444 latest_per_commitment_point: None,
446 current_remote_commitment_txid: None,
447 prev_remote_commitment_txid: None,
449 their_htlc_base_key: None,
450 their_delayed_payment_base_key: None,
451 their_cur_revocation_points: None,
453 our_to_self_delay: our_to_self_delay,
454 their_to_self_delay: None,
456 old_secrets: [([0; 32], 1 << 48); 49],
457 remote_claimable_outpoints: HashMap::new(),
458 remote_commitment_txn_on_chain: HashMap::new(),
459 remote_hash_commitment_number: HashMap::new(),
461 prev_local_signed_commitment_tx: None,
462 current_local_signed_commitment_tx: None,
463 current_remote_commitment_number: 1 << 48,
465 payment_preimages: HashMap::new(),
466 destination_script: destination_script,
468 last_block_hash: Default::default(),
469 secp_ctx: Secp256k1::new(),
475 fn place_secret(idx: u64) -> u8 {
477 if idx & (1 << i) == (1 << i) {
485 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
486 let mut res: [u8; 32] = secret;
488 let bitpos = bits - 1 - i;
489 if idx & (1 << bitpos) == (1 << bitpos) {
490 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
491 res = Sha256::hash(&res).into_inner();
497 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
498 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
499 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
500 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
501 let pos = ChannelMonitor::place_secret(idx);
503 let (old_secret, old_idx) = self.old_secrets[i as usize];
504 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
505 return Err(MonitorUpdateError("Previous secret did not match new one"));
508 if self.get_min_seen_secret() <= idx {
511 self.old_secrets[pos as usize] = (secret, idx);
513 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
514 // events for now-revoked/fulfilled HTLCs.
515 // TODO: We should probably consider whether we're really getting the next secret here.
516 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
517 if let Some(txid) = prev_remote_commitment_txid.take() {
518 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
524 if !self.payment_preimages.is_empty() {
525 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
526 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
527 let min_idx = self.get_min_seen_secret();
528 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
530 self.payment_preimages.retain(|&k, _| {
531 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
532 if k == htlc.payment_hash {
536 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
537 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
538 if k == htlc.payment_hash {
543 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
550 remote_hash_commitment_number.remove(&k);
559 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
560 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
561 /// possibly future revocation/preimage information) to claim outputs where possible.
562 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
563 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey) {
564 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
565 // so that a remote monitor doesn't learn anything unless there is a malicious close.
566 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
568 for &(ref htlc, _) in &htlc_outputs {
569 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
572 let new_txid = unsigned_commitment_tx.txid();
573 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
574 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
575 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
576 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
577 *current_remote_commitment_txid = Some(new_txid);
579 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
580 self.current_remote_commitment_number = commitment_number;
581 //TODO: Merge this into the other per-remote-transaction output storage stuff
582 match self.their_cur_revocation_points {
583 Some(old_points) => {
584 if old_points.0 == commitment_number + 1 {
585 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
586 } else if old_points.0 == commitment_number + 2 {
587 if let Some(old_second_point) = old_points.2 {
588 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
590 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
593 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
597 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
602 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
603 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
604 /// is important that any clones of this channel monitor (including remote clones) by kept
605 /// up-to-date as our local commitment transaction is updated.
606 /// Panics if set_their_to_self_delay has never been called.
607 /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
608 /// case of onchain HTLC tx
609 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, Option<(Signature, Signature)>, Option<HTLCSource>)>) {
610 assert!(self.their_to_self_delay.is_some());
611 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
612 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
613 txid: signed_commitment_tx.txid(),
614 tx: signed_commitment_tx,
615 revocation_key: local_keys.revocation_key,
616 a_htlc_key: local_keys.a_htlc_key,
617 b_htlc_key: local_keys.b_htlc_key,
618 delayed_payment_key: local_keys.a_delayed_payment_key,
623 if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
624 *latest_per_commitment_point = Some(local_keys.per_commitment_point);
626 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
630 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
631 /// commitment_tx_infos which contain the payment hash have been revoked.
632 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
633 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
636 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
637 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
638 /// chain for new blocks/transactions.
639 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
640 match self.key_storage {
641 Storage::Local { ref funding_info, .. } => {
642 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
643 let our_funding_info = funding_info;
644 if let Storage::Local { ref funding_info, .. } = other.key_storage {
645 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
646 // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially
647 // easy to collide the funding_txo hash and have a different scriptPubKey.
648 if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
649 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
652 return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
655 Storage::Watchtower { .. } => {
656 if let Storage::Watchtower { .. } = other.key_storage {
659 return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
663 let other_min_secret = other.get_min_seen_secret();
664 let our_min_secret = self.get_min_seen_secret();
665 if our_min_secret > other_min_secret {
666 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
668 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
669 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
670 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);
671 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);
672 if our_commitment_number >= other_commitment_number {
673 self.key_storage = other.key_storage;
677 // TODO: We should use current_remote_commitment_number and the commitment number out of
678 // local transactions to decide how to merge
679 if our_min_secret >= other_min_secret {
680 self.their_cur_revocation_points = other.their_cur_revocation_points;
681 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
682 self.remote_claimable_outpoints.insert(txid, htlcs);
684 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
685 self.prev_local_signed_commitment_tx = Some(local_tx);
687 if let Some(local_tx) = other.current_local_signed_commitment_tx {
688 self.current_local_signed_commitment_tx = Some(local_tx);
690 self.payment_preimages = other.payment_preimages;
693 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
697 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
698 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
699 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
700 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
703 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
704 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
705 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
706 /// provides slightly better privacy.
707 /// It's the responsibility of the caller to register outpoint and script with passing the former
708 /// value as key to add_update_monitor.
709 pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
710 match self.key_storage {
711 Storage::Local { ref mut funding_info, .. } => {
712 *funding_info = Some(new_funding_info);
714 Storage::Watchtower { .. } => {
715 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
720 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
721 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
722 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
723 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
726 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
727 self.their_to_self_delay = Some(their_to_self_delay);
730 pub(super) fn unset_funding_info(&mut self) {
731 match self.key_storage {
732 Storage::Local { ref mut funding_info, .. } => {
733 *funding_info = None;
735 Storage::Watchtower { .. } => {
736 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
741 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
742 pub fn get_funding_txo(&self) -> Option<OutPoint> {
743 match self.key_storage {
744 Storage::Local { ref funding_info, .. } => {
746 &Some((outpoint, _)) => Some(outpoint),
750 Storage::Watchtower { .. } => {
756 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
757 /// Generally useful when deserializing as during normal operation the return values of
758 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
759 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
760 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
761 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
762 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
763 for (idx, output) in outputs.iter().enumerate() {
764 res.push(((*txid).clone(), idx as u32, output));
770 /// Serializes into a vec, with various modes for the exposed pub fns
771 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
772 //TODO: We still write out all the serialization here manually instead of using the fancy
773 //serialization framework we have, we should migrate things over to it.
774 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
775 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
777 // Set in initial Channel-object creation, so should always be set by now:
778 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
780 macro_rules! write_option {
787 &None => 0u8.write(writer)?,
792 match self.key_storage {
793 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
794 writer.write_all(&[0; 1])?;
795 writer.write_all(&revocation_base_key[..])?;
796 writer.write_all(&htlc_base_key[..])?;
797 writer.write_all(&delayed_payment_base_key[..])?;
798 writer.write_all(&payment_base_key[..])?;
799 writer.write_all(&shutdown_pubkey.serialize())?;
800 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
801 writer.write_all(&[1; 1])?;
802 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
804 writer.write_all(&[0; 1])?;
806 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
807 writer.write_all(&[1; 1])?;
808 writer.write_all(&latest_per_commitment_point.serialize())?;
810 writer.write_all(&[0; 1])?;
813 &Some((ref outpoint, ref script)) => {
814 writer.write_all(&outpoint.txid[..])?;
815 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
816 script.write(writer)?;
819 debug_assert!(false, "Try to serialize a useless Local monitor !");
822 write_option!(current_remote_commitment_txid);
823 write_option!(prev_remote_commitment_txid);
825 Storage::Watchtower { .. } => unimplemented!(),
828 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
829 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
831 match self.their_cur_revocation_points {
832 Some((idx, pubkey, second_option)) => {
833 writer.write_all(&byte_utils::be48_to_array(idx))?;
834 writer.write_all(&pubkey.serialize())?;
835 match second_option {
836 Some(second_pubkey) => {
837 writer.write_all(&second_pubkey.serialize())?;
840 writer.write_all(&[0; 33])?;
845 writer.write_all(&byte_utils::be48_to_array(0))?;
849 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
850 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
852 for &(ref secret, ref idx) in self.old_secrets.iter() {
853 writer.write_all(secret)?;
854 writer.write_all(&byte_utils::be64_to_array(*idx))?;
857 macro_rules! serialize_htlc_in_commitment {
858 ($htlc_output: expr) => {
859 writer.write_all(&[$htlc_output.offered as u8; 1])?;
860 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
861 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
862 writer.write_all(&$htlc_output.payment_hash.0[..])?;
863 write_option!(&$htlc_output.transaction_output_index);
867 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
868 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
869 writer.write_all(&txid[..])?;
870 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
871 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
872 serialize_htlc_in_commitment!(htlc_output);
873 write_option!(htlc_source);
877 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
878 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
879 writer.write_all(&txid[..])?;
880 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
881 (txouts.len() as u64).write(writer)?;
882 for script in txouts.iter() {
883 script.write(writer)?;
887 if for_local_storage {
888 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
889 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
890 writer.write_all(&payment_hash.0[..])?;
891 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
894 writer.write_all(&byte_utils::be64_to_array(0))?;
897 macro_rules! serialize_local_tx {
898 ($local_tx: expr) => {
899 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
901 encode::Error::Io(e) => return Err(e),
902 _ => panic!("local tx must have been well-formed!"),
906 writer.write_all(&$local_tx.revocation_key.serialize())?;
907 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
908 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
909 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
911 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
912 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
913 for &(ref htlc_output, ref sigs, ref htlc_source) in $local_tx.htlc_outputs.iter() {
914 serialize_htlc_in_commitment!(htlc_output);
915 if let &Some((ref their_sig, ref our_sig)) = sigs {
917 writer.write_all(&their_sig.serialize_compact())?;
918 writer.write_all(&our_sig.serialize_compact())?;
922 write_option!(htlc_source);
927 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
928 writer.write_all(&[1; 1])?;
929 serialize_local_tx!(prev_local_tx);
931 writer.write_all(&[0; 1])?;
934 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
935 writer.write_all(&[1; 1])?;
936 serialize_local_tx!(cur_local_tx);
938 writer.write_all(&[0; 1])?;
941 if for_local_storage {
942 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
944 writer.write_all(&byte_utils::be48_to_array(0))?;
947 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
948 for payment_preimage in self.payment_preimages.values() {
949 writer.write_all(&payment_preimage.0[..])?;
952 self.last_block_hash.write(writer)?;
953 self.destination_script.write(writer)?;
958 /// Writes this monitor into the given writer, suitable for writing to disk.
960 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
961 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
962 /// the "reorg path" (ie not just starting at the same height but starting at the highest
963 /// common block that appears on your best chain as well as on the chain which contains the
964 /// last block hash returned) upon deserializing the object!
965 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
966 self.write(writer, true)
969 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
971 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
972 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
973 /// the "reorg path" (ie not just starting at the same height but starting at the highest
974 /// common block that appears on your best chain as well as on the chain which contains the
975 /// last block hash returned) upon deserializing the object!
976 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
977 self.write(writer, false)
980 /// Can only fail if idx is < get_min_seen_secret
981 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
982 for i in 0..self.old_secrets.len() {
983 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
984 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
987 assert!(idx < self.get_min_seen_secret());
991 pub(super) fn get_min_seen_secret(&self) -> u64 {
992 //TODO This can be optimized?
993 let mut min = 1 << 48;
994 for &(_, idx) in self.old_secrets.iter() {
1002 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1003 self.current_remote_commitment_number
1006 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1007 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1008 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)
1009 } else { 0xffff_ffff_ffff }
1012 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1013 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1014 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1015 /// HTLC-Success/HTLC-Timeout transactions.
1016 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1017 /// revoked remote commitment tx
1018 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
1019 // Most secp and related errors trying to create keys means we have no hope of constructing
1020 // a spend transaction...so we return no transactions to broadcast
1021 let mut txn_to_broadcast = Vec::new();
1022 let mut watch_outputs = Vec::new();
1023 let mut spendable_outputs = Vec::new();
1024 let mut htlc_updated = Vec::new();
1026 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1027 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1029 macro_rules! ignore_error {
1030 ( $thing : expr ) => {
1033 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1038 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);
1039 if commitment_number >= self.get_min_seen_secret() {
1040 let secret = self.get_secret(commitment_number).unwrap();
1041 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1042 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1043 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1044 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1045 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1046 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1047 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1049 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1050 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1051 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1052 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1056 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()));
1057 let a_htlc_key = match self.their_htlc_base_key {
1058 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1059 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)),
1062 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1063 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1065 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1066 // Note that the Network here is ignored as we immediately drop the address for the
1067 // script_pubkey version.
1068 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1069 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1072 let mut total_value = 0;
1073 let mut values = Vec::new();
1074 let mut inputs = Vec::new();
1075 let mut htlc_idxs = Vec::new();
1077 for (idx, outp) in tx.output.iter().enumerate() {
1078 if outp.script_pubkey == revokeable_p2wsh {
1080 previous_output: BitcoinOutPoint {
1081 txid: commitment_txid,
1084 script_sig: Script::new(),
1085 sequence: 0xfffffffd,
1086 witness: Vec::new(),
1088 htlc_idxs.push(None);
1089 values.push(outp.value);
1090 total_value += outp.value;
1091 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1092 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1093 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1094 key: local_payment_key.unwrap(),
1095 output: outp.clone(),
1100 macro_rules! sign_input {
1101 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1103 let (sig, redeemscript) = match self.key_storage {
1104 Storage::Local { ref revocation_base_key, .. } => {
1105 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1106 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1107 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1109 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1110 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1111 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1113 Storage::Watchtower { .. } => {
1117 $input.witness.push(sig.serialize_der().to_vec());
1118 $input.witness[0].push(SigHashType::All as u8);
1119 if $htlc_idx.is_none() {
1120 $input.witness.push(vec!(1));
1122 $input.witness.push(revocation_pubkey.serialize().to_vec());
1124 $input.witness.push(redeemscript.into_bytes());
1129 if let Some(ref per_commitment_data) = per_commitment_option {
1130 inputs.reserve_exact(per_commitment_data.len());
1132 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1133 if let Some(transaction_output_index) = htlc.transaction_output_index {
1134 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1135 if transaction_output_index as usize >= tx.output.len() ||
1136 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1137 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1138 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1141 previous_output: BitcoinOutPoint {
1142 txid: commitment_txid,
1143 vout: transaction_output_index,
1145 script_sig: Script::new(),
1146 sequence: 0xfffffffd,
1147 witness: Vec::new(),
1149 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1151 htlc_idxs.push(Some(idx));
1152 values.push(tx.output[transaction_output_index as usize].value);
1153 total_value += htlc.amount_msat / 1000;
1155 let mut single_htlc_tx = Transaction {
1159 output: vec!(TxOut {
1160 script_pubkey: self.destination_script.clone(),
1161 value: htlc.amount_msat / 1000, //TODO: - fee
1164 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1165 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1166 txn_to_broadcast.push(single_htlc_tx);
1172 if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1173 // We're definitely a remote commitment transaction!
1174 log_trace!(self, "Got broadcast of revoked remote commitment transaction, generating general spend tx with {} inputs and {} other txn to broadcast", inputs.len(), txn_to_broadcast.len());
1175 watch_outputs.append(&mut tx.output.clone());
1176 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1178 // TODO: We really should only fail backwards after our revocation claims have been
1179 // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1180 // on-chain claims, so we can do that at the same time.
1181 macro_rules! check_htlc_fails {
1182 ($txid: expr, $commitment_tx: expr) => {
1183 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1184 for &(ref htlc, ref source_option) in outpoints.iter() {
1185 if let &Some(ref source) = source_option {
1186 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of revoked remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1187 htlc_updated.push(((**source).clone(), None, htlc.payment_hash.clone()));
1193 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1194 if let &Some(ref txid) = current_remote_commitment_txid {
1195 check_htlc_fails!(txid, "current");
1197 if let &Some(ref txid) = prev_remote_commitment_txid {
1198 check_htlc_fails!(txid, "remote");
1201 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1203 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); } // Nothing to be done...probably a false positive/local tx
1205 let outputs = vec!(TxOut {
1206 script_pubkey: self.destination_script.clone(),
1207 value: total_value, //TODO: - fee
1209 let mut spend_tx = Transaction {
1216 let mut values_drain = values.drain(..);
1217 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1219 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1220 let value = values_drain.next().unwrap();
1221 sign_input!(sighash_parts, input, htlc_idx, value);
1224 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1225 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1226 output: spend_tx.output[0].clone(),
1228 txn_to_broadcast.push(spend_tx);
1229 } else if let Some(per_commitment_data) = per_commitment_option {
1230 // While this isn't useful yet, there is a potential race where if a counterparty
1231 // revokes a state at the same time as the commitment transaction for that state is
1232 // confirmed, and the watchtower receives the block before the user, the user could
1233 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1234 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1235 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1237 watch_outputs.append(&mut tx.output.clone());
1238 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1240 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1242 // TODO: We really should only fail backwards after our revocation claims have been
1243 // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1244 // on-chain claims, so we can do that at the same time.
1245 macro_rules! check_htlc_fails {
1246 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1247 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1248 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1249 if let &Some(ref source) = source_option {
1250 // Check if the HTLC is present in the commitment transaction that was
1251 // broadcast, but not if it was below the dust limit, which we should
1252 // fail backwards immediately as there is no way for us to learn the
1253 // payment_preimage.
1254 // Note that if the dust limit were allowed to change between
1255 // commitment transactions we'd want to be check whether *any*
1256 // broadcastable commitment transaction has the HTLC in it, but it
1257 // cannot currently change after channel initialization, so we don't
1259 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1260 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1264 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1265 htlc_updated.push(((**source).clone(), None, htlc.payment_hash.clone()));
1271 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1272 if let &Some(ref txid) = current_remote_commitment_txid {
1273 check_htlc_fails!(txid, "current", 'current_loop);
1275 if let &Some(ref txid) = prev_remote_commitment_txid {
1276 check_htlc_fails!(txid, "previous", 'prev_loop);
1280 if let Some(revocation_points) = self.their_cur_revocation_points {
1281 let revocation_point_option =
1282 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1283 else if let Some(point) = revocation_points.2.as_ref() {
1284 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1286 if let Some(revocation_point) = revocation_point_option {
1287 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1288 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1289 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1290 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1292 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1293 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1294 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1297 let a_htlc_key = match self.their_htlc_base_key {
1298 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1299 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1302 for (idx, outp) in tx.output.iter().enumerate() {
1303 if outp.script_pubkey.is_v0_p2wpkh() {
1304 match self.key_storage {
1305 Storage::Local { ref payment_base_key, .. } => {
1306 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1307 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1308 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1310 output: outp.clone(),
1314 Storage::Watchtower { .. } => {}
1316 break; // Only to_remote ouput is claimable
1320 let mut total_value = 0;
1321 let mut values = Vec::new();
1322 let mut inputs = Vec::new();
1324 macro_rules! sign_input {
1325 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1327 let (sig, redeemscript) = match self.key_storage {
1328 Storage::Local { ref htlc_base_key, .. } => {
1329 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize].0;
1330 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1331 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1332 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1333 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1335 Storage::Watchtower { .. } => {
1339 $input.witness.push(sig.serialize_der().to_vec());
1340 $input.witness[0].push(SigHashType::All as u8);
1341 $input.witness.push($preimage);
1342 $input.witness.push(redeemscript.into_bytes());
1347 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1348 if let Some(transaction_output_index) = htlc.transaction_output_index {
1349 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1350 if transaction_output_index as usize >= tx.output.len() ||
1351 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1352 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1353 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1355 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1357 previous_output: BitcoinOutPoint {
1358 txid: commitment_txid,
1359 vout: transaction_output_index,
1361 script_sig: Script::new(),
1362 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1363 witness: Vec::new(),
1365 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1367 values.push((tx.output[transaction_output_index as usize].value, payment_preimage));
1368 total_value += htlc.amount_msat / 1000;
1370 let mut single_htlc_tx = Transaction {
1374 output: vec!(TxOut {
1375 script_pubkey: self.destination_script.clone(),
1376 value: htlc.amount_msat / 1000, //TODO: - fee
1379 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1380 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
1381 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1382 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1383 output: single_htlc_tx.output[0].clone(),
1385 txn_to_broadcast.push(single_htlc_tx);
1389 // TODO: If the HTLC has already expired, potentially merge it with the
1390 // rest of the claim transaction, as above.
1392 previous_output: BitcoinOutPoint {
1393 txid: commitment_txid,
1394 vout: transaction_output_index,
1396 script_sig: Script::new(),
1397 sequence: idx as u32,
1398 witness: Vec::new(),
1400 let mut timeout_tx = Transaction {
1402 lock_time: htlc.cltv_expiry,
1404 output: vec!(TxOut {
1405 script_pubkey: self.destination_script.clone(),
1406 value: htlc.amount_msat / 1000,
1409 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1410 sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1411 txn_to_broadcast.push(timeout_tx);
1416 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); } // Nothing to be done...probably a false positive/local tx
1418 let outputs = vec!(TxOut {
1419 script_pubkey: self.destination_script.clone(),
1420 value: total_value, //TODO: - fee
1422 let mut spend_tx = Transaction {
1429 let mut values_drain = values.drain(..);
1430 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1432 for input in spend_tx.input.iter_mut() {
1433 let value = values_drain.next().unwrap();
1434 sign_input!(sighash_parts, input, value.0, (value.1).0.to_vec());
1437 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1438 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1439 output: spend_tx.output[0].clone(),
1441 txn_to_broadcast.push(spend_tx);
1446 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1449 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1450 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1451 if tx.input.len() != 1 || tx.output.len() != 1 {
1455 macro_rules! ignore_error {
1456 ( $thing : expr ) => {
1459 Err(_) => return (None, None)
1464 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1465 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1466 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1467 let revocation_pubkey = match self.key_storage {
1468 Storage::Local { ref revocation_base_key, .. } => {
1469 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1471 Storage::Watchtower { ref revocation_base_key, .. } => {
1472 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1475 let delayed_key = match self.their_delayed_payment_base_key {
1476 None => return (None, None),
1477 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1479 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1480 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1481 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1483 let mut inputs = Vec::new();
1486 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1488 previous_output: BitcoinOutPoint {
1492 script_sig: Script::new(),
1493 sequence: 0xfffffffd,
1494 witness: Vec::new(),
1496 amount = tx.output[0].value;
1499 if !inputs.is_empty() {
1500 let outputs = vec!(TxOut {
1501 script_pubkey: self.destination_script.clone(),
1502 value: amount, //TODO: - fee
1505 let mut spend_tx = Transaction {
1512 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1514 let sig = match self.key_storage {
1515 Storage::Local { ref revocation_base_key, .. } => {
1516 let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
1517 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1518 self.secp_ctx.sign(&sighash, &revocation_key)
1520 Storage::Watchtower { .. } => {
1524 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
1525 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1526 spend_tx.input[0].witness.push(vec!(1));
1527 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1529 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1530 let output = spend_tx.output[0].clone();
1531 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1532 } else { (None, None) }
1535 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>) {
1536 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1537 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1538 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1540 macro_rules! add_dynamic_output {
1541 ($father_tx: expr, $vout: expr) => {
1542 if let Some(ref per_commitment_point) = *per_commitment_point {
1543 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1544 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1545 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1546 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1547 key: local_delayedkey,
1548 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1549 to_self_delay: self.our_to_self_delay,
1550 output: $father_tx.output[$vout as usize].clone(),
1559 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1560 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1561 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1562 if output.script_pubkey == revokeable_p2wsh {
1563 add_dynamic_output!(local_tx.tx, idx as u32);
1568 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
1569 if let Some(transaction_output_index) = htlc.transaction_output_index {
1570 if let &Some((ref their_sig, ref our_sig)) = sigs {
1572 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
1573 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);
1575 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1577 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1578 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1579 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1580 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1582 htlc_timeout_tx.input[0].witness.push(Vec::new());
1583 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());
1585 add_dynamic_output!(htlc_timeout_tx, 0);
1586 res.push(htlc_timeout_tx);
1588 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1589 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
1590 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);
1592 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1594 htlc_success_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1595 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1596 htlc_success_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1597 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1599 htlc_success_tx.input[0].witness.push(payment_preimage.0.to_vec());
1600 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());
1602 add_dynamic_output!(htlc_success_tx, 0);
1603 res.push(htlc_success_tx);
1606 watch_outputs.push(local_tx.tx.output[transaction_output_index as usize].clone());
1607 } else { panic!("Should have sigs for non-dust local tx outputs!") }
1611 (res, spendable_outputs, watch_outputs)
1614 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1615 /// revoked using data in local_claimable_outpoints.
1616 /// Should not be used if check_spend_revoked_transaction succeeds.
1617 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1618 let commitment_txid = tx.txid();
1619 // TODO: If we find a match here we need to fail back HTLCs that weren't included in the
1620 // broadcast commitment transaction, either because they didn't meet dust or because they
1621 // weren't yet included in our commitment transaction(s).
1622 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1623 if local_tx.txid == commitment_txid {
1624 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
1625 match self.key_storage {
1626 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1627 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1628 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1630 Storage::Watchtower { .. } => {
1631 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1632 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1637 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1638 if local_tx.txid == commitment_txid {
1639 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
1640 match self.key_storage {
1641 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1642 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1643 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1645 Storage::Watchtower { .. } => {
1646 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1647 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1652 (Vec::new(), Vec::new(), (commitment_txid, Vec::new()))
1655 /// Generate a spendable output event when closing_transaction get registered onchain.
1656 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1657 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1658 match self.key_storage {
1659 Storage::Local { ref shutdown_pubkey, .. } => {
1660 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
1661 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1662 for (idx, output) in tx.output.iter().enumerate() {
1663 if shutdown_script == output.script_pubkey {
1664 return Some(SpendableOutputDescriptor::StaticOutput {
1665 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1666 output: output.clone(),
1671 Storage::Watchtower { .. } => {
1672 //TODO: we need to ensure an offline client will generate the event when it
1673 // comes back online after only the watchtower saw the transaction
1680 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1681 /// the Channel was out-of-date.
1682 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1683 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1684 let mut res = vec![local_tx.tx.clone()];
1685 match self.key_storage {
1686 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1687 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1689 _ => panic!("Can only broadcast by local channelmonitor"),
1697 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
1698 let mut watch_outputs = Vec::new();
1699 let mut spendable_outputs = Vec::new();
1700 let mut htlc_updated = Vec::new();
1701 for tx in txn_matched {
1702 if tx.input.len() == 1 {
1703 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1704 // commitment transactions and HTLC transactions will all only ever have one input,
1705 // which is an easy way to filter out any potential non-matching txn for lazy
1707 let prevout = &tx.input[0].previous_output;
1708 let mut txn: Vec<Transaction> = Vec::new();
1709 let funding_txo = match self.key_storage {
1710 Storage::Local { ref funding_info, .. } => {
1711 funding_info.clone()
1713 Storage::Watchtower { .. } => {
1717 if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
1718 let (remote_txn, new_outputs, mut spendable_output, mut updated) = self.check_spend_remote_transaction(tx, height);
1720 spendable_outputs.append(&mut spendable_output);
1721 if !new_outputs.1.is_empty() {
1722 watch_outputs.push(new_outputs);
1725 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
1726 spendable_outputs.append(&mut spendable_output);
1728 if !new_outputs.1.is_empty() {
1729 watch_outputs.push(new_outputs);
1732 if !funding_txo.is_none() && txn.is_empty() {
1733 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1734 spendable_outputs.push(spendable_output);
1737 if updated.len() > 0 {
1738 htlc_updated.append(&mut updated);
1741 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1742 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1743 if let Some(tx) = tx {
1746 if let Some(spendable_output) = spendable_output {
1747 spendable_outputs.push(spendable_output);
1751 for tx in txn.iter() {
1752 broadcaster.broadcast_transaction(tx);
1755 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
1756 // can also be resolved in a few other ways which can have more than one output. Thus,
1757 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
1758 let mut updated = self.is_resolving_htlc_output(tx);
1759 if updated.len() > 0 {
1760 htlc_updated.append(&mut updated);
1763 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1764 if self.would_broadcast_at_height(height) {
1765 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1766 match self.key_storage {
1767 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1768 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1769 spendable_outputs.append(&mut spendable_output);
1770 if !new_outputs.is_empty() {
1771 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1774 broadcaster.broadcast_transaction(&tx);
1777 Storage::Watchtower { .. } => {
1778 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1779 spendable_outputs.append(&mut spendable_output);
1780 if !new_outputs.is_empty() {
1781 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1784 broadcaster.broadcast_transaction(&tx);
1790 self.last_block_hash = block_hash.clone();
1791 (watch_outputs, spendable_outputs, htlc_updated)
1794 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1795 // We need to consider all HTLCs which are:
1796 // * in any unrevoked remote commitment transaction, as they could broadcast said
1797 // transactions and we'd end up in a race, or
1798 // * are in our latest local commitment transaction, as this is the thing we will
1799 // broadcast if we go on-chain.
1800 // Note that we consider HTLCs which were below dust threshold here - while they don't
1801 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
1802 // to the source, and if we don't fail the channel we will have to ensure that the next
1803 // updates that peer sends us are update_fails, failing the channel if not. It's probably
1804 // easier to just fail the channel as this case should be rare enough anyway.
1805 macro_rules! scan_commitment {
1806 ($htlcs: expr, $local_tx: expr) => {
1807 for ref htlc in $htlcs {
1808 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1809 // chain with enough room to claim the HTLC without our counterparty being able to
1810 // time out the HTLC first.
1811 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1812 // concern is being able to claim the corresponding inbound HTLC (on another
1813 // channel) before it expires. In fact, we don't even really care if our
1814 // counterparty here claims such an outbound HTLC after it expired as long as we
1815 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1816 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1817 // we give ourselves a few blocks of headroom after expiration before going
1818 // on-chain for an expired HTLC.
1819 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1820 // from us until we've reached the point where we go on-chain with the
1821 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1822 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1823 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1824 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1825 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1826 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
1827 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
1828 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
1829 // The final, above, condition is checked for statically in channelmanager
1830 // with CHECK_CLTV_EXPIRY_SANITY_2.
1831 let htlc_outbound = $local_tx == htlc.offered;
1832 if ( htlc_outbound && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1833 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1834 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
1841 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1842 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
1845 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1846 if let &Some(ref txid) = current_remote_commitment_txid {
1847 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
1848 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
1851 if let &Some(ref txid) = prev_remote_commitment_txid {
1852 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
1853 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
1861 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
1862 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
1863 fn is_resolving_htlc_output(&mut self, tx: &Transaction) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
1864 let mut htlc_updated = Vec::new();
1866 'outer_loop: for input in &tx.input {
1867 let mut payment_data = None;
1868 let revocation_sig_claim = (input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33)
1869 || (input.witness.len() == 3 && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33);
1870 let accepted_preimage_claim = input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT;
1871 let offered_preimage_claim = input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT;
1873 macro_rules! log_claim {
1874 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
1875 // We found the output in question, but aren't failing it backwards
1876 // as we have no corresponding source and no valid remote commitment txid
1877 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
1878 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
1879 let outbound_htlc = $local_tx == $htlc.offered;
1880 if ($local_tx && revocation_sig_claim) ||
1881 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
1882 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
1883 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
1884 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
1885 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
1887 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
1888 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
1889 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
1890 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
1895 macro_rules! check_htlc_valid_remote {
1896 ($remote_txid: expr, $htlc_output: expr) => {
1897 if let &Some(txid) = $remote_txid {
1898 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
1899 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
1900 if let &Some(ref source) = pending_source {
1901 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
1902 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
1911 macro_rules! scan_commitment {
1912 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
1913 for (ref htlc_output, source_option) in $htlcs {
1914 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
1915 if let Some(ref source) = source_option {
1916 log_claim!($tx_info, $local_tx, htlc_output, true);
1917 // We have a resolution of an HTLC either from one of our latest
1918 // local commitment transactions or an unrevoked remote commitment
1919 // transaction. This implies we either learned a preimage, the HTLC
1920 // has timed out, or we screwed up. In any case, we should now
1921 // resolve the source HTLC with the original sender.
1922 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
1923 } else if !$local_tx {
1924 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
1925 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
1927 if payment_data.is_none() {
1928 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
1929 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
1933 if payment_data.is_none() {
1934 log_claim!($tx_info, $local_tx, htlc_output, false);
1935 continue 'outer_loop;
1942 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
1943 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
1944 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
1945 "our latest local commitment tx", true);
1948 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
1949 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
1950 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
1951 "our previous local commitment tx", true);
1954 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
1955 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
1956 "remote commitment tx", false);
1959 // Check that scan_commitment, above, decided there is some source worth relaying an
1960 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
1961 if let Some((source, payment_hash)) = payment_data {
1962 let mut payment_preimage = PaymentPreimage([0; 32]);
1963 if accepted_preimage_claim {
1964 payment_preimage.0.copy_from_slice(&input.witness[3]);
1965 htlc_updated.push((source, Some(payment_preimage), payment_hash));
1966 } else if offered_preimage_claim {
1967 payment_preimage.0.copy_from_slice(&input.witness[1]);
1968 htlc_updated.push((source, Some(payment_preimage), payment_hash));
1970 htlc_updated.push((source, None, payment_hash));
1978 const MAX_ALLOC_SIZE: usize = 64*1024;
1980 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1981 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1982 let secp_ctx = Secp256k1::new();
1983 macro_rules! unwrap_obj {
1987 Err(_) => return Err(DecodeError::InvalidValue),
1992 let _ver: u8 = Readable::read(reader)?;
1993 let min_ver: u8 = Readable::read(reader)?;
1994 if min_ver > SERIALIZATION_VERSION {
1995 return Err(DecodeError::UnknownVersion);
1998 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
2000 let key_storage = match <u8 as Readable<R>>::read(reader)? {
2002 let revocation_base_key = Readable::read(reader)?;
2003 let htlc_base_key = Readable::read(reader)?;
2004 let delayed_payment_base_key = Readable::read(reader)?;
2005 let payment_base_key = Readable::read(reader)?;
2006 let shutdown_pubkey = Readable::read(reader)?;
2007 let prev_latest_per_commitment_point = Readable::read(reader)?;
2008 let latest_per_commitment_point = Readable::read(reader)?;
2009 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2010 // barely-init'd ChannelMonitors that we can't do anything with.
2011 let outpoint = OutPoint {
2012 txid: Readable::read(reader)?,
2013 index: Readable::read(reader)?,
2015 let funding_info = Some((outpoint, Readable::read(reader)?));
2016 let current_remote_commitment_txid = Readable::read(reader)?;
2017 let prev_remote_commitment_txid = Readable::read(reader)?;
2019 revocation_base_key,
2021 delayed_payment_base_key,
2024 prev_latest_per_commitment_point,
2025 latest_per_commitment_point,
2027 current_remote_commitment_txid,
2028 prev_remote_commitment_txid,
2031 _ => return Err(DecodeError::InvalidValue),
2034 let their_htlc_base_key = Some(Readable::read(reader)?);
2035 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
2037 let their_cur_revocation_points = {
2038 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
2042 let first_point = Readable::read(reader)?;
2043 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2044 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2045 Some((first_idx, first_point, None))
2047 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2052 let our_to_self_delay: u16 = Readable::read(reader)?;
2053 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
2055 let mut old_secrets = [([0; 32], 1 << 48); 49];
2056 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
2057 *secret = Readable::read(reader)?;
2058 *idx = Readable::read(reader)?;
2061 macro_rules! read_htlc_in_commitment {
2064 let offered: bool = Readable::read(reader)?;
2065 let amount_msat: u64 = Readable::read(reader)?;
2066 let cltv_expiry: u32 = Readable::read(reader)?;
2067 let payment_hash: PaymentHash = Readable::read(reader)?;
2068 let transaction_output_index: Option<u32> = Readable::read(reader)?;
2070 HTLCOutputInCommitment {
2071 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2077 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
2078 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2079 for _ in 0..remote_claimable_outpoints_len {
2080 let txid: Sha256dHash = Readable::read(reader)?;
2081 let htlcs_count: u64 = Readable::read(reader)?;
2082 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2083 for _ in 0..htlcs_count {
2084 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2086 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
2087 return Err(DecodeError::InvalidValue);
2091 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2092 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2093 for _ in 0..remote_commitment_txn_on_chain_len {
2094 let txid: Sha256dHash = Readable::read(reader)?;
2095 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2096 let outputs_count = <u64 as Readable<R>>::read(reader)?;
2097 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2098 for _ in 0..outputs_count {
2099 outputs.push(Readable::read(reader)?);
2101 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2102 return Err(DecodeError::InvalidValue);
2106 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2107 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2108 for _ in 0..remote_hash_commitment_number_len {
2109 let payment_hash: PaymentHash = Readable::read(reader)?;
2110 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2111 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2112 return Err(DecodeError::InvalidValue);
2116 macro_rules! read_local_tx {
2119 let tx = match Transaction::consensus_decode(reader.by_ref()) {
2122 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
2123 _ => return Err(DecodeError::InvalidValue),
2127 if tx.input.is_empty() {
2128 // Ensure tx didn't hit the 0-input ambiguity case.
2129 return Err(DecodeError::InvalidValue);
2132 let revocation_key = Readable::read(reader)?;
2133 let a_htlc_key = Readable::read(reader)?;
2134 let b_htlc_key = Readable::read(reader)?;
2135 let delayed_payment_key = Readable::read(reader)?;
2136 let feerate_per_kw: u64 = Readable::read(reader)?;
2138 let htlcs_len: u64 = Readable::read(reader)?;
2139 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2140 for _ in 0..htlcs_len {
2141 let htlc = read_htlc_in_commitment!();
2142 let sigs = match <u8 as Readable<R>>::read(reader)? {
2144 1 => Some((Readable::read(reader)?, Readable::read(reader)?)),
2145 _ => return Err(DecodeError::InvalidValue),
2147 htlcs.push((htlc, sigs, Readable::read(reader)?));
2152 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw,
2159 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2162 Some(read_local_tx!())
2164 _ => return Err(DecodeError::InvalidValue),
2167 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2170 Some(read_local_tx!())
2172 _ => return Err(DecodeError::InvalidValue),
2175 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2177 let payment_preimages_len: u64 = Readable::read(reader)?;
2178 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2179 for _ in 0..payment_preimages_len {
2180 let preimage: PaymentPreimage = Readable::read(reader)?;
2181 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2182 if let Some(_) = payment_preimages.insert(hash, preimage) {
2183 return Err(DecodeError::InvalidValue);
2187 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2188 let destination_script = Readable::read(reader)?;
2190 Ok((last_block_hash.clone(), ChannelMonitor {
2191 commitment_transaction_number_obscure_factor,
2194 their_htlc_base_key,
2195 their_delayed_payment_base_key,
2196 their_cur_revocation_points,
2199 their_to_self_delay,
2202 remote_claimable_outpoints,
2203 remote_commitment_txn_on_chain,
2204 remote_hash_commitment_number,
2206 prev_local_signed_commitment_tx,
2207 current_local_signed_commitment_tx,
2208 current_remote_commitment_number,
2223 use bitcoin::blockdata::script::Script;
2224 use bitcoin::blockdata::transaction::Transaction;
2225 use bitcoin_hashes::Hash;
2226 use bitcoin_hashes::sha256::Hash as Sha256;
2228 use ln::channelmanager::{PaymentPreimage, PaymentHash};
2229 use ln::channelmonitor::ChannelMonitor;
2230 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
2231 use util::test_utils::TestLogger;
2232 use secp256k1::key::{SecretKey,PublicKey};
2233 use secp256k1::Secp256k1;
2234 use rand::{thread_rng,Rng};
2238 fn test_per_commitment_storage() {
2239 // Test vectors from BOLT 3:
2240 let mut secrets: Vec<[u8; 32]> = Vec::new();
2241 let mut monitor: ChannelMonitor;
2242 let secp_ctx = Secp256k1::new();
2243 let logger = Arc::new(TestLogger::new());
2245 macro_rules! test_secrets {
2247 let mut idx = 281474976710655;
2248 for secret in secrets.iter() {
2249 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2252 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2253 assert!(monitor.get_secret(idx).is_none());
2258 // insert_secret correct sequence
2259 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2262 secrets.push([0; 32]);
2263 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2264 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2267 secrets.push([0; 32]);
2268 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2269 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2272 secrets.push([0; 32]);
2273 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2274 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2277 secrets.push([0; 32]);
2278 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2279 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2282 secrets.push([0; 32]);
2283 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2284 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2287 secrets.push([0; 32]);
2288 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2289 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2292 secrets.push([0; 32]);
2293 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2294 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2297 secrets.push([0; 32]);
2298 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2299 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2304 // insert_secret #1 incorrect
2305 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2308 secrets.push([0; 32]);
2309 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2310 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2313 secrets.push([0; 32]);
2314 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2315 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
2316 "Previous secret did not match new one");
2320 // insert_secret #2 incorrect (#1 derived from incorrect)
2321 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2324 secrets.push([0; 32]);
2325 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2326 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2329 secrets.push([0; 32]);
2330 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2331 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2334 secrets.push([0; 32]);
2335 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2336 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2339 secrets.push([0; 32]);
2340 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2341 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2342 "Previous secret did not match new one");
2346 // insert_secret #3 incorrect
2347 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2350 secrets.push([0; 32]);
2351 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2352 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2355 secrets.push([0; 32]);
2356 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2357 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2360 secrets.push([0; 32]);
2361 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2362 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2365 secrets.push([0; 32]);
2366 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2367 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2368 "Previous secret did not match new one");
2372 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2373 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2376 secrets.push([0; 32]);
2377 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2378 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2381 secrets.push([0; 32]);
2382 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2383 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2386 secrets.push([0; 32]);
2387 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2388 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2391 secrets.push([0; 32]);
2392 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2393 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2396 secrets.push([0; 32]);
2397 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2398 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2401 secrets.push([0; 32]);
2402 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2403 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2406 secrets.push([0; 32]);
2407 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2408 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2411 secrets.push([0; 32]);
2412 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2413 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2414 "Previous secret did not match new one");
2418 // insert_secret #5 incorrect
2419 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2422 secrets.push([0; 32]);
2423 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2424 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2427 secrets.push([0; 32]);
2428 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2429 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2432 secrets.push([0; 32]);
2433 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2434 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2437 secrets.push([0; 32]);
2438 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2439 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2442 secrets.push([0; 32]);
2443 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2444 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2447 secrets.push([0; 32]);
2448 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2449 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2450 "Previous secret did not match new one");
2454 // insert_secret #6 incorrect (5 derived from incorrect)
2455 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2458 secrets.push([0; 32]);
2459 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2460 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2463 secrets.push([0; 32]);
2464 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2465 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2468 secrets.push([0; 32]);
2469 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2470 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2473 secrets.push([0; 32]);
2474 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2475 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2478 secrets.push([0; 32]);
2479 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2480 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2483 secrets.push([0; 32]);
2484 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2485 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2488 secrets.push([0; 32]);
2489 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2490 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2493 secrets.push([0; 32]);
2494 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2495 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2496 "Previous secret did not match new one");
2500 // insert_secret #7 incorrect
2501 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2504 secrets.push([0; 32]);
2505 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2506 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2509 secrets.push([0; 32]);
2510 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2511 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2514 secrets.push([0; 32]);
2515 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2516 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2519 secrets.push([0; 32]);
2520 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2521 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2524 secrets.push([0; 32]);
2525 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2526 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2529 secrets.push([0; 32]);
2530 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2531 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2534 secrets.push([0; 32]);
2535 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2536 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2539 secrets.push([0; 32]);
2540 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2541 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2542 "Previous secret did not match new one");
2546 // insert_secret #8 incorrect
2547 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2550 secrets.push([0; 32]);
2551 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2552 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2555 secrets.push([0; 32]);
2556 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2557 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2560 secrets.push([0; 32]);
2561 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2562 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2565 secrets.push([0; 32]);
2566 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2567 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2570 secrets.push([0; 32]);
2571 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2572 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2575 secrets.push([0; 32]);
2576 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2577 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2580 secrets.push([0; 32]);
2581 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2582 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2585 secrets.push([0; 32]);
2586 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2587 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2588 "Previous secret did not match new one");
2593 fn test_prune_preimages() {
2594 let secp_ctx = Secp256k1::new();
2595 let logger = Arc::new(TestLogger::new());
2597 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2598 macro_rules! dummy_keys {
2602 per_commitment_point: dummy_key.clone(),
2603 revocation_key: dummy_key.clone(),
2604 a_htlc_key: dummy_key.clone(),
2605 b_htlc_key: dummy_key.clone(),
2606 a_delayed_payment_key: dummy_key.clone(),
2607 b_payment_key: dummy_key.clone(),
2612 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2614 let mut preimages = Vec::new();
2616 let mut rng = thread_rng();
2618 let mut preimage = PaymentPreimage([0; 32]);
2619 rng.fill_bytes(&mut preimage.0[..]);
2620 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2621 preimages.push((preimage, hash));
2625 macro_rules! preimages_slice_to_htlc_outputs {
2626 ($preimages_slice: expr) => {
2628 let mut res = Vec::new();
2629 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2630 res.push((HTLCOutputInCommitment {
2634 payment_hash: preimage.1.clone(),
2635 transaction_output_index: Some(idx as u32),
2642 macro_rules! preimages_to_local_htlcs {
2643 ($preimages_slice: expr) => {
2645 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2646 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2652 macro_rules! test_preimages_exist {
2653 ($preimages_slice: expr, $monitor: expr) => {
2654 for preimage in $preimages_slice {
2655 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2660 // Prune with one old state and a local commitment tx holding a few overlaps with the
2662 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2663 monitor.set_their_to_self_delay(10);
2665 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2666 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2667 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2668 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2669 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2670 for &(ref preimage, ref hash) in preimages.iter() {
2671 monitor.provide_payment_preimage(hash, preimage);
2674 // Now provide a secret, pruning preimages 10-15
2675 let mut secret = [0; 32];
2676 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2677 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2678 assert_eq!(monitor.payment_preimages.len(), 15);
2679 test_preimages_exist!(&preimages[0..10], monitor);
2680 test_preimages_exist!(&preimages[15..20], monitor);
2682 // Now provide a further secret, pruning preimages 15-17
2683 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2684 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2685 assert_eq!(monitor.payment_preimages.len(), 13);
2686 test_preimages_exist!(&preimages[0..10], monitor);
2687 test_preimages_exist!(&preimages[17..20], monitor);
2689 // Now update local commitment tx info, pruning only element 18 as we still care about the
2690 // previous commitment tx's preimages too
2691 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2692 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2693 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2694 assert_eq!(monitor.payment_preimages.len(), 12);
2695 test_preimages_exist!(&preimages[0..10], monitor);
2696 test_preimages_exist!(&preimages[18..20], monitor);
2698 // But if we do it again, we'll prune 5-10
2699 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2700 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2701 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2702 assert_eq!(monitor.payment_preimages.len(), 5);
2703 test_preimages_exist!(&preimages[0..5], monitor);
2706 // Further testing is done in the ChannelManager integration tests.