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