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