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