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