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