1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode::{self, Decodable, Encodable};
20 use bitcoin::util::hash::{Hash160, BitcoinHash,Sha256dHash};
21 use bitcoin::util::bip143;
23 use bitcoin_hashes::Hash;
24 use bitcoin_hashes::sha256::Hash as Sha256;
26 use secp256k1::{Secp256k1,Message,Signature};
27 use secp256k1::key::{SecretKey,PublicKey};
30 use ln::msgs::DecodeError;
32 use ln::chan_utils::HTLCOutputInCommitment;
33 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
34 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
35 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
36 use chain::transaction::OutPoint;
37 use chain::keysinterface::SpendableOutputDescriptor;
38 use util::logger::Logger;
39 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
40 use util::{byte_utils, events};
42 use std::collections::{HashMap, hash_map};
43 use std::sync::{Arc,Mutex};
44 use std::{hash,cmp, mem};
46 /// An error enum representing a failure to persist a channel monitor update.
48 pub enum ChannelMonitorUpdateErr {
49 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
50 /// to succeed at some point in the future).
52 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
53 /// submitting new commitment transactions to the remote party.
54 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
55 /// the channel to an operational state.
57 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
58 /// persisted is unsafe - if you failed to store the update on your own local disk you should
59 /// instead return PermanentFailure to force closure of the channel ASAP.
61 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
62 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
63 /// to claim it on this channel) and those updates must be applied wherever they can be. At
64 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
65 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
66 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
69 /// Note that even if updates made after TemporaryFailure succeed you must still call
70 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
71 /// channel operation.
73 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
74 /// different watchtower and cannot update with all watchtowers that were previously informed
75 /// of this channel). This will force-close the channel in question.
77 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
81 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
82 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
83 /// means you tried to merge two monitors for different channels or for a channel which was
84 /// restored from a backup and then generated new commitment updates.
85 /// Contains a human-readable error message.
87 pub struct MonitorUpdateError(pub &'static str);
89 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
90 /// forward channel and from which info are needed to update HTLC in a backward channel.
91 pub struct HTLCUpdate {
92 pub(super) payment_hash: PaymentHash,
93 pub(super) payment_preimage: Option<PaymentPreimage>,
94 pub(super) source: HTLCSource
97 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
98 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
99 /// events to it, while also taking any add_update_monitor events and passing them to some remote
102 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
103 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
104 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
105 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
106 pub trait ManyChannelMonitor: Send + Sync {
107 /// Adds or updates a monitor for the given `funding_txo`.
109 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
110 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
111 /// any spends of it.
112 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
114 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
115 /// with success or failure backward
116 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate>;
119 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
120 /// watchtower or watch our own channels.
122 /// Note that you must provide your own key by which to refer to channels.
124 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
125 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
126 /// index by a PublicKey which is required to sign any updates.
128 /// If you're using this for local monitoring of your own channels, you probably want to use
129 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
130 pub struct SimpleManyChannelMonitor<Key> {
131 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
132 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
134 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
135 chain_monitor: Arc<ChainWatchInterface>,
136 broadcaster: Arc<BroadcasterInterface>,
137 pending_events: Mutex<Vec<events::Event>>,
138 pending_htlc_updated: Mutex<HashMap<PaymentHash, Vec<(HTLCSource, Option<PaymentPreimage>)>>>,
142 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
143 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
144 let block_hash = header.bitcoin_hash();
145 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
146 let mut htlc_updated_infos = Vec::new();
148 let mut monitors = self.monitors.lock().unwrap();
149 for monitor in monitors.values_mut() {
150 let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster);
151 if spendable_outputs.len() > 0 {
152 new_events.push(events::Event::SpendableOutputs {
153 outputs: spendable_outputs,
157 for (ref txid, ref outputs) in txn_outputs {
158 for (idx, output) in outputs.iter().enumerate() {
159 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
162 htlc_updated_infos.append(&mut htlc_updated);
166 // ChannelManager will just need to fetch pending_htlc_updated and pass state backward
167 let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap();
168 for htlc in htlc_updated_infos.drain(..) {
169 match pending_htlc_updated.entry(htlc.2) {
170 hash_map::Entry::Occupied(mut e) => {
171 // In case of reorg we may have htlc outputs solved in a different way so
172 // we prefer to keep claims but don't store duplicate updates for a given
173 // (payment_hash, HTLCSource) pair.
174 // TODO: Note that we currently don't really use this as ChannelManager
175 // will fail/claim backwards after the first block. We really should delay
176 // a few blocks before failing backwards (but can claim backwards
177 // immediately) as long as we have a few blocks of headroom.
178 let mut existing_claim = false;
179 e.get_mut().retain(|htlc_data| {
180 if htlc.0 == htlc_data.0 {
181 if htlc_data.1.is_some() {
182 existing_claim = true;
188 e.get_mut().push((htlc.0, htlc.1));
191 hash_map::Entry::Vacant(e) => {
192 e.insert(vec![(htlc.0, htlc.1)]);
197 let mut pending_events = self.pending_events.lock().unwrap();
198 pending_events.append(&mut new_events);
201 fn block_disconnected(&self, _: &BlockHeader) { }
204 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
205 /// Creates a new object which can be used to monitor several channels given the chain
206 /// interface with which to register to receive notifications.
207 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Arc<SimpleManyChannelMonitor<Key>> {
208 let res = Arc::new(SimpleManyChannelMonitor {
209 monitors: Mutex::new(HashMap::new()),
212 pending_events: Mutex::new(Vec::new()),
213 pending_htlc_updated: Mutex::new(HashMap::new()),
216 let weak_res = Arc::downgrade(&res);
217 res.chain_monitor.register_listener(weak_res);
221 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
222 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
223 let mut monitors = self.monitors.lock().unwrap();
224 match monitors.get_mut(&key) {
225 Some(orig_monitor) => {
226 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
227 return orig_monitor.insert_combine(monitor);
231 match monitor.key_storage {
232 Storage::Local { ref funding_info, .. } => {
235 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
237 &Some((ref outpoint, ref script)) => {
238 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
239 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
240 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
244 Storage::Watchtower { .. } => {
245 self.chain_monitor.watch_all_txn();
248 monitors.insert(key, monitor);
253 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
254 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
255 match self.add_update_monitor_by_key(funding_txo, monitor) {
257 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
261 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
262 let mut updated = self.pending_htlc_updated.lock().unwrap();
263 let mut pending_htlcs_updated = Vec::with_capacity(updated.len());
264 for (k, v) in updated.drain() {
266 pending_htlcs_updated.push(HTLCUpdate {
268 payment_preimage: htlc_data.1,
273 pending_htlcs_updated
277 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
278 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
279 let mut pending_events = self.pending_events.lock().unwrap();
280 let mut ret = Vec::new();
281 mem::swap(&mut ret, &mut *pending_events);
286 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
287 /// instead claiming it in its own individual transaction.
288 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
289 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
290 /// HTLC-Success transaction.
291 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
292 /// transaction confirmed (and we use it in a few more, equivalent, places).
293 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
294 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
295 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
296 /// copies of ChannelMonitors, including watchtowers).
297 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
298 /// Number of blocks we wait on seeing a confirmed HTLC-Timeout or previous revoked commitment
299 /// transaction before we fail corresponding inbound HTLCs. This prevents us from failing backwards
300 /// and then getting a reorg resulting in us losing money.
301 //TODO: We currently dont actually use this...we should
302 pub(crate) const HTLC_FAIL_ANTI_REORG_DELAY: u32 = 6;
304 #[derive(Clone, PartialEq)]
307 revocation_base_key: SecretKey,
308 htlc_base_key: SecretKey,
309 delayed_payment_base_key: SecretKey,
310 payment_base_key: SecretKey,
311 shutdown_pubkey: PublicKey,
312 prev_latest_per_commitment_point: Option<PublicKey>,
313 latest_per_commitment_point: Option<PublicKey>,
314 funding_info: Option<(OutPoint, Script)>,
315 current_remote_commitment_txid: Option<Sha256dHash>,
316 prev_remote_commitment_txid: Option<Sha256dHash>,
319 revocation_base_key: PublicKey,
320 htlc_base_key: PublicKey,
324 #[derive(Clone, PartialEq)]
325 struct LocalSignedTx {
326 /// txid of the transaction in tx, just used to make comparison faster
329 revocation_key: PublicKey,
330 a_htlc_key: PublicKey,
331 b_htlc_key: PublicKey,
332 delayed_payment_key: PublicKey,
334 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
335 htlc_sources: Vec<(PaymentHash, HTLCSource, Option<u32>)>,
338 const SERIALIZATION_VERSION: u8 = 1;
339 const MIN_SERIALIZATION_VERSION: u8 = 1;
341 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
342 /// on-chain transactions to ensure no loss of funds occurs.
344 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
345 /// information and are actively monitoring the chain.
347 pub struct ChannelMonitor {
348 commitment_transaction_number_obscure_factor: u64,
350 key_storage: Storage,
351 their_htlc_base_key: Option<PublicKey>,
352 their_delayed_payment_base_key: Option<PublicKey>,
353 // first is the idx of the first of the two revocation points
354 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
356 our_to_self_delay: u16,
357 their_to_self_delay: Option<u16>,
359 old_secrets: [([u8; 32], u64); 49],
360 remote_claimable_outpoints: HashMap<Sha256dHash, (Vec<HTLCOutputInCommitment>, Vec<(PaymentHash, HTLCSource, Option<u32>)>)>,
361 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
362 /// Nor can we figure out their commitment numbers without the commitment transaction they are
363 /// spending. Thus, in order to claim them via revocation key, we track all the remote
364 /// commitment transactions which we find on-chain, mapping them to the commitment number which
365 /// can be used to derive the revocation key and claim the transactions.
366 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
367 /// Cache used to make pruning of payment_preimages faster.
368 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
369 /// remote transactions (ie should remain pretty small).
370 /// Serialized to disk but should generally not be sent to Watchtowers.
371 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
373 // We store two local commitment transactions to avoid any race conditions where we may update
374 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
375 // various monitors for one channel being out of sync, and us broadcasting a local
376 // transaction for which we have deleted claim information on some watchtowers.
377 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
378 current_local_signed_commitment_tx: Option<LocalSignedTx>,
380 // Used just for ChannelManager to make sure it has the latest channel data during
382 current_remote_commitment_number: u64,
384 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
386 destination_script: Script,
388 // We simply modify last_block_hash in Channel's block_connected so that serialization is
389 // consistent but hopefully the users' copy handles block_connected in a consistent way.
390 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
391 // their last_block_hash from its state and not based on updated copies that didn't run through
392 // the full block_connected).
393 pub(crate) last_block_hash: Sha256dHash,
394 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
398 #[cfg(any(test, feature = "fuzztarget"))]
399 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
400 /// underlying object
401 impl PartialEq for ChannelMonitor {
402 fn eq(&self, other: &Self) -> bool {
403 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
404 self.key_storage != other.key_storage ||
405 self.their_htlc_base_key != other.their_htlc_base_key ||
406 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
407 self.their_cur_revocation_points != other.their_cur_revocation_points ||
408 self.our_to_self_delay != other.our_to_self_delay ||
409 self.their_to_self_delay != other.their_to_self_delay ||
410 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
411 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
412 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
413 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
414 self.current_remote_commitment_number != other.current_remote_commitment_number ||
415 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
416 self.payment_preimages != other.payment_preimages ||
417 self.destination_script != other.destination_script
421 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
422 if secret != o_secret || idx != o_idx {
431 impl ChannelMonitor {
432 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 {
434 commitment_transaction_number_obscure_factor: 0,
436 key_storage: Storage::Local {
437 revocation_base_key: revocation_base_key.clone(),
438 htlc_base_key: htlc_base_key.clone(),
439 delayed_payment_base_key: delayed_payment_base_key.clone(),
440 payment_base_key: payment_base_key.clone(),
441 shutdown_pubkey: shutdown_pubkey.clone(),
442 prev_latest_per_commitment_point: None,
443 latest_per_commitment_point: None,
445 current_remote_commitment_txid: None,
446 prev_remote_commitment_txid: None,
448 their_htlc_base_key: None,
449 their_delayed_payment_base_key: None,
450 their_cur_revocation_points: None,
452 our_to_self_delay: our_to_self_delay,
453 their_to_self_delay: None,
455 old_secrets: [([0; 32], 1 << 48); 49],
456 remote_claimable_outpoints: HashMap::new(),
457 remote_commitment_txn_on_chain: HashMap::new(),
458 remote_hash_commitment_number: HashMap::new(),
460 prev_local_signed_commitment_tx: None,
461 current_local_signed_commitment_tx: None,
462 current_remote_commitment_number: 1 << 48,
464 payment_preimages: HashMap::new(),
465 destination_script: destination_script,
467 last_block_hash: Default::default(),
468 secp_ctx: Secp256k1::new(),
474 fn place_secret(idx: u64) -> u8 {
476 if idx & (1 << i) == (1 << i) {
484 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
485 let mut res: [u8; 32] = secret;
487 let bitpos = bits - 1 - i;
488 if idx & (1 << bitpos) == (1 << bitpos) {
489 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
490 res = Sha256::hash(&res).into_inner();
496 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
497 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
498 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
499 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
500 let pos = ChannelMonitor::place_secret(idx);
502 let (old_secret, old_idx) = self.old_secrets[i as usize];
503 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
504 return Err(MonitorUpdateError("Previous secret did not match new one"));
507 if self.get_min_seen_secret() <= idx {
510 self.old_secrets[pos as usize] = (secret, idx);
512 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
513 // events for now-revoked/fulfilled HTLCs.
514 // TODO: We should probably consider whether we're really getting the next secret here.
515 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
516 if let Some(txid) = prev_remote_commitment_txid.take() {
517 self.remote_claimable_outpoints.get_mut(&txid).unwrap().1 = Vec::new();
521 if !self.payment_preimages.is_empty() {
522 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
523 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
524 let min_idx = self.get_min_seen_secret();
525 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
527 self.payment_preimages.retain(|&k, _| {
528 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
529 if k == htlc.payment_hash {
533 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
534 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
535 if k == htlc.payment_hash {
540 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
547 remote_hash_commitment_number.remove(&k);
556 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
557 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
558 /// possibly future revocation/preimage information) to claim outputs where possible.
559 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
560 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, htlc_sources: Vec<(PaymentHash, HTLCSource, Option<u32>)>, commitment_number: u64, their_revocation_point: PublicKey) {
561 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
562 // so that a remote monitor doesn't learn anything unless there is a malicious close.
563 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
565 for ref htlc in &htlc_outputs {
566 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
569 let new_txid = unsigned_commitment_tx.txid();
570 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
571 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
572 *current_remote_commitment_txid = Some(new_txid);
574 self.remote_claimable_outpoints.insert(new_txid, (htlc_outputs, htlc_sources));
575 self.current_remote_commitment_number = commitment_number;
576 //TODO: Merge this into the other per-remote-transaction output storage stuff
577 match self.their_cur_revocation_points {
578 Some(old_points) => {
579 if old_points.0 == commitment_number + 1 {
580 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
581 } else if old_points.0 == commitment_number + 2 {
582 if let Some(old_second_point) = old_points.2 {
583 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
585 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
588 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
592 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
597 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
598 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
599 /// is important that any clones of this channel monitor (including remote clones) by kept
600 /// up-to-date as our local commitment transaction is updated.
601 /// Panics if set_their_to_self_delay has never been called.
602 /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
603 /// case of onchain HTLC tx
604 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, signed_commitment_tx: Transaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>, htlc_sources: Vec<(PaymentHash, HTLCSource, Option<u32>)>) {
605 assert!(self.their_to_self_delay.is_some());
606 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
607 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
608 txid: signed_commitment_tx.txid(),
609 tx: signed_commitment_tx,
610 revocation_key: local_keys.revocation_key,
611 a_htlc_key: local_keys.a_htlc_key,
612 b_htlc_key: local_keys.b_htlc_key,
613 delayed_payment_key: local_keys.a_delayed_payment_key,
619 if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
620 *latest_per_commitment_point = Some(local_keys.per_commitment_point);
622 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
626 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
627 /// commitment_tx_infos which contain the payment hash have been revoked.
628 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
629 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
632 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
633 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
634 /// chain for new blocks/transactions.
635 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
636 match self.key_storage {
637 Storage::Local { ref funding_info, .. } => {
638 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
639 let our_funding_info = funding_info;
640 if let Storage::Local { ref funding_info, .. } = other.key_storage {
641 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
642 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
643 // easy to collide the funding_txo hash and have a different scriptPubKey.
644 if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
645 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
648 return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
651 Storage::Watchtower { .. } => {
652 if let Storage::Watchtower { .. } = other.key_storage {
655 return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
659 let other_min_secret = other.get_min_seen_secret();
660 let our_min_secret = self.get_min_seen_secret();
661 if our_min_secret > other_min_secret {
662 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
664 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
665 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
666 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);
667 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);
668 if our_commitment_number >= other_commitment_number {
669 self.key_storage = other.key_storage;
673 // TODO: We should use current_remote_commitment_number and the commitment number out of
674 // local transactions to decide how to merge
675 if our_min_secret >= other_min_secret {
676 self.their_cur_revocation_points = other.their_cur_revocation_points;
677 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
678 self.remote_claimable_outpoints.insert(txid, htlcs);
680 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
681 self.prev_local_signed_commitment_tx = Some(local_tx);
683 if let Some(local_tx) = other.current_local_signed_commitment_tx {
684 self.current_local_signed_commitment_tx = Some(local_tx);
686 self.payment_preimages = other.payment_preimages;
689 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
693 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
694 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
695 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
696 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
699 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
700 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
701 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
702 /// provides slightly better privacy.
703 /// It's the responsibility of the caller to register outpoint and script with passing the former
704 /// value as key to add_update_monitor.
705 pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
706 match self.key_storage {
707 Storage::Local { ref mut funding_info, .. } => {
708 *funding_info = Some(new_funding_info);
710 Storage::Watchtower { .. } => {
711 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
716 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
717 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
718 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
719 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
722 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
723 self.their_to_self_delay = Some(their_to_self_delay);
726 pub(super) fn unset_funding_info(&mut self) {
727 match self.key_storage {
728 Storage::Local { ref mut funding_info, .. } => {
729 *funding_info = None;
731 Storage::Watchtower { .. } => {
732 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
737 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
738 pub fn get_funding_txo(&self) -> Option<OutPoint> {
739 match self.key_storage {
740 Storage::Local { ref funding_info, .. } => {
742 &Some((outpoint, _)) => Some(outpoint),
746 Storage::Watchtower { .. } => {
752 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
753 /// Generally useful when deserializing as during normal operation the return values of
754 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
755 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
756 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
757 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
758 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
759 for (idx, output) in outputs.iter().enumerate() {
760 res.push(((*txid).clone(), idx as u32, output));
766 /// Serializes into a vec, with various modes for the exposed pub fns
767 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
768 //TODO: We still write out all the serialization here manually instead of using the fancy
769 //serialization framework we have, we should migrate things over to it.
770 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
771 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
773 // Set in initial Channel-object creation, so should always be set by now:
774 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
776 match self.key_storage {
777 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, current_remote_commitment_txid, prev_remote_commitment_txid } => {
778 writer.write_all(&[0; 1])?;
779 writer.write_all(&revocation_base_key[..])?;
780 writer.write_all(&htlc_base_key[..])?;
781 writer.write_all(&delayed_payment_base_key[..])?;
782 writer.write_all(&payment_base_key[..])?;
783 writer.write_all(&shutdown_pubkey.serialize())?;
784 if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
785 writer.write_all(&[1; 1])?;
786 writer.write_all(&prev_latest_per_commitment_point.serialize())?;
788 writer.write_all(&[0; 1])?;
790 if let Some(ref latest_per_commitment_point) = *latest_per_commitment_point {
791 writer.write_all(&[1; 1])?;
792 writer.write_all(&latest_per_commitment_point.serialize())?;
794 writer.write_all(&[0; 1])?;
797 &Some((ref outpoint, ref script)) => {
798 writer.write_all(&outpoint.txid[..])?;
799 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
800 script.write(writer)?;
803 debug_assert!(false, "Try to serialize a useless Local monitor !");
806 if let Some(ref txid) = current_remote_commitment_txid {
807 writer.write_all(&[1; 1])?;
808 writer.write_all(&txid[..])?;
810 writer.write_all(&[0; 1])?;
812 if let Some(ref txid) = prev_remote_commitment_txid {
813 writer.write_all(&[1; 1])?;
814 writer.write_all(&txid[..])?;
816 writer.write_all(&[0; 1])?;
819 Storage::Watchtower { .. } => unimplemented!(),
822 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
823 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
825 match self.their_cur_revocation_points {
826 Some((idx, pubkey, second_option)) => {
827 writer.write_all(&byte_utils::be48_to_array(idx))?;
828 writer.write_all(&pubkey.serialize())?;
829 match second_option {
830 Some(second_pubkey) => {
831 writer.write_all(&second_pubkey.serialize())?;
834 writer.write_all(&[0; 33])?;
839 writer.write_all(&byte_utils::be48_to_array(0))?;
843 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
844 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
846 for &(ref secret, ref idx) in self.old_secrets.iter() {
847 writer.write_all(secret)?;
848 writer.write_all(&byte_utils::be64_to_array(*idx))?;
851 macro_rules! serialize_htlc_in_commitment {
852 ($htlc_output: expr) => {
853 writer.write_all(&[$htlc_output.offered as u8; 1])?;
854 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
855 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
856 writer.write_all(&$htlc_output.payment_hash.0[..])?;
857 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
861 macro_rules! serialize_htlc_source {
862 ($htlc_source: expr) => {
863 $htlc_source.0.write(writer)?;
864 $htlc_source.1.write(writer)?;
865 if let &Some(ref txo) = &$htlc_source.2 {
866 writer.write_all(&[1; 1])?;
869 writer.write_all(&[0; 1])?;
875 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
876 for (ref txid, &(ref htlc_infos, ref htlc_sources)) in self.remote_claimable_outpoints.iter() {
877 writer.write_all(&txid[..])?;
878 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
879 for ref htlc_output in htlc_infos.iter() {
880 serialize_htlc_in_commitment!(htlc_output);
882 writer.write_all(&byte_utils::be64_to_array(htlc_sources.len() as u64))?;
883 for ref htlc_source in htlc_sources.iter() {
884 serialize_htlc_source!(htlc_source);
888 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
889 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
890 writer.write_all(&txid[..])?;
891 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
892 (txouts.len() as u64).write(writer)?;
893 for script in txouts.iter() {
894 script.write(writer)?;
898 if for_local_storage {
899 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
900 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
901 writer.write_all(&payment_hash.0[..])?;
902 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
905 writer.write_all(&byte_utils::be64_to_array(0))?;
908 macro_rules! serialize_local_tx {
909 ($local_tx: expr) => {
910 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
912 encode::Error::Io(e) => return Err(e),
913 _ => panic!("local tx must have been well-formed!"),
917 writer.write_all(&$local_tx.revocation_key.serialize())?;
918 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
919 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
920 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
922 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
923 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
924 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
925 serialize_htlc_in_commitment!(htlc_output);
926 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
927 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
929 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_sources.len() as u64))?;
930 for ref htlc_source in $local_tx.htlc_sources.iter() {
931 serialize_htlc_source!(htlc_source);
936 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
937 writer.write_all(&[1; 1])?;
938 serialize_local_tx!(prev_local_tx);
940 writer.write_all(&[0; 1])?;
943 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
944 writer.write_all(&[1; 1])?;
945 serialize_local_tx!(cur_local_tx);
947 writer.write_all(&[0; 1])?;
950 if for_local_storage {
951 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
953 writer.write_all(&byte_utils::be48_to_array(0))?;
956 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
957 for payment_preimage in self.payment_preimages.values() {
958 writer.write_all(&payment_preimage.0[..])?;
961 self.last_block_hash.write(writer)?;
962 self.destination_script.write(writer)?;
967 /// Writes this monitor into the given writer, suitable for writing to disk.
969 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
970 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
971 /// the "reorg path" (ie not just starting at the same height but starting at the highest
972 /// common block that appears on your best chain as well as on the chain which contains the
973 /// last block hash returned) upon deserializing the object!
974 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
975 self.write(writer, true)
978 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
980 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
981 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
982 /// the "reorg path" (ie not just starting at the same height but starting at the highest
983 /// common block that appears on your best chain as well as on the chain which contains the
984 /// last block hash returned) upon deserializing the object!
985 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
986 self.write(writer, false)
989 //TODO: Functions to serialize/deserialize (with different forms depending on which information
990 //we want to leave out (eg funding_txo, etc).
992 /// Can only fail if idx is < get_min_seen_secret
993 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
994 for i in 0..self.old_secrets.len() {
995 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
996 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
999 assert!(idx < self.get_min_seen_secret());
1003 pub(super) fn get_min_seen_secret(&self) -> u64 {
1004 //TODO This can be optimized?
1005 let mut min = 1 << 48;
1006 for &(_, idx) in self.old_secrets.iter() {
1014 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1015 self.current_remote_commitment_number
1018 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1019 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1020 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)
1021 } else { 0xffff_ffff_ffff }
1024 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1025 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1026 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1027 /// HTLC-Success/HTLC-Timeout transactions.
1028 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1029 /// revoked remote commitment tx
1030 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
1031 // Most secp and related errors trying to create keys means we have no hope of constructing
1032 // a spend transaction...so we return no transactions to broadcast
1033 let mut txn_to_broadcast = Vec::new();
1034 let mut watch_outputs = Vec::new();
1035 let mut spendable_outputs = Vec::new();
1036 let mut htlc_updated = Vec::new();
1038 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1039 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1041 macro_rules! ignore_error {
1042 ( $thing : expr ) => {
1045 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1050 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);
1051 if commitment_number >= self.get_min_seen_secret() {
1052 let secret = self.get_secret(commitment_number).unwrap();
1053 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1054 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1055 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1056 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1057 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1058 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1059 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1061 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1062 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1063 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1064 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1068 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()));
1069 let a_htlc_key = match self.their_htlc_base_key {
1070 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1071 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)),
1074 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1075 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1077 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1078 // Note that the Network here is ignored as we immediately drop the address for the
1079 // script_pubkey version.
1080 let payment_hash160 = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1081 Some(Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1084 let mut total_value = 0;
1085 let mut values = Vec::new();
1086 let mut inputs = Vec::new();
1087 let mut htlc_idxs = Vec::new();
1089 for (idx, outp) in tx.output.iter().enumerate() {
1090 if outp.script_pubkey == revokeable_p2wsh {
1092 previous_output: BitcoinOutPoint {
1093 txid: commitment_txid,
1096 script_sig: Script::new(),
1097 sequence: 0xfffffffd,
1098 witness: Vec::new(),
1100 htlc_idxs.push(None);
1101 values.push(outp.value);
1102 total_value += outp.value;
1103 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1104 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1105 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1106 key: local_payment_key.unwrap(),
1107 output: outp.clone(),
1112 macro_rules! sign_input {
1113 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1115 let (sig, redeemscript) = match self.key_storage {
1116 Storage::Local { ref revocation_base_key, .. } => {
1117 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1118 let htlc = &per_commitment_option.unwrap().0[$htlc_idx.unwrap()];
1119 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1121 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1122 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1123 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1125 Storage::Watchtower { .. } => {
1129 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1130 $input.witness[0].push(SigHashType::All as u8);
1131 if $htlc_idx.is_none() {
1132 $input.witness.push(vec!(1));
1134 $input.witness.push(revocation_pubkey.serialize().to_vec());
1136 $input.witness.push(redeemscript.into_bytes());
1141 if let Some(&(ref per_commitment_data, _)) = per_commitment_option {
1142 inputs.reserve_exact(per_commitment_data.len());
1144 for (idx, ref htlc) in per_commitment_data.iter().enumerate() {
1145 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1146 if htlc.transaction_output_index as usize >= tx.output.len() ||
1147 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1148 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1149 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1152 previous_output: BitcoinOutPoint {
1153 txid: commitment_txid,
1154 vout: htlc.transaction_output_index,
1156 script_sig: Script::new(),
1157 sequence: 0xfffffffd,
1158 witness: Vec::new(),
1160 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1162 htlc_idxs.push(Some(idx));
1163 values.push(tx.output[htlc.transaction_output_index as usize].value);
1164 total_value += htlc.amount_msat / 1000;
1166 let mut single_htlc_tx = Transaction {
1170 output: vec!(TxOut {
1171 script_pubkey: self.destination_script.clone(),
1172 value: htlc.amount_msat / 1000, //TODO: - fee
1175 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1176 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1177 txn_to_broadcast.push(single_htlc_tx);
1182 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
1183 // We're definitely a remote commitment transaction!
1184 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());
1185 watch_outputs.append(&mut tx.output.clone());
1186 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1188 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
1190 let outputs = vec!(TxOut {
1191 script_pubkey: self.destination_script.clone(),
1192 value: total_value, //TODO: - fee
1194 let mut spend_tx = Transaction {
1201 let mut values_drain = values.drain(..);
1202 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1204 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1205 let value = values_drain.next().unwrap();
1206 sign_input!(sighash_parts, input, htlc_idx, value);
1209 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1210 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1211 output: spend_tx.output[0].clone(),
1213 txn_to_broadcast.push(spend_tx);
1215 // TODO: We really should only fail backwards after our revocation claims have been
1216 // confirmed, but we also need to do more other tracking of in-flight pre-confirm
1217 // on-chain claims, so we can do that at the same time.
1218 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1219 if let &Some(ref txid) = current_remote_commitment_txid {
1220 if let Some(&(_, ref latest_outpoints)) = self.remote_claimable_outpoints.get(&txid) {
1221 for &(ref payment_hash, ref source, _) in latest_outpoints.iter() {
1222 log_trace!(self, "Failing HTLC with payment_hash {} from current remote commitment tx due to broadcast of revoked remote commitment transaction", log_bytes!(payment_hash.0));
1223 htlc_updated.push(((*source).clone(), None, payment_hash.clone()));
1227 if let &Some(ref txid) = prev_remote_commitment_txid {
1228 if let Some(&(_, ref prev_outpoint)) = self.remote_claimable_outpoints.get(&txid) {
1229 for &(ref payment_hash, ref source, _) in prev_outpoint.iter() {
1230 log_trace!(self, "Failing HTLC with payment_hash {} from previous remote commitment tx due to broadcast of revoked remote commitment transaction", log_bytes!(payment_hash.0));
1231 htlc_updated.push(((*source).clone(), None, payment_hash.clone()));
1236 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1237 } else if let Some(per_commitment_data) = per_commitment_option {
1238 // While this isn't useful yet, there is a potential race where if a counterparty
1239 // revokes a state at the same time as the commitment transaction for that state is
1240 // confirmed, and the watchtower receives the block before the user, the user could
1241 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1242 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1243 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1245 watch_outputs.append(&mut tx.output.clone());
1246 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1248 if let Some(revocation_points) = self.their_cur_revocation_points {
1249 let revocation_point_option =
1250 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1251 else if let Some(point) = revocation_points.2.as_ref() {
1252 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1254 if let Some(revocation_point) = revocation_point_option {
1255 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1256 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1257 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1258 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1260 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1261 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1262 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1265 let a_htlc_key = match self.their_htlc_base_key {
1266 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated),
1267 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1270 for (idx, outp) in tx.output.iter().enumerate() {
1271 if outp.script_pubkey.is_v0_p2wpkh() {
1272 match self.key_storage {
1273 Storage::Local { ref payment_base_key, .. } => {
1274 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1275 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1276 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1278 output: outp.clone(),
1282 Storage::Watchtower { .. } => {}
1284 break; // Only to_remote ouput is claimable
1288 let mut total_value = 0;
1289 let mut values = Vec::new();
1290 let mut inputs = Vec::new();
1292 macro_rules! sign_input {
1293 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1295 let (sig, redeemscript) = match self.key_storage {
1296 Storage::Local { ref htlc_base_key, .. } => {
1297 let htlc = &per_commitment_option.unwrap().0[$input.sequence as usize];
1298 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1299 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
1300 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1301 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1303 Storage::Watchtower { .. } => {
1307 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1308 $input.witness[0].push(SigHashType::All as u8);
1309 $input.witness.push($preimage);
1310 $input.witness.push(redeemscript.into_bytes());
1315 for (idx, ref htlc) in per_commitment_data.0.iter().enumerate() {
1316 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1317 if htlc.transaction_output_index as usize >= tx.output.len() ||
1318 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1319 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1320 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated); // Corrupted per_commitment_data, fuck this user
1322 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1324 previous_output: BitcoinOutPoint {
1325 txid: commitment_txid,
1326 vout: htlc.transaction_output_index,
1328 script_sig: Script::new(),
1329 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1330 witness: Vec::new(),
1332 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1334 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
1335 total_value += htlc.amount_msat / 1000;
1337 let mut single_htlc_tx = Transaction {
1341 output: vec!(TxOut {
1342 script_pubkey: self.destination_script.clone(),
1343 value: htlc.amount_msat / 1000, //TODO: - fee
1346 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1347 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
1348 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1349 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1350 output: single_htlc_tx.output[0].clone(),
1352 txn_to_broadcast.push(single_htlc_tx);
1356 // TODO: If the HTLC has already expired, potentially merge it with the
1357 // rest of the claim transaction, as above.
1359 previous_output: BitcoinOutPoint {
1360 txid: commitment_txid,
1361 vout: htlc.transaction_output_index,
1363 script_sig: Script::new(),
1364 sequence: idx as u32,
1365 witness: Vec::new(),
1367 let mut timeout_tx = Transaction {
1369 lock_time: htlc.cltv_expiry,
1371 output: vec!(TxOut {
1372 script_pubkey: self.destination_script.clone(),
1373 value: htlc.amount_msat / 1000,
1376 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1377 sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1378 txn_to_broadcast.push(timeout_tx);
1382 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
1384 let outputs = vec!(TxOut {
1385 script_pubkey: self.destination_script.clone(),
1386 value: total_value, //TODO: - fee
1388 let mut spend_tx = Transaction {
1395 let mut values_drain = values.drain(..);
1396 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1398 for input in spend_tx.input.iter_mut() {
1399 let value = values_drain.next().unwrap();
1400 sign_input!(sighash_parts, input, value.0, (value.1).0.to_vec());
1403 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1404 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1405 output: spend_tx.output[0].clone(),
1407 txn_to_broadcast.push(spend_tx);
1409 // TODO: We need to fail back HTLCs that were't included in the broadcast
1410 // commitment transaction, either because they didn't meet dust or because a
1411 // stale (but not yet revoked) commitment transaction was broadcast!
1416 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs, htlc_updated)
1419 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1420 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1421 if tx.input.len() != 1 || tx.output.len() != 1 {
1425 macro_rules! ignore_error {
1426 ( $thing : expr ) => {
1429 Err(_) => return (None, None)
1434 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1435 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1436 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1437 let revocation_pubkey = match self.key_storage {
1438 Storage::Local { ref revocation_base_key, .. } => {
1439 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1441 Storage::Watchtower { ref revocation_base_key, .. } => {
1442 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1445 let delayed_key = match self.their_delayed_payment_base_key {
1446 None => return (None, None),
1447 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1449 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1450 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1451 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1453 let mut inputs = Vec::new();
1456 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1458 previous_output: BitcoinOutPoint {
1462 script_sig: Script::new(),
1463 sequence: 0xfffffffd,
1464 witness: Vec::new(),
1466 amount = tx.output[0].value;
1469 if !inputs.is_empty() {
1470 let outputs = vec!(TxOut {
1471 script_pubkey: self.destination_script.clone(),
1472 value: amount, //TODO: - fee
1475 let mut spend_tx = Transaction {
1482 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1484 let sig = match self.key_storage {
1485 Storage::Local { ref revocation_base_key, .. } => {
1486 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1487 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1488 self.secp_ctx.sign(&sighash, &revocation_key)
1490 Storage::Watchtower { .. } => {
1494 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1495 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1496 spend_tx.input[0].witness.push(vec!(1));
1497 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1499 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1500 let output = spend_tx.output[0].clone();
1501 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1502 } else { (None, None) }
1505 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>) {
1506 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1507 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1508 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1510 macro_rules! add_dynamic_output {
1511 ($father_tx: expr, $vout: expr) => {
1512 if let Some(ref per_commitment_point) = *per_commitment_point {
1513 if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1514 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1515 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1516 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1517 key: local_delayedkey,
1518 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1519 to_self_delay: self.our_to_self_delay,
1520 output: $father_tx.output[$vout as usize].clone(),
1529 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1530 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1531 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1532 if output.script_pubkey == revokeable_p2wsh {
1533 add_dynamic_output!(local_tx.tx, idx as u32);
1538 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1540 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);
1542 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1544 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1545 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1546 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1547 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1549 htlc_timeout_tx.input[0].witness.push(Vec::new());
1550 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());
1552 add_dynamic_output!(htlc_timeout_tx, 0);
1553 res.push(htlc_timeout_tx);
1555 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1556 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);
1558 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1560 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1561 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1562 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1563 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1565 htlc_success_tx.input[0].witness.push(payment_preimage.0.to_vec());
1566 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());
1568 add_dynamic_output!(htlc_success_tx, 0);
1569 res.push(htlc_success_tx);
1572 watch_outputs.push(local_tx.tx.output[htlc.transaction_output_index as usize].clone());
1575 (res, spendable_outputs, watch_outputs)
1578 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1579 /// revoked using data in local_claimable_outpoints.
1580 /// Should not be used if check_spend_revoked_transaction succeeds.
1581 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1582 let commitment_txid = tx.txid();
1583 // TODO: If we find a match here we need to fail back HTLCs that were't included in the
1584 // broadcast commitment transaction, either because they didn't meet dust or because they
1585 // weren't yet included in our commitment transaction(s).
1586 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1587 if local_tx.txid == commitment_txid {
1588 match self.key_storage {
1589 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1590 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1591 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1593 Storage::Watchtower { .. } => {
1594 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1595 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1600 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1601 if local_tx.txid == commitment_txid {
1602 match self.key_storage {
1603 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1604 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
1605 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1607 Storage::Watchtower { .. } => {
1608 let (local_txn, spendable_outputs, watch_outputs) = self.broadcast_by_local_state(local_tx, &None, &None);
1609 return (local_txn, spendable_outputs, (commitment_txid, watch_outputs));
1614 (Vec::new(), Vec::new(), (commitment_txid, Vec::new()))
1617 /// Generate a spendable output event when closing_transaction get registered onchain.
1618 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1619 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1620 match self.key_storage {
1621 Storage::Local { ref shutdown_pubkey, .. } => {
1622 let our_channel_close_key_hash = Hash160::from_data(&shutdown_pubkey.serialize());
1623 let shutdown_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1624 for (idx, output) in tx.output.iter().enumerate() {
1625 if shutdown_script == output.script_pubkey {
1626 return Some(SpendableOutputDescriptor::StaticOutput {
1627 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1628 output: output.clone(),
1633 Storage::Watchtower { .. } => {
1634 //TODO: we need to ensure an offline client will generate the event when it
1635 // cames back online after only the watchtower saw the transaction
1642 /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1643 /// the Channel was out-of-date.
1644 pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1645 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1646 let mut res = vec![local_tx.tx.clone()];
1647 match self.key_storage {
1648 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1649 res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1651 _ => panic!("Can only broadcast by local channelmonitor"),
1659 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)>) {
1660 let mut watch_outputs = Vec::new();
1661 let mut spendable_outputs = Vec::new();
1662 let mut htlc_updated = Vec::new();
1663 for tx in txn_matched {
1664 if tx.input.len() == 1 {
1665 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1666 // commitment transactions and HTLC transactions will all only ever have one input,
1667 // which is an easy way to filter out any potential non-matching txn for lazy
1669 let prevout = &tx.input[0].previous_output;
1670 let mut txn: Vec<Transaction> = Vec::new();
1671 let funding_txo = match self.key_storage {
1672 Storage::Local { ref funding_info, .. } => {
1673 funding_info.clone()
1675 Storage::Watchtower { .. } => {
1679 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) {
1680 let (remote_txn, new_outputs, mut spendable_output, mut updated) = self.check_spend_remote_transaction(tx, height);
1682 spendable_outputs.append(&mut spendable_output);
1683 if !new_outputs.1.is_empty() {
1684 watch_outputs.push(new_outputs);
1687 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
1688 spendable_outputs.append(&mut spendable_output);
1690 if !new_outputs.1.is_empty() {
1691 watch_outputs.push(new_outputs);
1694 if !funding_txo.is_none() && txn.is_empty() {
1695 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1696 spendable_outputs.push(spendable_output);
1699 if updated.len() > 0 {
1700 htlc_updated.append(&mut updated);
1703 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1704 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
1705 if let Some(tx) = tx {
1708 if let Some(spendable_output) = spendable_output {
1709 spendable_outputs.push(spendable_output);
1713 for tx in txn.iter() {
1714 broadcaster.broadcast_transaction(tx);
1716 let mut updated = self.is_resolving_htlc_output(tx);
1717 if updated.len() > 0 {
1718 htlc_updated.append(&mut updated);
1722 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1723 if self.would_broadcast_at_height(height) {
1724 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1725 match self.key_storage {
1726 Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1727 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1728 spendable_outputs.append(&mut spendable_output);
1729 if !new_outputs.is_empty() {
1730 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1733 broadcaster.broadcast_transaction(&tx);
1736 Storage::Watchtower { .. } => {
1737 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1738 spendable_outputs.append(&mut spendable_output);
1739 if !new_outputs.is_empty() {
1740 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1743 broadcaster.broadcast_transaction(&tx);
1749 self.last_block_hash = block_hash.clone();
1750 (watch_outputs, spendable_outputs, htlc_updated)
1753 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1754 // TODO: We need to consider HTLCs which weren't included in latest local commitment
1755 // transaction (or in any of the latest two local commitment transactions). This probably
1756 // needs to use the same logic as the revoked-tx-announe logic - checking the last two
1757 // remote commitment transactions. This probably has implications for what data we need to
1758 // store in local commitment transactions.
1759 // TODO: We need to consider HTLCs which were below dust threshold here - while they don't
1760 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
1761 // to the source, and if we don't fail the channel we will have to ensure that the next
1762 // updates that peer sends us are update_fails, failing the channel if not. It's probably
1763 // easier to just fail the channel as this case should be rare enough anyway.
1764 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1765 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1766 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1767 // chain with enough room to claim the HTLC without our counterparty being able to
1768 // time out the HTLC first.
1769 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1770 // concern is being able to claim the corresponding inbound HTLC (on another
1771 // channel) before it expires. In fact, we don't even really care if our
1772 // counterparty here claims such an outbound HTLC after it expired as long as we
1773 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1774 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1775 // we give ourselves a few blocks of headroom after expiration before going
1776 // on-chain for an expired HTLC.
1777 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1778 // from us until we've reached the point where we go on-chain with the
1779 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1780 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1781 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1782 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1783 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1784 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1785 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1786 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1787 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1795 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
1796 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
1797 fn is_resolving_htlc_output(&mut self, tx: &Transaction) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
1798 let mut htlc_updated = Vec::new();
1800 'outer_loop: for input in &tx.input {
1801 let mut payment_data = None;
1803 macro_rules! scan_commitment {
1804 ($htlc_outputs: expr, $htlc_sources: expr, $source: expr) => {
1805 for &(ref payment_hash, ref source, ref vout) in $htlc_sources.iter() {
1806 if &Some(input.previous_output.vout) == vout {
1807 log_trace!(self, "Input spending {}:{} resolves HTLC with payment hash {} from {}", input.previous_output.txid, input.previous_output.vout, log_bytes!(payment_hash.0), $source);
1808 payment_data = Some((source.clone(), *payment_hash));
1811 if payment_data.is_none() {
1812 for htlc_output in $htlc_outputs {
1813 if input.previous_output.vout == htlc_output.transaction_output_index {
1814 log_info!(self, "Input spending {}:{} in {} resolves inbound HTLC with timeout from {}", input.previous_output.txid, input.previous_output.vout, tx.txid(), $source);
1815 continue 'outer_loop;
1822 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
1823 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
1824 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a),
1825 current_local_signed_commitment_tx.htlc_sources,
1826 "our latest local commitment tx");
1829 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
1830 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
1831 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a),
1832 prev_local_signed_commitment_tx.htlc_sources,
1833 "our latest local commitment tx");
1836 if let Some(&(ref htlc_outputs, ref htlc_sources)) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
1837 scan_commitment!(htlc_outputs, htlc_sources, "remote commitment tx");
1840 // If tx isn't solving htlc output from local/remote commitment tx and htlc isn't outbound we don't need
1841 // to broadcast solving backward
1842 if let Some((source, payment_hash)) = payment_data {
1843 let mut payment_preimage = PaymentPreimage([0; 32]);
1844 if (input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33)
1845 || (input.witness.len() == 3 && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33) {
1846 log_error!(self, "Remote used revocation sig to take a {} HTLC output at index {} from commitment_tx {}", if input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT { "offered" } else { "accepted" }, input.previous_output.vout, input.previous_output.txid);
1847 } else if input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
1848 payment_preimage.0.copy_from_slice(&tx.input[0].witness[3]);
1849 htlc_updated.push((source, Some(payment_preimage), payment_hash));
1850 } else if input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT {
1851 payment_preimage.0.copy_from_slice(&tx.input[0].witness[1]);
1852 htlc_updated.push((source, Some(payment_preimage), payment_hash));
1854 htlc_updated.push((source, None, payment_hash));
1862 const MAX_ALLOC_SIZE: usize = 64*1024;
1864 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
1865 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
1866 let secp_ctx = Secp256k1::new();
1867 macro_rules! unwrap_obj {
1871 Err(_) => return Err(DecodeError::InvalidValue),
1876 let _ver: u8 = Readable::read(reader)?;
1877 let min_ver: u8 = Readable::read(reader)?;
1878 if min_ver > SERIALIZATION_VERSION {
1879 return Err(DecodeError::UnknownVersion);
1882 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
1884 let key_storage = match <u8 as Readable<R>>::read(reader)? {
1886 let revocation_base_key = Readable::read(reader)?;
1887 let htlc_base_key = Readable::read(reader)?;
1888 let delayed_payment_base_key = Readable::read(reader)?;
1889 let payment_base_key = Readable::read(reader)?;
1890 let shutdown_pubkey = Readable::read(reader)?;
1891 let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1893 1 => Some(Readable::read(reader)?),
1894 _ => return Err(DecodeError::InvalidValue),
1896 let latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
1898 1 => Some(Readable::read(reader)?),
1899 _ => return Err(DecodeError::InvalidValue),
1901 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1902 // barely-init'd ChannelMonitors that we can't do anything with.
1903 let outpoint = OutPoint {
1904 txid: Readable::read(reader)?,
1905 index: Readable::read(reader)?,
1907 let funding_info = Some((outpoint, Readable::read(reader)?));
1908 let current_remote_commitment_txid = match <u8 as Readable<R>>::read(reader)? {
1910 1 => Some(Readable::read(reader)?),
1911 _ => return Err(DecodeError::InvalidValue),
1913 let prev_remote_commitment_txid = match <u8 as Readable<R>>::read(reader)? {
1915 1 => Some(Readable::read(reader)?),
1916 _ => return Err(DecodeError::InvalidValue),
1919 revocation_base_key,
1921 delayed_payment_base_key,
1924 prev_latest_per_commitment_point,
1925 latest_per_commitment_point,
1927 current_remote_commitment_txid,
1928 prev_remote_commitment_txid,
1931 _ => return Err(DecodeError::InvalidValue),
1934 let their_htlc_base_key = Some(Readable::read(reader)?);
1935 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
1937 let their_cur_revocation_points = {
1938 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
1942 let first_point = Readable::read(reader)?;
1943 let second_point_slice: [u8; 33] = Readable::read(reader)?;
1944 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1945 Some((first_idx, first_point, None))
1947 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, &second_point_slice)))))
1952 let our_to_self_delay: u16 = Readable::read(reader)?;
1953 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
1955 let mut old_secrets = [([0; 32], 1 << 48); 49];
1956 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1957 *secret = Readable::read(reader)?;
1958 *idx = Readable::read(reader)?;
1961 macro_rules! read_htlc_in_commitment {
1964 let offered: bool = Readable::read(reader)?;
1965 let amount_msat: u64 = Readable::read(reader)?;
1966 let cltv_expiry: u32 = Readable::read(reader)?;
1967 let payment_hash: PaymentHash = Readable::read(reader)?;
1968 let transaction_output_index: u32 = Readable::read(reader)?;
1970 HTLCOutputInCommitment {
1971 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1977 macro_rules! read_htlc_source {
1980 (Readable::read(reader)?, Readable::read(reader)?,
1981 match <u8 as Readable<R>>::read(reader)? {
1983 1 => Some(Readable::read(reader)?),
1984 _ => return Err(DecodeError::InvalidValue),
1991 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
1992 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
1993 for _ in 0..remote_claimable_outpoints_len {
1994 let txid: Sha256dHash = Readable::read(reader)?;
1995 let outputs_count: u64 = Readable::read(reader)?;
1996 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 32));
1997 for _ in 0..outputs_count {
1998 outputs.push(read_htlc_in_commitment!());
2000 let sources_count: u64 = Readable::read(reader)?;
2001 let mut sources = Vec::with_capacity(cmp::min(sources_count as usize, MAX_ALLOC_SIZE / 32));
2002 for _ in 0..sources_count {
2003 sources.push(read_htlc_source!());
2005 if let Some(_) = remote_claimable_outpoints.insert(txid, (outputs, sources)) {
2006 return Err(DecodeError::InvalidValue);
2010 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2011 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2012 for _ in 0..remote_commitment_txn_on_chain_len {
2013 let txid: Sha256dHash = Readable::read(reader)?;
2014 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2015 let outputs_count = <u64 as Readable<R>>::read(reader)?;
2016 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2017 for _ in 0..outputs_count {
2018 outputs.push(Readable::read(reader)?);
2020 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2021 return Err(DecodeError::InvalidValue);
2025 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2026 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2027 for _ in 0..remote_hash_commitment_number_len {
2028 let payment_hash: PaymentHash = Readable::read(reader)?;
2029 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2030 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2031 return Err(DecodeError::InvalidValue);
2035 macro_rules! read_local_tx {
2038 let tx = match Transaction::consensus_decode(reader.by_ref()) {
2041 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
2042 _ => return Err(DecodeError::InvalidValue),
2046 if tx.input.is_empty() {
2047 // Ensure tx didn't hit the 0-input ambiguity case.
2048 return Err(DecodeError::InvalidValue);
2051 let revocation_key = Readable::read(reader)?;
2052 let a_htlc_key = Readable::read(reader)?;
2053 let b_htlc_key = Readable::read(reader)?;
2054 let delayed_payment_key = Readable::read(reader)?;
2055 let feerate_per_kw: u64 = Readable::read(reader)?;
2057 let htlc_outputs_len: u64 = Readable::read(reader)?;
2058 let mut htlc_outputs = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
2059 for _ in 0..htlc_outputs_len {
2060 let out = read_htlc_in_commitment!();
2061 let sigs = (Readable::read(reader)?, Readable::read(reader)?);
2062 htlc_outputs.push((out, sigs.0, sigs.1));
2065 let htlc_sources_len: u64 = Readable::read(reader)?;
2066 let mut htlc_sources = Vec::with_capacity(cmp::min(htlc_outputs_len as usize, MAX_ALLOC_SIZE / 128));
2067 for _ in 0..htlc_sources_len {
2068 htlc_sources.push(read_htlc_source!());
2073 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs, htlc_sources
2079 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2082 Some(read_local_tx!())
2084 _ => return Err(DecodeError::InvalidValue),
2087 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2090 Some(read_local_tx!())
2092 _ => return Err(DecodeError::InvalidValue),
2095 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2097 let payment_preimages_len: u64 = Readable::read(reader)?;
2098 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2099 for _ in 0..payment_preimages_len {
2100 let preimage: PaymentPreimage = Readable::read(reader)?;
2101 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2102 if let Some(_) = payment_preimages.insert(hash, preimage) {
2103 return Err(DecodeError::InvalidValue);
2107 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2108 let destination_script = Readable::read(reader)?;
2110 Ok((last_block_hash.clone(), ChannelMonitor {
2111 commitment_transaction_number_obscure_factor,
2114 their_htlc_base_key,
2115 their_delayed_payment_base_key,
2116 their_cur_revocation_points,
2119 their_to_self_delay,
2122 remote_claimable_outpoints,
2123 remote_commitment_txn_on_chain,
2124 remote_hash_commitment_number,
2126 prev_local_signed_commitment_tx,
2127 current_local_signed_commitment_tx,
2128 current_remote_commitment_number,
2143 use bitcoin::blockdata::script::Script;
2144 use bitcoin::blockdata::transaction::Transaction;
2145 use bitcoin_hashes::Hash;
2146 use bitcoin_hashes::sha256::Hash as Sha256;
2148 use ln::channelmanager::{PaymentPreimage, PaymentHash};
2149 use ln::channelmonitor::ChannelMonitor;
2150 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
2151 use util::test_utils::TestLogger;
2152 use secp256k1::key::{SecretKey,PublicKey};
2153 use secp256k1::{Secp256k1, Signature};
2154 use rand::{thread_rng,Rng};
2158 fn test_per_commitment_storage() {
2159 // Test vectors from BOLT 3:
2160 let mut secrets: Vec<[u8; 32]> = Vec::new();
2161 let mut monitor: ChannelMonitor;
2162 let secp_ctx = Secp256k1::new();
2163 let logger = Arc::new(TestLogger::new());
2165 macro_rules! test_secrets {
2167 let mut idx = 281474976710655;
2168 for secret in secrets.iter() {
2169 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2172 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2173 assert!(monitor.get_secret(idx).is_none());
2178 // insert_secret correct sequence
2179 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2182 secrets.push([0; 32]);
2183 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2184 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2187 secrets.push([0; 32]);
2188 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2189 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2192 secrets.push([0; 32]);
2193 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2194 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2197 secrets.push([0; 32]);
2198 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2199 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2202 secrets.push([0; 32]);
2203 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2204 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2207 secrets.push([0; 32]);
2208 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2209 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2212 secrets.push([0; 32]);
2213 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2214 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2217 secrets.push([0; 32]);
2218 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2219 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2224 // insert_secret #1 incorrect
2225 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2228 secrets.push([0; 32]);
2229 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2230 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2233 secrets.push([0; 32]);
2234 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2235 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
2236 "Previous secret did not match new one");
2240 // insert_secret #2 incorrect (#1 derived from incorrect)
2241 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2244 secrets.push([0; 32]);
2245 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2246 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2249 secrets.push([0; 32]);
2250 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2251 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2254 secrets.push([0; 32]);
2255 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2256 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2259 secrets.push([0; 32]);
2260 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2261 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2262 "Previous secret did not match new one");
2266 // insert_secret #3 incorrect
2267 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2270 secrets.push([0; 32]);
2271 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2272 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2275 secrets.push([0; 32]);
2276 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2277 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2280 secrets.push([0; 32]);
2281 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2282 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2285 secrets.push([0; 32]);
2286 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2287 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2288 "Previous secret did not match new one");
2292 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2293 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2296 secrets.push([0; 32]);
2297 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2298 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2301 secrets.push([0; 32]);
2302 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2303 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2306 secrets.push([0; 32]);
2307 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2308 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2311 secrets.push([0; 32]);
2312 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2313 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2316 secrets.push([0; 32]);
2317 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2318 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2321 secrets.push([0; 32]);
2322 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2323 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2326 secrets.push([0; 32]);
2327 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2328 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2331 secrets.push([0; 32]);
2332 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2333 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2334 "Previous secret did not match new one");
2338 // insert_secret #5 incorrect
2339 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2342 secrets.push([0; 32]);
2343 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2344 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2347 secrets.push([0; 32]);
2348 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2349 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2352 secrets.push([0; 32]);
2353 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2354 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2357 secrets.push([0; 32]);
2358 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2359 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2362 secrets.push([0; 32]);
2363 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2364 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2367 secrets.push([0; 32]);
2368 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2369 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2370 "Previous secret did not match new one");
2374 // insert_secret #6 incorrect (5 derived from incorrect)
2375 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2378 secrets.push([0; 32]);
2379 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2380 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2383 secrets.push([0; 32]);
2384 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2385 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2388 secrets.push([0; 32]);
2389 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2390 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2393 secrets.push([0; 32]);
2394 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2395 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2398 secrets.push([0; 32]);
2399 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2400 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2403 secrets.push([0; 32]);
2404 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2405 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2408 secrets.push([0; 32]);
2409 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2410 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2413 secrets.push([0; 32]);
2414 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2415 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2416 "Previous secret did not match new one");
2420 // insert_secret #7 incorrect
2421 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2424 secrets.push([0; 32]);
2425 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2426 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2429 secrets.push([0; 32]);
2430 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2431 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2434 secrets.push([0; 32]);
2435 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2436 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2439 secrets.push([0; 32]);
2440 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2441 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2444 secrets.push([0; 32]);
2445 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2446 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2449 secrets.push([0; 32]);
2450 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2451 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2454 secrets.push([0; 32]);
2455 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2456 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2459 secrets.push([0; 32]);
2460 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2461 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2462 "Previous secret did not match new one");
2466 // insert_secret #8 incorrect
2467 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2470 secrets.push([0; 32]);
2471 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2472 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2475 secrets.push([0; 32]);
2476 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2477 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2480 secrets.push([0; 32]);
2481 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2482 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2485 secrets.push([0; 32]);
2486 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2487 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2490 secrets.push([0; 32]);
2491 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2492 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2495 secrets.push([0; 32]);
2496 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2497 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2500 secrets.push([0; 32]);
2501 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2502 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2505 secrets.push([0; 32]);
2506 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2507 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2508 "Previous secret did not match new one");
2513 fn test_prune_preimages() {
2514 let secp_ctx = Secp256k1::new();
2515 let logger = Arc::new(TestLogger::new());
2516 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
2518 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
2519 macro_rules! dummy_keys {
2523 per_commitment_point: dummy_key.clone(),
2524 revocation_key: dummy_key.clone(),
2525 a_htlc_key: dummy_key.clone(),
2526 b_htlc_key: dummy_key.clone(),
2527 a_delayed_payment_key: dummy_key.clone(),
2528 b_payment_key: dummy_key.clone(),
2533 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2535 let mut preimages = Vec::new();
2537 let mut rng = thread_rng();
2539 let mut preimage = PaymentPreimage([0; 32]);
2540 rng.fill_bytes(&mut preimage.0[..]);
2541 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2542 preimages.push((preimage, hash));
2546 macro_rules! preimages_slice_to_htlc_outputs {
2547 ($preimages_slice: expr) => {
2549 let mut res = Vec::new();
2550 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2551 res.push(HTLCOutputInCommitment {
2555 payment_hash: preimage.1.clone(),
2556 transaction_output_index: idx as u32,
2563 macro_rules! preimages_to_local_htlcs {
2564 ($preimages_slice: expr) => {
2566 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2567 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
2573 macro_rules! test_preimages_exist {
2574 ($preimages_slice: expr, $monitor: expr) => {
2575 for preimage in $preimages_slice {
2576 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2581 // Prune with one old state and a local commitment tx holding a few overlaps with the
2583 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2584 monitor.set_their_to_self_delay(10);
2586 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]), Vec::new());
2587 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), Vec::new(), 281474976710655, dummy_key);
2588 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), Vec::new(), 281474976710654, dummy_key);
2589 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), Vec::new(), 281474976710653, dummy_key);
2590 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), Vec::new(), 281474976710652, dummy_key);
2591 for &(ref preimage, ref hash) in preimages.iter() {
2592 monitor.provide_payment_preimage(hash, preimage);
2595 // Now provide a secret, pruning preimages 10-15
2596 let mut secret = [0; 32];
2597 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2598 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2599 assert_eq!(monitor.payment_preimages.len(), 15);
2600 test_preimages_exist!(&preimages[0..10], monitor);
2601 test_preimages_exist!(&preimages[15..20], monitor);
2603 // Now provide a further secret, pruning preimages 15-17
2604 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2605 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2606 assert_eq!(monitor.payment_preimages.len(), 13);
2607 test_preimages_exist!(&preimages[0..10], monitor);
2608 test_preimages_exist!(&preimages[17..20], monitor);
2610 // Now update local commitment tx info, pruning only element 18 as we still care about the
2611 // previous commitment tx's preimages too
2612 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]), Vec::new());
2613 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2614 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2615 assert_eq!(monitor.payment_preimages.len(), 12);
2616 test_preimages_exist!(&preimages[0..10], monitor);
2617 test_preimages_exist!(&preimages[18..20], monitor);
2619 // But if we do it again, we'll prune 5-10
2620 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]), Vec::new());
2621 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2622 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2623 assert_eq!(monitor.payment_preimages.len(), 5);
2624 test_preimages_exist!(&preimages[0..5], monitor);
2627 // Further testing is done in the ChannelManager integration tests.