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