2ddb2690ad8ed00de00090c7d3449b9397cba8f9
[rust-lightning] / src / ln / channelmonitor.rs
1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
2 //! here.
3 //!
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.
7 //!
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.
13
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode::{self, Decodable, Encodable};
20 use bitcoin::util::hash::BitcoinHash;
21 use bitcoin::util::bip143;
22
23 use bitcoin_hashes::Hash;
24 use bitcoin_hashes::sha256::Hash as Sha256;
25 use bitcoin_hashes::hash160::Hash as Hash160;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
27
28 use secp256k1::{Secp256k1,Signature};
29 use secp256k1::key::{SecretKey,PublicKey};
30 use secp256k1;
31
32 use ln::msgs::DecodeError;
33 use ln::chan_utils;
34 use ln::chan_utils::HTLCOutputInCommitment;
35 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
36 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
37 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget};
38 use chain::transaction::OutPoint;
39 use chain::keysinterface::SpendableOutputDescriptor;
40 use util::logger::Logger;
41 use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48};
42 use util::{byte_utils, events};
43
44 use std::collections::{HashMap, hash_map};
45 use std::sync::{Arc,Mutex};
46 use std::{hash,cmp, mem};
47
48 /// An error enum representing a failure to persist a channel monitor update.
49 #[derive(Clone)]
50 pub enum ChannelMonitorUpdateErr {
51         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
52         /// our state failed, but is expected to succeed at some point in the future).
53         ///
54         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
55         /// submitting new commitment transactions to the remote party.
56         /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
57         /// the channel to an operational state.
58         ///
59         /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
60         /// persisted is unsafe - if you failed to store the update on your own local disk you should
61         /// instead return PermanentFailure to force closure of the channel ASAP.
62         ///
63         /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
64         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
65         /// to claim it on this channel) and those updates must be applied wherever they can be. At
66         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
67         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
68         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
69         /// been "frozen".
70         ///
71         /// Note that even if updates made after TemporaryFailure succeed you must still call
72         /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
73         /// channel operation.
74         ///
75         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
76         /// remote location (with local copies persisted immediately), it is anticipated that all
77         /// updates will return TemporaryFailure until the remote copies could be updated.
78         TemporaryFailure,
79         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
80         /// different watchtower and cannot update with all watchtowers that were previously informed
81         /// of this channel). This will force-close the channel in question.
82         ///
83         /// Should also be used to indicate a failure to update the local copy of the channel monitor.
84         PermanentFailure,
85 }
86
87 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
88 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
89 /// means you tried to merge two monitors for different channels or for a channel which was
90 /// restored from a backup and then generated new commitment updates.
91 /// Contains a human-readable error message.
92 #[derive(Debug)]
93 pub struct MonitorUpdateError(pub &'static str);
94
95 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
96 /// forward channel and from which info are needed to update HTLC in a backward channel.
97 pub struct HTLCUpdate {
98         pub(super) payment_hash: PaymentHash,
99         pub(super) payment_preimage: Option<PaymentPreimage>,
100         pub(super) source: HTLCSource
101 }
102
103 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
104 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
105 /// events to it, while also taking any add_update_monitor events and passing them to some remote
106 /// server(s).
107 ///
108 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
109 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
110 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
111 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
112 pub trait ManyChannelMonitor: Send + Sync {
113         /// Adds or updates a monitor for the given `funding_txo`.
114         ///
115         /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
116         /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
117         /// any spends of it.
118         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
119
120         /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
121         /// with success or failure backward
122         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate>;
123 }
124
125 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
126 /// watchtower or watch our own channels.
127 ///
128 /// Note that you must provide your own key by which to refer to channels.
129 ///
130 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
131 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
132 /// index by a PublicKey which is required to sign any updates.
133 ///
134 /// If you're using this for local monitoring of your own channels, you probably want to use
135 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
136 pub struct SimpleManyChannelMonitor<Key> {
137         #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
138         pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
139         #[cfg(not(test))]
140         monitors: Mutex<HashMap<Key, ChannelMonitor>>,
141         chain_monitor: Arc<ChainWatchInterface>,
142         broadcaster: Arc<BroadcasterInterface>,
143         pending_events: Mutex<Vec<events::Event>>,
144         pending_htlc_updated: Mutex<HashMap<PaymentHash, Vec<(HTLCSource, Option<PaymentPreimage>)>>>,
145         logger: Arc<Logger>,
146         fee_estimator: Arc<FeeEstimator>
147 }
148
149 impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
150         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
151                 let block_hash = header.bitcoin_hash();
152                 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
153                 let mut htlc_updated_infos = Vec::new();
154                 {
155                         let mut monitors = self.monitors.lock().unwrap();
156                         for monitor in monitors.values_mut() {
157                                 let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
158                                 if spendable_outputs.len() > 0 {
159                                         new_events.push(events::Event::SpendableOutputs {
160                                                 outputs: spendable_outputs,
161                                         });
162                                 }
163
164                                 for (ref txid, ref outputs) in txn_outputs {
165                                         for (idx, output) in outputs.iter().enumerate() {
166                                                 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
167                                         }
168                                 }
169                                 htlc_updated_infos.append(&mut htlc_updated);
170                         }
171                 }
172                 {
173                         // ChannelManager will just need to fetch pending_htlc_updated and pass state backward
174                         let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap();
175                         for htlc in htlc_updated_infos.drain(..) {
176                                 match pending_htlc_updated.entry(htlc.2) {
177                                         hash_map::Entry::Occupied(mut e) => {
178                                                 // In case of reorg we may have htlc outputs solved in a different way so
179                                                 // we prefer to keep claims but don't store duplicate updates for a given
180                                                 // (payment_hash, HTLCSource) pair.
181                                                 let mut existing_claim = false;
182                                                 e.get_mut().retain(|htlc_data| {
183                                                         if htlc.0 == htlc_data.0 {
184                                                                 if htlc_data.1.is_some() {
185                                                                         existing_claim = true;
186                                                                         true
187                                                                 } else { false }
188                                                         } else { true }
189                                                 });
190                                                 if !existing_claim {
191                                                         e.get_mut().push((htlc.0, htlc.1));
192                                                 }
193                                         }
194                                         hash_map::Entry::Vacant(e) => {
195                                                 e.insert(vec![(htlc.0, htlc.1)]);
196                                         }
197                                 }
198                         }
199                 }
200                 let mut pending_events = self.pending_events.lock().unwrap();
201                 pending_events.append(&mut new_events);
202         }
203
204         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
205                 let block_hash = header.bitcoin_hash();
206                 let mut monitors = self.monitors.lock().unwrap();
207                 for monitor in monitors.values_mut() {
208                         monitor.block_disconnected(disconnected_height, &block_hash);
209                 }
210         }
211 }
212
213 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
214         /// Creates a new object which can be used to monitor several channels given the chain
215         /// interface with which to register to receive notifications.
216         pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> Arc<SimpleManyChannelMonitor<Key>> {
217                 let res = Arc::new(SimpleManyChannelMonitor {
218                         monitors: Mutex::new(HashMap::new()),
219                         chain_monitor,
220                         broadcaster,
221                         pending_events: Mutex::new(Vec::new()),
222                         pending_htlc_updated: Mutex::new(HashMap::new()),
223                         logger,
224                         fee_estimator: feeest,
225                 });
226                 let weak_res = Arc::downgrade(&res);
227                 res.chain_monitor.register_listener(weak_res);
228                 res
229         }
230
231         /// Adds or updates the monitor which monitors the channel referred to by the given key.
232         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
233                 let mut monitors = self.monitors.lock().unwrap();
234                 match monitors.get_mut(&key) {
235                         Some(orig_monitor) => {
236                                 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
237                                 return orig_monitor.insert_combine(monitor);
238                         },
239                         None => {}
240                 };
241                 match monitor.key_storage {
242                         Storage::Local { ref funding_info, .. } => {
243                                 match funding_info {
244                                         &None => {
245                                                 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
246                                         },
247                                         &Some((ref outpoint, ref script)) => {
248                                                 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
249                                                 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
250                                                 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
251                                         },
252                                 }
253                         },
254                         Storage::Watchtower { .. } => {
255                                 self.chain_monitor.watch_all_txn();
256                         }
257                 }
258                 monitors.insert(key, monitor);
259                 Ok(())
260         }
261 }
262
263 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
264         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
265                 match self.add_update_monitor_by_key(funding_txo, monitor) {
266                         Ok(_) => Ok(()),
267                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
268                 }
269         }
270
271         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
272                 let mut updated = self.pending_htlc_updated.lock().unwrap();
273                 let mut pending_htlcs_updated = Vec::with_capacity(updated.len());
274                 for (k, v) in updated.drain() {
275                         for htlc_data in v {
276                                 pending_htlcs_updated.push(HTLCUpdate {
277                                         payment_hash: k,
278                                         payment_preimage: htlc_data.1,
279                                         source: htlc_data.0,
280                                 });
281                         }
282                 }
283                 pending_htlcs_updated
284         }
285 }
286
287 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
288         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
289                 let mut pending_events = self.pending_events.lock().unwrap();
290                 let mut ret = Vec::new();
291                 mem::swap(&mut ret, &mut *pending_events);
292                 ret
293         }
294 }
295
296 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
297 /// instead claiming it in its own individual transaction.
298 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
299 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
300 /// HTLC-Success transaction.
301 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
302 /// transaction confirmed (and we use it in a few more, equivalent, places).
303 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
304 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
305 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
306 /// copies of ChannelMonitors, including watchtowers).
307 pub(crate) const HTLC_FAIL_TIMEOUT_BLOCKS: u32 = 3;
308 /// Number of blocks we wait on seeing a confirmed HTLC-Timeout or previous revoked commitment
309 /// transaction before we fail corresponding inbound HTLCs. This prevents us from failing backwards
310 /// and then getting a reorg resulting in us losing money.
311 pub(crate) const HTLC_FAIL_ANTI_REORG_DELAY: u32 = 6;
312
313 #[derive(Clone, PartialEq)]
314 enum Storage {
315         Local {
316                 revocation_base_key: SecretKey,
317                 htlc_base_key: SecretKey,
318                 delayed_payment_base_key: SecretKey,
319                 payment_base_key: SecretKey,
320                 shutdown_pubkey: PublicKey,
321                 prev_latest_per_commitment_point: Option<PublicKey>,
322                 latest_per_commitment_point: Option<PublicKey>,
323                 funding_info: Option<(OutPoint, Script)>,
324                 current_remote_commitment_txid: Option<Sha256dHash>,
325                 prev_remote_commitment_txid: Option<Sha256dHash>,
326         },
327         Watchtower {
328                 revocation_base_key: PublicKey,
329                 htlc_base_key: PublicKey,
330         }
331 }
332
333 #[derive(Clone, PartialEq)]
334 struct LocalSignedTx {
335         /// txid of the transaction in tx, just used to make comparison faster
336         txid: Sha256dHash,
337         tx: Transaction,
338         revocation_key: PublicKey,
339         a_htlc_key: PublicKey,
340         b_htlc_key: PublicKey,
341         delayed_payment_key: PublicKey,
342         feerate_per_kw: u64,
343         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option<HTLCSource>)>,
344 }
345
346 #[derive(PartialEq)]
347 enum InputDescriptors {
348         RevokedOfferedHTLC,
349         RevokedReceivedHTLC,
350         OfferedHTLC,
351         ReceivedHTLC,
352         RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
353 }
354
355 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
356 /// once they mature to enough confirmations (HTLC_FAIL_ANTI_REORG_DELAY)
357 #[derive(Clone, PartialEq)]
358 enum OnchainEvent {
359         /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
360         /// bump-txn candidate buffer.
361         Claim {
362                 outpoint: BitcoinOutPoint,
363         },
364         /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
365         /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
366         /// only win from it, so it's never an OnchainEvent
367         HTLCUpdate {
368                 htlc_update: (HTLCSource, PaymentHash),
369         },
370 }
371
372 const SERIALIZATION_VERSION: u8 = 1;
373 const MIN_SERIALIZATION_VERSION: u8 = 1;
374
375 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
376 /// on-chain transactions to ensure no loss of funds occurs.
377 ///
378 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
379 /// information and are actively monitoring the chain.
380 #[derive(Clone)]
381 pub struct ChannelMonitor {
382         commitment_transaction_number_obscure_factor: u64,
383
384         key_storage: Storage,
385         their_htlc_base_key: Option<PublicKey>,
386         their_delayed_payment_base_key: Option<PublicKey>,
387         // first is the idx of the first of the two revocation points
388         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
389
390         our_to_self_delay: u16,
391         their_to_self_delay: Option<u16>,
392
393         old_secrets: [([u8; 32], u64); 49],
394         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
395         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
396         /// Nor can we figure out their commitment numbers without the commitment transaction they are
397         /// spending. Thus, in order to claim them via revocation key, we track all the remote
398         /// commitment transactions which we find on-chain, mapping them to the commitment number which
399         /// can be used to derive the revocation key and claim the transactions.
400         remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
401         /// Cache used to make pruning of payment_preimages faster.
402         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
403         /// remote transactions (ie should remain pretty small).
404         /// Serialized to disk but should generally not be sent to Watchtowers.
405         remote_hash_commitment_number: HashMap<PaymentHash, u64>,
406
407         // We store two local commitment transactions to avoid any race conditions where we may update
408         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
409         // various monitors for one channel being out of sync, and us broadcasting a local
410         // transaction for which we have deleted claim information on some watchtowers.
411         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
412         current_local_signed_commitment_tx: Option<LocalSignedTx>,
413
414         // Used just for ChannelManager to make sure it has the latest channel data during
415         // deserialization
416         current_remote_commitment_number: u64,
417
418         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
419
420         destination_script: Script,
421
422         // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
423         // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
424         // actions when we receive a block with given height. Actions depend on OnchainEvent type.
425         onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
426
427         // We simply modify last_block_hash in Channel's block_connected so that serialization is
428         // consistent but hopefully the users' copy handles block_connected in a consistent way.
429         // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
430         // their last_block_hash from its state and not based on updated copies that didn't run through
431         // the full block_connected).
432         pub(crate) last_block_hash: Sha256dHash,
433         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
434         logger: Arc<Logger>,
435 }
436
437 macro_rules! subtract_high_prio_fee {
438         ($self: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $spent_txid: expr) => {
439                 {
440                         let mut fee = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) * $predicted_weight / 1000;
441                         if $value <= fee {
442                                 fee = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) * $predicted_weight / 1000;
443                                 if $value <= fee {
444                                         fee = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background) * $predicted_weight / 1000;
445                                         if $value <= fee {
446                                                 log_error!($self, "Failed to generate an on-chain punishment tx spending {} as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
447                                                         $spent_txid, fee, $value);
448                                                 false
449                                         } else {
450                                                 log_warn!($self, "Used low priority fee for on-chain punishment tx spending {} as high priority fee was more than the entire claim balance ({} sat)",
451                                                         $spent_txid, $value);
452                                                 $value -= fee;
453                                                 true
454                                         }
455                                 } else {
456                                         log_warn!($self, "Used medium priority fee for on-chain punishment tx spending {} as high priority fee was more than the entire claim balance ({} sat)",
457                                                 $spent_txid, $value);
458                                         $value -= fee;
459                                         true
460                                 }
461                         } else {
462                                 $value -= fee;
463                                 true
464                         }
465                 }
466         }
467 }
468
469 #[cfg(any(test, feature = "fuzztarget"))]
470 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
471 /// underlying object
472 impl PartialEq for ChannelMonitor {
473         fn eq(&self, other: &Self) -> bool {
474                 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
475                         self.key_storage != other.key_storage ||
476                         self.their_htlc_base_key != other.their_htlc_base_key ||
477                         self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
478                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
479                         self.our_to_self_delay != other.our_to_self_delay ||
480                         self.their_to_self_delay != other.their_to_self_delay ||
481                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
482                         self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
483                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
484                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
485                         self.current_remote_commitment_number != other.current_remote_commitment_number ||
486                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
487                         self.payment_preimages != other.payment_preimages ||
488                         self.destination_script != other.destination_script ||
489                         self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf
490                 {
491                         false
492                 } else {
493                         for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
494                                 if secret != o_secret || idx != o_idx {
495                                         return false
496                                 }
497                         }
498                         true
499                 }
500         }
501 }
502
503 impl ChannelMonitor {
504         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 {
505                 ChannelMonitor {
506                         commitment_transaction_number_obscure_factor: 0,
507
508                         key_storage: Storage::Local {
509                                 revocation_base_key: revocation_base_key.clone(),
510                                 htlc_base_key: htlc_base_key.clone(),
511                                 delayed_payment_base_key: delayed_payment_base_key.clone(),
512                                 payment_base_key: payment_base_key.clone(),
513                                 shutdown_pubkey: shutdown_pubkey.clone(),
514                                 prev_latest_per_commitment_point: None,
515                                 latest_per_commitment_point: None,
516                                 funding_info: None,
517                                 current_remote_commitment_txid: None,
518                                 prev_remote_commitment_txid: None,
519                         },
520                         their_htlc_base_key: None,
521                         their_delayed_payment_base_key: None,
522                         their_cur_revocation_points: None,
523
524                         our_to_self_delay: our_to_self_delay,
525                         their_to_self_delay: None,
526
527                         old_secrets: [([0; 32], 1 << 48); 49],
528                         remote_claimable_outpoints: HashMap::new(),
529                         remote_commitment_txn_on_chain: HashMap::new(),
530                         remote_hash_commitment_number: HashMap::new(),
531
532                         prev_local_signed_commitment_tx: None,
533                         current_local_signed_commitment_tx: None,
534                         current_remote_commitment_number: 1 << 48,
535
536                         payment_preimages: HashMap::new(),
537                         destination_script: destination_script,
538
539                         onchain_events_waiting_threshold_conf: HashMap::new(),
540
541                         last_block_hash: Default::default(),
542                         secp_ctx: Secp256k1::new(),
543                         logger,
544                 }
545         }
546
547         fn get_witnesses_weight(inputs: &[InputDescriptors]) -> u64 {
548                 let mut tx_weight = 2; // count segwit flags
549                 for inp in inputs {
550                         // We use expected weight (and not actual) as signatures and time lock delays may vary
551                         tx_weight +=  match inp {
552                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
553                                 &InputDescriptors::RevokedOfferedHTLC => {
554                                         1 + 1 + 73 + 1 + 33 + 1 + 133
555                                 },
556                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
557                                 &InputDescriptors::RevokedReceivedHTLC => {
558                                         1 + 1 + 73 + 1 + 33 + 1 + 139
559                                 },
560                                 // number_of_witness_elements + sig_length + remotehtlc_sig  + preimage_length + preimage + witness_script_length + witness_script
561                                 &InputDescriptors::OfferedHTLC => {
562                                         1 + 1 + 73 + 1 + 32 + 1 + 133
563                                 },
564                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
565                                 &InputDescriptors::ReceivedHTLC => {
566                                         1 + 1 + 73 + 1 + 1 + 1 + 139
567                                 },
568                                 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
569                                 &InputDescriptors::RevokedOutput => {
570                                         1 + 1 + 73 + 1 + 1 + 1 + 77
571                                 },
572                         };
573                 }
574                 tx_weight
575         }
576
577         #[inline]
578         fn place_secret(idx: u64) -> u8 {
579                 for i in 0..48 {
580                         if idx & (1 << i) == (1 << i) {
581                                 return i
582                         }
583                 }
584                 48
585         }
586
587         #[inline]
588         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
589                 let mut res: [u8; 32] = secret;
590                 for i in 0..bits {
591                         let bitpos = bits - 1 - i;
592                         if idx & (1 << bitpos) == (1 << bitpos) {
593                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
594                                 res = Sha256::hash(&res).into_inner();
595                         }
596                 }
597                 res
598         }
599
600         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
601         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
602         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
603         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
604                 let pos = ChannelMonitor::place_secret(idx);
605                 for i in 0..pos {
606                         let (old_secret, old_idx) = self.old_secrets[i as usize];
607                         if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
608                                 return Err(MonitorUpdateError("Previous secret did not match new one"));
609                         }
610                 }
611                 if self.get_min_seen_secret() <= idx {
612                         return Ok(());
613                 }
614                 self.old_secrets[pos as usize] = (secret, idx);
615
616                 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
617                 // events for now-revoked/fulfilled HTLCs.
618                 // TODO: We should probably consider whether we're really getting the next secret here.
619                 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
620                         if let Some(txid) = prev_remote_commitment_txid.take() {
621                                 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
622                                         *source = None;
623                                 }
624                         }
625                 }
626
627                 if !self.payment_preimages.is_empty() {
628                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
629                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
630                         let min_idx = self.get_min_seen_secret();
631                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
632
633                         self.payment_preimages.retain(|&k, _| {
634                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
635                                         if k == htlc.payment_hash {
636                                                 return true
637                                         }
638                                 }
639                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
640                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
641                                                 if k == htlc.payment_hash {
642                                                         return true
643                                                 }
644                                         }
645                                 }
646                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
647                                         if *cn < min_idx {
648                                                 return true
649                                         }
650                                         true
651                                 } else { false };
652                                 if contains {
653                                         remote_hash_commitment_number.remove(&k);
654                                 }
655                                 false
656                         });
657                 }
658
659                 Ok(())
660         }
661
662         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
663         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
664         /// possibly future revocation/preimage information) to claim outputs where possible.
665         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
666         pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey) {
667                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
668                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
669                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
670                 // timeouts)
671                 for &(ref htlc, _) in &htlc_outputs {
672                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
673                 }
674
675                 let new_txid = unsigned_commitment_tx.txid();
676                 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
677                 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
678                 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
679                         *prev_remote_commitment_txid = current_remote_commitment_txid.take();
680                         *current_remote_commitment_txid = Some(new_txid);
681                 }
682                 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
683                 self.current_remote_commitment_number = commitment_number;
684                 //TODO: Merge this into the other per-remote-transaction output storage stuff
685                 match self.their_cur_revocation_points {
686                         Some(old_points) => {
687                                 if old_points.0 == commitment_number + 1 {
688                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
689                                 } else if old_points.0 == commitment_number + 2 {
690                                         if let Some(old_second_point) = old_points.2 {
691                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
692                                         } else {
693                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
694                                         }
695                                 } else {
696                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
697                                 }
698                         },
699                         None => {
700                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
701                         }
702                 }
703         }
704
705         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
706         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
707         /// is important that any clones of this channel monitor (including remote clones) by kept
708         /// up-to-date as our local commitment transaction is updated.
709         /// Panics if set_their_to_self_delay has never been called.
710         /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
711         /// case of onchain HTLC tx
712         pub(super) fn provide_latest_local_commitment_tx_info(&mut self, signed_commitment_tx: Transaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option<HTLCSource>)>) {
713                 assert!(self.their_to_self_delay.is_some());
714                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
715                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
716                         txid: signed_commitment_tx.txid(),
717                         tx: signed_commitment_tx,
718                         revocation_key: local_keys.revocation_key,
719                         a_htlc_key: local_keys.a_htlc_key,
720                         b_htlc_key: local_keys.b_htlc_key,
721                         delayed_payment_key: local_keys.a_delayed_payment_key,
722                         feerate_per_kw,
723                         htlc_outputs,
724                 });
725
726                 if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
727                         *latest_per_commitment_point = Some(local_keys.per_commitment_point);
728                 } else {
729                         panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
730                 }
731         }
732
733         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
734         /// commitment_tx_infos which contain the payment hash have been revoked.
735         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
736                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
737         }
738
739         /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
740         /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
741         /// chain for new blocks/transactions.
742         pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
743                 match self.key_storage {
744                         Storage::Local { ref funding_info, .. } => {
745                                 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
746                                 let our_funding_info = funding_info;
747                                 if let Storage::Local { ref funding_info, .. } = other.key_storage {
748                                         if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
749                                         // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially
750                                         // easy to collide the funding_txo hash and have a different scriptPubKey.
751                                         if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
752                                                 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
753                                         }
754                                 } else {
755                                         return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
756                                 }
757                         },
758                         Storage::Watchtower { .. } => {
759                                 if let Storage::Watchtower { .. } = other.key_storage {
760                                         unimplemented!();
761                                 } else {
762                                         return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
763                                 }
764                         },
765                 }
766                 let other_min_secret = other.get_min_seen_secret();
767                 let our_min_secret = self.get_min_seen_secret();
768                 if our_min_secret > other_min_secret {
769                         self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
770                 }
771                 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
772                         if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
773                                 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);
774                                 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);
775                                 if our_commitment_number >= other_commitment_number {
776                                         self.key_storage = other.key_storage;
777                                 }
778                         }
779                 }
780                 // TODO: We should use current_remote_commitment_number and the commitment number out of
781                 // local transactions to decide how to merge
782                 if our_min_secret >= other_min_secret {
783                         self.their_cur_revocation_points = other.their_cur_revocation_points;
784                         for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
785                                 self.remote_claimable_outpoints.insert(txid, htlcs);
786                         }
787                         if let Some(local_tx) = other.prev_local_signed_commitment_tx {
788                                 self.prev_local_signed_commitment_tx = Some(local_tx);
789                         }
790                         if let Some(local_tx) = other.current_local_signed_commitment_tx {
791                                 self.current_local_signed_commitment_tx = Some(local_tx);
792                         }
793                         self.payment_preimages = other.payment_preimages;
794                 }
795
796                 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
797                 Ok(())
798         }
799
800         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
801         pub(super) fn set_commitment_obscure_factor(&mut self, commitment_transaction_number_obscure_factor: u64) {
802                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
803                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
804         }
805
806         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
807         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
808         /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
809         /// provides slightly better privacy.
810         /// It's the responsibility of the caller to register outpoint and script with passing the former
811         /// value as key to add_update_monitor.
812         pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
813                 match self.key_storage {
814                         Storage::Local { ref mut funding_info, .. } => {
815                                 *funding_info = Some(new_funding_info);
816                         },
817                         Storage::Watchtower { .. } => {
818                                 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
819                         }
820                 }
821         }
822
823         /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
824         pub(super) fn set_their_base_keys(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey) {
825                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
826                 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
827         }
828
829         pub(super) fn set_their_to_self_delay(&mut self, their_to_self_delay: u16) {
830                 self.their_to_self_delay = Some(their_to_self_delay);
831         }
832
833         pub(super) fn unset_funding_info(&mut self) {
834                 match self.key_storage {
835                         Storage::Local { ref mut funding_info, .. } => {
836                                 *funding_info = None;
837                         },
838                         Storage::Watchtower { .. } => {
839                                 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
840                         },
841                 }
842         }
843
844         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
845         pub fn get_funding_txo(&self) -> Option<OutPoint> {
846                 match self.key_storage {
847                         Storage::Local { ref funding_info, .. } => {
848                                 match funding_info {
849                                         &Some((outpoint, _)) => Some(outpoint),
850                                         &None => None
851                                 }
852                         },
853                         Storage::Watchtower { .. } => {
854                                 return None;
855                         }
856                 }
857         }
858
859         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
860         /// Generally useful when deserializing as during normal operation the return values of
861         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
862         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
863         pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
864                 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
865                 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
866                         for (idx, output) in outputs.iter().enumerate() {
867                                 res.push(((*txid).clone(), idx as u32, output));
868                         }
869                 }
870                 res
871         }
872
873         /// Serializes into a vec, with various modes for the exposed pub fns
874         fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
875                 //TODO: We still write out all the serialization here manually instead of using the fancy
876                 //serialization framework we have, we should migrate things over to it.
877                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
878                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
879
880                 // Set in initial Channel-object creation, so should always be set by now:
881                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
882
883                 macro_rules! write_option {
884                         ($thing: expr) => {
885                                 match $thing {
886                                         &Some(ref t) => {
887                                                 1u8.write(writer)?;
888                                                 t.write(writer)?;
889                                         },
890                                         &None => 0u8.write(writer)?,
891                                 }
892                         }
893                 }
894
895                 match self.key_storage {
896                         Storage::Local { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
897                                 writer.write_all(&[0; 1])?;
898                                 writer.write_all(&revocation_base_key[..])?;
899                                 writer.write_all(&htlc_base_key[..])?;
900                                 writer.write_all(&delayed_payment_base_key[..])?;
901                                 writer.write_all(&payment_base_key[..])?;
902                                 writer.write_all(&shutdown_pubkey.serialize())?;
903                                 prev_latest_per_commitment_point.write(writer)?;
904                                 latest_per_commitment_point.write(writer)?;
905                                 match funding_info  {
906                                         &Some((ref outpoint, ref script)) => {
907                                                 writer.write_all(&outpoint.txid[..])?;
908                                                 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
909                                                 script.write(writer)?;
910                                         },
911                                         &None => {
912                                                 debug_assert!(false, "Try to serialize a useless Local monitor !");
913                                         },
914                                 }
915                                 current_remote_commitment_txid.write(writer)?;
916                                 prev_remote_commitment_txid.write(writer)?;
917                         },
918                         Storage::Watchtower { .. } => unimplemented!(),
919                 }
920
921                 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
922                 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
923
924                 match self.their_cur_revocation_points {
925                         Some((idx, pubkey, second_option)) => {
926                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
927                                 writer.write_all(&pubkey.serialize())?;
928                                 match second_option {
929                                         Some(second_pubkey) => {
930                                                 writer.write_all(&second_pubkey.serialize())?;
931                                         },
932                                         None => {
933                                                 writer.write_all(&[0; 33])?;
934                                         },
935                                 }
936                         },
937                         None => {
938                                 writer.write_all(&byte_utils::be48_to_array(0))?;
939                         },
940                 }
941
942                 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
943                 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
944
945                 for &(ref secret, ref idx) in self.old_secrets.iter() {
946                         writer.write_all(secret)?;
947                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
948                 }
949
950                 macro_rules! serialize_htlc_in_commitment {
951                         ($htlc_output: expr) => {
952                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
953                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
954                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
955                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
956                                 $htlc_output.transaction_output_index.write(writer)?;
957                         }
958                 }
959
960                 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
961                 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
962                         writer.write_all(&txid[..])?;
963                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
964                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
965                                 serialize_htlc_in_commitment!(htlc_output);
966                                 write_option!(htlc_source);
967                         }
968                 }
969
970                 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
971                 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
972                         writer.write_all(&txid[..])?;
973                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
974                         (txouts.len() as u64).write(writer)?;
975                         for script in txouts.iter() {
976                                 script.write(writer)?;
977                         }
978                 }
979
980                 if for_local_storage {
981                         writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
982                         for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
983                                 writer.write_all(&payment_hash.0[..])?;
984                                 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
985                         }
986                 } else {
987                         writer.write_all(&byte_utils::be64_to_array(0))?;
988                 }
989
990                 macro_rules! serialize_local_tx {
991                         ($local_tx: expr) => {
992                                 if let Err(e) = $local_tx.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
993                                         match e {
994                                                 encode::Error::Io(e) => return Err(e),
995                                                 _ => panic!("local tx must have been well-formed!"),
996                                         }
997                                 }
998
999                                 writer.write_all(&$local_tx.revocation_key.serialize())?;
1000                                 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
1001                                 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
1002                                 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
1003
1004                                 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
1005                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
1006                                 for &(ref htlc_output, ref sigs, ref htlc_source) in $local_tx.htlc_outputs.iter() {
1007                                         serialize_htlc_in_commitment!(htlc_output);
1008                                         if let &Some((ref their_sig, ref our_sig)) = sigs {
1009                                                 1u8.write(writer)?;
1010                                                 writer.write_all(&their_sig.serialize_compact())?;
1011                                                 writer.write_all(&our_sig.serialize_compact())?;
1012                                         } else {
1013                                                 0u8.write(writer)?;
1014                                         }
1015                                         write_option!(htlc_source);
1016                                 }
1017                         }
1018                 }
1019
1020                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
1021                         writer.write_all(&[1; 1])?;
1022                         serialize_local_tx!(prev_local_tx);
1023                 } else {
1024                         writer.write_all(&[0; 1])?;
1025                 }
1026
1027                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1028                         writer.write_all(&[1; 1])?;
1029                         serialize_local_tx!(cur_local_tx);
1030                 } else {
1031                         writer.write_all(&[0; 1])?;
1032                 }
1033
1034                 if for_local_storage {
1035                         writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1036                 } else {
1037                         writer.write_all(&byte_utils::be48_to_array(0))?;
1038                 }
1039
1040                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1041                 for payment_preimage in self.payment_preimages.values() {
1042                         writer.write_all(&payment_preimage.0[..])?;
1043                 }
1044
1045                 self.last_block_hash.write(writer)?;
1046                 self.destination_script.write(writer)?;
1047
1048                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1049                 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1050                         writer.write_all(&byte_utils::be32_to_array(**target))?;
1051                         writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1052                         for ev in events.iter() {
1053                                 match *ev {
1054                                         OnchainEvent::Claim { ref outpoint } => {
1055                                                 writer.write_all(&[0; 1])?;
1056                                                 outpoint.write(writer)?;
1057                                         },
1058                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1059                                                 writer.write_all(&[1; 1])?;
1060                                                 htlc_update.0.write(writer)?;
1061                                                 htlc_update.1.write(writer)?;
1062                                         }
1063                                 }
1064                         }
1065                 }
1066
1067                 Ok(())
1068         }
1069
1070         /// Writes this monitor into the given writer, suitable for writing to disk.
1071         ///
1072         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1073         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1074         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1075         /// common block that appears on your best chain as well as on the chain which contains the
1076         /// last block hash returned) upon deserializing the object!
1077         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1078                 self.write(writer, true)
1079         }
1080
1081         /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1082         ///
1083         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1084         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1085         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1086         /// common block that appears on your best chain as well as on the chain which contains the
1087         /// last block hash returned) upon deserializing the object!
1088         pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1089                 self.write(writer, false)
1090         }
1091
1092         /// Can only fail if idx is < get_min_seen_secret
1093         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1094                 for i in 0..self.old_secrets.len() {
1095                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
1096                                 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
1097                         }
1098                 }
1099                 assert!(idx < self.get_min_seen_secret());
1100                 None
1101         }
1102
1103         pub(super) fn get_min_seen_secret(&self) -> u64 {
1104                 //TODO This can be optimized?
1105                 let mut min = 1 << 48;
1106                 for &(_, idx) in self.old_secrets.iter() {
1107                         if idx < min {
1108                                 min = idx;
1109                         }
1110                 }
1111                 min
1112         }
1113
1114         pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1115                 self.current_remote_commitment_number
1116         }
1117
1118         pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1119                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1120                         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)
1121                 } else { 0xffff_ffff_ffff }
1122         }
1123
1124         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1125         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1126         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1127         /// HTLC-Success/HTLC-Timeout transactions.
1128         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1129         /// revoked remote commitment tx
1130         fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32, fee_estimator: &FeeEstimator) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1131                 // Most secp and related errors trying to create keys means we have no hope of constructing
1132                 // a spend transaction...so we return no transactions to broadcast
1133                 let mut txn_to_broadcast = Vec::new();
1134                 let mut watch_outputs = Vec::new();
1135                 let mut spendable_outputs = Vec::new();
1136
1137                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1138                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1139
1140                 macro_rules! ignore_error {
1141                         ( $thing : expr ) => {
1142                                 match $thing {
1143                                         Ok(a) => a,
1144                                         Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1145                                 }
1146                         };
1147                 }
1148
1149                 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);
1150                 if commitment_number >= self.get_min_seen_secret() {
1151                         let secret = self.get_secret(commitment_number).unwrap();
1152                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1153                         let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1154                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1155                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1156                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1157                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1158                                         Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1159                                 },
1160                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1161                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1162                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1163                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1164                                         None)
1165                                 },
1166                         };
1167                         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()));
1168                         let a_htlc_key = match self.their_htlc_base_key {
1169                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1170                                 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)),
1171                         };
1172
1173                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1174                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1175
1176                         let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1177                                 // Note that the Network here is ignored as we immediately drop the address for the
1178                                 // script_pubkey version.
1179                                 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1180                                 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1181                         } else { None };
1182
1183                         let mut total_value = 0;
1184                         let mut values = Vec::new();
1185                         let mut inputs = Vec::new();
1186                         let mut htlc_idxs = Vec::new();
1187                         let mut input_descriptors = Vec::new();
1188
1189                         for (idx, outp) in tx.output.iter().enumerate() {
1190                                 if outp.script_pubkey == revokeable_p2wsh {
1191                                         inputs.push(TxIn {
1192                                                 previous_output: BitcoinOutPoint {
1193                                                         txid: commitment_txid,
1194                                                         vout: idx as u32,
1195                                                 },
1196                                                 script_sig: Script::new(),
1197                                                 sequence: 0xfffffffd,
1198                                                 witness: Vec::new(),
1199                                         });
1200                                         htlc_idxs.push(None);
1201                                         values.push(outp.value);
1202                                         total_value += outp.value;
1203                                         input_descriptors.push(InputDescriptors::RevokedOutput);
1204                                 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1205                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1206                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1207                                                 key: local_payment_key.unwrap(),
1208                                                 output: outp.clone(),
1209                                         });
1210                                 }
1211                         }
1212
1213                         macro_rules! sign_input {
1214                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1215                                         {
1216                                                 let (sig, redeemscript) = match self.key_storage {
1217                                                         Storage::Local { ref revocation_base_key, .. } => {
1218                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1219                                                                         let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1220                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1221                                                                 };
1222                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1223                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1224                                                                 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript)
1225                                                         },
1226                                                         Storage::Watchtower { .. } => {
1227                                                                 unimplemented!();
1228                                                         }
1229                                                 };
1230                                                 $input.witness.push(sig.serialize_der().to_vec());
1231                                                 $input.witness[0].push(SigHashType::All as u8);
1232                                                 if $htlc_idx.is_none() {
1233                                                         $input.witness.push(vec!(1));
1234                                                 } else {
1235                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
1236                                                 }
1237                                                 $input.witness.push(redeemscript.into_bytes());
1238                                         }
1239                                 }
1240                         }
1241
1242                         if let Some(ref per_commitment_data) = per_commitment_option {
1243                                 inputs.reserve_exact(per_commitment_data.len());
1244
1245                                 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1246                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1247                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1248                                                 if transaction_output_index as usize >= tx.output.len() ||
1249                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1250                                                                 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1251                                                         return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1252                                                 }
1253                                                 let input = TxIn {
1254                                                         previous_output: BitcoinOutPoint {
1255                                                                 txid: commitment_txid,
1256                                                                 vout: transaction_output_index,
1257                                                         },
1258                                                         script_sig: Script::new(),
1259                                                         sequence: 0xfffffffd,
1260                                                         witness: Vec::new(),
1261                                                 };
1262                                                 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1263                                                         inputs.push(input);
1264                                                         htlc_idxs.push(Some(idx));
1265                                                         values.push(tx.output[transaction_output_index as usize].value);
1266                                                         total_value += htlc.amount_msat / 1000;
1267                                                         input_descriptors.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1268                                                 } else {
1269                                                         let mut single_htlc_tx = Transaction {
1270                                                                 version: 2,
1271                                                                 lock_time: 0,
1272                                                                 input: vec![input],
1273                                                                 output: vec!(TxOut {
1274                                                                         script_pubkey: self.destination_script.clone(),
1275                                                                         value: htlc.amount_msat / 1000,
1276                                                                 }),
1277                                                         };
1278                                                         let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1279                                                         if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, tx.txid()) {
1280                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1281                                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1282                                                                 assert!(predicted_weight >= single_htlc_tx.get_weight());
1283                                                                 txn_to_broadcast.push(single_htlc_tx);
1284                                                         }
1285                                                 }
1286                                         }
1287                                 }
1288                         }
1289
1290                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1291                                 // We're definitely a remote commitment transaction!
1292                                 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());
1293                                 watch_outputs.append(&mut tx.output.clone());
1294                                 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1295
1296                                 macro_rules! check_htlc_fails {
1297                                         ($txid: expr, $commitment_tx: expr) => {
1298                                                 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1299                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1300                                                                 if let &Some(ref source) = source_option {
1301                                                                         log_info!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of revoked remote commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, height + HTLC_FAIL_ANTI_REORG_DELAY - 1);
1302                                                                         match self.onchain_events_waiting_threshold_conf.entry(height + HTLC_FAIL_ANTI_REORG_DELAY - 1) {
1303                                                                                 hash_map::Entry::Occupied(mut entry) => {
1304                                                                                         let e = entry.get_mut();
1305                                                                                         e.retain(|ref event| {
1306                                                                                                 match **event {
1307                                                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1308                                                                                                                 return htlc_update.0 != **source
1309                                                                                                         },
1310                                                                                                         _ => return true
1311                                                                                                 }
1312                                                                                         });
1313                                                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1314                                                                                 }
1315                                                                                 hash_map::Entry::Vacant(entry) => {
1316                                                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1317                                                                                 }
1318                                                                         }
1319                                                                 }
1320                                                         }
1321                                                 }
1322                                         }
1323                                 }
1324                                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1325                                         if let &Some(ref txid) = current_remote_commitment_txid {
1326                                                 check_htlc_fails!(txid, "current");
1327                                         }
1328                                         if let &Some(ref txid) = prev_remote_commitment_txid {
1329                                                 check_htlc_fails!(txid, "remote");
1330                                         }
1331                                 }
1332                                 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1333                         }
1334                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1335
1336                         let outputs = vec!(TxOut {
1337                                 script_pubkey: self.destination_script.clone(),
1338                                 value: total_value,
1339                         });
1340                         let mut spend_tx = Transaction {
1341                                 version: 2,
1342                                 lock_time: 0,
1343                                 input: inputs,
1344                                 output: outputs,
1345                         };
1346                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&input_descriptors[..]);
1347
1348                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, tx.txid()) {
1349                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1350                         }
1351
1352                         let mut values_drain = values.drain(..);
1353                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1354
1355                         for (input, htlc_idx) in spend_tx.input.iter_mut().zip(htlc_idxs.iter()) {
1356                                 let value = values_drain.next().unwrap();
1357                                 sign_input!(sighash_parts, input, htlc_idx, value);
1358                         }
1359                         assert!(predicted_weight >= spend_tx.get_weight());
1360
1361                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1362                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1363                                 output: spend_tx.output[0].clone(),
1364                         });
1365                         txn_to_broadcast.push(spend_tx);
1366                 } else if let Some(per_commitment_data) = per_commitment_option {
1367                         // While this isn't useful yet, there is a potential race where if a counterparty
1368                         // revokes a state at the same time as the commitment transaction for that state is
1369                         // confirmed, and the watchtower receives the block before the user, the user could
1370                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1371                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1372                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1373                         // insert it here.
1374                         watch_outputs.append(&mut tx.output.clone());
1375                         self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1376
1377                         log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1378
1379                         macro_rules! check_htlc_fails {
1380                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1381                                         if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1382                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1383                                                         if let &Some(ref source) = source_option {
1384                                                                 // Check if the HTLC is present in the commitment transaction that was
1385                                                                 // broadcast, but not if it was below the dust limit, which we should
1386                                                                 // fail backwards immediately as there is no way for us to learn the
1387                                                                 // payment_preimage.
1388                                                                 // Note that if the dust limit were allowed to change between
1389                                                                 // commitment transactions we'd want to be check whether *any*
1390                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1391                                                                 // cannot currently change after channel initialization, so we don't
1392                                                                 // need to here.
1393                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1394                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1395                                                                                 continue $id;
1396                                                                         }
1397                                                                 }
1398                                                                 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1399                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + HTLC_FAIL_ANTI_REORG_DELAY - 1) {
1400                                                                         hash_map::Entry::Occupied(mut entry) => {
1401                                                                                 let e = entry.get_mut();
1402                                                                                 e.retain(|ref event| {
1403                                                                                         match **event {
1404                                                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1405                                                                                                         return htlc_update.0 != **source
1406                                                                                                 },
1407                                                                                                 _ => return true
1408                                                                                         }
1409                                                                                 });
1410                                                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1411                                                                         }
1412                                                                         hash_map::Entry::Vacant(entry) => {
1413                                                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1414                                                                         }
1415                                                                 }
1416                                                         }
1417                                                 }
1418                                         }
1419                                 }
1420                         }
1421                         if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1422                                 if let &Some(ref txid) = current_remote_commitment_txid {
1423                                         check_htlc_fails!(txid, "current", 'current_loop);
1424                                 }
1425                                 if let &Some(ref txid) = prev_remote_commitment_txid {
1426                                         check_htlc_fails!(txid, "previous", 'prev_loop);
1427                                 }
1428                         }
1429
1430                         if let Some(revocation_points) = self.their_cur_revocation_points {
1431                                 let revocation_point_option =
1432                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1433                                         else if let Some(point) = revocation_points.2.as_ref() {
1434                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1435                                         } else { None };
1436                                 if let Some(revocation_point) = revocation_point_option {
1437                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1438                                                 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1439                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1440                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1441                                                 },
1442                                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1443                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1444                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1445                                                 },
1446                                         };
1447                                         let a_htlc_key = match self.their_htlc_base_key {
1448                                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1449                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1450                                         };
1451
1452                                         for (idx, outp) in tx.output.iter().enumerate() {
1453                                                 if outp.script_pubkey.is_v0_p2wpkh() {
1454                                                         match self.key_storage {
1455                                                                 Storage::Local { ref payment_base_key, .. } => {
1456                                                                         if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1457                                                                                 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1458                                                                                         outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1459                                                                                         key: local_key,
1460                                                                                         output: outp.clone(),
1461                                                                                 });
1462                                                                         }
1463                                                                 },
1464                                                                 Storage::Watchtower { .. } => {}
1465                                                         }
1466                                                         break; // Only to_remote ouput is claimable
1467                                                 }
1468                                         }
1469
1470                                         let mut total_value = 0;
1471                                         let mut values = Vec::new();
1472                                         let mut inputs = Vec::new();
1473                                         let mut input_descriptors = Vec::new();
1474
1475                                         macro_rules! sign_input {
1476                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1477                                                         {
1478                                                                 let (sig, redeemscript) = match self.key_storage {
1479                                                                         Storage::Local { ref htlc_base_key, .. } => {
1480                                                                                 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize].0;
1481                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1482                                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1483                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1484                                                                                 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript)
1485                                                                         },
1486                                                                         Storage::Watchtower { .. } => {
1487                                                                                 unimplemented!();
1488                                                                         }
1489                                                                 };
1490                                                                 $input.witness.push(sig.serialize_der().to_vec());
1491                                                                 $input.witness[0].push(SigHashType::All as u8);
1492                                                                 $input.witness.push($preimage);
1493                                                                 $input.witness.push(redeemscript.into_bytes());
1494                                                         }
1495                                                 }
1496                                         }
1497
1498                                         for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1499                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1500                                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1501                                                         if transaction_output_index as usize >= tx.output.len() ||
1502                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1503                                                                         tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1504                                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1505                                                         }
1506                                                         if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1507                                                                 let input = TxIn {
1508                                                                         previous_output: BitcoinOutPoint {
1509                                                                                 txid: commitment_txid,
1510                                                                                 vout: transaction_output_index,
1511                                                                         },
1512                                                                         script_sig: Script::new(),
1513                                                                         sequence: idx as u32, // reset to 0xfffffffd in sign_input
1514                                                                         witness: Vec::new(),
1515                                                                 };
1516                                                                 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1517                                                                         inputs.push(input);
1518                                                                         values.push((tx.output[transaction_output_index as usize].value, payment_preimage));
1519                                                                         total_value += htlc.amount_msat / 1000;
1520                                                                         input_descriptors.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
1521                                                                 } else {
1522                                                                         let mut single_htlc_tx = Transaction {
1523                                                                                 version: 2,
1524                                                                                 lock_time: 0,
1525                                                                                 input: vec![input],
1526                                                                                 output: vec!(TxOut {
1527                                                                                         script_pubkey: self.destination_script.clone(),
1528                                                                                         value: htlc.amount_msat / 1000,
1529                                                                                 }),
1530                                                                         };
1531                                                                         let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
1532                                                                         if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, tx.txid()) {
1533                                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1534                                                                                 sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
1535                                                                                 assert!(predicted_weight >= single_htlc_tx.get_weight());
1536                                                                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1537                                                                                         outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1538                                                                                         output: single_htlc_tx.output[0].clone(),
1539                                                                                 });
1540                                                                                 txn_to_broadcast.push(single_htlc_tx);
1541                                                                         }
1542                                                                 }
1543                                                         }
1544                                                         if !htlc.offered {
1545                                                                 // TODO: If the HTLC has already expired, potentially merge it with the
1546                                                                 // rest of the claim transaction, as above.
1547                                                                 let input = TxIn {
1548                                                                         previous_output: BitcoinOutPoint {
1549                                                                                 txid: commitment_txid,
1550                                                                                 vout: transaction_output_index,
1551                                                                         },
1552                                                                         script_sig: Script::new(),
1553                                                                         sequence: idx as u32,
1554                                                                         witness: Vec::new(),
1555                                                                 };
1556                                                                 let mut timeout_tx = Transaction {
1557                                                                         version: 2,
1558                                                                         lock_time: htlc.cltv_expiry,
1559                                                                         input: vec![input],
1560                                                                         output: vec!(TxOut {
1561                                                                                 script_pubkey: self.destination_script.clone(),
1562                                                                                 value: htlc.amount_msat / 1000,
1563                                                                         }),
1564                                                                 };
1565                                                                 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1566                                                                 sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1567                                                                 txn_to_broadcast.push(timeout_tx);
1568                                                         }
1569                                                 }
1570                                         }
1571
1572                                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1573
1574                                         let outputs = vec!(TxOut {
1575                                                 script_pubkey: self.destination_script.clone(),
1576                                                 value: total_value
1577                                         });
1578                                         let mut spend_tx = Transaction {
1579                                                 version: 2,
1580                                                 lock_time: 0,
1581                                                 input: inputs,
1582                                                 output: outputs,
1583                                         };
1584                                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&input_descriptors[..]);
1585                                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, tx.txid()) {
1586                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1587                                         }
1588
1589                                         let mut values_drain = values.drain(..);
1590                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1591
1592                                         for input in spend_tx.input.iter_mut() {
1593                                                 let value = values_drain.next().unwrap();
1594                                                 sign_input!(sighash_parts, input, value.0, (value.1).0.to_vec());
1595                                         }
1596
1597                                         assert!(predicted_weight >= spend_tx.get_weight());
1598                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1599                                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1600                                                 output: spend_tx.output[0].clone(),
1601                                         });
1602                                         txn_to_broadcast.push(spend_tx);
1603                                 }
1604                         }
1605                 }
1606
1607                 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1608         }
1609
1610         /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1611         fn check_spend_remote_htlc(&self, tx: &Transaction, commitment_number: u64, fee_estimator: &FeeEstimator) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1612                 if tx.input.len() != 1 || tx.output.len() != 1 {
1613                         return (None, None)
1614                 }
1615
1616                 macro_rules! ignore_error {
1617                         ( $thing : expr ) => {
1618                                 match $thing {
1619                                         Ok(a) => a,
1620                                         Err(_) => return (None, None)
1621                                 }
1622                         };
1623                 }
1624
1625                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1626                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1627                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1628                 let revocation_pubkey = match self.key_storage {
1629                         Storage::Local { ref revocation_base_key, .. } => {
1630                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1631                         },
1632                         Storage::Watchtower { ref revocation_base_key, .. } => {
1633                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1634                         },
1635                 };
1636                 let delayed_key = match self.their_delayed_payment_base_key {
1637                         None => return (None, None),
1638                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1639                 };
1640                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.their_to_self_delay.unwrap(), &delayed_key);
1641                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1642                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1643
1644                 let mut inputs = Vec::new();
1645                 let mut amount = 0;
1646
1647                 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
1648                         inputs.push(TxIn {
1649                                 previous_output: BitcoinOutPoint {
1650                                         txid: htlc_txid,
1651                                         vout: 0,
1652                                 },
1653                                 script_sig: Script::new(),
1654                                 sequence: 0xfffffffd,
1655                                 witness: Vec::new(),
1656                         });
1657                         amount = tx.output[0].value;
1658                 }
1659
1660                 if !inputs.is_empty() {
1661                         let outputs = vec!(TxOut {
1662                                 script_pubkey: self.destination_script.clone(),
1663                                 value: amount
1664                         });
1665
1666                         let mut spend_tx = Transaction {
1667                                 version: 2,
1668                                 lock_time: 0,
1669                                 input: inputs,
1670                                 output: outputs,
1671                         };
1672                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
1673                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, tx.txid()) {
1674                                 return (None, None);
1675                         }
1676
1677                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1678
1679                         let sig = match self.key_storage {
1680                                 Storage::Local { ref revocation_base_key, .. } => {
1681                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
1682                                         let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1683                                         self.secp_ctx.sign(&sighash, &revocation_key)
1684                                 }
1685                                 Storage::Watchtower { .. } => {
1686                                         unimplemented!();
1687                                 }
1688                         };
1689                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
1690                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
1691                         spend_tx.input[0].witness.push(vec!(1));
1692                         spend_tx.input[0].witness.push(redeemscript.into_bytes());
1693
1694                         assert!(predicted_weight >= spend_tx.get_weight());
1695                         let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
1696                         let output = spend_tx.output[0].clone();
1697                         (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
1698                 } else { (None, None) }
1699         }
1700
1701         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>) {
1702                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1703                 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1704                 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1705
1706                 macro_rules! add_dynamic_output {
1707                         ($father_tx: expr, $vout: expr) => {
1708                                 if let Some(ref per_commitment_point) = *per_commitment_point {
1709                                         if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
1710                                                 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
1711                                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1712                                                                 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1713                                                                 key: local_delayedkey,
1714                                                                 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1715                                                                 to_self_delay: self.our_to_self_delay,
1716                                                                 output: $father_tx.output[$vout as usize].clone(),
1717                                                         });
1718                                                 }
1719                                         }
1720                                 }
1721                         }
1722                 }
1723
1724
1725                 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1726                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1727                 for (idx, output) in local_tx.tx.output.iter().enumerate() {
1728                         if output.script_pubkey == revokeable_p2wsh {
1729                                 add_dynamic_output!(local_tx.tx, idx as u32);
1730                                 break;
1731                         }
1732                 }
1733
1734                 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
1735                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1736                                 if let &Some((ref their_sig, ref our_sig)) = sigs {
1737                                         if htlc.offered {
1738                                                 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
1739                                                 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);
1740
1741                                                 htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1742
1743                                                 htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1744                                                 htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
1745                                                 htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1746                                                 htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
1747
1748                                                 htlc_timeout_tx.input[0].witness.push(Vec::new());
1749                                                 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());
1750
1751                                                 add_dynamic_output!(htlc_timeout_tx, 0);
1752                                                 res.push(htlc_timeout_tx);
1753                                         } else {
1754                                                 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1755                                                         log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
1756                                                         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);
1757
1758                                                         htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
1759
1760                                                         htlc_success_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
1761                                                         htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
1762                                                         htlc_success_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
1763                                                         htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
1764
1765                                                         htlc_success_tx.input[0].witness.push(payment_preimage.0.to_vec());
1766                                                         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());
1767
1768                                                         add_dynamic_output!(htlc_success_tx, 0);
1769                                                         res.push(htlc_success_tx);
1770                                                 }
1771                                         }
1772                                         watch_outputs.push(local_tx.tx.output[transaction_output_index as usize].clone());
1773                                 } else { panic!("Should have sigs for non-dust local tx outputs!") }
1774                         }
1775                 }
1776
1777                 (res, spendable_outputs, watch_outputs)
1778         }
1779
1780         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1781         /// revoked using data in local_claimable_outpoints.
1782         /// Should not be used if check_spend_revoked_transaction succeeds.
1783         fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1784                 let commitment_txid = tx.txid();
1785                 let mut local_txn = Vec::new();
1786                 let mut spendable_outputs = Vec::new();
1787                 let mut watch_outputs = Vec::new();
1788
1789                 macro_rules! wait_threshold_conf {
1790                         ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1791                                 log_trace!(self, "Failing HTLC with payment_hash {} from {} local commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, height + HTLC_FAIL_ANTI_REORG_DELAY - 1);
1792                                 match self.onchain_events_waiting_threshold_conf.entry($height + HTLC_FAIL_ANTI_REORG_DELAY - 1) {
1793                                         hash_map::Entry::Occupied(mut entry) => {
1794                                                 let e = entry.get_mut();
1795                                                 e.retain(|ref event| {
1796                                                         match **event {
1797                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1798                                                                         return htlc_update.0 != $source
1799                                                                 },
1800                                                                 _ => return true
1801                                                         }
1802                                                 });
1803                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
1804                                         }
1805                                         hash_map::Entry::Vacant(entry) => {
1806                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
1807                                         }
1808                                 }
1809                         }
1810                 }
1811
1812                 macro_rules! append_onchain_update {
1813                         ($updates: expr) => {
1814                                 local_txn.append(&mut $updates.0);
1815                                 spendable_outputs.append(&mut $updates.1);
1816                                 watch_outputs.append(&mut $updates.2);
1817                         }
1818                 }
1819
1820                 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1821                 let mut is_local_tx = false;
1822
1823                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1824                         if local_tx.txid == commitment_txid {
1825                                 is_local_tx = true;
1826                                 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
1827                                 match self.key_storage {
1828                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1829                                                 append_onchain_update!(self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key)));
1830                                         },
1831                                         Storage::Watchtower { .. } => {
1832                                                 append_onchain_update!(self.broadcast_by_local_state(local_tx, &None, &None));
1833                                         }
1834                                 }
1835                         }
1836                 }
1837                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1838                         if local_tx.txid == commitment_txid {
1839                                 is_local_tx = true;
1840                                 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
1841                                 match self.key_storage {
1842                                         Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1843                                                 append_onchain_update!(self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)));
1844                                         },
1845                                         Storage::Watchtower { .. } => {
1846                                                 append_onchain_update!(self.broadcast_by_local_state(local_tx, &None, &None));
1847                                         }
1848                                 }
1849                         }
1850                 }
1851
1852                 macro_rules! fail_dust_htlcs_after_threshold_conf {
1853                         ($local_tx: expr) => {
1854                                 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
1855                                         if htlc.transaction_output_index.is_none() {
1856                                                 if let &Some(ref source) = source {
1857                                                         wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
1858                                                 }
1859                                         }
1860                                 }
1861                         }
1862                 }
1863
1864                 if is_local_tx {
1865                         if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1866                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
1867                         }
1868                         if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1869                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
1870                         }
1871                 }
1872
1873                 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
1874         }
1875
1876         /// Generate a spendable output event when closing_transaction get registered onchain.
1877         fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1878                 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1879                         match self.key_storage {
1880                                 Storage::Local { ref shutdown_pubkey, .. } =>  {
1881                                         let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
1882                                         let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1883                                         for (idx, output) in tx.output.iter().enumerate() {
1884                                                 if shutdown_script == output.script_pubkey {
1885                                                         return Some(SpendableOutputDescriptor::StaticOutput {
1886                                                                 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1887                                                                 output: output.clone(),
1888                                                         });
1889                                                 }
1890                                         }
1891                                 }
1892                                 Storage::Watchtower { .. } => {
1893                                         //TODO: we need to ensure an offline client will generate the event when it
1894                                         // comes back online after only the watchtower saw the transaction
1895                                 }
1896                         }
1897                 }
1898                 None
1899         }
1900
1901         /// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
1902         /// the Channel was out-of-date.
1903         pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
1904                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1905                         let mut res = vec![local_tx.tx.clone()];
1906                         match self.key_storage {
1907                                 Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
1908                                         res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key)).0);
1909                                 },
1910                                 _ => panic!("Can only broadcast by local channelmonitor"),
1911                         };
1912                         res
1913                 } else {
1914                         Vec::new()
1915                 }
1916         }
1917
1918         fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
1919                 let mut watch_outputs = Vec::new();
1920                 let mut spendable_outputs = Vec::new();
1921                 let mut htlc_updated = Vec::new();
1922                 for tx in txn_matched {
1923                         if tx.input.len() == 1 {
1924                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1925                                 // commitment transactions and HTLC transactions will all only ever have one input,
1926                                 // which is an easy way to filter out any potential non-matching txn for lazy
1927                                 // filters.
1928                                 let prevout = &tx.input[0].previous_output;
1929                                 let mut txn: Vec<Transaction> = Vec::new();
1930                                 let funding_txo = match self.key_storage {
1931                                         Storage::Local { ref funding_info, .. } => {
1932                                                 funding_info.clone()
1933                                         }
1934                                         Storage::Watchtower { .. } => {
1935                                                 unimplemented!();
1936                                         }
1937                                 };
1938                                 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) {
1939                                         let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height, fee_estimator);
1940                                         txn = remote_txn;
1941                                         spendable_outputs.append(&mut spendable_output);
1942                                         if !new_outputs.1.is_empty() {
1943                                                 watch_outputs.push(new_outputs);
1944                                         }
1945                                         if txn.is_empty() {
1946                                                 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
1947                                                 spendable_outputs.append(&mut spendable_output);
1948                                                 txn = local_txn;
1949                                                 if !new_outputs.1.is_empty() {
1950                                                         watch_outputs.push(new_outputs);
1951                                                 }
1952                                         }
1953                                         if !funding_txo.is_none() && txn.is_empty() {
1954                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
1955                                                         spendable_outputs.push(spendable_output);
1956                                                 }
1957                                         }
1958                                 } else {
1959                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1960                                                 let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number, fee_estimator);
1961                                                 if let Some(tx) = tx {
1962                                                         txn.push(tx);
1963                                                 }
1964                                                 if let Some(spendable_output) = spendable_output {
1965                                                         spendable_outputs.push(spendable_output);
1966                                                 }
1967                                         }
1968                                 }
1969                                 for tx in txn.iter() {
1970                                         broadcaster.broadcast_transaction(tx);
1971                                 }
1972                         }
1973                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
1974                         // can also be resolved in a few other ways which can have more than one output. Thus,
1975                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
1976                         let mut updated = self.is_resolving_htlc_output(tx, height);
1977                         if updated.len() > 0 {
1978                                 htlc_updated.append(&mut updated);
1979                         }
1980                 }
1981                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1982                         if self.would_broadcast_at_height(height) {
1983                                 broadcaster.broadcast_transaction(&cur_local_tx.tx);
1984                                 match self.key_storage {
1985                                         Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
1986                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
1987                                                 spendable_outputs.append(&mut spendable_output);
1988                                                 if !new_outputs.is_empty() {
1989                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
1990                                                 }
1991                                                 for tx in txs {
1992                                                         broadcaster.broadcast_transaction(&tx);
1993                                                 }
1994                                         },
1995                                         Storage::Watchtower { .. } => {
1996                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, &None, &None);
1997                                                 spendable_outputs.append(&mut spendable_output);
1998                                                 if !new_outputs.is_empty() {
1999                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2000                                                 }
2001                                                 for tx in txs {
2002                                                         broadcaster.broadcast_transaction(&tx);
2003                                                 }
2004                                         }
2005                                 }
2006                         }
2007                 }
2008                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2009                         for ev in events {
2010                                 match ev {
2011                                         OnchainEvent::Claim { outpoint: _ } => {
2012                                         },
2013                                         OnchainEvent::HTLCUpdate { htlc_update } => {
2014                                                 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2015                                                 htlc_updated.push((htlc_update.0, None, htlc_update.1));
2016                                         },
2017                                 }
2018                         }
2019                 }
2020                 self.last_block_hash = block_hash.clone();
2021                 (watch_outputs, spendable_outputs, htlc_updated)
2022         }
2023
2024         fn block_disconnected(&mut self, height: u32, block_hash: &Sha256dHash) {
2025                 if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + HTLC_FAIL_ANTI_REORG_DELAY - 1)) {
2026                         //We may discard:
2027                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2028                         //- our claim tx on a commitment tx output
2029                 }
2030                 self.last_block_hash = block_hash.clone();
2031         }
2032
2033         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2034                 // We need to consider all HTLCs which are:
2035                 //  * in any unrevoked remote commitment transaction, as they could broadcast said
2036                 //    transactions and we'd end up in a race, or
2037                 //  * are in our latest local commitment transaction, as this is the thing we will
2038                 //    broadcast if we go on-chain.
2039                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2040                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2041                 // to the source, and if we don't fail the channel we will have to ensure that the next
2042                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2043                 // easier to just fail the channel as this case should be rare enough anyway.
2044                 macro_rules! scan_commitment {
2045                         ($htlcs: expr, $local_tx: expr) => {
2046                                 for ref htlc in $htlcs {
2047                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2048                                         // chain with enough room to claim the HTLC without our counterparty being able to
2049                                         // time out the HTLC first.
2050                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2051                                         // concern is being able to claim the corresponding inbound HTLC (on another
2052                                         // channel) before it expires. In fact, we don't even really care if our
2053                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2054                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2055                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2056                                         // we give ourselves a few blocks of headroom after expiration before going
2057                                         // on-chain for an expired HTLC.
2058                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2059                                         // from us until we've reached the point where we go on-chain with the
2060                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2061                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2062                                         //  aka outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS == height - CLTV_CLAIM_BUFFER
2063                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2064                                         //      outbound_cltv + HTLC_FAIL_TIMEOUT_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2065                                         //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2066                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2067                                         //      HTLC_FAIL_TIMEOUT_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2068                                         //  The final, above, condition is checked for statically in channelmanager
2069                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2070                                         let htlc_outbound = $local_tx == htlc.offered;
2071                                         if ( htlc_outbound && htlc.cltv_expiry + HTLC_FAIL_TIMEOUT_BLOCKS <= height) ||
2072                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2073                                                 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2074                                                 return true;
2075                                         }
2076                                 }
2077                         }
2078                 }
2079
2080                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2081                         scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2082                 }
2083
2084                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2085                         if let &Some(ref txid) = current_remote_commitment_txid {
2086                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2087                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2088                                 }
2089                         }
2090                         if let &Some(ref txid) = prev_remote_commitment_txid {
2091                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2092                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2093                                 }
2094                         }
2095                 }
2096
2097                 false
2098         }
2099
2100         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2101         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2102         fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
2103                 let mut htlc_updated = Vec::new();
2104
2105                 'outer_loop: for input in &tx.input {
2106                         let mut payment_data = None;
2107                         let revocation_sig_claim = (input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33)
2108                                 || (input.witness.len() == 3 && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33);
2109                         let accepted_preimage_claim = input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT;
2110                         let offered_preimage_claim = input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT;
2111
2112                         macro_rules! log_claim {
2113                                 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2114                                         // We found the output in question, but aren't failing it backwards
2115                                         // as we have no corresponding source and no valid remote commitment txid
2116                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2117                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2118                                         let outbound_htlc = $local_tx == $htlc.offered;
2119                                         if ($local_tx && revocation_sig_claim) ||
2120                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2121                                                 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2122                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2123                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2124                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2125                                         } else {
2126                                                 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2127                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2128                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2129                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2130                                         }
2131                                 }
2132                         }
2133
2134                         macro_rules! check_htlc_valid_remote {
2135                                 ($remote_txid: expr, $htlc_output: expr) => {
2136                                         if let &Some(txid) = $remote_txid {
2137                                                 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2138                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2139                                                                 if let &Some(ref source) = pending_source {
2140                                                                         log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2141                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2142                                                                         break;
2143                                                                 }
2144                                                         }
2145                                                 }
2146                                         }
2147                                 }
2148                         }
2149
2150                         macro_rules! scan_commitment {
2151                                 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2152                                         for (ref htlc_output, source_option) in $htlcs {
2153                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2154                                                         if let Some(ref source) = source_option {
2155                                                                 log_claim!($tx_info, $local_tx, htlc_output, true);
2156                                                                 // We have a resolution of an HTLC either from one of our latest
2157                                                                 // local commitment transactions or an unrevoked remote commitment
2158                                                                 // transaction. This implies we either learned a preimage, the HTLC
2159                                                                 // has timed out, or we screwed up. In any case, we should now
2160                                                                 // resolve the source HTLC with the original sender.
2161                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2162                                                         } else if !$local_tx {
2163                                                                 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2164                                                                         check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2165                                                                 }
2166                                                                 if payment_data.is_none() {
2167                                                                         if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2168                                                                                 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2169                                                                         }
2170                                                                 }
2171                                                         }
2172                                                         if payment_data.is_none() {
2173                                                                 log_claim!($tx_info, $local_tx, htlc_output, false);
2174                                                                 continue 'outer_loop;
2175                                                         }
2176                                                 }
2177                                         }
2178                                 }
2179                         }
2180
2181                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2182                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2183                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2184                                                 "our latest local commitment tx", true);
2185                                 }
2186                         }
2187                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2188                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2189                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2190                                                 "our previous local commitment tx", true);
2191                                 }
2192                         }
2193                         if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2194                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2195                                         "remote commitment tx", false);
2196                         }
2197
2198                         // Check that scan_commitment, above, decided there is some source worth relaying an
2199                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2200                         if let Some((source, payment_hash)) = payment_data {
2201                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2202                                 if accepted_preimage_claim {
2203                                         payment_preimage.0.copy_from_slice(&input.witness[3]);
2204                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
2205                                 } else if offered_preimage_claim {
2206                                         payment_preimage.0.copy_from_slice(&input.witness[1]);
2207                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
2208                                 } else {
2209                                         log_info!(self, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), height + HTLC_FAIL_ANTI_REORG_DELAY - 1);
2210                                         match self.onchain_events_waiting_threshold_conf.entry(height + HTLC_FAIL_ANTI_REORG_DELAY - 1) {
2211                                                 hash_map::Entry::Occupied(mut entry) => {
2212                                                         let e = entry.get_mut();
2213                                                         e.retain(|ref event| {
2214                                                                 match **event {
2215                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2216                                                                                 return htlc_update.0 != source
2217                                                                         },
2218                                                                         _ => return true
2219                                                                 }
2220                                                         });
2221                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2222                                                 }
2223                                                 hash_map::Entry::Vacant(entry) => {
2224                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2225                                                 }
2226                                         }
2227                                 }
2228                         }
2229                 }
2230                 htlc_updated
2231         }
2232 }
2233
2234 const MAX_ALLOC_SIZE: usize = 64*1024;
2235
2236 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
2237         fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
2238                 let secp_ctx = Secp256k1::new();
2239                 macro_rules! unwrap_obj {
2240                         ($key: expr) => {
2241                                 match $key {
2242                                         Ok(res) => res,
2243                                         Err(_) => return Err(DecodeError::InvalidValue),
2244                                 }
2245                         }
2246                 }
2247
2248                 let _ver: u8 = Readable::read(reader)?;
2249                 let min_ver: u8 = Readable::read(reader)?;
2250                 if min_ver > SERIALIZATION_VERSION {
2251                         return Err(DecodeError::UnknownVersion);
2252                 }
2253
2254                 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
2255
2256                 let key_storage = match <u8 as Readable<R>>::read(reader)? {
2257                         0 => {
2258                                 let revocation_base_key = Readable::read(reader)?;
2259                                 let htlc_base_key = Readable::read(reader)?;
2260                                 let delayed_payment_base_key = Readable::read(reader)?;
2261                                 let payment_base_key = Readable::read(reader)?;
2262                                 let shutdown_pubkey = Readable::read(reader)?;
2263                                 let prev_latest_per_commitment_point = Readable::read(reader)?;
2264                                 let latest_per_commitment_point = Readable::read(reader)?;
2265                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2266                                 // barely-init'd ChannelMonitors that we can't do anything with.
2267                                 let outpoint = OutPoint {
2268                                         txid: Readable::read(reader)?,
2269                                         index: Readable::read(reader)?,
2270                                 };
2271                                 let funding_info = Some((outpoint, Readable::read(reader)?));
2272                                 let current_remote_commitment_txid = Readable::read(reader)?;
2273                                 let prev_remote_commitment_txid = Readable::read(reader)?;
2274                                 Storage::Local {
2275                                         revocation_base_key,
2276                                         htlc_base_key,
2277                                         delayed_payment_base_key,
2278                                         payment_base_key,
2279                                         shutdown_pubkey,
2280                                         prev_latest_per_commitment_point,
2281                                         latest_per_commitment_point,
2282                                         funding_info,
2283                                         current_remote_commitment_txid,
2284                                         prev_remote_commitment_txid,
2285                                 }
2286                         },
2287                         _ => return Err(DecodeError::InvalidValue),
2288                 };
2289
2290                 let their_htlc_base_key = Some(Readable::read(reader)?);
2291                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
2292
2293                 let their_cur_revocation_points = {
2294                         let first_idx = <U48 as Readable<R>>::read(reader)?.0;
2295                         if first_idx == 0 {
2296                                 None
2297                         } else {
2298                                 let first_point = Readable::read(reader)?;
2299                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2300                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2301                                         Some((first_idx, first_point, None))
2302                                 } else {
2303                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2304                                 }
2305                         }
2306                 };
2307
2308                 let our_to_self_delay: u16 = Readable::read(reader)?;
2309                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
2310
2311                 let mut old_secrets = [([0; 32], 1 << 48); 49];
2312                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
2313                         *secret = Readable::read(reader)?;
2314                         *idx = Readable::read(reader)?;
2315                 }
2316
2317                 macro_rules! read_htlc_in_commitment {
2318                         () => {
2319                                 {
2320                                         let offered: bool = Readable::read(reader)?;
2321                                         let amount_msat: u64 = Readable::read(reader)?;
2322                                         let cltv_expiry: u32 = Readable::read(reader)?;
2323                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2324                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2325
2326                                         HTLCOutputInCommitment {
2327                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2328                                         }
2329                                 }
2330                         }
2331                 }
2332
2333                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
2334                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2335                 for _ in 0..remote_claimable_outpoints_len {
2336                         let txid: Sha256dHash = Readable::read(reader)?;
2337                         let htlcs_count: u64 = Readable::read(reader)?;
2338                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2339                         for _ in 0..htlcs_count {
2340                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2341                         }
2342                         if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
2343                                 return Err(DecodeError::InvalidValue);
2344                         }
2345                 }
2346
2347                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2348                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2349                 for _ in 0..remote_commitment_txn_on_chain_len {
2350                         let txid: Sha256dHash = Readable::read(reader)?;
2351                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2352                         let outputs_count = <u64 as Readable<R>>::read(reader)?;
2353                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2354                         for _ in 0..outputs_count {
2355                                 outputs.push(Readable::read(reader)?);
2356                         }
2357                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2358                                 return Err(DecodeError::InvalidValue);
2359                         }
2360                 }
2361
2362                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2363                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2364                 for _ in 0..remote_hash_commitment_number_len {
2365                         let payment_hash: PaymentHash = Readable::read(reader)?;
2366                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2367                         if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2368                                 return Err(DecodeError::InvalidValue);
2369                         }
2370                 }
2371
2372                 macro_rules! read_local_tx {
2373                         () => {
2374                                 {
2375                                         let tx = match Transaction::consensus_decode(reader.by_ref()) {
2376                                                 Ok(tx) => tx,
2377                                                 Err(e) => match e {
2378                                                         encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
2379                                                         _ => return Err(DecodeError::InvalidValue),
2380                                                 },
2381                                         };
2382
2383                                         if tx.input.is_empty() {
2384                                                 // Ensure tx didn't hit the 0-input ambiguity case.
2385                                                 return Err(DecodeError::InvalidValue);
2386                                         }
2387
2388                                         let revocation_key = Readable::read(reader)?;
2389                                         let a_htlc_key = Readable::read(reader)?;
2390                                         let b_htlc_key = Readable::read(reader)?;
2391                                         let delayed_payment_key = Readable::read(reader)?;
2392                                         let feerate_per_kw: u64 = Readable::read(reader)?;
2393
2394                                         let htlcs_len: u64 = Readable::read(reader)?;
2395                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2396                                         for _ in 0..htlcs_len {
2397                                                 let htlc = read_htlc_in_commitment!();
2398                                                 let sigs = match <u8 as Readable<R>>::read(reader)? {
2399                                                         0 => None,
2400                                                         1 => Some((Readable::read(reader)?, Readable::read(reader)?)),
2401                                                         _ => return Err(DecodeError::InvalidValue),
2402                                                 };
2403                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
2404                                         }
2405
2406                                         LocalSignedTx {
2407                                                 txid: tx.txid(),
2408                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw,
2409                                                 htlc_outputs: htlcs
2410                                         }
2411                                 }
2412                         }
2413                 }
2414
2415                 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2416                         0 => None,
2417                         1 => {
2418                                 Some(read_local_tx!())
2419                         },
2420                         _ => return Err(DecodeError::InvalidValue),
2421                 };
2422
2423                 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
2424                         0 => None,
2425                         1 => {
2426                                 Some(read_local_tx!())
2427                         },
2428                         _ => return Err(DecodeError::InvalidValue),
2429                 };
2430
2431                 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
2432
2433                 let payment_preimages_len: u64 = Readable::read(reader)?;
2434                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2435                 for _ in 0..payment_preimages_len {
2436                         let preimage: PaymentPreimage = Readable::read(reader)?;
2437                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2438                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2439                                 return Err(DecodeError::InvalidValue);
2440                         }
2441                 }
2442
2443                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2444                 let destination_script = Readable::read(reader)?;
2445
2446                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2447                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2448                 for _ in 0..waiting_threshold_conf_len {
2449                         let height_target = Readable::read(reader)?;
2450                         let events_len: u64 = Readable::read(reader)?;
2451                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
2452                         for _ in 0..events_len {
2453                                 let ev = match <u8 as Readable<R>>::read(reader)? {
2454                                         0 => {
2455                                                 let outpoint = Readable::read(reader)?;
2456                                                 OnchainEvent::Claim {
2457                                                         outpoint
2458                                                 }
2459                                         },
2460                                         1 => {
2461                                                 let htlc_source = Readable::read(reader)?;
2462                                                 let hash = Readable::read(reader)?;
2463                                                 OnchainEvent::HTLCUpdate {
2464                                                         htlc_update: (htlc_source, hash)
2465                                                 }
2466                                         },
2467                                         _ => return Err(DecodeError::InvalidValue),
2468                                 };
2469                                 events.push(ev);
2470                         }
2471                         onchain_events_waiting_threshold_conf.insert(height_target, events);
2472                 }
2473
2474                 Ok((last_block_hash.clone(), ChannelMonitor {
2475                         commitment_transaction_number_obscure_factor,
2476
2477                         key_storage,
2478                         their_htlc_base_key,
2479                         their_delayed_payment_base_key,
2480                         their_cur_revocation_points,
2481
2482                         our_to_self_delay,
2483                         their_to_self_delay,
2484
2485                         old_secrets,
2486                         remote_claimable_outpoints,
2487                         remote_commitment_txn_on_chain,
2488                         remote_hash_commitment_number,
2489
2490                         prev_local_signed_commitment_tx,
2491                         current_local_signed_commitment_tx,
2492                         current_remote_commitment_number,
2493
2494                         payment_preimages,
2495
2496                         destination_script,
2497
2498                         onchain_events_waiting_threshold_conf,
2499
2500                         last_block_hash,
2501                         secp_ctx,
2502                         logger,
2503                 }))
2504         }
2505
2506 }
2507
2508 #[cfg(test)]
2509 mod tests {
2510         use bitcoin::blockdata::script::{Script, Builder};
2511         use bitcoin::blockdata::opcodes;
2512         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2513         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2514         use bitcoin::util::bip143;
2515         use bitcoin_hashes::Hash;
2516         use bitcoin_hashes::sha256::Hash as Sha256;
2517         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
2518         use bitcoin_hashes::hex::FromHex;
2519         use hex;
2520         use ln::channelmanager::{PaymentPreimage, PaymentHash};
2521         use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
2522         use ln::chan_utils;
2523         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys};
2524         use util::test_utils::TestLogger;
2525         use secp256k1::key::{SecretKey,PublicKey};
2526         use secp256k1::Secp256k1;
2527         use rand::{thread_rng,Rng};
2528         use std::sync::Arc;
2529
2530         #[test]
2531         fn test_per_commitment_storage() {
2532                 // Test vectors from BOLT 3:
2533                 let mut secrets: Vec<[u8; 32]> = Vec::new();
2534                 let mut monitor: ChannelMonitor;
2535                 let secp_ctx = Secp256k1::new();
2536                 let logger = Arc::new(TestLogger::new());
2537
2538                 macro_rules! test_secrets {
2539                         () => {
2540                                 let mut idx = 281474976710655;
2541                                 for secret in secrets.iter() {
2542                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2543                                         idx -= 1;
2544                                 }
2545                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2546                                 assert!(monitor.get_secret(idx).is_none());
2547                         };
2548                 }
2549
2550                 {
2551                         // insert_secret correct sequence
2552                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2553                         secrets.clear();
2554
2555                         secrets.push([0; 32]);
2556                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2557                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2558                         test_secrets!();
2559
2560                         secrets.push([0; 32]);
2561                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2562                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2563                         test_secrets!();
2564
2565                         secrets.push([0; 32]);
2566                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2567                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2568                         test_secrets!();
2569
2570                         secrets.push([0; 32]);
2571                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2572                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2573                         test_secrets!();
2574
2575                         secrets.push([0; 32]);
2576                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2577                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2578                         test_secrets!();
2579
2580                         secrets.push([0; 32]);
2581                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2582                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2583                         test_secrets!();
2584
2585                         secrets.push([0; 32]);
2586                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2587                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2588                         test_secrets!();
2589
2590                         secrets.push([0; 32]);
2591                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2592                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2593                         test_secrets!();
2594                 }
2595
2596                 {
2597                         // insert_secret #1 incorrect
2598                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2599                         secrets.clear();
2600
2601                         secrets.push([0; 32]);
2602                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2603                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2604                         test_secrets!();
2605
2606                         secrets.push([0; 32]);
2607                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2608                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
2609                                         "Previous secret did not match new one");
2610                 }
2611
2612                 {
2613                         // insert_secret #2 incorrect (#1 derived from incorrect)
2614                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2615                         secrets.clear();
2616
2617                         secrets.push([0; 32]);
2618                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2619                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2620                         test_secrets!();
2621
2622                         secrets.push([0; 32]);
2623                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2624                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2625                         test_secrets!();
2626
2627                         secrets.push([0; 32]);
2628                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2629                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2630                         test_secrets!();
2631
2632                         secrets.push([0; 32]);
2633                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2634                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2635                                         "Previous secret did not match new one");
2636                 }
2637
2638                 {
2639                         // insert_secret #3 incorrect
2640                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2641                         secrets.clear();
2642
2643                         secrets.push([0; 32]);
2644                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2645                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2646                         test_secrets!();
2647
2648                         secrets.push([0; 32]);
2649                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2650                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2651                         test_secrets!();
2652
2653                         secrets.push([0; 32]);
2654                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2655                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2656                         test_secrets!();
2657
2658                         secrets.push([0; 32]);
2659                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2660                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
2661                                         "Previous secret did not match new one");
2662                 }
2663
2664                 {
2665                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2666                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2667                         secrets.clear();
2668
2669                         secrets.push([0; 32]);
2670                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2671                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2672                         test_secrets!();
2673
2674                         secrets.push([0; 32]);
2675                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2676                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2677                         test_secrets!();
2678
2679                         secrets.push([0; 32]);
2680                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2681                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2682                         test_secrets!();
2683
2684                         secrets.push([0; 32]);
2685                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2686                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2687                         test_secrets!();
2688
2689                         secrets.push([0; 32]);
2690                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2691                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2692                         test_secrets!();
2693
2694                         secrets.push([0; 32]);
2695                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2696                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2697                         test_secrets!();
2698
2699                         secrets.push([0; 32]);
2700                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2701                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2702                         test_secrets!();
2703
2704                         secrets.push([0; 32]);
2705                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2706                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2707                                         "Previous secret did not match new one");
2708                 }
2709
2710                 {
2711                         // insert_secret #5 incorrect
2712                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2713                         secrets.clear();
2714
2715                         secrets.push([0; 32]);
2716                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2717                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2718                         test_secrets!();
2719
2720                         secrets.push([0; 32]);
2721                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2722                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2723                         test_secrets!();
2724
2725                         secrets.push([0; 32]);
2726                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2727                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2728                         test_secrets!();
2729
2730                         secrets.push([0; 32]);
2731                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2732                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2733                         test_secrets!();
2734
2735                         secrets.push([0; 32]);
2736                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2737                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2738                         test_secrets!();
2739
2740                         secrets.push([0; 32]);
2741                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2742                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
2743                                         "Previous secret did not match new one");
2744                 }
2745
2746                 {
2747                         // insert_secret #6 incorrect (5 derived from incorrect)
2748                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2749                         secrets.clear();
2750
2751                         secrets.push([0; 32]);
2752                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2753                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2754                         test_secrets!();
2755
2756                         secrets.push([0; 32]);
2757                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2758                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2759                         test_secrets!();
2760
2761                         secrets.push([0; 32]);
2762                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2763                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2764                         test_secrets!();
2765
2766                         secrets.push([0; 32]);
2767                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2768                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2769                         test_secrets!();
2770
2771                         secrets.push([0; 32]);
2772                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2773                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2774                         test_secrets!();
2775
2776                         secrets.push([0; 32]);
2777                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2778                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2779                         test_secrets!();
2780
2781                         secrets.push([0; 32]);
2782                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2783                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2784                         test_secrets!();
2785
2786                         secrets.push([0; 32]);
2787                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2788                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2789                                         "Previous secret did not match new one");
2790                 }
2791
2792                 {
2793                         // insert_secret #7 incorrect
2794                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2795                         secrets.clear();
2796
2797                         secrets.push([0; 32]);
2798                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2799                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2800                         test_secrets!();
2801
2802                         secrets.push([0; 32]);
2803                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2804                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2805                         test_secrets!();
2806
2807                         secrets.push([0; 32]);
2808                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2809                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2810                         test_secrets!();
2811
2812                         secrets.push([0; 32]);
2813                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2814                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2815                         test_secrets!();
2816
2817                         secrets.push([0; 32]);
2818                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2819                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2820                         test_secrets!();
2821
2822                         secrets.push([0; 32]);
2823                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2824                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2825                         test_secrets!();
2826
2827                         secrets.push([0; 32]);
2828                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2829                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2830                         test_secrets!();
2831
2832                         secrets.push([0; 32]);
2833                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2834                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2835                                         "Previous secret did not match new one");
2836                 }
2837
2838                 {
2839                         // insert_secret #8 incorrect
2840                         monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2841                         secrets.clear();
2842
2843                         secrets.push([0; 32]);
2844                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2845                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2846                         test_secrets!();
2847
2848                         secrets.push([0; 32]);
2849                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2850                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2851                         test_secrets!();
2852
2853                         secrets.push([0; 32]);
2854                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2855                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2856                         test_secrets!();
2857
2858                         secrets.push([0; 32]);
2859                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2860                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2861                         test_secrets!();
2862
2863                         secrets.push([0; 32]);
2864                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2865                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2866                         test_secrets!();
2867
2868                         secrets.push([0; 32]);
2869                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2870                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2871                         test_secrets!();
2872
2873                         secrets.push([0; 32]);
2874                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2875                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2876                         test_secrets!();
2877
2878                         secrets.push([0; 32]);
2879                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2880                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
2881                                         "Previous secret did not match new one");
2882                 }
2883         }
2884
2885         #[test]
2886         fn test_prune_preimages() {
2887                 let secp_ctx = Secp256k1::new();
2888                 let logger = Arc::new(TestLogger::new());
2889
2890                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2891                 macro_rules! dummy_keys {
2892                         () => {
2893                                 {
2894                                         TxCreationKeys {
2895                                                 per_commitment_point: dummy_key.clone(),
2896                                                 revocation_key: dummy_key.clone(),
2897                                                 a_htlc_key: dummy_key.clone(),
2898                                                 b_htlc_key: dummy_key.clone(),
2899                                                 a_delayed_payment_key: dummy_key.clone(),
2900                                                 b_payment_key: dummy_key.clone(),
2901                                         }
2902                                 }
2903                         }
2904                 }
2905                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2906
2907                 let mut preimages = Vec::new();
2908                 {
2909                         let mut rng  = thread_rng();
2910                         for _ in 0..20 {
2911                                 let mut preimage = PaymentPreimage([0; 32]);
2912                                 rng.fill_bytes(&mut preimage.0[..]);
2913                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2914                                 preimages.push((preimage, hash));
2915                         }
2916                 }
2917
2918                 macro_rules! preimages_slice_to_htlc_outputs {
2919                         ($preimages_slice: expr) => {
2920                                 {
2921                                         let mut res = Vec::new();
2922                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2923                                                 res.push((HTLCOutputInCommitment {
2924                                                         offered: true,
2925                                                         amount_msat: 0,
2926                                                         cltv_expiry: 0,
2927                                                         payment_hash: preimage.1.clone(),
2928                                                         transaction_output_index: Some(idx as u32),
2929                                                 }, None));
2930                                         }
2931                                         res
2932                                 }
2933                         }
2934                 }
2935                 macro_rules! preimages_to_local_htlcs {
2936                         ($preimages_slice: expr) => {
2937                                 {
2938                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2939                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2940                                         res
2941                                 }
2942                         }
2943                 }
2944
2945                 macro_rules! test_preimages_exist {
2946                         ($preimages_slice: expr, $monitor: expr) => {
2947                                 for preimage in $preimages_slice {
2948                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2949                                 }
2950                         }
2951                 }
2952
2953                 // Prune with one old state and a local commitment tx holding a few overlaps with the
2954                 // old state.
2955                 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
2956                 monitor.set_their_to_self_delay(10);
2957
2958                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
2959                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2960                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2961                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2962                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2963                 for &(ref preimage, ref hash) in preimages.iter() {
2964                         monitor.provide_payment_preimage(hash, preimage);
2965                 }
2966
2967                 // Now provide a secret, pruning preimages 10-15
2968                 let mut secret = [0; 32];
2969                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2970                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2971                 assert_eq!(monitor.payment_preimages.len(), 15);
2972                 test_preimages_exist!(&preimages[0..10], monitor);
2973                 test_preimages_exist!(&preimages[15..20], monitor);
2974
2975                 // Now provide a further secret, pruning preimages 15-17
2976                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2977                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2978                 assert_eq!(monitor.payment_preimages.len(), 13);
2979                 test_preimages_exist!(&preimages[0..10], monitor);
2980                 test_preimages_exist!(&preimages[17..20], monitor);
2981
2982                 // Now update local commitment tx info, pruning only element 18 as we still care about the
2983                 // previous commitment tx's preimages too
2984                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
2985                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2986                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2987                 assert_eq!(monitor.payment_preimages.len(), 12);
2988                 test_preimages_exist!(&preimages[0..10], monitor);
2989                 test_preimages_exist!(&preimages[18..20], monitor);
2990
2991                 // But if we do it again, we'll prune 5-10
2992                 monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
2993                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2994                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2995                 assert_eq!(monitor.payment_preimages.len(), 5);
2996                 test_preimages_exist!(&preimages[0..5], monitor);
2997         }
2998
2999         #[test]
3000         fn test_claim_txn_weight_computation() {
3001                 // We test Claim txn weight, knowing that we want expected weigth and
3002                 // not actual case to avoid sigs and time-lock delays hell variances.
3003
3004                 let secp_ctx = Secp256k1::new();
3005                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3006                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3007                 let mut sum_actual_sigs: u64 = 0;
3008
3009                 macro_rules! sign_input {
3010                         ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3011                                 let htlc = HTLCOutputInCommitment {
3012                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3013                                         amount_msat: 0,
3014                                         cltv_expiry: 2 << 16,
3015                                         payment_hash: PaymentHash([1; 32]),
3016                                         transaction_output_index: Some($idx),
3017                                 };
3018                                 let redeem_script = if *$input_type == InputDescriptors::RevokedOutput { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
3019                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3020                                 let sig = secp_ctx.sign(&sighash, &privkey);
3021                                 $input.witness.push(sig.serialize_der().to_vec());
3022                                 $input.witness[0].push(SigHashType::All as u8);
3023                                 sum_actual_sigs += $input.witness[0].len() as u64;
3024                                 if *$input_type == InputDescriptors::RevokedOutput {
3025                                         $input.witness.push(vec!(1));
3026                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3027                                         $input.witness.push(pubkey.clone().serialize().to_vec());
3028                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3029                                         $input.witness.push(vec![0]);
3030                                 } else {
3031                                         $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3032                                 }
3033                                 $input.witness.push(redeem_script.into_bytes());
3034                                 println!("witness[0] {}", $input.witness[0].len());
3035                                 println!("witness[1] {}", $input.witness[1].len());
3036                                 println!("witness[2] {}", $input.witness[2].len());
3037                         }
3038                 }
3039
3040                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3041                 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3042
3043                 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3044                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3045                 for i in 0..4 {
3046                         claim_tx.input.push(TxIn {
3047                                 previous_output: BitcoinOutPoint {
3048                                         txid,
3049                                         vout: i,
3050                                 },
3051                                 script_sig: Script::new(),
3052                                 sequence: 0xfffffffd,
3053                                 witness: Vec::new(),
3054                         });
3055                 }
3056                 claim_tx.output.push(TxOut {
3057                         script_pubkey: script_pubkey.clone(),
3058                         value: 0,
3059                 });
3060                 let base_weight = claim_tx.get_weight();
3061                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3062                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3063                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3064                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3065                 }
3066                 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() as u64 - sum_actual_sigs));
3067
3068                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3069                 claim_tx.input.clear();
3070                 sum_actual_sigs = 0;
3071                 for i in 0..4 {
3072                         claim_tx.input.push(TxIn {
3073                                 previous_output: BitcoinOutPoint {
3074                                         txid,
3075                                         vout: i,
3076                                 },
3077                                 script_sig: Script::new(),
3078                                 sequence: 0xfffffffd,
3079                                 witness: Vec::new(),
3080                         });
3081                 }
3082                 let base_weight = claim_tx.get_weight();
3083                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3084                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3085                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3086                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3087                 }
3088                 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() as u64 - sum_actual_sigs));
3089
3090                 // Justice tx with 1 revoked HTLC-Success tx output
3091                 claim_tx.input.clear();
3092                 sum_actual_sigs = 0;
3093                 claim_tx.input.push(TxIn {
3094                         previous_output: BitcoinOutPoint {
3095                                 txid,
3096                                 vout: 0,
3097                         },
3098                         script_sig: Script::new(),
3099                         sequence: 0xfffffffd,
3100                         witness: Vec::new(),
3101                 });
3102                 let base_weight = claim_tx.get_weight();
3103                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3104                 let inputs_des = vec![InputDescriptors::RevokedOutput];
3105                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3106                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3107                 }
3108                 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() as u64 - sum_actual_sigs));
3109         }
3110
3111         // Further testing is done in the ChannelManager integration tests.
3112 }