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