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