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