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