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