Add ChannelKeys to ChannelMonitor
[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                 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2367                 let mut watch_outputs = Vec::new();
2368                 let mut spendable_outputs = Vec::new();
2369                 let mut htlc_updated = Vec::new();
2370                 let mut bump_candidates = HashSet::new();
2371                 for tx in txn_matched {
2372                         if tx.input.len() == 1 {
2373                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2374                                 // commitment transactions and HTLC transactions will all only ever have one input,
2375                                 // which is an easy way to filter out any potential non-matching txn for lazy
2376                                 // filters.
2377                                 let prevout = &tx.input[0].previous_output;
2378                                 let mut txn: Vec<Transaction> = Vec::new();
2379                                 let funding_txo = match self.key_storage {
2380                                         Storage::Local { ref funding_info, .. } => {
2381                                                 funding_info.clone()
2382                                         }
2383                                         Storage::Watchtower { .. } => {
2384                                                 unimplemented!();
2385                                         }
2386                                 };
2387                                 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) {
2388                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2389                                                 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
2390                                                 txn = remote_txn;
2391                                                 spendable_outputs.append(&mut spendable_output);
2392                                                 if !new_outputs.1.is_empty() {
2393                                                         watch_outputs.push(new_outputs);
2394                                                 }
2395                                                 if txn.is_empty() {
2396                                                         let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2397                                                         spendable_outputs.append(&mut spendable_output);
2398                                                         txn = local_txn;
2399                                                         if !new_outputs.1.is_empty() {
2400                                                                 watch_outputs.push(new_outputs);
2401                                                         }
2402                                                 }
2403                                         }
2404                                         if !funding_txo.is_none() && txn.is_empty() {
2405                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2406                                                         spendable_outputs.push(spendable_output);
2407                                                 }
2408                                         }
2409                                 } else {
2410                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2411                                                 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
2412                                                 if let Some(tx) = tx {
2413                                                         txn.push(tx);
2414                                                 }
2415                                                 if let Some(spendable_output) = spendable_output {
2416                                                         spendable_outputs.push(spendable_output);
2417                                                 }
2418                                         }
2419                                 }
2420                                 for tx in txn.iter() {
2421                                         log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2422                                         broadcaster.broadcast_transaction(tx);
2423                                 }
2424                         }
2425                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2426                         // can also be resolved in a few other ways which can have more than one output. Thus,
2427                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2428                         let mut updated = self.is_resolving_htlc_output(&tx, height);
2429                         if updated.len() > 0 {
2430                                 htlc_updated.append(&mut updated);
2431                         }
2432
2433                         // Scan all input to verify is one of the outpoint spent is of interest for us
2434                         let mut claimed_outputs_material = Vec::new();
2435                         for inp in &tx.input {
2436                                 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2437                                         // If outpoint has claim request pending on it...
2438                                         if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2439                                                 //... we need to verify equality between transaction outpoints and claim request
2440                                                 // outpoints to know if transaction is the original claim or a bumped one issued
2441                                                 // by us.
2442                                                 let mut set_equality = true;
2443                                                 if claim_material.per_input_material.len() != tx.input.len() {
2444                                                         set_equality = false;
2445                                                 } else {
2446                                                         for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2447                                                                 if *claim_inp != tx_inp.previous_output {
2448                                                                         set_equality = false;
2449                                                                 }
2450                                                         }
2451                                                 }
2452
2453                                                 macro_rules! clean_claim_request_after_safety_delay {
2454                                                         () => {
2455                                                                 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2456                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2457                                                                         hash_map::Entry::Occupied(mut entry) => {
2458                                                                                 if !entry.get().contains(&new_event) {
2459                                                                                         entry.get_mut().push(new_event);
2460                                                                                 }
2461                                                                         },
2462                                                                         hash_map::Entry::Vacant(entry) => {
2463                                                                                 entry.insert(vec![new_event]);
2464                                                                         }
2465                                                                 }
2466                                                         }
2467                                                 }
2468
2469                                                 // If this is our transaction (or our counterparty spent all the outputs
2470                                                 // before we could anyway with same inputs order than us), wait for
2471                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
2472                                                 if set_equality {
2473                                                         clean_claim_request_after_safety_delay!();
2474                                                 } else { // If false, generate new claim request with update outpoint set
2475                                                         for input in tx.input.iter() {
2476                                                                 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2477                                                                         claimed_outputs_material.push((input.previous_output, input_material));
2478                                                                 }
2479                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2480                                                                 if claim_material.per_input_material.is_empty() {
2481                                                                         clean_claim_request_after_safety_delay!();
2482                                                                 }
2483                                                         }
2484                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2485                                                         bump_candidates.insert(first_claim_txid_height.0.clone());
2486                                                 }
2487                                                 break; //No need to iterate further, either tx is our or their
2488                                         } else {
2489                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2490                                         }
2491                                 }
2492                         }
2493                         for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2494                                 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2495                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2496                                         hash_map::Entry::Occupied(mut entry) => {
2497                                                 if !entry.get().contains(&new_event) {
2498                                                         entry.get_mut().push(new_event);
2499                                                 }
2500                                         },
2501                                         hash_map::Entry::Vacant(entry) => {
2502                                                 entry.insert(vec![new_event]);
2503                                         }
2504                                 }
2505                         }
2506                 }
2507                 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2508                         self.would_broadcast_at_height(height)
2509                 } else { false };
2510                 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2511                         if should_broadcast {
2512                                 match self.key_storage {
2513                                         Storage::Local { ref funding_key, .. } => {
2514                                                 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2515                                         },
2516                                         _ => {}
2517                                 }
2518                         }
2519                 }
2520                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2521                         if should_broadcast {
2522                                 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2523                                 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2524                                 match self.key_storage {
2525                                         Storage::Local { ref delayed_payment_base_key, .. } => {
2526                                                 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2527                                                 spendable_outputs.append(&mut spendable_output);
2528                                                 if !new_outputs.is_empty() {
2529                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2530                                                 }
2531                                                 for tx in txs {
2532                                                         log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2533                                                         broadcaster.broadcast_transaction(&tx);
2534                                                 }
2535                                         },
2536                                         Storage::Watchtower { .. } => { },
2537                                 }
2538                         }
2539                 }
2540                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2541                         for ev in events {
2542                                 match ev {
2543                                         OnchainEvent::Claim { claim_request } => {
2544                                                 // We may remove a whole set of claim outpoints here, as these one may have
2545                                                 // been aggregated in a single tx and claimed so atomically
2546                                                 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2547                                                         for outpoint in bump_material.per_input_material.keys() {
2548                                                                 self.claimable_outpoints.remove(&outpoint);
2549                                                         }
2550                                                 }
2551                                         },
2552                                         OnchainEvent::HTLCUpdate { htlc_update } => {
2553                                                 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2554                                                 htlc_updated.push((htlc_update.0, None, htlc_update.1));
2555                                         },
2556                                         OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2557                                                 self.claimable_outpoints.remove(&outpoint);
2558                                         }
2559                                 }
2560                         }
2561                 }
2562                 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2563                         if cached_claim_datas.height_timer == height {
2564                                 bump_candidates.insert(first_claim_txid.clone());
2565                         }
2566                 }
2567                 for first_claim_txid in bump_candidates.iter() {
2568                         if let Some((new_timer, new_feerate)) = {
2569                                 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2570                                         if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2571                                                 broadcaster.broadcast_transaction(&bump_tx);
2572                                                 Some((new_timer, new_feerate))
2573                                         } else { None }
2574                                 } else { unreachable!(); }
2575                         } {
2576                                 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2577                                         claim_material.height_timer = new_timer;
2578                                         claim_material.feerate_previous = new_feerate;
2579                                 } else { unreachable!(); }
2580                         }
2581                 }
2582                 self.last_block_hash = block_hash.clone();
2583                 (watch_outputs, spendable_outputs, htlc_updated)
2584         }
2585
2586         fn block_disconnected(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator) {
2587                 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2588                 let mut bump_candidates = HashMap::new();
2589                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2590                         //We may discard:
2591                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2592                         //- our claim tx on a commitment tx output
2593                         //- resurect outpoint back in its claimable set and regenerate tx
2594                         for ev in events {
2595                                 match ev {
2596                                         OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2597                                                 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2598                                                         if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2599                                                                 claim_material.per_input_material.insert(outpoint, input_material);
2600                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
2601                                                                 // resurrected only one bump claim tx is going to be broadcast
2602                                                                 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2603                                                         }
2604                                                 }
2605                                         },
2606                                         _ => {},
2607                                 }
2608                         }
2609                 }
2610                 for (_, claim_material) in bump_candidates.iter_mut() {
2611                         if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2612                                 claim_material.height_timer = new_timer;
2613                                 claim_material.feerate_previous = new_feerate;
2614                                 broadcaster.broadcast_transaction(&bump_tx);
2615                         }
2616                 }
2617                 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2618                         self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2619                 }
2620                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2621                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2622                 let mut remove_request = Vec::new();
2623                 self.claimable_outpoints.retain(|_, ref v|
2624                         if v.1 == height {
2625                         remove_request.push(v.0.clone());
2626                         false
2627                         } else { true });
2628                 for req in remove_request {
2629                         self.pending_claim_requests.remove(&req);
2630                 }
2631                 self.last_block_hash = block_hash.clone();
2632         }
2633
2634         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2635                 // We need to consider all HTLCs which are:
2636                 //  * in any unrevoked remote commitment transaction, as they could broadcast said
2637                 //    transactions and we'd end up in a race, or
2638                 //  * are in our latest local commitment transaction, as this is the thing we will
2639                 //    broadcast if we go on-chain.
2640                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2641                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2642                 // to the source, and if we don't fail the channel we will have to ensure that the next
2643                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2644                 // easier to just fail the channel as this case should be rare enough anyway.
2645                 macro_rules! scan_commitment {
2646                         ($htlcs: expr, $local_tx: expr) => {
2647                                 for ref htlc in $htlcs {
2648                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2649                                         // chain with enough room to claim the HTLC without our counterparty being able to
2650                                         // time out the HTLC first.
2651                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2652                                         // concern is being able to claim the corresponding inbound HTLC (on another
2653                                         // channel) before it expires. In fact, we don't even really care if our
2654                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2655                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2656                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2657                                         // we give ourselves a few blocks of headroom after expiration before going
2658                                         // on-chain for an expired HTLC.
2659                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2660                                         // from us until we've reached the point where we go on-chain with the
2661                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2662                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2663                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2664                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2665                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2666                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2667                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2668                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2669                                         //  The final, above, condition is checked for statically in channelmanager
2670                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2671                                         let htlc_outbound = $local_tx == htlc.offered;
2672                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2673                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2674                                                 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2675                                                 return true;
2676                                         }
2677                                 }
2678                         }
2679                 }
2680
2681                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2682                         scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2683                 }
2684
2685                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2686                         if let &Some(ref txid) = current_remote_commitment_txid {
2687                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2688                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2689                                 }
2690                         }
2691                         if let &Some(ref txid) = prev_remote_commitment_txid {
2692                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2693                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2694                                 }
2695                         }
2696                 }
2697
2698                 false
2699         }
2700
2701         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2702         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2703         fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
2704                 let mut htlc_updated = Vec::new();
2705
2706                 'outer_loop: for input in &tx.input {
2707                         let mut payment_data = None;
2708                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2709                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2710                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2711                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2712
2713                         macro_rules! log_claim {
2714                                 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2715                                         // We found the output in question, but aren't failing it backwards
2716                                         // as we have no corresponding source and no valid remote commitment txid
2717                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2718                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2719                                         let outbound_htlc = $local_tx == $htlc.offered;
2720                                         if ($local_tx && revocation_sig_claim) ||
2721                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2722                                                 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2723                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2724                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2725                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2726                                         } else {
2727                                                 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2728                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2729                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2730                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2731                                         }
2732                                 }
2733                         }
2734
2735                         macro_rules! check_htlc_valid_remote {
2736                                 ($remote_txid: expr, $htlc_output: expr) => {
2737                                         if let &Some(txid) = $remote_txid {
2738                                                 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2739                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2740                                                                 if let &Some(ref source) = pending_source {
2741                                                                         log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2742                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2743                                                                         break;
2744                                                                 }
2745                                                         }
2746                                                 }
2747                                         }
2748                                 }
2749                         }
2750
2751                         macro_rules! scan_commitment {
2752                                 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2753                                         for (ref htlc_output, source_option) in $htlcs {
2754                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2755                                                         if let Some(ref source) = source_option {
2756                                                                 log_claim!($tx_info, $local_tx, htlc_output, true);
2757                                                                 // We have a resolution of an HTLC either from one of our latest
2758                                                                 // local commitment transactions or an unrevoked remote commitment
2759                                                                 // transaction. This implies we either learned a preimage, the HTLC
2760                                                                 // has timed out, or we screwed up. In any case, we should now
2761                                                                 // resolve the source HTLC with the original sender.
2762                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2763                                                         } else if !$local_tx {
2764                                                                 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2765                                                                         check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2766                                                                 }
2767                                                                 if payment_data.is_none() {
2768                                                                         if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2769                                                                                 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2770                                                                         }
2771                                                                 }
2772                                                         }
2773                                                         if payment_data.is_none() {
2774                                                                 log_claim!($tx_info, $local_tx, htlc_output, false);
2775                                                                 continue 'outer_loop;
2776                                                         }
2777                                                 }
2778                                         }
2779                                 }
2780                         }
2781
2782                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2783                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2784                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2785                                                 "our latest local commitment tx", true);
2786                                 }
2787                         }
2788                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2789                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2790                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2791                                                 "our previous local commitment tx", true);
2792                                 }
2793                         }
2794                         if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2795                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2796                                         "remote commitment tx", false);
2797                         }
2798
2799                         // Check that scan_commitment, above, decided there is some source worth relaying an
2800                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2801                         if let Some((source, payment_hash)) = payment_data {
2802                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2803                                 if accepted_preimage_claim {
2804                                         payment_preimage.0.copy_from_slice(&input.witness[3]);
2805                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
2806                                 } else if offered_preimage_claim {
2807                                         payment_preimage.0.copy_from_slice(&input.witness[1]);
2808                                         htlc_updated.push((source, Some(payment_preimage), payment_hash));
2809                                 } else {
2810                                         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);
2811                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2812                                                 hash_map::Entry::Occupied(mut entry) => {
2813                                                         let e = entry.get_mut();
2814                                                         e.retain(|ref event| {
2815                                                                 match **event {
2816                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2817                                                                                 return htlc_update.0 != source
2818                                                                         },
2819                                                                         _ => return true
2820                                                                 }
2821                                                         });
2822                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2823                                                 }
2824                                                 hash_map::Entry::Vacant(entry) => {
2825                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2826                                                 }
2827                                         }
2828                                 }
2829                         }
2830                 }
2831                 htlc_updated
2832         }
2833
2834         /// 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
2835         /// (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.
2836         fn bump_claim_tx(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: &FeeEstimator) -> Option<(u32, u64, Transaction)> {
2837                 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
2838                 let mut inputs = Vec::new();
2839                 for outp in cached_claim_datas.per_input_material.keys() {
2840                         inputs.push(TxIn {
2841                                 previous_output: *outp,
2842                                 script_sig: Script::new(),
2843                                 sequence: 0xfffffffd,
2844                                 witness: Vec::new(),
2845                         });
2846                 }
2847                 let mut bumped_tx = Transaction {
2848                         version: 2,
2849                         lock_time: 0,
2850                         input: inputs,
2851                         output: vec![TxOut {
2852                                 script_pubkey: self.destination_script.clone(),
2853                                 value: 0
2854                         }],
2855                 };
2856
2857                 macro_rules! RBF_bump {
2858                         ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
2859                                 {
2860                                         let mut used_feerate;
2861                                         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
2862                                         let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
2863                                                 let mut value = $amount;
2864                                                 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
2865                                                         // Overflow check is done in subtract_high_prio_fee
2866                                                         $amount - value
2867                                                 } else {
2868                                                         log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
2869                                                         return None;
2870                                                 }
2871                                         // ...else just increase the previous feerate by 25% (because that's a nice number)
2872                                         } else {
2873                                                 let fee = $old_feerate * $predicted_weight / 750;
2874                                                 if $amount <= fee {
2875                                                         log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
2876                                                         return None;
2877                                                 }
2878                                                 fee
2879                                         };
2880
2881                                         let previous_fee = $old_feerate * $predicted_weight / 1000;
2882                                         let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
2883                                         // BIP 125 Opt-in Full Replace-by-Fee Signaling
2884                                         //      * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
2885                                         //      * 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.
2886                                         let new_fee = if new_fee < previous_fee + min_relay_fee {
2887                                                 new_fee + previous_fee + min_relay_fee - new_fee
2888                                         } else {
2889                                                 new_fee
2890                                         };
2891                                         Some((new_fee, new_fee * 1000 / $predicted_weight))
2892                                 }
2893                         }
2894                 }
2895
2896                 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
2897                 let mut inputs_witnesses_weight = 0;
2898                 let mut amt = 0;
2899                 for per_outp_material in cached_claim_datas.per_input_material.values() {
2900                         match per_outp_material {
2901                                 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
2902                                         log_trace!(self, "Is HLTC ? {}", is_htlc);
2903                                         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!() });
2904                                         amt += *amount;
2905                                 },
2906                                 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
2907                                         inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
2908                                         amt += *amount;
2909                                 },
2910                                 &InputMaterial::LocalHTLC { .. } => { return None; }
2911                         }
2912                 }
2913
2914                 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
2915                 let new_feerate;
2916                 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
2917                         // If new computed fee is superior at the whole claimable amount burn all in fees
2918                         if new_fee > amt {
2919                                 bumped_tx.output[0].value = 0;
2920                         } else {
2921                                 bumped_tx.output[0].value = amt - new_fee;
2922                         }
2923                         new_feerate = feerate;
2924                 } else {
2925                         return None;
2926                 }
2927                 assert!(new_feerate != 0);
2928
2929                 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
2930                         match per_outp_material {
2931                                 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
2932                                         let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
2933                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
2934                                         let sig = self.secp_ctx.sign(&sighash, &key);
2935                                         bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
2936                                         bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
2937                                         if *is_htlc {
2938                                                 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
2939                                         } else {
2940                                                 bumped_tx.input[i].witness.push(vec!(1));
2941                                         }
2942                                         bumped_tx.input[i].witness.push(script.clone().into_bytes());
2943                                         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);
2944                                 },
2945                                 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
2946                                         if !preimage.is_some() { bumped_tx.lock_time = *locktime };
2947                                         let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
2948                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
2949                                         let sig = self.secp_ctx.sign(&sighash, &key);
2950                                         bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
2951                                         bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
2952                                         if let &Some(preimage) = preimage {
2953                                                 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
2954                                         } else {
2955                                                 bumped_tx.input[i].witness.push(vec![0]);
2956                                         }
2957                                         bumped_tx.input[i].witness.push(script.clone().into_bytes());
2958                                         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);
2959                                 },
2960                                 &InputMaterial::LocalHTLC { .. } => {
2961                                         //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
2962                                         // RBF them. Need a Lightning specs change and package relay modification :
2963                                         // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
2964                                         return None;
2965                                 }
2966                         }
2967                 }
2968                 assert!(predicted_weight >= bumped_tx.get_weight());
2969                 Some((new_timer, new_feerate, bumped_tx))
2970         }
2971 }
2972
2973 const MAX_ALLOC_SIZE: usize = 64*1024;
2974
2975 impl<R: ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
2976         fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
2977                 let secp_ctx = Secp256k1::new();
2978                 macro_rules! unwrap_obj {
2979                         ($key: expr) => {
2980                                 match $key {
2981                                         Ok(res) => res,
2982                                         Err(_) => return Err(DecodeError::InvalidValue),
2983                                 }
2984                         }
2985                 }
2986
2987                 let _ver: u8 = Readable::read(reader)?;
2988                 let min_ver: u8 = Readable::read(reader)?;
2989                 if min_ver > SERIALIZATION_VERSION {
2990                         return Err(DecodeError::UnknownVersion);
2991                 }
2992
2993                 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
2994
2995                 let key_storage = match <u8 as Readable<R>>::read(reader)? {
2996                         0 => {
2997                                 let keys = Readable::read(reader)?;
2998                                 let funding_key = Readable::read(reader)?;
2999                                 let revocation_base_key = Readable::read(reader)?;
3000                                 let htlc_base_key = Readable::read(reader)?;
3001                                 let delayed_payment_base_key = Readable::read(reader)?;
3002                                 let payment_base_key = Readable::read(reader)?;
3003                                 let shutdown_pubkey = Readable::read(reader)?;
3004                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3005                                 // barely-init'd ChannelMonitors that we can't do anything with.
3006                                 let outpoint = OutPoint {
3007                                         txid: Readable::read(reader)?,
3008                                         index: Readable::read(reader)?,
3009                                 };
3010                                 let funding_info = Some((outpoint, Readable::read(reader)?));
3011                                 let current_remote_commitment_txid = Readable::read(reader)?;
3012                                 let prev_remote_commitment_txid = Readable::read(reader)?;
3013                                 Storage::Local {
3014                                         keys,
3015                                         funding_key,
3016                                         revocation_base_key,
3017                                         htlc_base_key,
3018                                         delayed_payment_base_key,
3019                                         payment_base_key,
3020                                         shutdown_pubkey,
3021                                         funding_info,
3022                                         current_remote_commitment_txid,
3023                                         prev_remote_commitment_txid,
3024                                 }
3025                         },
3026                         _ => return Err(DecodeError::InvalidValue),
3027                 };
3028
3029                 let their_htlc_base_key = Some(Readable::read(reader)?);
3030                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3031                 let funding_redeemscript = Some(Readable::read(reader)?);
3032                 let channel_value_satoshis = Some(Readable::read(reader)?);
3033
3034                 let their_cur_revocation_points = {
3035                         let first_idx = <U48 as Readable<R>>::read(reader)?.0;
3036                         if first_idx == 0 {
3037                                 None
3038                         } else {
3039                                 let first_point = Readable::read(reader)?;
3040                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3041                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3042                                         Some((first_idx, first_point, None))
3043                                 } else {
3044                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3045                                 }
3046                         }
3047                 };
3048
3049                 let our_to_self_delay: u16 = Readable::read(reader)?;
3050                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3051
3052                 let mut old_secrets = [([0; 32], 1 << 48); 49];
3053                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
3054                         *secret = Readable::read(reader)?;
3055                         *idx = Readable::read(reader)?;
3056                 }
3057
3058                 macro_rules! read_htlc_in_commitment {
3059                         () => {
3060                                 {
3061                                         let offered: bool = Readable::read(reader)?;
3062                                         let amount_msat: u64 = Readable::read(reader)?;
3063                                         let cltv_expiry: u32 = Readable::read(reader)?;
3064                                         let payment_hash: PaymentHash = Readable::read(reader)?;
3065                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
3066
3067                                         HTLCOutputInCommitment {
3068                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3069                                         }
3070                                 }
3071                         }
3072                 }
3073
3074                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3075                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3076                 for _ in 0..remote_claimable_outpoints_len {
3077                         let txid: Sha256dHash = Readable::read(reader)?;
3078                         let htlcs_count: u64 = Readable::read(reader)?;
3079                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3080                         for _ in 0..htlcs_count {
3081                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3082                         }
3083                         if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3084                                 return Err(DecodeError::InvalidValue);
3085                         }
3086                 }
3087
3088                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3089                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3090                 for _ in 0..remote_commitment_txn_on_chain_len {
3091                         let txid: Sha256dHash = Readable::read(reader)?;
3092                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3093                         let outputs_count = <u64 as Readable<R>>::read(reader)?;
3094                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3095                         for _ in 0..outputs_count {
3096                                 outputs.push(Readable::read(reader)?);
3097                         }
3098                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3099                                 return Err(DecodeError::InvalidValue);
3100                         }
3101                 }
3102
3103                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3104                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3105                 for _ in 0..remote_hash_commitment_number_len {
3106                         let payment_hash: PaymentHash = Readable::read(reader)?;
3107                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3108                         if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3109                                 return Err(DecodeError::InvalidValue);
3110                         }
3111                 }
3112
3113                 macro_rules! read_local_tx {
3114                         () => {
3115                                 {
3116                                         let tx = <LocalCommitmentTransaction as Readable<R>>::read(reader)?;
3117                                         let revocation_key = Readable::read(reader)?;
3118                                         let a_htlc_key = Readable::read(reader)?;
3119                                         let b_htlc_key = Readable::read(reader)?;
3120                                         let delayed_payment_key = Readable::read(reader)?;
3121                                         let per_commitment_point = Readable::read(reader)?;
3122                                         let feerate_per_kw: u64 = Readable::read(reader)?;
3123
3124                                         let htlcs_len: u64 = Readable::read(reader)?;
3125                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3126                                         for _ in 0..htlcs_len {
3127                                                 let htlc = read_htlc_in_commitment!();
3128                                                 let sigs = match <u8 as Readable<R>>::read(reader)? {
3129                                                         0 => None,
3130                                                         1 => Some(Readable::read(reader)?),
3131                                                         _ => return Err(DecodeError::InvalidValue),
3132                                                 };
3133                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
3134                                         }
3135
3136                                         LocalSignedTx {
3137                                                 txid: tx.txid(),
3138                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3139                                                 htlc_outputs: htlcs
3140                                         }
3141                                 }
3142                         }
3143                 }
3144
3145                 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3146                         0 => None,
3147                         1 => {
3148                                 Some(read_local_tx!())
3149                         },
3150                         _ => return Err(DecodeError::InvalidValue),
3151                 };
3152
3153                 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3154                         0 => None,
3155                         1 => {
3156                                 Some(read_local_tx!())
3157                         },
3158                         _ => return Err(DecodeError::InvalidValue),
3159                 };
3160
3161                 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3162
3163                 let payment_preimages_len: u64 = Readable::read(reader)?;
3164                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3165                 for _ in 0..payment_preimages_len {
3166                         let preimage: PaymentPreimage = Readable::read(reader)?;
3167                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3168                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3169                                 return Err(DecodeError::InvalidValue);
3170                         }
3171                 }
3172
3173                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3174                 let destination_script = Readable::read(reader)?;
3175                 let to_remote_rescue = match <u8 as Readable<R>>::read(reader)? {
3176                         0 => None,
3177                         1 => {
3178                                 let to_remote_script = Readable::read(reader)?;
3179                                 let local_key = Readable::read(reader)?;
3180                                 Some((to_remote_script, local_key))
3181                         }
3182                         _ => return Err(DecodeError::InvalidValue),
3183                 };
3184
3185                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3186                 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3187                 for _ in 0..pending_claim_requests_len {
3188                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3189                 }
3190
3191                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3192                 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3193                 for _ in 0..claimable_outpoints_len {
3194                         let outpoint = Readable::read(reader)?;
3195                         let ancestor_claim_txid = Readable::read(reader)?;
3196                         let height = Readable::read(reader)?;
3197                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3198                 }
3199
3200                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3201                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3202                 for _ in 0..waiting_threshold_conf_len {
3203                         let height_target = Readable::read(reader)?;
3204                         let events_len: u64 = Readable::read(reader)?;
3205                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3206                         for _ in 0..events_len {
3207                                 let ev = match <u8 as Readable<R>>::read(reader)? {
3208                                         0 => {
3209                                                 let claim_request = Readable::read(reader)?;
3210                                                 OnchainEvent::Claim {
3211                                                         claim_request
3212                                                 }
3213                                         },
3214                                         1 => {
3215                                                 let htlc_source = Readable::read(reader)?;
3216                                                 let hash = Readable::read(reader)?;
3217                                                 OnchainEvent::HTLCUpdate {
3218                                                         htlc_update: (htlc_source, hash)
3219                                                 }
3220                                         },
3221                                         2 => {
3222                                                 let outpoint = Readable::read(reader)?;
3223                                                 let input_material = Readable::read(reader)?;
3224                                                 OnchainEvent::ContentiousOutpoint {
3225                                                         outpoint,
3226                                                         input_material
3227                                                 }
3228                                         }
3229                                         _ => return Err(DecodeError::InvalidValue),
3230                                 };
3231                                 events.push(ev);
3232                         }
3233                         onchain_events_waiting_threshold_conf.insert(height_target, events);
3234                 }
3235
3236                 Ok((last_block_hash.clone(), ChannelMonitor {
3237                         commitment_transaction_number_obscure_factor,
3238
3239                         key_storage,
3240                         their_htlc_base_key,
3241                         their_delayed_payment_base_key,
3242                         funding_redeemscript,
3243                         channel_value_satoshis,
3244                         their_cur_revocation_points,
3245
3246                         our_to_self_delay,
3247                         their_to_self_delay,
3248
3249                         old_secrets,
3250                         remote_claimable_outpoints,
3251                         remote_commitment_txn_on_chain,
3252                         remote_hash_commitment_number,
3253
3254                         prev_local_signed_commitment_tx,
3255                         current_local_signed_commitment_tx,
3256                         current_remote_commitment_number,
3257
3258                         payment_preimages,
3259
3260                         destination_script,
3261                         to_remote_rescue,
3262
3263                         pending_claim_requests,
3264
3265                         claimable_outpoints,
3266
3267                         onchain_events_waiting_threshold_conf,
3268
3269                         last_block_hash,
3270                         secp_ctx,
3271                         logger,
3272                 }))
3273         }
3274
3275 }
3276
3277 #[cfg(test)]
3278 mod tests {
3279         use bitcoin::blockdata::script::{Script, Builder};
3280         use bitcoin::blockdata::opcodes;
3281         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3282         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3283         use bitcoin::util::bip143;
3284         use bitcoin_hashes::Hash;
3285         use bitcoin_hashes::sha256::Hash as Sha256;
3286         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3287         use bitcoin_hashes::hex::FromHex;
3288         use hex;
3289         use ln::channelmanager::{PaymentPreimage, PaymentHash};
3290         use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3291         use ln::chan_utils;
3292         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3293         use util::test_utils::TestLogger;
3294         use secp256k1::key::{SecretKey,PublicKey};
3295         use secp256k1::Secp256k1;
3296         use rand::{thread_rng,Rng};
3297         use std::sync::Arc;
3298         use chain::keysinterface::InMemoryChannelKeys;
3299
3300
3301         #[test]
3302         fn test_per_commitment_storage() {
3303                 // Test vectors from BOLT 3:
3304                 let mut secrets: Vec<[u8; 32]> = Vec::new();
3305                 let mut monitor: ChannelMonitor<InMemoryChannelKeys>;
3306                 let secp_ctx = Secp256k1::new();
3307                 let logger = Arc::new(TestLogger::new());
3308
3309                 macro_rules! test_secrets {
3310                         () => {
3311                                 let mut idx = 281474976710655;
3312                                 for secret in secrets.iter() {
3313                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
3314                                         idx -= 1;
3315                                 }
3316                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
3317                                 assert!(monitor.get_secret(idx).is_none());
3318                         };
3319                 }
3320
3321                 let keys = InMemoryChannelKeys::new(
3322                         &secp_ctx,
3323                         SecretKey::from_slice(&[41; 32]).unwrap(),
3324                         SecretKey::from_slice(&[41; 32]).unwrap(),
3325                         SecretKey::from_slice(&[41; 32]).unwrap(),
3326                         SecretKey::from_slice(&[41; 32]).unwrap(),
3327                         SecretKey::from_slice(&[41; 32]).unwrap(),
3328                         [41; 32],
3329                         0,
3330                 );
3331
3332                 {
3333                         // insert_secret correct sequence
3334                         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());
3335                         secrets.clear();
3336
3337                         secrets.push([0; 32]);
3338                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3339                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3340                         test_secrets!();
3341
3342                         secrets.push([0; 32]);
3343                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3344                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3345                         test_secrets!();
3346
3347                         secrets.push([0; 32]);
3348                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3349                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3350                         test_secrets!();
3351
3352                         secrets.push([0; 32]);
3353                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3354                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3355                         test_secrets!();
3356
3357                         secrets.push([0; 32]);
3358                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3359                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3360                         test_secrets!();
3361
3362                         secrets.push([0; 32]);
3363                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3364                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3365                         test_secrets!();
3366
3367                         secrets.push([0; 32]);
3368                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3369                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3370                         test_secrets!();
3371
3372                         secrets.push([0; 32]);
3373                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3374                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
3375                         test_secrets!();
3376                 }
3377
3378                 {
3379                         // insert_secret #1 incorrect
3380                         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());
3381                         secrets.clear();
3382
3383                         secrets.push([0; 32]);
3384                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3385                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3386                         test_secrets!();
3387
3388                         secrets.push([0; 32]);
3389                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3390                         assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
3391                                         "Previous secret did not match new one");
3392                 }
3393
3394                 {
3395                         // insert_secret #2 incorrect (#1 derived from incorrect)
3396                         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());
3397                         secrets.clear();
3398
3399                         secrets.push([0; 32]);
3400                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3401                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3402                         test_secrets!();
3403
3404                         secrets.push([0; 32]);
3405                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
3406                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3407                         test_secrets!();
3408
3409                         secrets.push([0; 32]);
3410                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3411                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3412                         test_secrets!();
3413
3414                         secrets.push([0; 32]);
3415                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3416                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
3417                                         "Previous secret did not match new one");
3418                 }
3419
3420                 {
3421                         // insert_secret #3 incorrect
3422                         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());
3423                         secrets.clear();
3424
3425                         secrets.push([0; 32]);
3426                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3427                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3428                         test_secrets!();
3429
3430                         secrets.push([0; 32]);
3431                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3432                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3433                         test_secrets!();
3434
3435                         secrets.push([0; 32]);
3436                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
3437                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3438                         test_secrets!();
3439
3440                         secrets.push([0; 32]);
3441                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3442                         assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
3443                                         "Previous secret did not match new one");
3444                 }
3445
3446                 {
3447                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
3448                         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());
3449                         secrets.clear();
3450
3451                         secrets.push([0; 32]);
3452                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3453                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3454                         test_secrets!();
3455
3456                         secrets.push([0; 32]);
3457                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
3458                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3459                         test_secrets!();
3460
3461                         secrets.push([0; 32]);
3462                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
3463                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3464                         test_secrets!();
3465
3466                         secrets.push([0; 32]);
3467                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
3468                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3469                         test_secrets!();
3470
3471                         secrets.push([0; 32]);
3472                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3473                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3474                         test_secrets!();
3475
3476                         secrets.push([0; 32]);
3477                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3478                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3479                         test_secrets!();
3480
3481                         secrets.push([0; 32]);
3482                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3483                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3484                         test_secrets!();
3485
3486                         secrets.push([0; 32]);
3487                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3488                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3489                                         "Previous secret did not match new one");
3490                 }
3491
3492                 {
3493                         // insert_secret #5 incorrect
3494                         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());
3495                         secrets.clear();
3496
3497                         secrets.push([0; 32]);
3498                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3499                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3500                         test_secrets!();
3501
3502                         secrets.push([0; 32]);
3503                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3504                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3505                         test_secrets!();
3506
3507                         secrets.push([0; 32]);
3508                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3509                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3510                         test_secrets!();
3511
3512                         secrets.push([0; 32]);
3513                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3514                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3515                         test_secrets!();
3516
3517                         secrets.push([0; 32]);
3518                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
3519                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3520                         test_secrets!();
3521
3522                         secrets.push([0; 32]);
3523                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3524                         assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
3525                                         "Previous secret did not match new one");
3526                 }
3527
3528                 {
3529                         // insert_secret #6 incorrect (5 derived from incorrect)
3530                         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());
3531                         secrets.clear();
3532
3533                         secrets.push([0; 32]);
3534                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3535                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3536                         test_secrets!();
3537
3538                         secrets.push([0; 32]);
3539                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3540                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3541                         test_secrets!();
3542
3543                         secrets.push([0; 32]);
3544                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3545                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3546                         test_secrets!();
3547
3548                         secrets.push([0; 32]);
3549                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3550                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3551                         test_secrets!();
3552
3553                         secrets.push([0; 32]);
3554                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
3555                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3556                         test_secrets!();
3557
3558                         secrets.push([0; 32]);
3559                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
3560                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3561                         test_secrets!();
3562
3563                         secrets.push([0; 32]);
3564                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3565                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3566                         test_secrets!();
3567
3568                         secrets.push([0; 32]);
3569                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3570                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3571                                         "Previous secret did not match new one");
3572                 }
3573
3574                 {
3575                         // insert_secret #7 incorrect
3576                         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());
3577                         secrets.clear();
3578
3579                         secrets.push([0; 32]);
3580                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3581                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3582                         test_secrets!();
3583
3584                         secrets.push([0; 32]);
3585                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3586                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3587                         test_secrets!();
3588
3589                         secrets.push([0; 32]);
3590                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3591                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3592                         test_secrets!();
3593
3594                         secrets.push([0; 32]);
3595                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3596                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3597                         test_secrets!();
3598
3599                         secrets.push([0; 32]);
3600                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3601                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3602                         test_secrets!();
3603
3604                         secrets.push([0; 32]);
3605                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3606                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3607                         test_secrets!();
3608
3609                         secrets.push([0; 32]);
3610                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
3611                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3612                         test_secrets!();
3613
3614                         secrets.push([0; 32]);
3615                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3616                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3617                                         "Previous secret did not match new one");
3618                 }
3619
3620                 {
3621                         // insert_secret #8 incorrect
3622                         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());
3623                         secrets.clear();
3624
3625                         secrets.push([0; 32]);
3626                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3627                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3628                         test_secrets!();
3629
3630                         secrets.push([0; 32]);
3631                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3632                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3633                         test_secrets!();
3634
3635                         secrets.push([0; 32]);
3636                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3637                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3638                         test_secrets!();
3639
3640                         secrets.push([0; 32]);
3641                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3642                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3643                         test_secrets!();
3644
3645                         secrets.push([0; 32]);
3646                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3647                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3648                         test_secrets!();
3649
3650                         secrets.push([0; 32]);
3651                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3652                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3653                         test_secrets!();
3654
3655                         secrets.push([0; 32]);
3656                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3657                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3658                         test_secrets!();
3659
3660                         secrets.push([0; 32]);
3661                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
3662                         assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3663                                         "Previous secret did not match new one");
3664                 }
3665         }
3666
3667         #[test]
3668         fn test_prune_preimages() {
3669                 let secp_ctx = Secp256k1::new();
3670                 let logger = Arc::new(TestLogger::new());
3671
3672                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3673                 macro_rules! dummy_keys {
3674                         () => {
3675                                 {
3676                                         TxCreationKeys {
3677                                                 per_commitment_point: dummy_key.clone(),
3678                                                 revocation_key: dummy_key.clone(),
3679                                                 a_htlc_key: dummy_key.clone(),
3680                                                 b_htlc_key: dummy_key.clone(),
3681                                                 a_delayed_payment_key: dummy_key.clone(),
3682                                                 b_payment_key: dummy_key.clone(),
3683                                         }
3684                                 }
3685                         }
3686                 }
3687                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3688
3689                 let mut preimages = Vec::new();
3690                 {
3691                         let mut rng  = thread_rng();
3692                         for _ in 0..20 {
3693                                 let mut preimage = PaymentPreimage([0; 32]);
3694                                 rng.fill_bytes(&mut preimage.0[..]);
3695                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3696                                 preimages.push((preimage, hash));
3697                         }
3698                 }
3699
3700                 macro_rules! preimages_slice_to_htlc_outputs {
3701                         ($preimages_slice: expr) => {
3702                                 {
3703                                         let mut res = Vec::new();
3704                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3705                                                 res.push((HTLCOutputInCommitment {
3706                                                         offered: true,
3707                                                         amount_msat: 0,
3708                                                         cltv_expiry: 0,
3709                                                         payment_hash: preimage.1.clone(),
3710                                                         transaction_output_index: Some(idx as u32),
3711                                                 }, None));
3712                                         }
3713                                         res
3714                                 }
3715                         }
3716                 }
3717                 macro_rules! preimages_to_local_htlcs {
3718                         ($preimages_slice: expr) => {
3719                                 {
3720                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3721                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3722                                         res
3723                                 }
3724                         }
3725                 }
3726
3727                 macro_rules! test_preimages_exist {
3728                         ($preimages_slice: expr, $monitor: expr) => {
3729                                 for preimage in $preimages_slice {
3730                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
3731                                 }
3732                         }
3733                 }
3734
3735                 let keys = InMemoryChannelKeys::new(
3736                         &secp_ctx,
3737                         SecretKey::from_slice(&[41; 32]).unwrap(),
3738                         SecretKey::from_slice(&[41; 32]).unwrap(),
3739                         SecretKey::from_slice(&[41; 32]).unwrap(),
3740                         SecretKey::from_slice(&[41; 32]).unwrap(),
3741                         SecretKey::from_slice(&[41; 32]).unwrap(),
3742                         [41; 32],
3743                         0,
3744                 );
3745
3746                 // Prune with one old state and a local commitment tx holding a few overlaps with the
3747                 // old state.
3748                 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());
3749                 monitor.their_to_self_delay = Some(10);
3750
3751                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3752                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3753                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3754                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3755                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3756                 for &(ref preimage, ref hash) in preimages.iter() {
3757                         monitor.provide_payment_preimage(hash, preimage);
3758                 }
3759
3760                 // Now provide a secret, pruning preimages 10-15
3761                 let mut secret = [0; 32];
3762                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3763                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3764                 assert_eq!(monitor.payment_preimages.len(), 15);
3765                 test_preimages_exist!(&preimages[0..10], monitor);
3766                 test_preimages_exist!(&preimages[15..20], monitor);
3767
3768                 // Now provide a further secret, pruning preimages 15-17
3769                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3770                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3771                 assert_eq!(monitor.payment_preimages.len(), 13);
3772                 test_preimages_exist!(&preimages[0..10], monitor);
3773                 test_preimages_exist!(&preimages[17..20], monitor);
3774
3775                 // Now update local commitment tx info, pruning only element 18 as we still care about the
3776                 // previous commitment tx's preimages too
3777                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3778                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3779                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3780                 assert_eq!(monitor.payment_preimages.len(), 12);
3781                 test_preimages_exist!(&preimages[0..10], monitor);
3782                 test_preimages_exist!(&preimages[18..20], monitor);
3783
3784                 // But if we do it again, we'll prune 5-10
3785                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
3786                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3787                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3788                 assert_eq!(monitor.payment_preimages.len(), 5);
3789                 test_preimages_exist!(&preimages[0..5], monitor);
3790         }
3791
3792         #[test]
3793         fn test_claim_txn_weight_computation() {
3794                 // We test Claim txn weight, knowing that we want expected weigth and
3795                 // not actual case to avoid sigs and time-lock delays hell variances.
3796
3797                 let secp_ctx = Secp256k1::new();
3798                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3799                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3800                 let mut sum_actual_sigs = 0;
3801
3802                 macro_rules! sign_input {
3803                         ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3804                                 let htlc = HTLCOutputInCommitment {
3805                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3806                                         amount_msat: 0,
3807                                         cltv_expiry: 2 << 16,
3808                                         payment_hash: PaymentHash([1; 32]),
3809                                         transaction_output_index: Some($idx),
3810                                 };
3811                                 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) };
3812                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3813                                 let sig = secp_ctx.sign(&sighash, &privkey);
3814                                 $input.witness.push(sig.serialize_der().to_vec());
3815                                 $input.witness[0].push(SigHashType::All as u8);
3816                                 sum_actual_sigs += $input.witness[0].len();
3817                                 if *$input_type == InputDescriptors::RevokedOutput {
3818                                         $input.witness.push(vec!(1));
3819                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3820                                         $input.witness.push(pubkey.clone().serialize().to_vec());
3821                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3822                                         $input.witness.push(vec![0]);
3823                                 } else {
3824                                         $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3825                                 }
3826                                 $input.witness.push(redeem_script.into_bytes());
3827                                 println!("witness[0] {}", $input.witness[0].len());
3828                                 println!("witness[1] {}", $input.witness[1].len());
3829                                 println!("witness[2] {}", $input.witness[2].len());
3830                         }
3831                 }
3832
3833                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3834                 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3835
3836                 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3837                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3838                 for i in 0..4 {
3839                         claim_tx.input.push(TxIn {
3840                                 previous_output: BitcoinOutPoint {
3841                                         txid,
3842                                         vout: i,
3843                                 },
3844                                 script_sig: Script::new(),
3845                                 sequence: 0xfffffffd,
3846                                 witness: Vec::new(),
3847                         });
3848                 }
3849                 claim_tx.output.push(TxOut {
3850                         script_pubkey: script_pubkey.clone(),
3851                         value: 0,
3852                 });
3853                 let base_weight = claim_tx.get_weight();
3854                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3855                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3856                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3857                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3858                 }
3859                 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));
3860
3861                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3862                 claim_tx.input.clear();
3863                 sum_actual_sigs = 0;
3864                 for i in 0..4 {
3865                         claim_tx.input.push(TxIn {
3866                                 previous_output: BitcoinOutPoint {
3867                                         txid,
3868                                         vout: i,
3869                                 },
3870                                 script_sig: Script::new(),
3871                                 sequence: 0xfffffffd,
3872                                 witness: Vec::new(),
3873                         });
3874                 }
3875                 let base_weight = claim_tx.get_weight();
3876                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3877                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3878                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3879                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3880                 }
3881                 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));
3882
3883                 // Justice tx with 1 revoked HTLC-Success tx output
3884                 claim_tx.input.clear();
3885                 sum_actual_sigs = 0;
3886                 claim_tx.input.push(TxIn {
3887                         previous_output: BitcoinOutPoint {
3888                                 txid,
3889                                 vout: 0,
3890                         },
3891                         script_sig: Script::new(),
3892                         sequence: 0xfffffffd,
3893                         witness: Vec::new(),
3894                 });
3895                 let base_weight = claim_tx.get_weight();
3896                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3897                 let inputs_des = vec![InputDescriptors::RevokedOutput];
3898                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3899                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3900                 }
3901                 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));
3902         }
3903
3904         // Further testing is done in the ChannelManager integration tests.
3905 }