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