1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
18 use bitcoin::network::serialize;
19 use bitcoin::util::hash::Sha256dHash;
20 use bitcoin::util::bip143;
22 use crypto::digest::Digest;
24 use secp256k1::{Secp256k1,Message,Signature};
25 use secp256k1::key::{SecretKey,PublicKey};
28 use ln::msgs::{DecodeError, HandleError};
30 use ln::chan_utils::HTLCOutputInCommitment;
31 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
32 use chain::transaction::OutPoint;
33 use util::ser::{Readable, Writer};
34 use util::sha2::Sha256;
37 use std::collections::HashMap;
38 use std::sync::{Arc,Mutex};
41 /// An error enum representing a failure to persist a channel monitor update.
43 pub enum ChannelMonitorUpdateErr {
44 /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected
45 /// to succeed at some point in the future).
47 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
48 /// submitting new commitment transactions to the remote party.
49 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
50 /// the channel to an operational state.
52 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
53 /// persisted is unsafe - if you failed to store the update on your own local disk you should
54 /// instead return PermanentFailure to force closure of the channel ASAP.
56 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
57 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
58 /// to claim it on this channel) and those updates must be applied wherever they can be. At
59 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
60 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
61 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
64 /// Note that even if updates made after TemporaryFailure succeed you must still call
65 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
66 /// channel operation.
68 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
69 /// different watchtower and cannot update with all watchtowers that were previously informed
70 /// of this channel). This will force-close the channel in question.
74 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
75 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
76 /// events to it, while also taking any add_update_monitor events and passing them to some remote
79 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
80 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
81 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
82 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
83 pub trait ManyChannelMonitor: Send + Sync {
84 /// Adds or updates a monitor for the given `funding_txo`.
86 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
87 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
89 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
92 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
93 /// watchtower or watch our own channels.
95 /// Note that you must provide your own key by which to refer to channels.
97 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
98 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
99 /// index by a PublicKey which is required to sign any updates.
101 /// If you're using this for local monitoring of your own channels, you probably want to use
102 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
103 pub struct SimpleManyChannelMonitor<Key> {
104 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
105 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
107 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
108 chain_monitor: Arc<ChainWatchInterface>,
109 broadcaster: Arc<BroadcasterInterface>
112 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
113 fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
114 let monitors = self.monitors.lock().unwrap();
115 for monitor in monitors.values() {
116 let txn_outputs = monitor.block_connected(txn_matched, height, &*self.broadcaster);
117 for (ref txid, ref outputs) in txn_outputs {
118 for (idx, output) in outputs.iter().enumerate() {
119 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
125 fn block_disconnected(&self, _: &BlockHeader) { }
128 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
129 /// Creates a new object which can be used to monitor several channels given the chain
130 /// interface with which to register to receive notifications.
131 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
132 let res = Arc::new(SimpleManyChannelMonitor {
133 monitors: Mutex::new(HashMap::new()),
137 let weak_res = Arc::downgrade(&res);
138 res.chain_monitor.register_listener(weak_res);
142 /// Adds or udpates the monitor which monitors the channel referred to by the given key.
143 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
144 let mut monitors = self.monitors.lock().unwrap();
145 match monitors.get_mut(&key) {
146 Some(orig_monitor) => return orig_monitor.insert_combine(monitor),
149 match &monitor.funding_txo {
150 &None => self.chain_monitor.watch_all_txn(),
151 &Some((ref outpoint, ref script)) => {
152 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
153 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
156 monitors.insert(key, monitor);
161 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
162 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
163 match self.add_update_monitor_by_key(funding_txo, monitor) {
165 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
170 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
171 /// instead claiming it in its own individual transaction.
172 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
173 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
174 /// HTLC-Success transaction.
175 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
176 /// transaction confirmed (and we use it in a few more, equivalent, places).
177 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
178 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
179 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
180 /// copies of ChannelMonitors, including watchtowers).
181 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
183 #[derive(Clone, PartialEq)]
186 revocation_base_key: SecretKey,
187 htlc_base_key: SecretKey,
190 revocation_base_key: PublicKey,
191 htlc_base_key: PublicKey,
192 sigs: HashMap<Sha256dHash, Signature>,
196 #[derive(Clone, PartialEq)]
197 struct LocalSignedTx {
198 /// txid of the transaction in tx, just used to make comparison faster
201 revocation_key: PublicKey,
202 a_htlc_key: PublicKey,
203 b_htlc_key: PublicKey,
204 delayed_payment_key: PublicKey,
206 htlc_outputs: Vec<(HTLCOutputInCommitment, Signature, Signature)>,
209 const SERIALIZATION_VERSION: u8 = 1;
210 const MIN_SERIALIZATION_VERSION: u8 = 1;
212 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
213 /// on-chain transactions to ensure no loss of funds occurs.
215 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
216 /// information and are actively monitoring the chain.
217 pub struct ChannelMonitor {
218 funding_txo: Option<(OutPoint, Script)>,
219 commitment_transaction_number_obscure_factor: u64,
221 key_storage: KeyStorage,
222 delayed_payment_base_key: PublicKey,
223 their_htlc_base_key: Option<PublicKey>,
224 their_delayed_payment_base_key: Option<PublicKey>,
225 // first is the idx of the first of the two revocation points
226 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
228 our_to_self_delay: u16,
229 their_to_self_delay: Option<u16>,
231 old_secrets: [([u8; 32], u64); 49],
232 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<HTLCOutputInCommitment>>,
233 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
234 /// Nor can we figure out their commitment numbers without the commitment transaction they are
235 /// spending. Thus, in order to claim them via revocation key, we track all the remote
236 /// commitment transactions which we find on-chain, mapping them to the commitment number which
237 /// can be used to derive the revocation key and claim the transactions.
238 remote_commitment_txn_on_chain: Mutex<HashMap<Sha256dHash, u64>>,
239 /// Cache used to make pruning of payment_preimages faster.
240 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
241 /// remote transactions (ie should remain pretty small).
242 /// Serialized to disk but should generally not be sent to Watchtowers.
243 remote_hash_commitment_number: HashMap<[u8; 32], u64>,
245 // We store two local commitment transactions to avoid any race conditions where we may update
246 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
247 // various monitors for one channel being out of sync, and us broadcasting a local
248 // transaction for which we have deleted claim information on some watchtowers.
249 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
250 current_local_signed_commitment_tx: Option<LocalSignedTx>,
252 payment_preimages: HashMap<[u8; 32], [u8; 32]>,
254 destination_script: Script,
255 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
257 impl Clone for ChannelMonitor {
258 fn clone(&self) -> Self {
260 funding_txo: self.funding_txo.clone(),
261 commitment_transaction_number_obscure_factor: self.commitment_transaction_number_obscure_factor.clone(),
263 key_storage: self.key_storage.clone(),
264 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
265 their_htlc_base_key: self.their_htlc_base_key.clone(),
266 their_delayed_payment_base_key: self.their_delayed_payment_base_key.clone(),
267 their_cur_revocation_points: self.their_cur_revocation_points.clone(),
269 our_to_self_delay: self.our_to_self_delay,
270 their_to_self_delay: self.their_to_self_delay,
272 old_secrets: self.old_secrets.clone(),
273 remote_claimable_outpoints: self.remote_claimable_outpoints.clone(),
274 remote_commitment_txn_on_chain: Mutex::new((*self.remote_commitment_txn_on_chain.lock().unwrap()).clone()),
275 remote_hash_commitment_number: self.remote_hash_commitment_number.clone(),
277 prev_local_signed_commitment_tx: self.prev_local_signed_commitment_tx.clone(),
278 current_local_signed_commitment_tx: self.current_local_signed_commitment_tx.clone(),
280 payment_preimages: self.payment_preimages.clone(),
282 destination_script: self.destination_script.clone(),
283 secp_ctx: self.secp_ctx.clone(),
288 #[cfg(any(test, feature = "fuzztarget"))]
289 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
290 /// underlying object
291 impl PartialEq for ChannelMonitor {
292 fn eq(&self, other: &Self) -> bool {
293 if self.funding_txo != other.funding_txo ||
294 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
295 self.key_storage != other.key_storage ||
296 self.delayed_payment_base_key != other.delayed_payment_base_key ||
297 self.their_htlc_base_key != other.their_htlc_base_key ||
298 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
299 self.their_cur_revocation_points != other.their_cur_revocation_points ||
300 self.our_to_self_delay != other.our_to_self_delay ||
301 self.their_to_self_delay != other.their_to_self_delay ||
302 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
303 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
304 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
305 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
306 self.payment_preimages != other.payment_preimages ||
307 self.destination_script != other.destination_script
311 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
312 if secret != o_secret || idx != o_idx {
316 let us = self.remote_commitment_txn_on_chain.lock().unwrap();
317 let them = other.remote_commitment_txn_on_chain.lock().unwrap();
323 impl ChannelMonitor {
324 pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &PublicKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script) -> ChannelMonitor {
327 commitment_transaction_number_obscure_factor: 0,
329 key_storage: KeyStorage::PrivMode {
330 revocation_base_key: revocation_base_key.clone(),
331 htlc_base_key: htlc_base_key.clone(),
333 delayed_payment_base_key: delayed_payment_base_key.clone(),
334 their_htlc_base_key: None,
335 their_delayed_payment_base_key: None,
336 their_cur_revocation_points: None,
338 our_to_self_delay: our_to_self_delay,
339 their_to_self_delay: None,
341 old_secrets: [([0; 32], 1 << 48); 49],
342 remote_claimable_outpoints: HashMap::new(),
343 remote_commitment_txn_on_chain: Mutex::new(HashMap::new()),
344 remote_hash_commitment_number: HashMap::new(),
346 prev_local_signed_commitment_tx: None,
347 current_local_signed_commitment_tx: None,
349 payment_preimages: HashMap::new(),
351 destination_script: destination_script,
352 secp_ctx: Secp256k1::new(),
357 fn place_secret(idx: u64) -> u8 {
359 if idx & (1 << i) == (1 << i) {
367 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
368 let mut res: [u8; 32] = secret;
370 let bitpos = bits - 1 - i;
371 if idx & (1 << bitpos) == (1 << bitpos) {
372 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
373 let mut sha = Sha256::new();
375 sha.result(&mut res);
381 /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
382 /// revocation point which may be required to claim HTLC outputs which we know the preimage of
383 /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
384 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
385 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
386 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
387 let pos = ChannelMonitor::place_secret(idx);
389 let (old_secret, old_idx) = self.old_secrets[i as usize];
390 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
391 return Err(HandleError{err: "Previous secret did not match new one", action: None})
394 self.old_secrets[pos as usize] = (secret, idx);
396 if let Some(new_revocation_point) = their_next_revocation_point {
397 match self.their_cur_revocation_points {
398 Some(old_points) => {
399 if old_points.0 == new_revocation_point.0 + 1 {
400 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
401 } else if old_points.0 == new_revocation_point.0 + 2 {
402 if let Some(old_second_point) = old_points.2 {
403 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
405 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
408 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
412 self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
417 if !self.payment_preimages.is_empty() {
418 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
419 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
420 let min_idx = self.get_min_seen_secret();
421 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
423 self.payment_preimages.retain(|&k, _| {
424 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
425 if k == htlc.payment_hash {
429 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
430 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
431 if k == htlc.payment_hash {
436 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
443 remote_hash_commitment_number.remove(&k);
452 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
453 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
454 /// possibly future revocation/preimage information) to claim outputs where possible.
455 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
456 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
457 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
458 // so that a remote monitor doesn't learn anything unless there is a malicious close.
459 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
461 for htlc in &htlc_outputs {
462 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
464 self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
467 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
468 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
469 /// is important that any clones of this channel monitor (including remote clones) by kept
470 /// up-to-date as our local commitment transaction is updated.
471 /// Panics if set_their_to_self_delay has never been called.
472 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)>) {
473 assert!(self.their_to_self_delay.is_some());
474 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
475 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
476 txid: signed_commitment_tx.txid(),
477 tx: signed_commitment_tx,
478 revocation_key: local_keys.revocation_key,
479 a_htlc_key: local_keys.a_htlc_key,
480 b_htlc_key: local_keys.b_htlc_key,
481 delayed_payment_key: local_keys.a_delayed_payment_key,
487 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
488 /// commitment_tx_infos which contain the payment hash have been revoked.
489 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &[u8; 32], payment_preimage: &[u8; 32]) {
490 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
493 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
494 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
495 /// chain for new blocks/transactions.
496 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
497 if self.funding_txo.is_some() {
498 // We should be able to compare the entire funding_txo, but in fuzztarget its trivially
499 // easy to collide the funding_txo hash and have a different scriptPubKey.
500 if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
501 return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
504 self.funding_txo = other.funding_txo.take();
506 let other_min_secret = other.get_min_seen_secret();
507 let our_min_secret = self.get_min_seen_secret();
508 if our_min_secret > other_min_secret {
509 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
511 if our_min_secret >= other_min_secret {
512 self.their_cur_revocation_points = other.their_cur_revocation_points;
513 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
514 self.remote_claimable_outpoints.insert(txid, htlcs);
516 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
517 self.prev_local_signed_commitment_tx = Some(local_tx);
519 if let Some(local_tx) = other.current_local_signed_commitment_tx {
520 self.current_local_signed_commitment_tx = Some(local_tx);
522 self.payment_preimages = other.payment_preimages;
527 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
528 pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
529 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
530 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
533 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
534 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
535 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
536 /// provides slightly better privacy.
537 /// It's the responsibility of the caller to register outpoint and script with passing the former
538 /// value as key to add_update_monitor.
539 pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
540 self.funding_txo = Some(funding_info);
543 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
544 pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
545 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
546 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
549 pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
550 self.their_to_self_delay = Some(their_to_self_delay);
553 pub(super) fn unset_funding_info(&mut self) {
554 self.funding_txo = None;
557 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
558 pub fn get_funding_txo(&self) -> Option<OutPoint> {
559 match self.funding_txo {
560 Some((outpoint, _)) => Some(outpoint),
565 /// Serializes into a vec, with various modes for the exposed pub fns
566 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
567 //TODO: We still write out all the serialization here manually instead of using the fancy
568 //serialization framework we have, we should migrate things over to it.
569 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
570 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
572 match &self.funding_txo {
573 &Some((ref outpoint, ref script)) => {
574 writer.write_all(&outpoint.txid[..])?;
575 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
576 writer.write_all(&byte_utils::be64_to_array(script.len() as u64))?;
577 writer.write_all(&script[..])?;
580 // We haven't even been initialized...not sure why anyone is serializing us, but
581 // not much to give them.
586 // Set in initial Channel-object creation, so should always be set by now:
587 writer.write_all(&byte_utils::be48_to_array(self.commitment_transaction_number_obscure_factor))?;
589 match self.key_storage {
590 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
591 writer.write_all(&[0; 1])?;
592 writer.write_all(&revocation_base_key[..])?;
593 writer.write_all(&htlc_base_key[..])?;
595 KeyStorage::SigsMode { .. } => unimplemented!(),
598 writer.write_all(&self.delayed_payment_base_key.serialize())?;
599 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
600 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
602 match self.their_cur_revocation_points {
603 Some((idx, pubkey, second_option)) => {
604 writer.write_all(&byte_utils::be48_to_array(idx))?;
605 writer.write_all(&pubkey.serialize())?;
606 match second_option {
607 Some(second_pubkey) => {
608 writer.write_all(&second_pubkey.serialize())?;
611 writer.write_all(&[0; 33])?;
616 writer.write_all(&byte_utils::be48_to_array(0))?;
620 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
621 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
623 for &(ref secret, ref idx) in self.old_secrets.iter() {
624 writer.write_all(secret)?;
625 writer.write_all(&byte_utils::be64_to_array(*idx))?;
628 macro_rules! serialize_htlc_in_commitment {
629 ($htlc_output: expr) => {
630 writer.write_all(&[$htlc_output.offered as u8; 1])?;
631 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
632 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
633 writer.write_all(&$htlc_output.payment_hash)?;
634 writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
638 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
639 for (txid, htlc_outputs) in self.remote_claimable_outpoints.iter() {
640 writer.write_all(&txid[..])?;
641 writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
642 for htlc_output in htlc_outputs.iter() {
643 serialize_htlc_in_commitment!(htlc_output);
648 let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
649 writer.write_all(&byte_utils::be64_to_array(remote_commitment_txn_on_chain.len() as u64))?;
650 for (txid, commitment_number) in remote_commitment_txn_on_chain.iter() {
651 writer.write_all(&txid[..])?;
652 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
656 if for_local_storage {
657 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
658 for (payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
659 writer.write_all(payment_hash)?;
660 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
663 writer.write_all(&byte_utils::be64_to_array(0))?;
666 macro_rules! serialize_local_tx {
667 ($local_tx: expr) => {
668 let tx_ser = serialize::serialize(&$local_tx.tx).unwrap();
669 writer.write_all(&byte_utils::be64_to_array(tx_ser.len() as u64))?;
670 writer.write_all(&tx_ser)?;
672 writer.write_all(&$local_tx.revocation_key.serialize())?;
673 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
674 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
675 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
677 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
678 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
679 for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
680 serialize_htlc_in_commitment!(htlc_output);
681 writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
682 writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
687 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
688 writer.write_all(&[1; 1])?;
689 serialize_local_tx!(prev_local_tx);
691 writer.write_all(&[0; 1])?;
694 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
695 writer.write_all(&[1; 1])?;
696 serialize_local_tx!(cur_local_tx);
698 writer.write_all(&[0; 1])?;
701 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
702 for payment_preimage in self.payment_preimages.values() {
703 writer.write_all(payment_preimage)?;
706 writer.write_all(&byte_utils::be64_to_array(self.destination_script.len() as u64))?;
707 writer.write_all(&self.destination_script[..])?;
712 /// Writes this monitor into the given writer, suitable for writing to disk.
713 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
714 self.write(writer, true)
717 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
718 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
719 self.write(writer, false)
722 //TODO: Functions to serialize/deserialize (with different forms depending on which information
723 //we want to leave out (eg funding_txo, etc).
725 /// Can only fail if idx is < get_min_seen_secret
726 pub(super) fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
727 for i in 0..self.old_secrets.len() {
728 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
729 return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
732 assert!(idx < self.get_min_seen_secret());
733 Err(HandleError{err: "idx too low", action: None})
736 pub(super) fn get_min_seen_secret(&self) -> u64 {
737 //TODO This can be optimized?
738 let mut min = 1 << 48;
739 for &(_, idx) in self.old_secrets.iter() {
747 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
748 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
749 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
750 /// HTLC-Success/HTLC-Timeout transactions.
751 fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>)) {
752 // Most secp and related errors trying to create keys means we have no hope of constructing
753 // a spend transaction...so we return no transactions to broadcast
754 let mut txn_to_broadcast = Vec::new();
755 let mut watch_outputs = Vec::new();
757 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
758 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
760 macro_rules! ignore_error {
761 ( $thing : expr ) => {
764 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs))
769 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);
770 if commitment_number >= self.get_min_seen_secret() {
771 let secret = self.get_secret(commitment_number).unwrap();
772 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
773 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
774 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
775 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
776 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
777 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
779 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
780 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
781 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
782 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
785 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()));
786 let a_htlc_key = match self.their_htlc_base_key {
787 None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
788 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)),
791 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
792 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
794 let mut total_value = 0;
795 let mut values = Vec::new();
796 let mut inputs = Vec::new();
797 let mut htlc_idxs = Vec::new();
799 for (idx, outp) in tx.output.iter().enumerate() {
800 if outp.script_pubkey == revokeable_p2wsh {
802 previous_output: BitcoinOutPoint {
803 txid: commitment_txid,
806 script_sig: Script::new(),
807 sequence: 0xfffffffd,
810 htlc_idxs.push(None);
811 values.push(outp.value);
812 total_value += outp.value;
813 break; // There can only be one of these
817 macro_rules! sign_input {
818 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
820 let (sig, redeemscript) = match self.key_storage {
821 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
822 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
823 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()];
824 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
826 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
827 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
828 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
830 KeyStorage::SigsMode { .. } => {
834 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
835 $input.witness[0].push(SigHashType::All as u8);
836 if $htlc_idx.is_none() {
837 $input.witness.push(vec!(1));
839 $input.witness.push(revocation_pubkey.serialize().to_vec());
841 $input.witness.push(redeemscript.into_bytes());
846 if let Some(per_commitment_data) = per_commitment_option {
847 inputs.reserve_exact(per_commitment_data.len());
849 for (idx, htlc) in per_commitment_data.iter().enumerate() {
850 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
851 if htlc.transaction_output_index as usize >= tx.output.len() ||
852 tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
853 tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
854 return (txn_to_broadcast, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
857 previous_output: BitcoinOutPoint {
858 txid: commitment_txid,
859 vout: htlc.transaction_output_index,
861 script_sig: Script::new(),
862 sequence: 0xfffffffd,
865 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
867 htlc_idxs.push(Some(idx));
868 values.push(tx.output[htlc.transaction_output_index as usize].value);
869 total_value += htlc.amount_msat / 1000;
871 let mut single_htlc_tx = Transaction {
876 script_pubkey: self.destination_script.clone(),
877 value: htlc.amount_msat / 1000, //TODO: - fee
880 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
881 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
882 txn_to_broadcast.push(single_htlc_tx);
887 if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
888 // We're definitely a remote commitment transaction!
889 watch_outputs.append(&mut tx.output.clone());
890 self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
892 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
894 let outputs = vec!(TxOut {
895 script_pubkey: self.destination_script.clone(),
896 value: total_value, //TODO: - fee
898 let mut spend_tx = Transaction {
905 let mut values_drain = values.drain(..);
906 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
908 for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
909 let value = values_drain.next().unwrap();
910 sign_input!(sighash_parts, input, htlc_idx, value);
913 txn_to_broadcast.push(spend_tx);
914 } else if let Some(per_commitment_data) = per_commitment_option {
915 // While this isn't useful yet, there is a potential race where if a counterparty
916 // revokes a state at the same time as the commitment transaction for that state is
917 // confirmed, and the watchtower receives the block before the user, the user could
918 // upload a new ChannelMonitor with the revocation secret but the watchtower has
919 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
920 // not being generated by the above conditional. Thus, to be safe, we go ahead and
922 watch_outputs.append(&mut tx.output.clone());
923 self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
925 if let Some(revocation_points) = self.their_cur_revocation_points {
926 let revocation_point_option =
927 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
928 else if let Some(point) = revocation_points.2.as_ref() {
929 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
931 if let Some(revocation_point) = revocation_point_option {
932 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
933 KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
934 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
935 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
937 KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
938 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
939 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
942 let a_htlc_key = match self.their_htlc_base_key {
943 None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
944 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
947 let mut total_value = 0;
948 let mut values = Vec::new();
949 let mut inputs = Vec::new();
951 macro_rules! sign_input {
952 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
954 let (sig, redeemscript) = match self.key_storage {
955 KeyStorage::PrivMode { ref htlc_base_key, .. } => {
956 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize];
957 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
958 let sighash = ignore_error!(Message::from_slice(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]));
959 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
960 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
962 KeyStorage::SigsMode { .. } => {
966 $input.witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
967 $input.witness[0].push(SigHashType::All as u8);
968 $input.witness.push($preimage);
969 $input.witness.push(redeemscript.into_bytes());
974 for (idx, htlc) in per_commitment_data.iter().enumerate() {
975 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
977 previous_output: BitcoinOutPoint {
978 txid: commitment_txid,
979 vout: htlc.transaction_output_index,
981 script_sig: Script::new(),
982 sequence: idx as u32, // reset to 0xfffffffd in sign_input
985 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
987 values.push((tx.output[htlc.transaction_output_index as usize].value, payment_preimage));
988 total_value += htlc.amount_msat / 1000;
990 let mut single_htlc_tx = Transaction {
995 script_pubkey: self.destination_script.clone(),
996 value: htlc.amount_msat / 1000, //TODO: - fee
999 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1000 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.to_vec());
1001 txn_to_broadcast.push(single_htlc_tx);
1006 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
1008 let outputs = vec!(TxOut {
1009 script_pubkey: self.destination_script.clone(),
1010 value: total_value, //TODO: - fee
1012 let mut spend_tx = Transaction {
1019 let mut values_drain = values.drain(..);
1020 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1022 for input in spend_tx.input.iter_mut() {
1023 let value = values_drain.next().unwrap();
1024 sign_input!(sighash_parts, input, value.0, value.1.to_vec());
1027 txn_to_broadcast.push(spend_tx);
1032 (txn_to_broadcast, (commitment_txid, watch_outputs))
1035 /// Attempst to claim a remote HTLC-Success/HTLC-Timeout s outputs using the revocation key
1036 fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64) -> Option<Transaction> {
1037 if tx.input.len() != 1 || tx.output.len() != 1 {
1041 macro_rules! ignore_error {
1042 ( $thing : expr ) => {
1045 Err(_) => return None
1050 let secret = ignore_error!(self.get_secret(commitment_number));
1051 let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
1052 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1053 let revocation_pubkey = match self.key_storage {
1054 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1055 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1057 KeyStorage::SigsMode { ref revocation_base_key, .. } => {
1058 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1061 let delayed_key = match self.their_delayed_payment_base_key {
1062 None => return None,
1063 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1065 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1066 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1067 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1069 let mut inputs = Vec::new();
1072 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1074 previous_output: BitcoinOutPoint {
1078 script_sig: Script::new(),
1079 sequence: 0xfffffffd,
1080 witness: Vec::new(),
1082 amount = tx.output[0].value;
1085 if !inputs.is_empty() {
1086 let outputs = vec!(TxOut {
1087 script_pubkey: self.destination_script.clone(),
1088 value: amount, //TODO: - fee
1091 let mut spend_tx = Transaction {
1098 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1100 let sig = match self.key_storage {
1101 KeyStorage::PrivMode { ref revocation_base_key, .. } => {
1102 let sighash = ignore_error!(Message::from_slice(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]));
1103 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1104 self.secp_ctx.sign(&sighash, &revocation_key)
1106 KeyStorage::SigsMode { .. } => {
1110 spend_tx.input[0].witness.push(sig.serialize_der(&self.secp_ctx).to_vec());
1111 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1112 spend_tx.input[0].witness.push(vec!(1));
1113 spend_tx.input[0].witness.push(redeemscript.into_bytes());
1119 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
1120 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1122 for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
1124 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);
1126 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1128 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1129 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1130 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1131 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1133 htlc_timeout_tx.input[0].witness.push(Vec::new());
1134 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());
1136 res.push(htlc_timeout_tx);
1138 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1139 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);
1141 htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1143 htlc_success_tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec());
1144 htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1145 htlc_success_tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec());
1146 htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1148 htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
1149 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());
1151 res.push(htlc_success_tx);
1159 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1160 /// revoked using data in local_claimable_outpoints.
1161 /// Should not be used if check_spend_revoked_transaction succeeds.
1162 fn check_spend_local_transaction(&self, tx: &Transaction, _height: u32) -> Vec<Transaction> {
1163 let commitment_txid = tx.txid();
1164 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1165 if local_tx.txid == commitment_txid {
1166 return self.broadcast_by_local_state(local_tx);
1169 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1170 if local_tx.txid == commitment_txid {
1171 return self.broadcast_by_local_state(local_tx);
1177 fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface)-> Vec<(Sha256dHash, Vec<TxOut>)> {
1178 let mut watch_outputs = Vec::new();
1179 for tx in txn_matched {
1180 if tx.input.len() == 1 {
1181 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1182 // commitment transactions and HTLC transactions will all only ever have one input,
1183 // which is an easy way to filter out any potential non-matching txn for lazy
1185 let prevout = &tx.input[0].previous_output;
1186 let mut txn: Vec<Transaction> = Vec::new();
1187 if self.funding_txo.is_none() || (prevout.txid == self.funding_txo.as_ref().unwrap().0.txid && prevout.vout == self.funding_txo.as_ref().unwrap().0.index as u32) {
1188 let (remote_txn, new_outputs) = self.check_spend_remote_transaction(tx, height);
1190 if !new_outputs.1.is_empty() {
1191 watch_outputs.push(new_outputs);
1194 txn = self.check_spend_local_transaction(tx, height);
1197 let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
1198 if let Some(commitment_number) = remote_commitment_txn_on_chain.get(&prevout.txid) {
1199 if let Some(tx) = self.check_spend_remote_htlc(tx, *commitment_number) {
1204 for tx in txn.iter() {
1205 broadcaster.broadcast_transaction(tx);
1209 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1210 if self.would_broadcast_at_height(height) {
1211 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1212 for tx in self.broadcast_by_local_state(&cur_local_tx) {
1213 broadcaster.broadcast_transaction(&tx);
1220 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
1221 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1222 for &(ref htlc, _, _) in cur_local_tx.htlc_outputs.iter() {
1223 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
1224 // chain with enough room to claim the HTLC without our counterparty being able to
1225 // time out the HTLC first.
1226 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
1227 // concern is being able to claim the corresponding inbound HTLC (on another
1228 // channel) before it expires. In fact, we don't even really care if our
1229 // counterparty here claims such an outbound HTLC after it expired as long as we
1230 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
1231 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
1232 // we give ourselves a few blocks of headroom after expiration before going
1233 // on-chain for an expired HTLC.
1234 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
1235 // from us until we've reached the point where we go on-chain with the
1236 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
1237 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
1238 // aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
1239 // inbound_cltv == height + CLTV_CLAIM_BUFFER
1240 // outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFER <= inbound_cltv - CLTV_CLAIM_BUFFER
1241 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= inbound_cltv - outbound_cltv
1242 // HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFER <= CLTV_EXPIRY_DELTA
1243 if ( htlc.offered && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
1244 (!htlc.offered && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
1253 impl<R: ::std::io::Read> Readable<R> for ChannelMonitor {
1254 fn read(reader: &mut R) -> Result<Self, DecodeError> {
1255 // TODO: read_to_end and then deserializing from that vector is really dumb, we should
1256 // actually use the fancy serialization framework we have instead of hacking around it.
1257 let mut datavec = Vec::new();
1258 reader.read_to_end(&mut datavec)?;
1259 let data = &datavec;
1261 let mut read_pos = 0;
1262 macro_rules! read_bytes {
1263 ($byte_count: expr) => {
1265 if ($byte_count as usize) > data.len() - read_pos {
1266 return Err(DecodeError::ShortRead);
1268 read_pos += $byte_count as usize;
1269 &data[read_pos - $byte_count as usize..read_pos]
1274 let secp_ctx = Secp256k1::new();
1275 macro_rules! unwrap_obj {
1279 Err(_) => return Err(DecodeError::InvalidValue),
1284 let _ver = read_bytes!(1)[0];
1285 let min_ver = read_bytes!(1)[0];
1286 if min_ver > SERIALIZATION_VERSION {
1287 return Err(DecodeError::UnknownVersion);
1290 // Technically this can fail and serialize fail a round-trip, but only for serialization of
1291 // barely-init'd ChannelMonitors that we can't do anything with.
1292 let outpoint = OutPoint {
1293 txid: Sha256dHash::from(read_bytes!(32)),
1294 index: byte_utils::slice_to_be16(read_bytes!(2)),
1296 let script_len = byte_utils::slice_to_be64(read_bytes!(8));
1297 let funding_txo = Some((outpoint, Script::from(read_bytes!(script_len).to_vec())));
1298 let commitment_transaction_number_obscure_factor = byte_utils::slice_to_be48(read_bytes!(6));
1300 let key_storage = match read_bytes!(1)[0] {
1302 KeyStorage::PrivMode {
1303 revocation_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
1304 htlc_base_key: unwrap_obj!(SecretKey::from_slice(&secp_ctx, read_bytes!(32))),
1307 _ => return Err(DecodeError::InvalidValue),
1310 let delayed_payment_base_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1311 let their_htlc_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
1312 let their_delayed_payment_base_key = Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33))));
1314 let their_cur_revocation_points = {
1315 let first_idx = byte_utils::slice_to_be48(read_bytes!(6));
1319 let first_point = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1320 let second_point_slice = read_bytes!(33);
1321 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
1322 Some((first_idx, first_point, None))
1324 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&secp_ctx, second_point_slice)))))
1329 let our_to_self_delay = byte_utils::slice_to_be16(read_bytes!(2));
1330 let their_to_self_delay = Some(byte_utils::slice_to_be16(read_bytes!(2)));
1332 let mut old_secrets = [([0; 32], 1 << 48); 49];
1333 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
1334 secret.copy_from_slice(read_bytes!(32));
1335 *idx = byte_utils::slice_to_be64(read_bytes!(8));
1338 macro_rules! read_htlc_in_commitment {
1341 let offered = match read_bytes!(1)[0] {
1342 0 => false, 1 => true,
1343 _ => return Err(DecodeError::InvalidValue),
1345 let amount_msat = byte_utils::slice_to_be64(read_bytes!(8));
1346 let cltv_expiry = byte_utils::slice_to_be32(read_bytes!(4));
1347 let mut payment_hash = [0; 32];
1348 payment_hash[..].copy_from_slice(read_bytes!(32));
1349 let transaction_output_index = byte_utils::slice_to_be32(read_bytes!(4));
1351 HTLCOutputInCommitment {
1352 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
1358 let remote_claimable_outpoints_len = byte_utils::slice_to_be64(read_bytes!(8));
1359 if remote_claimable_outpoints_len > data.len() as u64 / 64 { return Err(DecodeError::BadLengthDescriptor); }
1360 let mut remote_claimable_outpoints = HashMap::with_capacity(remote_claimable_outpoints_len as usize);
1361 for _ in 0..remote_claimable_outpoints_len {
1362 let txid = Sha256dHash::from(read_bytes!(32));
1363 let outputs_count = byte_utils::slice_to_be64(read_bytes!(8));
1364 if outputs_count > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1365 let mut outputs = Vec::with_capacity(outputs_count as usize);
1366 for _ in 0..outputs_count {
1367 outputs.push(read_htlc_in_commitment!());
1369 if let Some(_) = remote_claimable_outpoints.insert(txid, outputs) {
1370 return Err(DecodeError::InvalidValue);
1374 let remote_commitment_txn_on_chain_len = byte_utils::slice_to_be64(read_bytes!(8));
1375 if remote_commitment_txn_on_chain_len > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1376 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(remote_commitment_txn_on_chain_len as usize);
1377 for _ in 0..remote_commitment_txn_on_chain_len {
1378 let txid = Sha256dHash::from(read_bytes!(32));
1379 let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
1380 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, commitment_number) {
1381 return Err(DecodeError::InvalidValue);
1385 let remote_hash_commitment_number_len = byte_utils::slice_to_be64(read_bytes!(8));
1386 if remote_hash_commitment_number_len > data.len() as u64 / 32 { return Err(DecodeError::BadLengthDescriptor); }
1387 let mut remote_hash_commitment_number = HashMap::with_capacity(remote_hash_commitment_number_len as usize);
1388 for _ in 0..remote_hash_commitment_number_len {
1389 let mut txid = [0; 32];
1390 txid[..].copy_from_slice(read_bytes!(32));
1391 let commitment_number = byte_utils::slice_to_be48(read_bytes!(6));
1392 if let Some(_) = remote_hash_commitment_number.insert(txid, commitment_number) {
1393 return Err(DecodeError::InvalidValue);
1397 macro_rules! read_local_tx {
1400 let tx_len = byte_utils::slice_to_be64(read_bytes!(8));
1401 let tx_ser = read_bytes!(tx_len);
1402 let tx: Transaction = unwrap_obj!(serialize::deserialize(tx_ser));
1403 if serialize::serialize(&tx).unwrap() != tx_ser {
1404 // We check that the tx re-serializes to the same form to ensure there is
1405 // no extra data, and as rust-bitcoin doesn't handle the 0-input ambiguity
1407 return Err(DecodeError::InvalidValue);
1410 let revocation_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1411 let a_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1412 let b_htlc_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1413 let delayed_payment_key = unwrap_obj!(PublicKey::from_slice(&secp_ctx, read_bytes!(33)));
1414 let feerate_per_kw = byte_utils::slice_to_be64(read_bytes!(8));
1416 let htlc_outputs_len = byte_utils::slice_to_be64(read_bytes!(8));
1417 if htlc_outputs_len > data.len() as u64 / 128 { return Err(DecodeError::BadLengthDescriptor); }
1418 let mut htlc_outputs = Vec::with_capacity(htlc_outputs_len as usize);
1419 for _ in 0..htlc_outputs_len {
1420 htlc_outputs.push((read_htlc_in_commitment!(),
1421 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64))),
1422 unwrap_obj!(Signature::from_compact(&secp_ctx, read_bytes!(64)))));
1427 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw, htlc_outputs
1433 let prev_local_signed_commitment_tx = match read_bytes!(1)[0] {
1436 Some(read_local_tx!())
1438 _ => return Err(DecodeError::InvalidValue),
1441 let current_local_signed_commitment_tx = match read_bytes!(1)[0] {
1444 Some(read_local_tx!())
1446 _ => return Err(DecodeError::InvalidValue),
1449 let payment_preimages_len = byte_utils::slice_to_be64(read_bytes!(8));
1450 if payment_preimages_len > data.len() as u64 / 32 { return Err(DecodeError::InvalidValue); }
1451 let mut payment_preimages = HashMap::with_capacity(payment_preimages_len as usize);
1452 let mut sha = Sha256::new();
1453 for _ in 0..payment_preimages_len {
1454 let mut preimage = [0; 32];
1455 preimage[..].copy_from_slice(read_bytes!(32));
1457 sha.input(&preimage);
1458 let mut hash = [0; 32];
1459 sha.result(&mut hash);
1460 if let Some(_) = payment_preimages.insert(hash, preimage) {
1461 return Err(DecodeError::InvalidValue);
1465 let destination_script_len = byte_utils::slice_to_be64(read_bytes!(8));
1466 let destination_script = Script::from(read_bytes!(destination_script_len).to_vec());
1470 commitment_transaction_number_obscure_factor,
1473 delayed_payment_base_key,
1474 their_htlc_base_key,
1475 their_delayed_payment_base_key,
1476 their_cur_revocation_points,
1479 their_to_self_delay,
1482 remote_claimable_outpoints,
1483 remote_commitment_txn_on_chain: Mutex::new(remote_commitment_txn_on_chain),
1484 remote_hash_commitment_number,
1486 prev_local_signed_commitment_tx,
1487 current_local_signed_commitment_tx,
1500 use bitcoin::blockdata::script::Script;
1501 use bitcoin::blockdata::transaction::Transaction;
1502 use crypto::digest::Digest;
1504 use ln::channelmonitor::ChannelMonitor;
1505 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
1506 use util::sha2::Sha256;
1507 use secp256k1::key::{SecretKey,PublicKey};
1508 use secp256k1::{Secp256k1, Signature};
1509 use rand::{thread_rng,Rng};
1512 fn test_per_commitment_storage() {
1513 // Test vectors from BOLT 3:
1514 let mut secrets: Vec<[u8; 32]> = Vec::new();
1515 let mut monitor: ChannelMonitor;
1516 let secp_ctx = Secp256k1::new();
1518 macro_rules! test_secrets {
1520 let mut idx = 281474976710655;
1521 for secret in secrets.iter() {
1522 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1525 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1526 assert!(monitor.get_secret(idx).is_err());
1530 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1533 // insert_secret correct sequence
1534 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1537 secrets.push([0; 32]);
1538 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1539 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1542 secrets.push([0; 32]);
1543 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1544 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1547 secrets.push([0; 32]);
1548 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1549 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1552 secrets.push([0; 32]);
1553 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1554 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1557 secrets.push([0; 32]);
1558 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1559 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1562 secrets.push([0; 32]);
1563 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1564 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1567 secrets.push([0; 32]);
1568 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1569 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1572 secrets.push([0; 32]);
1573 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1574 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
1579 // insert_secret #1 incorrect
1580 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1583 secrets.push([0; 32]);
1584 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1585 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1588 secrets.push([0; 32]);
1589 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1590 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
1591 "Previous secret did not match new one");
1595 // insert_secret #2 incorrect (#1 derived from incorrect)
1596 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1599 secrets.push([0; 32]);
1600 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1601 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1604 secrets.push([0; 32]);
1605 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1606 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1609 secrets.push([0; 32]);
1610 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1611 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1614 secrets.push([0; 32]);
1615 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1616 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1617 "Previous secret did not match new one");
1621 // insert_secret #3 incorrect
1622 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1625 secrets.push([0; 32]);
1626 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1627 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1630 secrets.push([0; 32]);
1631 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1632 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1635 secrets.push([0; 32]);
1636 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1637 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1640 secrets.push([0; 32]);
1641 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1642 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
1643 "Previous secret did not match new one");
1647 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1648 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1651 secrets.push([0; 32]);
1652 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1653 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1656 secrets.push([0; 32]);
1657 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1658 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1661 secrets.push([0; 32]);
1662 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1663 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1666 secrets.push([0; 32]);
1667 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1668 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1671 secrets.push([0; 32]);
1672 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1673 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1676 secrets.push([0; 32]);
1677 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1678 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1681 secrets.push([0; 32]);
1682 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1683 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1686 secrets.push([0; 32]);
1687 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1688 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1689 "Previous secret did not match new one");
1693 // insert_secret #5 incorrect
1694 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1697 secrets.push([0; 32]);
1698 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1699 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1702 secrets.push([0; 32]);
1703 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1704 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1707 secrets.push([0; 32]);
1708 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1709 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1712 secrets.push([0; 32]);
1713 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1714 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1717 secrets.push([0; 32]);
1718 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1719 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1722 secrets.push([0; 32]);
1723 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1724 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
1725 "Previous secret did not match new one");
1729 // insert_secret #6 incorrect (5 derived from incorrect)
1730 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1733 secrets.push([0; 32]);
1734 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1735 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1738 secrets.push([0; 32]);
1739 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1740 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1743 secrets.push([0; 32]);
1744 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1745 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1748 secrets.push([0; 32]);
1749 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1750 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1753 secrets.push([0; 32]);
1754 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1755 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1758 secrets.push([0; 32]);
1759 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1760 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1763 secrets.push([0; 32]);
1764 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1765 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1768 secrets.push([0; 32]);
1769 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1770 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1771 "Previous secret did not match new one");
1775 // insert_secret #7 incorrect
1776 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1779 secrets.push([0; 32]);
1780 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1781 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1784 secrets.push([0; 32]);
1785 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1786 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1789 secrets.push([0; 32]);
1790 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1791 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1794 secrets.push([0; 32]);
1795 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1796 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1799 secrets.push([0; 32]);
1800 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1801 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1804 secrets.push([0; 32]);
1805 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1806 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1809 secrets.push([0; 32]);
1810 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1811 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1814 secrets.push([0; 32]);
1815 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1816 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1817 "Previous secret did not match new one");
1821 // insert_secret #8 incorrect
1822 monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1825 secrets.push([0; 32]);
1826 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1827 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
1830 secrets.push([0; 32]);
1831 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1832 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
1835 secrets.push([0; 32]);
1836 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1837 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
1840 secrets.push([0; 32]);
1841 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1842 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
1845 secrets.push([0; 32]);
1846 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1847 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
1850 secrets.push([0; 32]);
1851 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1852 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
1855 secrets.push([0; 32]);
1856 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1857 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
1860 secrets.push([0; 32]);
1861 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1862 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
1863 "Previous secret did not match new one");
1868 fn test_prune_preimages() {
1869 let secp_ctx = Secp256k1::new();
1870 let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
1872 macro_rules! dummy_keys {
1875 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1877 per_commitment_point: dummy_key.clone(),
1878 revocation_key: dummy_key.clone(),
1879 a_htlc_key: dummy_key.clone(),
1880 b_htlc_key: dummy_key.clone(),
1881 a_delayed_payment_key: dummy_key.clone(),
1882 b_payment_key: dummy_key.clone(),
1887 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
1889 let mut preimages = Vec::new();
1891 let mut rng = thread_rng();
1893 let mut preimage = [0; 32];
1894 rng.fill_bytes(&mut preimage);
1895 let mut sha = Sha256::new();
1896 sha.input(&preimage);
1897 let mut hash = [0; 32];
1898 sha.result(&mut hash);
1899 preimages.push((preimage, hash));
1903 macro_rules! preimages_slice_to_htlc_outputs {
1904 ($preimages_slice: expr) => {
1906 let mut res = Vec::new();
1907 for (idx, preimage) in $preimages_slice.iter().enumerate() {
1908 res.push(HTLCOutputInCommitment {
1912 payment_hash: preimage.1.clone(),
1913 transaction_output_index: idx as u32,
1920 macro_rules! preimages_to_local_htlcs {
1921 ($preimages_slice: expr) => {
1923 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
1924 let res: Vec<_> = inp.drain(..).map(|e| { (e, dummy_sig.clone(), dummy_sig.clone()) }).collect();
1930 macro_rules! test_preimages_exist {
1931 ($preimages_slice: expr, $monitor: expr) => {
1932 for preimage in $preimages_slice {
1933 assert!($monitor.payment_preimages.contains_key(&preimage.1));
1938 // Prune with one old state and a local commitment tx holding a few overlaps with the
1940 let delayed_payment_base_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
1941 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &delayed_payment_base_key, &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), 0, Script::new());
1942 monitor.set_their_to_self_delay(10);
1944 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
1945 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
1946 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
1947 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
1948 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
1949 for &(ref preimage, ref hash) in preimages.iter() {
1950 monitor.provide_payment_preimage(hash, preimage);
1953 // Now provide a secret, pruning preimages 10-15
1954 let mut secret = [0; 32];
1955 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1956 monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
1957 assert_eq!(monitor.payment_preimages.len(), 15);
1958 test_preimages_exist!(&preimages[0..10], monitor);
1959 test_preimages_exist!(&preimages[15..20], monitor);
1961 // Now provide a further secret, pruning preimages 15-17
1962 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1963 monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
1964 assert_eq!(monitor.payment_preimages.len(), 13);
1965 test_preimages_exist!(&preimages[0..10], monitor);
1966 test_preimages_exist!(&preimages[17..20], monitor);
1968 // Now update local commitment tx info, pruning only element 18 as we still care about the
1969 // previous commitment tx's preimages too
1970 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
1971 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1972 monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
1973 assert_eq!(monitor.payment_preimages.len(), 12);
1974 test_preimages_exist!(&preimages[0..10], monitor);
1975 test_preimages_exist!(&preimages[18..20], monitor);
1977 // But if we do it again, we'll prune 5-10
1978 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
1979 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1980 monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
1981 assert_eq!(monitor.payment_preimages.len(), 5);
1982 test_preimages_exist!(&preimages[0..5], monitor);
1985 // Further testing is done in the ChannelManager integration tests.