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