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