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