Introduce OnchainTxHandler, move bumping and tracking logic
[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::{TxOut,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
22 use bitcoin_hashes::Hash;
23 use bitcoin_hashes::sha256::Hash as Sha256;
24 use bitcoin_hashes::hash160::Hash as Hash160;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
26
27 use secp256k1::{Secp256k1,Signature};
28 use secp256k1::key::{SecretKey,PublicKey};
29 use secp256k1;
30
31 use ln::msgs::DecodeError;
32 use ln::chan_utils;
33 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType};
34 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
35 use ln::onchaintx::OnchainTxHandler;
36 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator};
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};
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 Readable for ChannelMonitorUpdate {
76         fn read<R: ::std::io::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 pub(crate) 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 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
449 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
450 /// a new bumped one in case of lenghty confirmation delay
451 #[derive(Clone, PartialEq)]
452 pub(crate) enum InputMaterial {
453         Revoked {
454                 script: Script,
455                 pubkey: Option<PublicKey>,
456                 key: SecretKey,
457                 is_htlc: bool,
458                 amount: u64,
459         },
460         RemoteHTLC {
461                 script: Script,
462                 key: SecretKey,
463                 preimage: Option<PaymentPreimage>,
464                 amount: u64,
465                 locktime: u32,
466         },
467         LocalHTLC {
468                 script: Script,
469                 sigs: (Signature, Signature),
470                 preimage: Option<PaymentPreimage>,
471                 amount: u64,
472         }
473 }
474
475 impl Writeable for InputMaterial  {
476         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
477                 match self {
478                         &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
479                                 writer.write_all(&[0; 1])?;
480                                 script.write(writer)?;
481                                 pubkey.write(writer)?;
482                                 writer.write_all(&key[..])?;
483                                 is_htlc.write(writer)?;
484                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
485                         },
486                         &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
487                                 writer.write_all(&[1; 1])?;
488                                 script.write(writer)?;
489                                 key.write(writer)?;
490                                 preimage.write(writer)?;
491                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
492                                 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
493                         },
494                         &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
495                                 writer.write_all(&[2; 1])?;
496                                 script.write(writer)?;
497                                 sigs.0.write(writer)?;
498                                 sigs.1.write(writer)?;
499                                 preimage.write(writer)?;
500                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
501                         }
502                 }
503                 Ok(())
504         }
505 }
506
507 impl Readable for InputMaterial {
508         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
509                 let input_material = match <u8 as Readable>::read(reader)? {
510                         0 => {
511                                 let script = Readable::read(reader)?;
512                                 let pubkey = Readable::read(reader)?;
513                                 let key = Readable::read(reader)?;
514                                 let is_htlc = Readable::read(reader)?;
515                                 let amount = Readable::read(reader)?;
516                                 InputMaterial::Revoked {
517                                         script,
518                                         pubkey,
519                                         key,
520                                         is_htlc,
521                                         amount
522                                 }
523                         },
524                         1 => {
525                                 let script = Readable::read(reader)?;
526                                 let key = Readable::read(reader)?;
527                                 let preimage = Readable::read(reader)?;
528                                 let amount = Readable::read(reader)?;
529                                 let locktime = Readable::read(reader)?;
530                                 InputMaterial::RemoteHTLC {
531                                         script,
532                                         key,
533                                         preimage,
534                                         amount,
535                                         locktime
536                                 }
537                         },
538                         2 => {
539                                 let script = Readable::read(reader)?;
540                                 let their_sig = Readable::read(reader)?;
541                                 let our_sig = Readable::read(reader)?;
542                                 let preimage = Readable::read(reader)?;
543                                 let amount = Readable::read(reader)?;
544                                 InputMaterial::LocalHTLC {
545                                         script,
546                                         sigs: (their_sig, our_sig),
547                                         preimage,
548                                         amount
549                                 }
550                         }
551                         _ => return Err(DecodeError::InvalidValue),
552                 };
553                 Ok(input_material)
554         }
555 }
556
557 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
558 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
559 #[derive(Clone, PartialEq)]
560 enum OnchainEvent {
561         /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
562         /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
563         /// only win from it, so it's never an OnchainEvent
564         HTLCUpdate {
565                 htlc_update: (HTLCSource, PaymentHash),
566         },
567 }
568
569 const SERIALIZATION_VERSION: u8 = 1;
570 const MIN_SERIALIZATION_VERSION: u8 = 1;
571
572 #[cfg_attr(test, derive(PartialEq))]
573 #[derive(Clone)]
574 pub(super) enum ChannelMonitorUpdateStep {
575         LatestLocalCommitmentTXInfo {
576                 // TODO: We really need to not be generating a fully-signed transaction in Channel and
577                 // passing it here, we need to hold off so that the ChanSigner can enforce a
578                 // only-sign-local-state-for-broadcast once invariant:
579                 commitment_tx: LocalCommitmentTransaction,
580                 local_keys: chan_utils::TxCreationKeys,
581                 feerate_per_kw: u64,
582                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
583         },
584         LatestRemoteCommitmentTXInfo {
585                 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
586                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
587                 commitment_number: u64,
588                 their_revocation_point: PublicKey,
589         },
590         PaymentPreimage {
591                 payment_preimage: PaymentPreimage,
592         },
593         CommitmentSecret {
594                 idx: u64,
595                 secret: [u8; 32],
596         },
597         /// Indicates our channel is likely a stale version, we're closing, but this update should
598         /// allow us to spend what is ours if our counterparty broadcasts their latest state.
599         RescueRemoteCommitmentTXInfo {
600                 their_current_per_commitment_point: PublicKey,
601         },
602 }
603
604 impl Writeable for ChannelMonitorUpdateStep {
605         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
606                 match self {
607                         &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
608                                 0u8.write(w)?;
609                                 commitment_tx.write(w)?;
610                                 local_keys.write(w)?;
611                                 feerate_per_kw.write(w)?;
612                                 (htlc_outputs.len() as u64).write(w)?;
613                                 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
614                                         output.write(w)?;
615                                         signature.write(w)?;
616                                         source.write(w)?;
617                                 }
618                         }
619                         &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
620                                 1u8.write(w)?;
621                                 unsigned_commitment_tx.write(w)?;
622                                 commitment_number.write(w)?;
623                                 their_revocation_point.write(w)?;
624                                 (htlc_outputs.len() as u64).write(w)?;
625                                 for &(ref output, ref source) in htlc_outputs.iter() {
626                                         output.write(w)?;
627                                         source.as_ref().map(|b| b.as_ref()).write(w)?;
628                                 }
629                         },
630                         &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
631                                 2u8.write(w)?;
632                                 payment_preimage.write(w)?;
633                         },
634                         &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
635                                 3u8.write(w)?;
636                                 idx.write(w)?;
637                                 secret.write(w)?;
638                         },
639                         &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => {
640                                 4u8.write(w)?;
641                                 their_current_per_commitment_point.write(w)?;
642                         },
643                 }
644                 Ok(())
645         }
646 }
647 impl Readable for ChannelMonitorUpdateStep {
648         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
649                 match Readable::read(r)? {
650                         0u8 => {
651                                 Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
652                                         commitment_tx: Readable::read(r)?,
653                                         local_keys: Readable::read(r)?,
654                                         feerate_per_kw: Readable::read(r)?,
655                                         htlc_outputs: {
656                                                 let len: u64 = Readable::read(r)?;
657                                                 let mut res = Vec::new();
658                                                 for _ in 0..len {
659                                                         res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
660                                                 }
661                                                 res
662                                         },
663                                 })
664                         },
665                         1u8 => {
666                                 Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
667                                         unsigned_commitment_tx: Readable::read(r)?,
668                                         commitment_number: Readable::read(r)?,
669                                         their_revocation_point: Readable::read(r)?,
670                                         htlc_outputs: {
671                                                 let len: u64 = Readable::read(r)?;
672                                                 let mut res = Vec::new();
673                                                 for _ in 0..len {
674                                                         res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
675                                                 }
676                                                 res
677                                         },
678                                 })
679                         },
680                         2u8 => {
681                                 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
682                                         payment_preimage: Readable::read(r)?,
683                                 })
684                         },
685                         3u8 => {
686                                 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
687                                         idx: Readable::read(r)?,
688                                         secret: Readable::read(r)?,
689                                 })
690                         },
691                         4u8 => {
692                                 Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo {
693                                         their_current_per_commitment_point: Readable::read(r)?,
694                                 })
695                         },
696                         _ => Err(DecodeError::InvalidValue),
697                 }
698         }
699 }
700
701 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
702 /// on-chain transactions to ensure no loss of funds occurs.
703 ///
704 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
705 /// information and are actively monitoring the chain.
706 ///
707 /// Pending Events or updated HTLCs which have not yet been read out by
708 /// get_and_clear_pending_htlcs_updated or get_and_clear_pending_events are serialized to disk and
709 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
710 /// gotten are fully handled before re-serializing the new state.
711 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
712         latest_update_id: u64,
713         commitment_transaction_number_obscure_factor: u64,
714
715         key_storage: Storage<ChanSigner>,
716         their_htlc_base_key: Option<PublicKey>,
717         their_delayed_payment_base_key: Option<PublicKey>,
718         funding_redeemscript: Option<Script>,
719         channel_value_satoshis: Option<u64>,
720         // first is the idx of the first of the two revocation points
721         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
722
723         our_to_self_delay: u16,
724         their_to_self_delay: Option<u16>,
725
726         commitment_secrets: CounterpartyCommitmentSecrets,
727         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
728         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
729         /// Nor can we figure out their commitment numbers without the commitment transaction they are
730         /// spending. Thus, in order to claim them via revocation key, we track all the remote
731         /// commitment transactions which we find on-chain, mapping them to the commitment number which
732         /// can be used to derive the revocation key and claim the transactions.
733         remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
734         /// Cache used to make pruning of payment_preimages faster.
735         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
736         /// remote transactions (ie should remain pretty small).
737         /// Serialized to disk but should generally not be sent to Watchtowers.
738         remote_hash_commitment_number: HashMap<PaymentHash, u64>,
739
740         // We store two local commitment transactions to avoid any race conditions where we may update
741         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
742         // various monitors for one channel being out of sync, and us broadcasting a local
743         // transaction for which we have deleted claim information on some watchtowers.
744         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
745         current_local_signed_commitment_tx: Option<LocalSignedTx>,
746
747         // Used just for ChannelManager to make sure it has the latest channel data during
748         // deserialization
749         current_remote_commitment_number: u64,
750
751         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
752
753         pending_htlcs_updated: Vec<HTLCUpdate>,
754         pending_events: Vec<events::Event>,
755
756         // Thanks to data loss protection, we may be able to claim our non-htlc funds
757         // back, this is the script we have to spend from but we need to
758         // scan every commitment transaction for that
759         to_remote_rescue: Option<(Script, SecretKey)>,
760
761         // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
762         // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
763         // actions when we receive a block with given height. Actions depend on OnchainEvent type.
764         onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
765
766         // If we get serialized out and re-read, we need to make sure that the chain monitoring
767         // interface knows about the TXOs that we want to be notified of spends of. We could probably
768         // be smart and derive them from the above storage fields, but its much simpler and more
769         // Obviously Correct (tm) if we just keep track of them explicitly.
770         outputs_to_watch: HashMap<Sha256dHash, Vec<Script>>,
771
772         #[cfg(test)]
773         pub onchain_tx_handler: OnchainTxHandler,
774         #[cfg(not(test))]
775         onchain_tx_handler: OnchainTxHandler,
776
777         // We simply modify last_block_hash in Channel's block_connected so that serialization is
778         // consistent but hopefully the users' copy handles block_connected in a consistent way.
779         // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
780         // their last_block_hash from its state and not based on updated copies that didn't run through
781         // the full block_connected).
782         pub(crate) last_block_hash: Sha256dHash,
783         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
784         logger: Arc<Logger>,
785 }
786
787 #[cfg(any(test, feature = "fuzztarget"))]
788 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
789 /// underlying object
790 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
791         fn eq(&self, other: &Self) -> bool {
792                 if self.latest_update_id != other.latest_update_id ||
793                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
794                         self.key_storage != other.key_storage ||
795                         self.their_htlc_base_key != other.their_htlc_base_key ||
796                         self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
797                         self.funding_redeemscript != other.funding_redeemscript ||
798                         self.channel_value_satoshis != other.channel_value_satoshis ||
799                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
800                         self.our_to_self_delay != other.our_to_self_delay ||
801                         self.their_to_self_delay != other.their_to_self_delay ||
802                         self.commitment_secrets != other.commitment_secrets ||
803                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
804                         self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
805                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
806                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
807                         self.current_remote_commitment_number != other.current_remote_commitment_number ||
808                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
809                         self.payment_preimages != other.payment_preimages ||
810                         self.pending_htlcs_updated != other.pending_htlcs_updated ||
811                         self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
812                         self.to_remote_rescue != other.to_remote_rescue ||
813                         self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
814                         self.outputs_to_watch != other.outputs_to_watch
815                 {
816                         false
817                 } else {
818                         true
819                 }
820         }
821 }
822
823 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
824         /// Serializes into a vec, with various modes for the exposed pub fns
825         fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
826                 //TODO: We still write out all the serialization here manually instead of using the fancy
827                 //serialization framework we have, we should migrate things over to it.
828                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
829                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
830
831                 self.latest_update_id.write(writer)?;
832
833                 // Set in initial Channel-object creation, so should always be set by now:
834                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
835
836                 match self.key_storage {
837                         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 } => {
838                                 writer.write_all(&[0; 1])?;
839                                 keys.write(writer)?;
840                                 writer.write_all(&funding_key[..])?;
841                                 writer.write_all(&revocation_base_key[..])?;
842                                 writer.write_all(&htlc_base_key[..])?;
843                                 writer.write_all(&delayed_payment_base_key[..])?;
844                                 writer.write_all(&payment_base_key[..])?;
845                                 writer.write_all(&shutdown_pubkey.serialize())?;
846                                 match funding_info  {
847                                         &Some((ref outpoint, ref script)) => {
848                                                 writer.write_all(&outpoint.txid[..])?;
849                                                 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
850                                                 script.write(writer)?;
851                                         },
852                                         &None => {
853                                                 debug_assert!(false, "Try to serialize a useless Local monitor !");
854                                         },
855                                 }
856                                 current_remote_commitment_txid.write(writer)?;
857                                 prev_remote_commitment_txid.write(writer)?;
858                         },
859                         Storage::Watchtower { .. } => unimplemented!(),
860                 }
861
862                 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
863                 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
864                 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
865                 self.channel_value_satoshis.unwrap().write(writer)?;
866
867                 match self.their_cur_revocation_points {
868                         Some((idx, pubkey, second_option)) => {
869                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
870                                 writer.write_all(&pubkey.serialize())?;
871                                 match second_option {
872                                         Some(second_pubkey) => {
873                                                 writer.write_all(&second_pubkey.serialize())?;
874                                         },
875                                         None => {
876                                                 writer.write_all(&[0; 33])?;
877                                         },
878                                 }
879                         },
880                         None => {
881                                 writer.write_all(&byte_utils::be48_to_array(0))?;
882                         },
883                 }
884
885                 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
886                 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
887
888                 self.commitment_secrets.write(writer)?;
889
890                 macro_rules! serialize_htlc_in_commitment {
891                         ($htlc_output: expr) => {
892                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
893                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
894                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
895                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
896                                 $htlc_output.transaction_output_index.write(writer)?;
897                         }
898                 }
899
900                 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
901                 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
902                         writer.write_all(&txid[..])?;
903                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
904                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
905                                 serialize_htlc_in_commitment!(htlc_output);
906                                 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
907                         }
908                 }
909
910                 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
911                 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
912                         writer.write_all(&txid[..])?;
913                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
914                         (txouts.len() as u64).write(writer)?;
915                         for script in txouts.iter() {
916                                 script.write(writer)?;
917                         }
918                 }
919
920                 if for_local_storage {
921                         writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
922                         for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
923                                 writer.write_all(&payment_hash.0[..])?;
924                                 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
925                         }
926                 } else {
927                         writer.write_all(&byte_utils::be64_to_array(0))?;
928                 }
929
930                 macro_rules! serialize_local_tx {
931                         ($local_tx: expr) => {
932                                 $local_tx.tx.write(writer)?;
933                                 writer.write_all(&$local_tx.revocation_key.serialize())?;
934                                 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
935                                 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
936                                 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
937                                 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
938
939                                 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
940                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
941                                 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
942                                         serialize_htlc_in_commitment!(htlc_output);
943                                         if let &Some(ref their_sig) = sig {
944                                                 1u8.write(writer)?;
945                                                 writer.write_all(&their_sig.serialize_compact())?;
946                                         } else {
947                                                 0u8.write(writer)?;
948                                         }
949                                         htlc_source.write(writer)?;
950                                 }
951                         }
952                 }
953
954                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
955                         writer.write_all(&[1; 1])?;
956                         serialize_local_tx!(prev_local_tx);
957                 } else {
958                         writer.write_all(&[0; 1])?;
959                 }
960
961                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
962                         writer.write_all(&[1; 1])?;
963                         serialize_local_tx!(cur_local_tx);
964                 } else {
965                         writer.write_all(&[0; 1])?;
966                 }
967
968                 if for_local_storage {
969                         writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
970                 } else {
971                         writer.write_all(&byte_utils::be48_to_array(0))?;
972                 }
973
974                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
975                 for payment_preimage in self.payment_preimages.values() {
976                         writer.write_all(&payment_preimage.0[..])?;
977                 }
978
979                 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
980                 for data in self.pending_htlcs_updated.iter() {
981                         data.write(writer)?;
982                 }
983
984                 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
985                 for event in self.pending_events.iter() {
986                         event.write(writer)?;
987                 }
988
989                 self.last_block_hash.write(writer)?;
990                 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
991                         writer.write_all(&[1; 1])?;
992                         to_remote_script.write(writer)?;
993                         local_key.write(writer)?;
994                 } else {
995                         writer.write_all(&[0; 1])?;
996                 }
997
998                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
999                 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1000                         writer.write_all(&byte_utils::be32_to_array(**target))?;
1001                         writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1002                         for ev in events.iter() {
1003                                 match *ev {
1004                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1005                                                 writer.write_all(&[1; 1])?;
1006                                                 htlc_update.0.write(writer)?;
1007                                                 htlc_update.1.write(writer)?;
1008                                         },
1009                                 }
1010                         }
1011                 }
1012
1013                 (self.outputs_to_watch.len() as u64).write(writer)?;
1014                 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1015                         txid.write(writer)?;
1016                         (output_scripts.len() as u64).write(writer)?;
1017                         for script in output_scripts.iter() {
1018                                 script.write(writer)?;
1019                         }
1020                 }
1021                 self.onchain_tx_handler.write(writer)?;
1022
1023                 Ok(())
1024         }
1025
1026         /// Writes this monitor into the given writer, suitable for writing to disk.
1027         ///
1028         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1029         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1030         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1031         /// common block that appears on your best chain as well as on the chain which contains the
1032         /// last block hash returned) upon deserializing the object!
1033         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1034                 self.write(writer, true)
1035         }
1036
1037         /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1038         ///
1039         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1040         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1041         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1042         /// common block that appears on your best chain as well as on the chain which contains the
1043         /// last block hash returned) upon deserializing the object!
1044         pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1045                 self.write(writer, false)
1046         }
1047 }
1048
1049 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1050         pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1051                         our_to_self_delay: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1052                         their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey,
1053                         their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1054                         commitment_transaction_number_obscure_factor: u64,
1055                         logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
1056
1057                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1058                 let funding_key = keys.funding_key().clone();
1059                 let revocation_base_key = keys.revocation_base_key().clone();
1060                 let htlc_base_key = keys.htlc_base_key().clone();
1061                 let delayed_payment_base_key = keys.delayed_payment_base_key().clone();
1062                 let payment_base_key = keys.payment_base_key().clone();
1063                 ChannelMonitor {
1064                         latest_update_id: 0,
1065                         commitment_transaction_number_obscure_factor,
1066
1067                         key_storage: Storage::Local {
1068                                 keys,
1069                                 funding_key,
1070                                 revocation_base_key,
1071                                 htlc_base_key,
1072                                 delayed_payment_base_key,
1073                                 payment_base_key,
1074                                 shutdown_pubkey: shutdown_pubkey.clone(),
1075                                 funding_info: Some(funding_info),
1076                                 current_remote_commitment_txid: None,
1077                                 prev_remote_commitment_txid: None,
1078                         },
1079                         their_htlc_base_key: Some(their_htlc_base_key.clone()),
1080                         their_delayed_payment_base_key: Some(their_delayed_payment_base_key.clone()),
1081                         funding_redeemscript: Some(funding_redeemscript),
1082                         channel_value_satoshis: Some(channel_value_satoshis),
1083                         their_cur_revocation_points: None,
1084
1085                         our_to_self_delay: our_to_self_delay,
1086                         their_to_self_delay: Some(their_to_self_delay),
1087
1088                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1089                         remote_claimable_outpoints: HashMap::new(),
1090                         remote_commitment_txn_on_chain: HashMap::new(),
1091                         remote_hash_commitment_number: HashMap::new(),
1092
1093                         prev_local_signed_commitment_tx: None,
1094                         current_local_signed_commitment_tx: None,
1095                         current_remote_commitment_number: 1 << 48,
1096
1097                         payment_preimages: HashMap::new(),
1098                         pending_htlcs_updated: Vec::new(),
1099                         pending_events: Vec::new(),
1100
1101                         to_remote_rescue: None,
1102
1103                         onchain_events_waiting_threshold_conf: HashMap::new(),
1104                         outputs_to_watch: HashMap::new(),
1105
1106                         onchain_tx_handler: OnchainTxHandler::new(destination_script.clone(), logger.clone()),
1107
1108                         last_block_hash: Default::default(),
1109                         secp_ctx: Secp256k1::new(),
1110                         logger,
1111                 }
1112         }
1113
1114         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1115         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1116         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1117         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1118                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1119                         return Err(MonitorUpdateError("Previous secret did not match new one"));
1120                 }
1121
1122                 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1123                 // events for now-revoked/fulfilled HTLCs.
1124                 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1125                         if let Some(txid) = prev_remote_commitment_txid.take() {
1126                                 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1127                                         *source = None;
1128                                 }
1129                         }
1130                 }
1131
1132                 if !self.payment_preimages.is_empty() {
1133                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1134                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1135                         let min_idx = self.get_min_seen_secret();
1136                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1137
1138                         self.payment_preimages.retain(|&k, _| {
1139                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1140                                         if k == htlc.payment_hash {
1141                                                 return true
1142                                         }
1143                                 }
1144                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1145                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1146                                                 if k == htlc.payment_hash {
1147                                                         return true
1148                                                 }
1149                                         }
1150                                 }
1151                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1152                                         if *cn < min_idx {
1153                                                 return true
1154                                         }
1155                                         true
1156                                 } else { false };
1157                                 if contains {
1158                                         remote_hash_commitment_number.remove(&k);
1159                                 }
1160                                 false
1161                         });
1162                 }
1163
1164                 Ok(())
1165         }
1166
1167         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1168         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1169         /// possibly future revocation/preimage information) to claim outputs where possible.
1170         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1171         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) {
1172                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1173                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1174                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1175                 // timeouts)
1176                 for &(ref htlc, _) in &htlc_outputs {
1177                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1178                 }
1179
1180                 let new_txid = unsigned_commitment_tx.txid();
1181                 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1182                 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1183                 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1184                         *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1185                         *current_remote_commitment_txid = Some(new_txid);
1186                 }
1187                 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1188                 self.current_remote_commitment_number = commitment_number;
1189                 //TODO: Merge this into the other per-remote-transaction output storage stuff
1190                 match self.their_cur_revocation_points {
1191                         Some(old_points) => {
1192                                 if old_points.0 == commitment_number + 1 {
1193                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1194                                 } else if old_points.0 == commitment_number + 2 {
1195                                         if let Some(old_second_point) = old_points.2 {
1196                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1197                                         } else {
1198                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1199                                         }
1200                                 } else {
1201                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1202                                 }
1203                         },
1204                         None => {
1205                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1206                         }
1207                 }
1208         }
1209
1210         pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1211                 match self.key_storage {
1212                         Storage::Local { ref payment_base_key, ref keys, .. } => {
1213                                 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1214                                         let to_remote_script =  Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1215                                                 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1216                                                 .into_script();
1217                                         if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1218                                                 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1219                                         }
1220                                 }
1221                         },
1222                         Storage::Watchtower { .. } => {}
1223                 }
1224         }
1225
1226         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1227         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1228         /// is important that any clones of this channel monitor (including remote clones) by kept
1229         /// up-to-date as our local commitment transaction is updated.
1230         /// Panics if set_their_to_self_delay has never been called.
1231         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> {
1232                 if self.their_to_self_delay.is_none() {
1233                         return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1234                 }
1235                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1236                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1237                         txid: commitment_tx.txid(),
1238                         tx: commitment_tx,
1239                         revocation_key: local_keys.revocation_key,
1240                         a_htlc_key: local_keys.a_htlc_key,
1241                         b_htlc_key: local_keys.b_htlc_key,
1242                         delayed_payment_key: local_keys.a_delayed_payment_key,
1243                         per_commitment_point: local_keys.per_commitment_point,
1244                         feerate_per_kw,
1245                         htlc_outputs,
1246                 });
1247                 Ok(())
1248         }
1249
1250         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1251         /// commitment_tx_infos which contain the payment hash have been revoked.
1252         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1253                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1254         }
1255
1256         /// Used in Channel to cheat wrt the update_ids since it plays games, will be removed soon!
1257         pub(super) fn update_monitor_ooo(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1258                 for update in updates.updates.drain(..) {
1259                         match update {
1260                                 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1261                                         self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1262                                 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1263                                         self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1264                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1265                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1266                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1267                                         self.provide_secret(idx, secret)?,
1268                                 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1269                                         self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1270                         }
1271                 }
1272                 self.latest_update_id = updates.update_id;
1273                 Ok(())
1274         }
1275
1276         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1277         /// itself.
1278         ///
1279         /// panics if the given update is not the next update by update_id.
1280         pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1281                 if self.latest_update_id + 1 != updates.update_id {
1282                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1283                 }
1284                 for update in updates.updates.drain(..) {
1285                         match update {
1286                                 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1287                                         self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1288                                 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1289                                         self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1290                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1291                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1292                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1293                                         self.provide_secret(idx, secret)?,
1294                                 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1295                                         self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1296                         }
1297                 }
1298                 self.latest_update_id = updates.update_id;
1299                 Ok(())
1300         }
1301
1302         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1303         /// ChannelMonitor.
1304         pub fn get_latest_update_id(&self) -> u64 {
1305                 self.latest_update_id
1306         }
1307
1308         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1309         pub fn get_funding_txo(&self) -> Option<OutPoint> {
1310                 match self.key_storage {
1311                         Storage::Local { ref funding_info, .. } => {
1312                                 match funding_info {
1313                                         &Some((outpoint, _)) => Some(outpoint),
1314                                         &None => None
1315                                 }
1316                         },
1317                         Storage::Watchtower { .. } => {
1318                                 return None;
1319                         }
1320                 }
1321         }
1322
1323         /// Gets a list of txids, with their output scripts (in the order they appear in the
1324         /// transaction), which we must learn about spends of via block_connected().
1325         pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1326                 &self.outputs_to_watch
1327         }
1328
1329         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1330         /// Generally useful when deserializing as during normal operation the return values of
1331         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1332         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1333         pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1334                 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1335                 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1336                         for (idx, output) in outputs.iter().enumerate() {
1337                                 res.push(((*txid).clone(), idx as u32, output));
1338                         }
1339                 }
1340                 res
1341         }
1342
1343         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1344         /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1345         pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1346                 let mut ret = Vec::new();
1347                 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1348                 ret
1349         }
1350
1351         /// Gets the list of pending events which were generated by previous actions, clearing the list
1352         /// in the process.
1353         ///
1354         /// This is called by ManyChannelMonitor::get_and_clear_pending_events() and is equivalent to
1355         /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1356         /// no internal locking in ChannelMonitors.
1357         pub fn get_and_clear_pending_events(&mut self) -> Vec<events::Event> {
1358                 let mut ret = Vec::new();
1359                 mem::swap(&mut ret, &mut self.pending_events);
1360                 ret
1361         }
1362
1363         /// Can only fail if idx is < get_min_seen_secret
1364         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1365                 self.commitment_secrets.get_secret(idx)
1366         }
1367
1368         pub(super) fn get_min_seen_secret(&self) -> u64 {
1369                 self.commitment_secrets.get_min_seen_secret()
1370         }
1371
1372         pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1373                 self.current_remote_commitment_number
1374         }
1375
1376         pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1377                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1378                         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)
1379                 } else { 0xffff_ffff_ffff }
1380         }
1381
1382         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1383         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1384         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1385         /// HTLC-Success/HTLC-Timeout transactions.
1386         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1387         /// revoked remote commitment tx
1388         fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<(u32, bool, BitcoinOutPoint, InputMaterial)>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1389                 // Most secp and related errors trying to create keys means we have no hope of constructing
1390                 // a spend transaction...so we return no transactions to broadcast
1391                 let mut claimable_outpoints = Vec::new();
1392                 let mut watch_outputs = Vec::new();
1393                 let mut spendable_outputs = Vec::new();
1394
1395                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1396                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1397
1398                 macro_rules! ignore_error {
1399                         ( $thing : expr ) => {
1400                                 match $thing {
1401                                         Ok(a) => a,
1402                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs)
1403                                 }
1404                         };
1405                 }
1406
1407                 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);
1408                 if commitment_number >= self.get_min_seen_secret() {
1409                         let secret = self.get_secret(commitment_number).unwrap();
1410                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1411                         let (revocation_pubkey, revocation_key, b_htlc_key, local_payment_key) = match self.key_storage {
1412                                 Storage::Local { ref keys, ref revocation_base_key, ref payment_base_key, .. } => {
1413                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1414                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1415                                         ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key)),
1416                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1417                                         Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1418                                 },
1419                                 Storage::Watchtower { .. } => {
1420                                         unimplemented!()
1421                                 },
1422                         };
1423                         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()));
1424                         let a_htlc_key = match self.their_htlc_base_key {
1425                                 None => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs),
1426                                 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)),
1427                         };
1428
1429                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1430                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1431
1432                         let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1433                                 // Note that the Network here is ignored as we immediately drop the address for the
1434                                 // script_pubkey version.
1435                                 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1436                                 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1437                         } else { None };
1438
1439                         // First, process non-htlc outputs (to_local & to_remote)
1440                         for (idx, outp) in tx.output.iter().enumerate() {
1441                                 if outp.script_pubkey == revokeable_p2wsh {
1442                                         claimable_outpoints.push((height + self.our_to_self_delay as u32, true, BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, InputMaterial::Revoked { script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: outp.value }));
1443                                 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1444                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1445                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1446                                                 key: local_payment_key.unwrap(),
1447                                                 output: outp.clone(),
1448                                         });
1449                                 }
1450                         }
1451
1452                         // Then, try to find revoked htlc outputs
1453                         if let Some(ref per_commitment_data) = per_commitment_option {
1454                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1455                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1456                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1457                                                 if transaction_output_index as usize >= tx.output.len() ||
1458                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1459                                                                 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1460                                                         return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1461                                                 }
1462                                                 claimable_outpoints.push((htlc.cltv_expiry, true, BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, InputMaterial::Revoked { script: expected_script, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: tx.output[transaction_output_index as usize].value }));
1463                                         }
1464                                 }
1465                         }
1466
1467                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1468                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1469                                 // We're definitely a remote commitment transaction!
1470                                 log_trace!(self, "Got broadcast of revoked remote commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1471                                 watch_outputs.append(&mut tx.output.clone());
1472                                 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1473
1474                                 macro_rules! check_htlc_fails {
1475                                         ($txid: expr, $commitment_tx: expr) => {
1476                                                 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1477                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1478                                                                 if let &Some(ref source) = source_option {
1479                                                                         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);
1480                                                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1481                                                                                 hash_map::Entry::Occupied(mut entry) => {
1482                                                                                         let e = entry.get_mut();
1483                                                                                         e.retain(|ref event| {
1484                                                                                                 match **event {
1485                                                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1486                                                                                                                 return htlc_update.0 != **source
1487                                                                                                         },
1488                                                                                                 }
1489                                                                                         });
1490                                                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1491                                                                                 }
1492                                                                                 hash_map::Entry::Vacant(entry) => {
1493                                                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1494                                                                                 }
1495                                                                         }
1496                                                                 }
1497                                                         }
1498                                                 }
1499                                         }
1500                                 }
1501                                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1502                                         if let &Some(ref txid) = current_remote_commitment_txid {
1503                                                 check_htlc_fails!(txid, "current");
1504                                         }
1505                                         if let &Some(ref txid) = prev_remote_commitment_txid {
1506                                                 check_htlc_fails!(txid, "remote");
1507                                         }
1508                                 }
1509                                 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1510                         }
1511                 } else if let Some(per_commitment_data) = per_commitment_option {
1512                         // While this isn't useful yet, there is a potential race where if a counterparty
1513                         // revokes a state at the same time as the commitment transaction for that state is
1514                         // confirmed, and the watchtower receives the block before the user, the user could
1515                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1516                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1517                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1518                         // insert it here.
1519                         watch_outputs.append(&mut tx.output.clone());
1520                         self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1521
1522                         log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1523
1524                         macro_rules! check_htlc_fails {
1525                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1526                                         if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1527                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1528                                                         if let &Some(ref source) = source_option {
1529                                                                 // Check if the HTLC is present in the commitment transaction that was
1530                                                                 // broadcast, but not if it was below the dust limit, which we should
1531                                                                 // fail backwards immediately as there is no way for us to learn the
1532                                                                 // payment_preimage.
1533                                                                 // Note that if the dust limit were allowed to change between
1534                                                                 // commitment transactions we'd want to be check whether *any*
1535                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1536                                                                 // cannot currently change after channel initialization, so we don't
1537                                                                 // need to here.
1538                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1539                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1540                                                                                 continue $id;
1541                                                                         }
1542                                                                 }
1543                                                                 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);
1544                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1545                                                                         hash_map::Entry::Occupied(mut entry) => {
1546                                                                                 let e = entry.get_mut();
1547                                                                                 e.retain(|ref event| {
1548                                                                                         match **event {
1549                                                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1550                                                                                                         return htlc_update.0 != **source
1551                                                                                                 },
1552                                                                                         }
1553                                                                                 });
1554                                                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1555                                                                         }
1556                                                                         hash_map::Entry::Vacant(entry) => {
1557                                                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1558                                                                         }
1559                                                                 }
1560                                                         }
1561                                                 }
1562                                         }
1563                                 }
1564                         }
1565                         if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1566                                 if let &Some(ref txid) = current_remote_commitment_txid {
1567                                         check_htlc_fails!(txid, "current", 'current_loop);
1568                                 }
1569                                 if let &Some(ref txid) = prev_remote_commitment_txid {
1570                                         check_htlc_fails!(txid, "previous", 'prev_loop);
1571                                 }
1572                         }
1573
1574                         if let Some(revocation_points) = self.their_cur_revocation_points {
1575                                 let revocation_point_option =
1576                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1577                                         else if let Some(point) = revocation_points.2.as_ref() {
1578                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1579                                         } else { None };
1580                                 if let Some(revocation_point) = revocation_point_option {
1581                                         let (revocation_pubkey, b_htlc_key, htlc_privkey) = match self.key_storage {
1582                                                 Storage::Local { ref keys, ref htlc_base_key, .. } => {
1583                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1584                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)),
1585                                                         ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1586                                                 },
1587                                                 Storage::Watchtower { .. } => { unimplemented!() }
1588                                         };
1589                                         let a_htlc_key = match self.their_htlc_base_key {
1590                                                 None => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs),
1591                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1592                                         };
1593
1594                                         // First, mark as spendable our to_remote output
1595                                         for (idx, outp) in tx.output.iter().enumerate() {
1596                                                 if outp.script_pubkey.is_v0_p2wpkh() {
1597                                                         match self.key_storage {
1598                                                                 Storage::Local { ref payment_base_key, .. } => {
1599                                                                         if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1600                                                                                 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1601                                                                                         outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1602                                                                                         key: local_key,
1603                                                                                         output: outp.clone(),
1604                                                                                 });
1605                                                                         }
1606                                                                 },
1607                                                                 Storage::Watchtower { .. } => {}
1608                                                         }
1609                                                         break; // Only to_remote ouput is claimable
1610                                                 }
1611                                         }
1612
1613                                         // Then, try to find htlc outputs
1614                                         for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1615                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1616                                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1617                                                         if transaction_output_index as usize >= tx.output.len() ||
1618                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1619                                                                         tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1620                                                                 return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1621                                                         }
1622                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1623                                                         let aggregable = if !htlc.offered { false } else { true };
1624                                                         if preimage.is_some() || !htlc.offered {
1625                                                                 claimable_outpoints.push((htlc.cltv_expiry, aggregable, BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, InputMaterial::RemoteHTLC { script: expected_script, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry }));
1626                                                         }
1627                                                 }
1628                                         }
1629                                 }
1630                         }
1631                 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
1632                         for (idx, outp) in tx.output.iter().enumerate() {
1633                                 if to_remote_rescue == &outp.script_pubkey {
1634                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1635                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1636                                                 key: local_key.clone(),
1637                                                 output: outp.clone(),
1638                                         });
1639                                 }
1640                         }
1641                 }
1642                 (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs)
1643         }
1644
1645         /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1646         fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32) -> Vec<(u32, bool, BitcoinOutPoint, InputMaterial)> {
1647                 //TODO: send back new outputs to guarantee pending_claim_request consistency
1648                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1649                         return Vec::new()
1650                 }
1651
1652                 macro_rules! ignore_error {
1653                         ( $thing : expr ) => {
1654                                 match $thing {
1655                                         Ok(a) => a,
1656                                         Err(_) => return Vec::new()
1657                                 }
1658                         };
1659                 }
1660
1661                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return Vec::new(); };
1662                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1663                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1664                 let (revocation_pubkey, revocation_key) = match self.key_storage {
1665                         Storage::Local { ref keys, ref revocation_base_key, .. } => {
1666                                 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1667                                 ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, revocation_base_key)))
1668                         },
1669                         Storage::Watchtower { .. } => { unimplemented!() }
1670                 };
1671                 let delayed_key = match self.their_delayed_payment_base_key {
1672                         None => return Vec::new(),
1673                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1674                 };
1675                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1676                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1677
1678                 log_trace!(self, "Remote HTLC broadcast {}:{}", htlc_txid, 0);
1679                 let claimable_outpoints = vec!((height + self.our_to_self_delay as u32, true, BitcoinOutPoint { txid: htlc_txid, vout: 0}, InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: tx.output[0].value }));
1680                 claimable_outpoints
1681         }
1682
1683         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>) {
1684                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1685                 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1686                 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1687
1688                 macro_rules! add_dynamic_output {
1689                         ($father_tx: expr, $vout: expr) => {
1690                                 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
1691                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1692                                                 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1693                                                 key: local_delayedkey,
1694                                                 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1695                                                 to_self_delay: self.our_to_self_delay,
1696                                                 output: $father_tx.output[$vout as usize].clone(),
1697                                         });
1698                                 }
1699                         }
1700                 }
1701
1702                 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1703                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1704                 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
1705                         if output.script_pubkey == revokeable_p2wsh {
1706                                 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
1707                                 break;
1708                         }
1709                 }
1710
1711                 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
1712                         for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
1713                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1714                                         if let &Some(ref their_sig) = sigs {
1715                                                 if htlc.offered {
1716                                                         log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
1717                                                         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);
1718                                                         let (our_sig, htlc_script) = match
1719                                                                         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) {
1720                                                                 Ok(res) => res,
1721                                                                 Err(_) => continue,
1722                                                         };
1723
1724                                                         add_dynamic_output!(htlc_timeout_tx, 0);
1725                                                         let mut per_input_material = HashMap::with_capacity(1);
1726                                                         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});
1727                                                         //TODO: with option_simplified_commitment track outpoint too
1728                                                         log_trace!(self, "Outpoint {}:{} is being being claimed", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid);
1729                                                         res.push(htlc_timeout_tx);
1730                                                 } else {
1731                                                         if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1732                                                                 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
1733                                                                 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);
1734                                                                 let (our_sig, htlc_script) = match
1735                                                                                 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) {
1736                                                                         Ok(res) => res,
1737                                                                         Err(_) => continue,
1738                                                                 };
1739
1740                                                                 add_dynamic_output!(htlc_success_tx, 0);
1741                                                                 let mut per_input_material = HashMap::with_capacity(1);
1742                                                                 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});
1743                                                                 //TODO: with option_simplified_commitment track outpoint too
1744                                                                 log_trace!(self, "Outpoint {}:{} is being being claimed", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid);
1745                                                                 res.push(htlc_success_tx);
1746                                                         }
1747                                                 }
1748                                                 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
1749                                         } else { panic!("Should have sigs for non-dust local tx outputs!") }
1750                                 }
1751                         }
1752                 }
1753
1754                 (res, spendable_outputs, watch_outputs)
1755         }
1756
1757         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1758         /// revoked using data in local_claimable_outpoints.
1759         /// Should not be used if check_spend_revoked_transaction succeeds.
1760         fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1761                 let commitment_txid = tx.txid();
1762                 let mut local_txn = Vec::new();
1763                 let mut spendable_outputs = Vec::new();
1764                 let mut watch_outputs = Vec::new();
1765
1766                 macro_rules! wait_threshold_conf {
1767                         ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1768                                 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);
1769                                 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
1770                                         hash_map::Entry::Occupied(mut entry) => {
1771                                                 let e = entry.get_mut();
1772                                                 e.retain(|ref event| {
1773                                                         match **event {
1774                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1775                                                                         return htlc_update.0 != $source
1776                                                                 },
1777                                                         }
1778                                                 });
1779                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
1780                                         }
1781                                         hash_map::Entry::Vacant(entry) => {
1782                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
1783                                         }
1784                                 }
1785                         }
1786                 }
1787
1788                 macro_rules! append_onchain_update {
1789                         ($updates: expr) => {
1790                                 local_txn.append(&mut $updates.0);
1791                                 spendable_outputs.append(&mut $updates.1);
1792                                 watch_outputs.append(&mut $updates.2);
1793                         }
1794                 }
1795
1796                 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1797                 let mut is_local_tx = false;
1798
1799                 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
1800                         if local_tx.txid == commitment_txid {
1801                                 match self.key_storage {
1802                                         Storage::Local { ref funding_key, .. } => {
1803                                                 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1804                                         },
1805                                         _ => {},
1806                                 }
1807                         }
1808                 }
1809                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1810                         if local_tx.txid == commitment_txid {
1811                                 is_local_tx = true;
1812                                 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
1813                                 assert!(local_tx.tx.has_local_sig());
1814                                 match self.key_storage {
1815                                         Storage::Local { ref delayed_payment_base_key, .. } => {
1816                                                 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key);
1817                                                 append_onchain_update!(res);
1818                                         },
1819                                         Storage::Watchtower { .. } => { }
1820                                 }
1821                         }
1822                 }
1823                 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
1824                         if local_tx.txid == commitment_txid {
1825                                 match self.key_storage {
1826                                         Storage::Local { ref funding_key, .. } => {
1827                                                 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1828                                         },
1829                                         _ => {},
1830                                 }
1831                         }
1832                 }
1833                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1834                         if local_tx.txid == commitment_txid {
1835                                 is_local_tx = true;
1836                                 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
1837                                 assert!(local_tx.tx.has_local_sig());
1838                                 match self.key_storage {
1839                                         Storage::Local { ref delayed_payment_base_key, .. } => {
1840                                                 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key);
1841                                                 append_onchain_update!(res);
1842                                         },
1843                                         Storage::Watchtower { .. } => { }
1844                                 }
1845                         }
1846                 }
1847
1848                 macro_rules! fail_dust_htlcs_after_threshold_conf {
1849                         ($local_tx: expr) => {
1850                                 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
1851                                         if htlc.transaction_output_index.is_none() {
1852                                                 if let &Some(ref source) = source {
1853                                                         wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
1854                                                 }
1855                                         }
1856                                 }
1857                         }
1858                 }
1859
1860                 if is_local_tx {
1861                         if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1862                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
1863                         }
1864                         if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1865                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
1866                         }
1867                 }
1868
1869                 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
1870         }
1871
1872         /// Generate a spendable output event when closing_transaction get registered onchain.
1873         fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1874                 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1875                         match self.key_storage {
1876                                 Storage::Local { ref shutdown_pubkey, .. } =>  {
1877                                         let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
1878                                         let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1879                                         for (idx, output) in tx.output.iter().enumerate() {
1880                                                 if shutdown_script == output.script_pubkey {
1881                                                         return Some(SpendableOutputDescriptor::StaticOutput {
1882                                                                 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1883                                                                 output: output.clone(),
1884                                                         });
1885                                                 }
1886                                         }
1887                                 }
1888                                 Storage::Watchtower { .. } => {
1889                                         //TODO: we need to ensure an offline client will generate the event when it
1890                                         // comes back online after only the watchtower saw the transaction
1891                                 }
1892                         }
1893                 }
1894                 None
1895         }
1896
1897         /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
1898         /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
1899         /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
1900         /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
1901         /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
1902         /// broadcast them if remote don't close channel with his higher commitment transaction after a
1903         /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1904         /// out-of-band the other node operator to coordinate with him if option is available to you.
1905         /// In any-case, choice is up to the user.
1906         pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
1907                 log_trace!(self, "Getting signed latest local commitment transaction!");
1908                 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
1909                         match self.key_storage {
1910                                 Storage::Local { ref funding_key, .. } => {
1911                                         local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1912                                 },
1913                                 _ => {},
1914                         }
1915                 }
1916                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1917                         let mut res = vec![local_tx.tx.with_valid_witness().clone()];
1918                         match self.key_storage {
1919                                 Storage::Local { ref delayed_payment_base_key, .. } => {
1920                                         res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key).0);
1921                                         // 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.
1922                                         // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
1923                                 },
1924                                 _ => panic!("Can only broadcast by local channelmonitor"),
1925                         };
1926                         res
1927                 } else {
1928                         Vec::new()
1929                 }
1930         }
1931
1932         /// Called by SimpleManyChannelMonitor::block_connected, which implements
1933         /// ChainListener::block_connected.
1934         /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
1935         /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
1936         /// on-chain.
1937         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>)>
1938                 where B::Target: BroadcasterInterface,
1939                       F::Target: FeeEstimator
1940         {
1941                 for tx in txn_matched {
1942                         let mut output_val = 0;
1943                         for out in tx.output.iter() {
1944                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1945                                 output_val += out.value;
1946                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1947                         }
1948                 }
1949
1950                 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
1951                 let mut watch_outputs = Vec::new();
1952                 let mut spendable_outputs = Vec::new();
1953                 let mut claimable_outpoints = Vec::new();
1954                 for tx in txn_matched {
1955                         if tx.input.len() == 1 {
1956                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1957                                 // commitment transactions and HTLC transactions will all only ever have one input,
1958                                 // which is an easy way to filter out any potential non-matching txn for lazy
1959                                 // filters.
1960                                 let prevout = &tx.input[0].previous_output;
1961                                 let funding_txo = match self.key_storage {
1962                                         Storage::Local { ref funding_info, .. } => {
1963                                                 funding_info.clone()
1964                                         }
1965                                         Storage::Watchtower { .. } => {
1966                                                 unimplemented!();
1967                                         }
1968                                 };
1969                                 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) {
1970                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1971                                                 let (mut new_outpoints, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height);
1972                                                 spendable_outputs.append(&mut spendable_output);
1973                                                 if !new_outputs.1.is_empty() {
1974                                                         watch_outputs.push(new_outputs);
1975                                                 }
1976                                                 if new_outpoints.is_empty() {
1977                                                         let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
1978                                                         spendable_outputs.append(&mut spendable_output);
1979                                                         for tx in local_txn.iter() {
1980                                                                 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
1981                                                                 broadcaster.broadcast_transaction(tx);
1982                                                         }
1983                                                         if !new_outputs.1.is_empty() {
1984                                                                 watch_outputs.push(new_outputs);
1985                                                         }
1986                                                 }
1987                                                 claimable_outpoints.push(new_outpoints);
1988                                         }
1989                                         if !funding_txo.is_none() && claimable_outpoints.is_empty() {
1990                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
1991                                                         spendable_outputs.push(spendable_output);
1992                                                 }
1993                                         }
1994                                 } else {
1995                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
1996                                                 let mut new_outpoints = self.check_spend_remote_htlc(&tx, commitment_number, height);
1997                                                 claimable_outpoints.push(new_outpoints);
1998                                         }
1999                                 }
2000                         }
2001                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2002                         // can also be resolved in a few other ways which can have more than one output. Thus,
2003                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2004                         self.is_resolving_htlc_output(&tx, height);
2005                 }
2006                 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2007                         self.would_broadcast_at_height(height)
2008                 } else { false };
2009                 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2010                         if should_broadcast {
2011                                 match self.key_storage {
2012                                         Storage::Local { ref funding_key, .. } => {
2013                                                 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2014                                         },
2015                                         _ => {}
2016                                 }
2017                         }
2018                 }
2019                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2020                         if should_broadcast {
2021                                 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2022                                 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2023                                 match self.key_storage {
2024                                         Storage::Local { ref delayed_payment_base_key, .. } => {
2025                                                 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key);
2026                                                 spendable_outputs.append(&mut spendable_output);
2027                                                 if !new_outputs.is_empty() {
2028                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2029                                                 }
2030                                                 for tx in txs {
2031                                                         log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2032                                                         broadcaster.broadcast_transaction(&tx);
2033                                                 }
2034                                         },
2035                                         Storage::Watchtower { .. } => { },
2036                                 }
2037                         }
2038                 }
2039                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2040                         for ev in events {
2041                                 match ev {
2042                                         OnchainEvent::HTLCUpdate { htlc_update } => {
2043                                                 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2044                                                 self.pending_htlcs_updated.push(HTLCUpdate {
2045                                                         payment_hash: htlc_update.1,
2046                                                         payment_preimage: None,
2047                                                         source: htlc_update.0,
2048                                                 });
2049                                         },
2050                                 }
2051                         }
2052                 }
2053                 let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, broadcaster, &*fee_estimator);
2054                 spendable_outputs.append(&mut spendable_output);
2055
2056                 self.last_block_hash = block_hash.clone();
2057                 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2058                         self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2059                 }
2060
2061                 if spendable_outputs.len() > 0 {
2062                         self.pending_events.push(events::Event::SpendableOutputs {
2063                                 outputs: spendable_outputs,
2064                         });
2065                 }
2066
2067                 watch_outputs
2068         }
2069
2070         fn block_disconnected<B: Deref, F: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)
2071                 where B::Target: BroadcasterInterface,
2072                       F::Target: FeeEstimator
2073         {
2074                 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2075                 if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2076                         //We may discard:
2077                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2078                 }
2079
2080                 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator);
2081
2082                 self.last_block_hash = block_hash.clone();
2083         }
2084
2085         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2086                 // We need to consider all HTLCs which are:
2087                 //  * in any unrevoked remote commitment transaction, as they could broadcast said
2088                 //    transactions and we'd end up in a race, or
2089                 //  * are in our latest local commitment transaction, as this is the thing we will
2090                 //    broadcast if we go on-chain.
2091                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2092                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2093                 // to the source, and if we don't fail the channel we will have to ensure that the next
2094                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2095                 // easier to just fail the channel as this case should be rare enough anyway.
2096                 macro_rules! scan_commitment {
2097                         ($htlcs: expr, $local_tx: expr) => {
2098                                 for ref htlc in $htlcs {
2099                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2100                                         // chain with enough room to claim the HTLC without our counterparty being able to
2101                                         // time out the HTLC first.
2102                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2103                                         // concern is being able to claim the corresponding inbound HTLC (on another
2104                                         // channel) before it expires. In fact, we don't even really care if our
2105                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2106                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2107                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2108                                         // we give ourselves a few blocks of headroom after expiration before going
2109                                         // on-chain for an expired HTLC.
2110                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2111                                         // from us until we've reached the point where we go on-chain with the
2112                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2113                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2114                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2115                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2116                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2117                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2118                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2119                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2120                                         //  The final, above, condition is checked for statically in channelmanager
2121                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2122                                         let htlc_outbound = $local_tx == htlc.offered;
2123                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2124                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2125                                                 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2126                                                 return true;
2127                                         }
2128                                 }
2129                         }
2130                 }
2131
2132                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2133                         scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2134                 }
2135
2136                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2137                         if let &Some(ref txid) = current_remote_commitment_txid {
2138                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2139                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2140                                 }
2141                         }
2142                         if let &Some(ref txid) = prev_remote_commitment_txid {
2143                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2144                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2145                                 }
2146                         }
2147                 }
2148
2149                 false
2150         }
2151
2152         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2153         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2154         fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2155                 'outer_loop: for input in &tx.input {
2156                         let mut payment_data = None;
2157                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2158                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2159                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2160                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2161
2162                         macro_rules! log_claim {
2163                                 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2164                                         // We found the output in question, but aren't failing it backwards
2165                                         // as we have no corresponding source and no valid remote commitment txid
2166                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2167                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2168                                         let outbound_htlc = $local_tx == $htlc.offered;
2169                                         if ($local_tx && revocation_sig_claim) ||
2170                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2171                                                 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2172                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2173                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2174                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2175                                         } else {
2176                                                 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2177                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2178                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2179                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2180                                         }
2181                                 }
2182                         }
2183
2184                         macro_rules! check_htlc_valid_remote {
2185                                 ($remote_txid: expr, $htlc_output: expr) => {
2186                                         if let &Some(txid) = $remote_txid {
2187                                                 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2188                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2189                                                                 if let &Some(ref source) = pending_source {
2190                                                                         log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2191                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2192                                                                         break;
2193                                                                 }
2194                                                         }
2195                                                 }
2196                                         }
2197                                 }
2198                         }
2199
2200                         macro_rules! scan_commitment {
2201                                 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2202                                         for (ref htlc_output, source_option) in $htlcs {
2203                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2204                                                         if let Some(ref source) = source_option {
2205                                                                 log_claim!($tx_info, $local_tx, htlc_output, true);
2206                                                                 // We have a resolution of an HTLC either from one of our latest
2207                                                                 // local commitment transactions or an unrevoked remote commitment
2208                                                                 // transaction. This implies we either learned a preimage, the HTLC
2209                                                                 // has timed out, or we screwed up. In any case, we should now
2210                                                                 // resolve the source HTLC with the original sender.
2211                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2212                                                         } else if !$local_tx {
2213                                                                 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2214                                                                         check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2215                                                                 }
2216                                                                 if payment_data.is_none() {
2217                                                                         if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2218                                                                                 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2219                                                                         }
2220                                                                 }
2221                                                         }
2222                                                         if payment_data.is_none() {
2223                                                                 log_claim!($tx_info, $local_tx, htlc_output, false);
2224                                                                 continue 'outer_loop;
2225                                                         }
2226                                                 }
2227                                         }
2228                                 }
2229                         }
2230
2231                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2232                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2233                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2234                                                 "our latest local commitment tx", true);
2235                                 }
2236                         }
2237                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2238                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2239                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2240                                                 "our previous local commitment tx", true);
2241                                 }
2242                         }
2243                         if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2244                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2245                                         "remote commitment tx", false);
2246                         }
2247
2248                         // Check that scan_commitment, above, decided there is some source worth relaying an
2249                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2250                         if let Some((source, payment_hash)) = payment_data {
2251                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2252                                 if accepted_preimage_claim {
2253                                         payment_preimage.0.copy_from_slice(&input.witness[3]);
2254                                         self.pending_htlcs_updated.push(HTLCUpdate {
2255                                                 source,
2256                                                 payment_preimage: Some(payment_preimage),
2257                                                 payment_hash
2258                                         });
2259                                 } else if offered_preimage_claim {
2260                                         payment_preimage.0.copy_from_slice(&input.witness[1]);
2261                                         self.pending_htlcs_updated.push(HTLCUpdate {
2262                                                 source,
2263                                                 payment_preimage: Some(payment_preimage),
2264                                                 payment_hash
2265                                         });
2266                                 } else {
2267                                         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);
2268                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2269                                                 hash_map::Entry::Occupied(mut entry) => {
2270                                                         let e = entry.get_mut();
2271                                                         e.retain(|ref event| {
2272                                                                 match **event {
2273                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2274                                                                                 return htlc_update.0 != source
2275                                                                         },
2276                                                                 }
2277                                                         });
2278                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2279                                                 }
2280                                                 hash_map::Entry::Vacant(entry) => {
2281                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2282                                                 }
2283                                         }
2284                                 }
2285                         }
2286                 }
2287         }
2288 }
2289
2290 const MAX_ALLOC_SIZE: usize = 64*1024;
2291
2292 impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
2293         fn read<R: ::std::io::Read>(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
2294                 macro_rules! unwrap_obj {
2295                         ($key: expr) => {
2296                                 match $key {
2297                                         Ok(res) => res,
2298                                         Err(_) => return Err(DecodeError::InvalidValue),
2299                                 }
2300                         }
2301                 }
2302
2303                 let _ver: u8 = Readable::read(reader)?;
2304                 let min_ver: u8 = Readable::read(reader)?;
2305                 if min_ver > SERIALIZATION_VERSION {
2306                         return Err(DecodeError::UnknownVersion);
2307                 }
2308
2309                 let latest_update_id: u64 = Readable::read(reader)?;
2310                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2311
2312                 let key_storage = match <u8 as Readable>::read(reader)? {
2313                         0 => {
2314                                 let keys = Readable::read(reader)?;
2315                                 let funding_key = Readable::read(reader)?;
2316                                 let revocation_base_key = Readable::read(reader)?;
2317                                 let htlc_base_key = Readable::read(reader)?;
2318                                 let delayed_payment_base_key = Readable::read(reader)?;
2319                                 let payment_base_key = Readable::read(reader)?;
2320                                 let shutdown_pubkey = Readable::read(reader)?;
2321                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2322                                 // barely-init'd ChannelMonitors that we can't do anything with.
2323                                 let outpoint = OutPoint {
2324                                         txid: Readable::read(reader)?,
2325                                         index: Readable::read(reader)?,
2326                                 };
2327                                 let funding_info = Some((outpoint, Readable::read(reader)?));
2328                                 let current_remote_commitment_txid = Readable::read(reader)?;
2329                                 let prev_remote_commitment_txid = Readable::read(reader)?;
2330                                 Storage::Local {
2331                                         keys,
2332                                         funding_key,
2333                                         revocation_base_key,
2334                                         htlc_base_key,
2335                                         delayed_payment_base_key,
2336                                         payment_base_key,
2337                                         shutdown_pubkey,
2338                                         funding_info,
2339                                         current_remote_commitment_txid,
2340                                         prev_remote_commitment_txid,
2341                                 }
2342                         },
2343                         _ => return Err(DecodeError::InvalidValue),
2344                 };
2345
2346                 let their_htlc_base_key = Some(Readable::read(reader)?);
2347                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
2348                 let funding_redeemscript = Some(Readable::read(reader)?);
2349                 let channel_value_satoshis = Some(Readable::read(reader)?);
2350
2351                 let their_cur_revocation_points = {
2352                         let first_idx = <U48 as Readable>::read(reader)?.0;
2353                         if first_idx == 0 {
2354                                 None
2355                         } else {
2356                                 let first_point = Readable::read(reader)?;
2357                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2358                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2359                                         Some((first_idx, first_point, None))
2360                                 } else {
2361                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2362                                 }
2363                         }
2364                 };
2365
2366                 let our_to_self_delay: u16 = Readable::read(reader)?;
2367                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
2368
2369                 let commitment_secrets = Readable::read(reader)?;
2370
2371                 macro_rules! read_htlc_in_commitment {
2372                         () => {
2373                                 {
2374                                         let offered: bool = Readable::read(reader)?;
2375                                         let amount_msat: u64 = Readable::read(reader)?;
2376                                         let cltv_expiry: u32 = Readable::read(reader)?;
2377                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2378                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2379
2380                                         HTLCOutputInCommitment {
2381                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2382                                         }
2383                                 }
2384                         }
2385                 }
2386
2387                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
2388                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2389                 for _ in 0..remote_claimable_outpoints_len {
2390                         let txid: Sha256dHash = Readable::read(reader)?;
2391                         let htlcs_count: u64 = Readable::read(reader)?;
2392                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2393                         for _ in 0..htlcs_count {
2394                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2395                         }
2396                         if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
2397                                 return Err(DecodeError::InvalidValue);
2398                         }
2399                 }
2400
2401                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2402                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2403                 for _ in 0..remote_commitment_txn_on_chain_len {
2404                         let txid: Sha256dHash = Readable::read(reader)?;
2405                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2406                         let outputs_count = <u64 as Readable>::read(reader)?;
2407                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2408                         for _ in 0..outputs_count {
2409                                 outputs.push(Readable::read(reader)?);
2410                         }
2411                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2412                                 return Err(DecodeError::InvalidValue);
2413                         }
2414                 }
2415
2416                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2417                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2418                 for _ in 0..remote_hash_commitment_number_len {
2419                         let payment_hash: PaymentHash = Readable::read(reader)?;
2420                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2421                         if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2422                                 return Err(DecodeError::InvalidValue);
2423                         }
2424                 }
2425
2426                 macro_rules! read_local_tx {
2427                         () => {
2428                                 {
2429                                         let tx = <LocalCommitmentTransaction as Readable>::read(reader)?;
2430                                         let revocation_key = Readable::read(reader)?;
2431                                         let a_htlc_key = Readable::read(reader)?;
2432                                         let b_htlc_key = Readable::read(reader)?;
2433                                         let delayed_payment_key = Readable::read(reader)?;
2434                                         let per_commitment_point = Readable::read(reader)?;
2435                                         let feerate_per_kw: u64 = Readable::read(reader)?;
2436
2437                                         let htlcs_len: u64 = Readable::read(reader)?;
2438                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2439                                         for _ in 0..htlcs_len {
2440                                                 let htlc = read_htlc_in_commitment!();
2441                                                 let sigs = match <u8 as Readable>::read(reader)? {
2442                                                         0 => None,
2443                                                         1 => Some(Readable::read(reader)?),
2444                                                         _ => return Err(DecodeError::InvalidValue),
2445                                                 };
2446                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
2447                                         }
2448
2449                                         LocalSignedTx {
2450                                                 txid: tx.txid(),
2451                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
2452                                                 htlc_outputs: htlcs
2453                                         }
2454                                 }
2455                         }
2456                 }
2457
2458                 let prev_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2459                         0 => None,
2460                         1 => {
2461                                 Some(read_local_tx!())
2462                         },
2463                         _ => return Err(DecodeError::InvalidValue),
2464                 };
2465
2466                 let current_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2467                         0 => None,
2468                         1 => {
2469                                 Some(read_local_tx!())
2470                         },
2471                         _ => return Err(DecodeError::InvalidValue),
2472                 };
2473
2474                 let current_remote_commitment_number = <U48 as Readable>::read(reader)?.0;
2475
2476                 let payment_preimages_len: u64 = Readable::read(reader)?;
2477                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2478                 for _ in 0..payment_preimages_len {
2479                         let preimage: PaymentPreimage = Readable::read(reader)?;
2480                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2481                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2482                                 return Err(DecodeError::InvalidValue);
2483                         }
2484                 }
2485
2486                 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
2487                 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2488                 for _ in 0..pending_htlcs_updated_len {
2489                         pending_htlcs_updated.push(Readable::read(reader)?);
2490                 }
2491
2492                 let pending_events_len: u64 = Readable::read(reader)?;
2493                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<events::Event>()));
2494                 for _ in 0..pending_events_len {
2495                         if let Some(event) = MaybeReadable::read(reader)? {
2496                                 pending_events.push(event);
2497                         }
2498                 }
2499
2500                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2501                 let to_remote_rescue = match <u8 as Readable>::read(reader)? {
2502                         0 => None,
2503                         1 => {
2504                                 let to_remote_script = Readable::read(reader)?;
2505                                 let local_key = Readable::read(reader)?;
2506                                 Some((to_remote_script, local_key))
2507                         }
2508                         _ => return Err(DecodeError::InvalidValue),
2509                 };
2510
2511                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2512                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2513                 for _ in 0..waiting_threshold_conf_len {
2514                         let height_target = Readable::read(reader)?;
2515                         let events_len: u64 = Readable::read(reader)?;
2516                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
2517                         for _ in 0..events_len {
2518                                 let ev = match <u8 as Readable>::read(reader)? {
2519                                         0 => {
2520                                                 let htlc_source = Readable::read(reader)?;
2521                                                 let hash = Readable::read(reader)?;
2522                                                 OnchainEvent::HTLCUpdate {
2523                                                         htlc_update: (htlc_source, hash)
2524                                                 }
2525                                         },
2526                                         _ => return Err(DecodeError::InvalidValue),
2527                                 };
2528                                 events.push(ev);
2529                         }
2530                         onchain_events_waiting_threshold_conf.insert(height_target, events);
2531                 }
2532
2533                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2534                 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>>())));
2535                 for _ in 0..outputs_to_watch_len {
2536                         let txid = Readable::read(reader)?;
2537                         let outputs_len: u64 = Readable::read(reader)?;
2538                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
2539                         for _ in 0..outputs_len {
2540                                 outputs.push(Readable::read(reader)?);
2541                         }
2542                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2543                                 return Err(DecodeError::InvalidValue);
2544                         }
2545                 }
2546                 let onchain_tx_handler = ReadableArgs::read(reader, logger.clone())?;
2547
2548                 Ok((last_block_hash.clone(), ChannelMonitor {
2549                         latest_update_id,
2550                         commitment_transaction_number_obscure_factor,
2551
2552                         key_storage,
2553                         their_htlc_base_key,
2554                         their_delayed_payment_base_key,
2555                         funding_redeemscript,
2556                         channel_value_satoshis,
2557                         their_cur_revocation_points,
2558
2559                         our_to_self_delay,
2560                         their_to_self_delay,
2561
2562                         commitment_secrets,
2563                         remote_claimable_outpoints,
2564                         remote_commitment_txn_on_chain,
2565                         remote_hash_commitment_number,
2566
2567                         prev_local_signed_commitment_tx,
2568                         current_local_signed_commitment_tx,
2569                         current_remote_commitment_number,
2570
2571                         payment_preimages,
2572                         pending_htlcs_updated,
2573                         pending_events,
2574
2575                         to_remote_rescue,
2576
2577                         onchain_events_waiting_threshold_conf,
2578                         outputs_to_watch,
2579
2580                         onchain_tx_handler,
2581
2582                         last_block_hash,
2583                         secp_ctx: Secp256k1::new(),
2584                         logger,
2585                 }))
2586         }
2587 }
2588
2589 #[cfg(test)]
2590 mod tests {
2591         use bitcoin::blockdata::script::{Script, Builder};
2592         use bitcoin::blockdata::opcodes;
2593         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2594         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2595         use bitcoin::util::bip143;
2596         use bitcoin_hashes::Hash;
2597         use bitcoin_hashes::sha256::Hash as Sha256;
2598         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
2599         use bitcoin_hashes::hex::FromHex;
2600         use hex;
2601         use chain::transaction::OutPoint;
2602         use ln::channelmanager::{PaymentPreimage, PaymentHash};
2603         use ln::channelmonitor::ChannelMonitor;
2604         use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
2605         use ln::chan_utils;
2606         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
2607         use util::test_utils::TestLogger;
2608         use secp256k1::key::{SecretKey,PublicKey};
2609         use secp256k1::Secp256k1;
2610         use rand::{thread_rng,Rng};
2611         use std::sync::Arc;
2612         use chain::keysinterface::InMemoryChannelKeys;
2613
2614         #[test]
2615         fn test_prune_preimages() {
2616                 let secp_ctx = Secp256k1::new();
2617                 let logger = Arc::new(TestLogger::new());
2618
2619                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2620                 macro_rules! dummy_keys {
2621                         () => {
2622                                 {
2623                                         TxCreationKeys {
2624                                                 per_commitment_point: dummy_key.clone(),
2625                                                 revocation_key: dummy_key.clone(),
2626                                                 a_htlc_key: dummy_key.clone(),
2627                                                 b_htlc_key: dummy_key.clone(),
2628                                                 a_delayed_payment_key: dummy_key.clone(),
2629                                                 b_payment_key: dummy_key.clone(),
2630                                         }
2631                                 }
2632                         }
2633                 }
2634                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2635
2636                 let mut preimages = Vec::new();
2637                 {
2638                         let mut rng  = thread_rng();
2639                         for _ in 0..20 {
2640                                 let mut preimage = PaymentPreimage([0; 32]);
2641                                 rng.fill_bytes(&mut preimage.0[..]);
2642                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2643                                 preimages.push((preimage, hash));
2644                         }
2645                 }
2646
2647                 macro_rules! preimages_slice_to_htlc_outputs {
2648                         ($preimages_slice: expr) => {
2649                                 {
2650                                         let mut res = Vec::new();
2651                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2652                                                 res.push((HTLCOutputInCommitment {
2653                                                         offered: true,
2654                                                         amount_msat: 0,
2655                                                         cltv_expiry: 0,
2656                                                         payment_hash: preimage.1.clone(),
2657                                                         transaction_output_index: Some(idx as u32),
2658                                                 }, None));
2659                                         }
2660                                         res
2661                                 }
2662                         }
2663                 }
2664                 macro_rules! preimages_to_local_htlcs {
2665                         ($preimages_slice: expr) => {
2666                                 {
2667                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2668                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2669                                         res
2670                                 }
2671                         }
2672                 }
2673
2674                 macro_rules! test_preimages_exist {
2675                         ($preimages_slice: expr, $monitor: expr) => {
2676                                 for preimage in $preimages_slice {
2677                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2678                                 }
2679                         }
2680                 }
2681
2682                 let keys = InMemoryChannelKeys::new(
2683                         &secp_ctx,
2684                         SecretKey::from_slice(&[41; 32]).unwrap(),
2685                         SecretKey::from_slice(&[41; 32]).unwrap(),
2686                         SecretKey::from_slice(&[41; 32]).unwrap(),
2687                         SecretKey::from_slice(&[41; 32]).unwrap(),
2688                         SecretKey::from_slice(&[41; 32]).unwrap(),
2689                         [41; 32],
2690                         0,
2691                 );
2692
2693                 // Prune with one old state and a local commitment tx holding a few overlaps with the
2694                 // old state.
2695                 let mut monitor = ChannelMonitor::new(keys,
2696                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
2697                         (OutPoint { txid: Sha256dHash::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2698                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2699                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2700                         0, Script::new(), 46, 0, logger.clone());
2701
2702                 monitor.their_to_self_delay = Some(10);
2703
2704                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
2705                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2706                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2707                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2708                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2709                 for &(ref preimage, ref hash) in preimages.iter() {
2710                         monitor.provide_payment_preimage(hash, preimage);
2711                 }
2712
2713                 // Now provide a secret, pruning preimages 10-15
2714                 let mut secret = [0; 32];
2715                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2716                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2717                 assert_eq!(monitor.payment_preimages.len(), 15);
2718                 test_preimages_exist!(&preimages[0..10], monitor);
2719                 test_preimages_exist!(&preimages[15..20], monitor);
2720
2721                 // Now provide a further secret, pruning preimages 15-17
2722                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2723                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2724                 assert_eq!(monitor.payment_preimages.len(), 13);
2725                 test_preimages_exist!(&preimages[0..10], monitor);
2726                 test_preimages_exist!(&preimages[17..20], monitor);
2727
2728                 // Now update local commitment tx info, pruning only element 18 as we still care about the
2729                 // previous commitment tx's preimages too
2730                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
2731                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2732                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2733                 assert_eq!(monitor.payment_preimages.len(), 12);
2734                 test_preimages_exist!(&preimages[0..10], monitor);
2735                 test_preimages_exist!(&preimages[18..20], monitor);
2736
2737                 // But if we do it again, we'll prune 5-10
2738                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
2739                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2740                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2741                 assert_eq!(monitor.payment_preimages.len(), 5);
2742                 test_preimages_exist!(&preimages[0..5], monitor);
2743         }
2744
2745         #[test]
2746         fn test_claim_txn_weight_computation() {
2747                 // We test Claim txn weight, knowing that we want expected weigth and
2748                 // not actual case to avoid sigs and time-lock delays hell variances.
2749
2750                 let secp_ctx = Secp256k1::new();
2751                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
2752                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
2753                 let mut sum_actual_sigs = 0;
2754
2755                 macro_rules! sign_input {
2756                         ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
2757                                 let htlc = HTLCOutputInCommitment {
2758                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
2759                                         amount_msat: 0,
2760                                         cltv_expiry: 2 << 16,
2761                                         payment_hash: PaymentHash([1; 32]),
2762                                         transaction_output_index: Some($idx),
2763                                 };
2764                                 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) };
2765                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
2766                                 let sig = secp_ctx.sign(&sighash, &privkey);
2767                                 $input.witness.push(sig.serialize_der().to_vec());
2768                                 $input.witness[0].push(SigHashType::All as u8);
2769                                 sum_actual_sigs += $input.witness[0].len();
2770                                 if *$input_type == InputDescriptors::RevokedOutput {
2771                                         $input.witness.push(vec!(1));
2772                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
2773                                         $input.witness.push(pubkey.clone().serialize().to_vec());
2774                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
2775                                         $input.witness.push(vec![0]);
2776                                 } else {
2777                                         $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
2778                                 }
2779                                 $input.witness.push(redeem_script.into_bytes());
2780                                 println!("witness[0] {}", $input.witness[0].len());
2781                                 println!("witness[1] {}", $input.witness[1].len());
2782                                 println!("witness[2] {}", $input.witness[2].len());
2783                         }
2784                 }
2785
2786                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
2787                 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
2788
2789                 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
2790                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2791                 for i in 0..4 {
2792                         claim_tx.input.push(TxIn {
2793                                 previous_output: BitcoinOutPoint {
2794                                         txid,
2795                                         vout: i,
2796                                 },
2797                                 script_sig: Script::new(),
2798                                 sequence: 0xfffffffd,
2799                                 witness: Vec::new(),
2800                         });
2801                 }
2802                 claim_tx.output.push(TxOut {
2803                         script_pubkey: script_pubkey.clone(),
2804                         value: 0,
2805                 });
2806                 let base_weight = claim_tx.get_weight();
2807                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2808                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
2809                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2810                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2811                 }
2812                 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2813
2814                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
2815                 claim_tx.input.clear();
2816                 sum_actual_sigs = 0;
2817                 for i in 0..4 {
2818                         claim_tx.input.push(TxIn {
2819                                 previous_output: BitcoinOutPoint {
2820                                         txid,
2821                                         vout: i,
2822                                 },
2823                                 script_sig: Script::new(),
2824                                 sequence: 0xfffffffd,
2825                                 witness: Vec::new(),
2826                         });
2827                 }
2828                 let base_weight = claim_tx.get_weight();
2829                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2830                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
2831                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2832                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2833                 }
2834                 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2835
2836                 // Justice tx with 1 revoked HTLC-Success tx output
2837                 claim_tx.input.clear();
2838                 sum_actual_sigs = 0;
2839                 claim_tx.input.push(TxIn {
2840                         previous_output: BitcoinOutPoint {
2841                                 txid,
2842                                 vout: 0,
2843                         },
2844                         script_sig: Script::new(),
2845                         sequence: 0xfffffffd,
2846                         witness: Vec::new(),
2847                 });
2848                 let base_weight = claim_tx.get_weight();
2849                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2850                 let inputs_des = vec![InputDescriptors::RevokedOutput];
2851                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2852                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2853                 }
2854                 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
2855         }
2856
2857         // Further testing is done in the ChannelManager integration tests.
2858 }