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