Replace use of ChainWatchInterface with WatchEvent
[rust-lightning] / lightning / src / ln / channelmonitor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
11 //! here.
12 //!
13 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
14 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15 //! be made in responding to certain messages, see ManyChannelMonitor for more.
16 //!
17 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20 //! security-domain-separated system design, you should consider having multiple paths for
21 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
22
23 use bitcoin::blockdata::block::BlockHeader;
24 use bitcoin::blockdata::transaction::{TxOut,Transaction};
25 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
26 use bitcoin::blockdata::script::{Script, Builder};
27 use bitcoin::blockdata::opcodes;
28 use bitcoin::consensus::encode;
29
30 use bitcoin::hashes::Hash;
31 use bitcoin::hashes::sha256::Hash as Sha256;
32 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
33
34 use bitcoin::secp256k1::{Secp256k1,Signature};
35 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
36 use bitcoin::secp256k1;
37
38 use ln::msgs::DecodeError;
39 use ln::chan_utils;
40 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, HTLCType};
41 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
42 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
43 use chain;
44 use chain::chaininterface::{ChainListener, ChainWatchInterface, ChainWatchedUtil, BroadcasterInterface, FeeEstimator};
45 use chain::transaction::OutPoint;
46 use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
47 use util::logger::Logger;
48 use util::ser::{Readable, MaybeReadable, Writer, Writeable, U48};
49 use util::{byte_utils, events};
50 use util::events::Event;
51
52 use std::collections::{HashMap, HashSet, hash_map};
53 use std::sync::Mutex;
54 use std::{hash,cmp, mem};
55 use std::ops::Deref;
56 use std::io::Error;
57
58 /// An update generated by the underlying Channel itself which contains some new information the
59 /// ChannelMonitor should be made aware of.
60 #[cfg_attr(test, derive(PartialEq))]
61 #[derive(Clone)]
62 #[must_use]
63 pub struct ChannelMonitorUpdate {
64         pub(super) updates: Vec<ChannelMonitorUpdateStep>,
65         /// The sequence number of this update. Updates *must* be replayed in-order according to this
66         /// sequence number (and updates may panic if they are not). The update_id values are strictly
67         /// increasing and increase by one for each new update.
68         ///
69         /// This sequence number is also used to track up to which points updates which returned
70         /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
71         /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
72         pub update_id: u64,
73 }
74
75 impl Writeable for ChannelMonitorUpdate {
76         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
77                 self.update_id.write(w)?;
78                 (self.updates.len() as u64).write(w)?;
79                 for update_step in self.updates.iter() {
80                         update_step.write(w)?;
81                 }
82                 Ok(())
83         }
84 }
85 impl Readable for ChannelMonitorUpdate {
86         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
87                 let update_id: u64 = Readable::read(r)?;
88                 let len: u64 = Readable::read(r)?;
89                 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
90                 for _ in 0..len {
91                         updates.push(Readable::read(r)?);
92                 }
93                 Ok(Self { update_id, updates })
94         }
95 }
96
97 /// An error enum representing a failure to persist a channel monitor update.
98 #[derive(Clone)]
99 pub enum ChannelMonitorUpdateErr {
100         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
101         /// our state failed, but is expected to succeed at some point in the future).
102         ///
103         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
104         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
105         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
106         /// restore the channel to an operational state.
107         ///
108         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
109         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
110         /// writing out the latest ChannelManager state.
111         ///
112         /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
113         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
114         /// to claim it on this channel) and those updates must be applied wherever they can be. At
115         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
116         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
117         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
118         /// been "frozen".
119         ///
120         /// Note that even if updates made after TemporaryFailure succeed you must still call
121         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
122         /// operation.
123         ///
124         /// Note that the update being processed here will not be replayed for you when you call
125         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
126         /// with the persisted ChannelMonitor on your own local disk prior to returning a
127         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
128         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
129         /// reload-time.
130         ///
131         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
132         /// remote location (with local copies persisted immediately), it is anticipated that all
133         /// updates will return TemporaryFailure until the remote copies could be updated.
134         TemporaryFailure,
135         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
136         /// different watchtower and cannot update with all watchtowers that were previously informed
137         /// of this channel).
138         ///
139         /// At reception of this error, ChannelManager will force-close the channel and return at
140         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
141         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
142         /// update must be rejected.
143         ///
144         /// This failure may also signal a failure to update the local persisted copy of one of
145         /// the channel monitor instance.
146         ///
147         /// Note that even when you fail a holder commitment transaction update, you must store the
148         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
149         /// broadcasts it (e.g distributed channel-monitor deployment)
150         PermanentFailure,
151 }
152
153 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
154 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
155 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
156 /// corrupted.
157 /// Contains a human-readable error message.
158 #[derive(Debug)]
159 pub struct MonitorUpdateError(pub &'static str);
160
161 /// An event to be processed by the ChannelManager.
162 #[derive(PartialEq)]
163 pub enum MonitorEvent {
164         /// A monitor event containing an HTLCUpdate.
165         HTLCEvent(HTLCUpdate),
166
167         /// A monitor event that the Channel's commitment transaction was broadcasted.
168         CommitmentTxBroadcasted(OutPoint),
169 }
170
171 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
172 /// forward channel and from which info are needed to update HTLC in a backward channel.
173 #[derive(Clone, PartialEq)]
174 pub struct HTLCUpdate {
175         pub(super) payment_hash: PaymentHash,
176         pub(super) payment_preimage: Option<PaymentPreimage>,
177         pub(super) source: HTLCSource
178 }
179 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
180
181 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
182 /// watchtower or watch our own channels.
183 ///
184 /// Note that you must provide your own key by which to refer to channels.
185 ///
186 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
187 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
188 /// index by a PublicKey which is required to sign any updates.
189 ///
190 /// If you're using this for local monitoring of your own channels, you probably want to use
191 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
192 ///
193 /// (C-not exported) due to an unconstrained generic in `Key`
194 pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref, C: Deref>
195         where T::Target: BroadcasterInterface,
196         F::Target: FeeEstimator,
197         L::Target: Logger,
198         C::Target: ChainWatchInterface,
199 {
200         /// The monitors
201         pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
202         watch_events: Mutex<WatchEventQueue>,
203         chain_monitor: C,
204         broadcaster: T,
205         logger: L,
206         fee_estimator: F
207 }
208
209 struct WatchEventQueue {
210         watched: ChainWatchedUtil,
211         events: Vec<chain::WatchEvent>,
212 }
213
214 impl WatchEventQueue {
215         fn new() -> Self {
216                 Self {
217                         watched: ChainWatchedUtil::new(),
218                         events: Vec::new(),
219                 }
220         }
221
222         fn watch_tx(&mut self, txid: &Txid, script_pubkey: &Script) {
223                 if self.watched.register_tx(txid, script_pubkey) {
224                         self.events.push(chain::WatchEvent::WatchTransaction {
225                                 txid: *txid,
226                                 script_pubkey: script_pubkey.clone()
227                         });
228                 }
229         }
230
231         fn watch_output(&mut self, outpoint: (&Txid, usize), script_pubkey: &Script) {
232                 let (txid, index) = outpoint;
233                 if self.watched.register_outpoint((*txid, index as u32), script_pubkey) {
234                         self.events.push(chain::WatchEvent::WatchOutput {
235                                 outpoint: OutPoint {
236                                         txid: *txid,
237                                         index: index as u16,
238                                 },
239                                 script_pubkey: script_pubkey.clone(),
240                         });
241                 }
242         }
243
244         fn dequeue_events(&mut self) -> Vec<chain::WatchEvent> {
245                 let mut pending_events = Vec::with_capacity(self.events.len());
246                 pending_events.append(&mut self.events);
247                 pending_events
248         }
249
250         fn filter_block<'a>(&self, txdata: &[(usize, &'a Transaction)]) -> Vec<(usize, &'a Transaction)> {
251                 let mut matched_txids = HashSet::new();
252                 txdata.iter().filter(|&&(_, tx)| {
253                         // A tx matches the filter if it either matches the filter directly (via does_match_tx)
254                         // or if it is a descendant of another matched transaction within the same block.
255                         let mut matched = self.watched.does_match_tx(tx);
256                         for input in tx.input.iter() {
257                                 if matched || matched_txids.contains(&input.previous_output.txid) {
258                                         matched = true;
259                                         break;
260                                 }
261                         }
262                         if matched {
263                                 matched_txids.insert(tx.txid());
264                         }
265                         matched
266                 }).map(|e| *e).collect()
267         }
268 }
269
270 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, C: Deref + Sync + Send>
271         ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T, F, L, C>
272         where T::Target: BroadcasterInterface,
273               F::Target: FeeEstimator,
274               L::Target: Logger,
275         C::Target: ChainWatchInterface,
276 {
277         fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32) {
278                 let mut watch_events = self.watch_events.lock().unwrap();
279                 let matched_txn = watch_events.filter_block(txdata);
280                 {
281                         let mut monitors = self.monitors.lock().unwrap();
282                         for monitor in monitors.values_mut() {
283                                 let txn_outputs = monitor.block_connected(header, &matched_txn, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
284
285                                 for (ref txid, ref outputs) in txn_outputs {
286                                         for (idx, output) in outputs.iter().enumerate() {
287                                                 watch_events.watch_output((txid, idx), &output.script_pubkey);
288                                         }
289                                 }
290                         }
291                 }
292         }
293
294         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
295                 let mut monitors = self.monitors.lock().unwrap();
296                 for monitor in monitors.values_mut() {
297                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
298                 }
299         }
300 }
301
302 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref, C: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T, F, L, C>
303         where T::Target: BroadcasterInterface,
304               F::Target: FeeEstimator,
305               L::Target: Logger,
306         C::Target: ChainWatchInterface,
307 {
308         /// Creates a new object which can be used to monitor several channels given the chain
309         /// interface with which to register to receive notifications.
310         pub fn new(chain_monitor: C, broadcaster: T, logger: L, feeest: F) -> SimpleManyChannelMonitor<Key, ChanSigner, T, F, L, C> {
311                 let res = SimpleManyChannelMonitor {
312                         monitors: Mutex::new(HashMap::new()),
313                         watch_events: Mutex::new(WatchEventQueue::new()),
314                         chain_monitor,
315                         broadcaster,
316                         logger,
317                         fee_estimator: feeest,
318                 };
319
320                 res
321         }
322
323         /// Adds or updates the monitor which monitors the channel referred to by the given key.
324         pub fn add_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
325                 let mut watch_events = self.watch_events.lock().unwrap();
326                 let mut monitors = self.monitors.lock().unwrap();
327                 let entry = match monitors.entry(key) {
328                         hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given key is already present")),
329                         hash_map::Entry::Vacant(e) => e,
330                 };
331                 {
332                         let funding_txo = monitor.get_funding_txo();
333                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
334                         watch_events.watch_tx(&funding_txo.0.txid, &funding_txo.1);
335                         watch_events.watch_output((&funding_txo.0.txid, funding_txo.0.index as usize), &funding_txo.1);
336                         for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
337                                 for (idx, script) in outputs.iter().enumerate() {
338                                         watch_events.watch_output((txid, idx), script);
339                                 }
340                         }
341                 }
342                 entry.insert(monitor);
343                 Ok(())
344         }
345
346         /// Updates the monitor which monitors the channel referred to by the given key.
347         pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
348                 let mut monitors = self.monitors.lock().unwrap();
349                 match monitors.get_mut(&key) {
350                         Some(orig_monitor) => {
351                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
352                                 orig_monitor.update_monitor(update, &self.broadcaster, &self.logger)
353                         },
354                         None => Err(MonitorUpdateError("No such monitor registered"))
355                 }
356         }
357 }
358
359 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, C: Deref + Sync + Send> ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint, ChanSigner, T, F, L, C>
360         where T::Target: BroadcasterInterface,
361               F::Target: FeeEstimator,
362               L::Target: Logger,
363         C::Target: ChainWatchInterface,
364 {
365         type Keys = ChanSigner;
366
367         fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
368                 match self.add_monitor_by_key(funding_txo, monitor) {
369                         Ok(_) => Ok(()),
370                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
371                 }
372         }
373
374         fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
375                 match self.update_monitor_by_key(funding_txo, update) {
376                         Ok(_) => Ok(()),
377                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
378                 }
379         }
380
381         fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
382                 let mut pending_monitor_events = Vec::new();
383                 for chan in self.monitors.lock().unwrap().values_mut() {
384                         pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
385                 }
386                 pending_monitor_events
387         }
388 }
389
390 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref, C: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T, F, L, C>
391         where T::Target: BroadcasterInterface,
392               F::Target: FeeEstimator,
393               L::Target: Logger,
394         C::Target: ChainWatchInterface,
395 {
396         fn get_and_clear_pending_events(&self) -> Vec<Event> {
397                 let mut pending_events = Vec::new();
398                 for chan in self.monitors.lock().unwrap().values_mut() {
399                         pending_events.append(&mut chan.get_and_clear_pending_events());
400                 }
401                 pending_events
402         }
403 }
404
405 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref, L: Deref, C: Deref> chain::WatchEventProvider for SimpleManyChannelMonitor<Key, ChanSigner, T, F, L, C>
406         where T::Target: BroadcasterInterface,
407               F::Target: FeeEstimator,
408               L::Target: Logger,
409         C::Target: ChainWatchInterface,
410 {
411         fn release_pending_watch_events(&self) -> Vec<chain::WatchEvent> {
412                 self.watch_events.lock().unwrap().dequeue_events()
413         }
414 }
415
416 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
417 /// instead claiming it in its own individual transaction.
418 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
419 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
420 /// HTLC-Success transaction.
421 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
422 /// transaction confirmed (and we use it in a few more, equivalent, places).
423 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
424 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
425 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
426 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
427 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
428 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
429 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
430 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
431 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
432 /// accurate block height.
433 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
434 /// with at worst this delay, so we are not only using this value as a mercy for them but also
435 /// us as a safeguard to delay with enough time.
436 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
437 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
438 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
439 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
440 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
441 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
442 /// keeping bumping another claim tx to solve the outpoint.
443 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
444 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
445 /// refuse to accept a new HTLC.
446 ///
447 /// This is used for a few separate purposes:
448 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
449 ///    waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
450 ///    fail this HTLC,
451 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
452 ///    condition with the above), we will fail this HTLC without telling the user we received it,
453 /// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
454 ///    that HTLC expires within this many blocks, we will simply fail the HTLC instead.
455 ///
456 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
457 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
458 ///
459 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
460 /// in a race condition between the user connecting a block (which would fail it) and the user
461 /// providing us the preimage (which would claim it).
462 ///
463 /// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
464 /// end up force-closing the channel on us to claim it.
465 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
466
467 #[derive(Clone, PartialEq)]
468 struct HolderSignedTx {
469         /// txid of the transaction in tx, just used to make comparison faster
470         txid: Txid,
471         revocation_key: PublicKey,
472         a_htlc_key: PublicKey,
473         b_htlc_key: PublicKey,
474         delayed_payment_key: PublicKey,
475         per_commitment_point: PublicKey,
476         feerate_per_kw: u32,
477         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
478 }
479
480 /// We use this to track counterparty commitment transactions and htlcs outputs and
481 /// use it to generate any justice or 2nd-stage preimage/timeout transactions.
482 #[derive(PartialEq)]
483 struct CounterpartyCommitmentTransaction {
484         counterparty_delayed_payment_base_key: PublicKey,
485         counterparty_htlc_base_key: PublicKey,
486         on_counterparty_tx_csv: u16,
487         per_htlc: HashMap<Txid, Vec<HTLCOutputInCommitment>>
488 }
489
490 impl Writeable for CounterpartyCommitmentTransaction {
491         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
492                 self.counterparty_delayed_payment_base_key.write(w)?;
493                 self.counterparty_htlc_base_key.write(w)?;
494                 w.write_all(&byte_utils::be16_to_array(self.on_counterparty_tx_csv))?;
495                 w.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
496                 for (ref txid, ref htlcs) in self.per_htlc.iter() {
497                         w.write_all(&txid[..])?;
498                         w.write_all(&byte_utils::be64_to_array(htlcs.len() as u64))?;
499                         for &ref htlc in htlcs.iter() {
500                                 htlc.write(w)?;
501                         }
502                 }
503                 Ok(())
504         }
505 }
506 impl Readable for CounterpartyCommitmentTransaction {
507         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
508                 let counterparty_commitment_transaction = {
509                         let counterparty_delayed_payment_base_key = Readable::read(r)?;
510                         let counterparty_htlc_base_key = Readable::read(r)?;
511                         let on_counterparty_tx_csv: u16 = Readable::read(r)?;
512                         let per_htlc_len: u64 = Readable::read(r)?;
513                         let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64));
514                         for _  in 0..per_htlc_len {
515                                 let txid: Txid = Readable::read(r)?;
516                                 let htlcs_count: u64 = Readable::read(r)?;
517                                 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
518                                 for _ in 0..htlcs_count {
519                                         let htlc = Readable::read(r)?;
520                                         htlcs.push(htlc);
521                                 }
522                                 if let Some(_) = per_htlc.insert(txid, htlcs) {
523                                         return Err(DecodeError::InvalidValue);
524                                 }
525                         }
526                         CounterpartyCommitmentTransaction {
527                                 counterparty_delayed_payment_base_key,
528                                 counterparty_htlc_base_key,
529                                 on_counterparty_tx_csv,
530                                 per_htlc,
531                         }
532                 };
533                 Ok(counterparty_commitment_transaction)
534         }
535 }
536
537 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
538 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
539 /// a new bumped one in case of lenghty confirmation delay
540 #[derive(Clone, PartialEq)]
541 pub(crate) enum InputMaterial {
542         Revoked {
543                 per_commitment_point: PublicKey,
544                 counterparty_delayed_payment_base_key: PublicKey,
545                 counterparty_htlc_base_key: PublicKey,
546                 per_commitment_key: SecretKey,
547                 input_descriptor: InputDescriptors,
548                 amount: u64,
549                 htlc: Option<HTLCOutputInCommitment>,
550                 on_counterparty_tx_csv: u16,
551         },
552         CounterpartyHTLC {
553                 per_commitment_point: PublicKey,
554                 counterparty_delayed_payment_base_key: PublicKey,
555                 counterparty_htlc_base_key: PublicKey,
556                 preimage: Option<PaymentPreimage>,
557                 htlc: HTLCOutputInCommitment
558         },
559         HolderHTLC {
560                 preimage: Option<PaymentPreimage>,
561                 amount: u64,
562         },
563         Funding {
564                 funding_redeemscript: Script,
565         }
566 }
567
568 impl Writeable for InputMaterial  {
569         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
570                 match self {
571                         &InputMaterial::Revoked { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_counterparty_tx_csv} => {
572                                 writer.write_all(&[0; 1])?;
573                                 per_commitment_point.write(writer)?;
574                                 counterparty_delayed_payment_base_key.write(writer)?;
575                                 counterparty_htlc_base_key.write(writer)?;
576                                 writer.write_all(&per_commitment_key[..])?;
577                                 input_descriptor.write(writer)?;
578                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
579                                 htlc.write(writer)?;
580                                 on_counterparty_tx_csv.write(writer)?;
581                         },
582                         &InputMaterial::CounterpartyHTLC { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref preimage, ref htlc} => {
583                                 writer.write_all(&[1; 1])?;
584                                 per_commitment_point.write(writer)?;
585                                 counterparty_delayed_payment_base_key.write(writer)?;
586                                 counterparty_htlc_base_key.write(writer)?;
587                                 preimage.write(writer)?;
588                                 htlc.write(writer)?;
589                         },
590                         &InputMaterial::HolderHTLC { ref preimage, ref amount } => {
591                                 writer.write_all(&[2; 1])?;
592                                 preimage.write(writer)?;
593                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
594                         },
595                         &InputMaterial::Funding { ref funding_redeemscript } => {
596                                 writer.write_all(&[3; 1])?;
597                                 funding_redeemscript.write(writer)?;
598                         }
599                 }
600                 Ok(())
601         }
602 }
603
604 impl Readable for InputMaterial {
605         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
606                 let input_material = match <u8 as Readable>::read(reader)? {
607                         0 => {
608                                 let per_commitment_point = Readable::read(reader)?;
609                                 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
610                                 let counterparty_htlc_base_key = Readable::read(reader)?;
611                                 let per_commitment_key = Readable::read(reader)?;
612                                 let input_descriptor = Readable::read(reader)?;
613                                 let amount = Readable::read(reader)?;
614                                 let htlc = Readable::read(reader)?;
615                                 let on_counterparty_tx_csv = Readable::read(reader)?;
616                                 InputMaterial::Revoked {
617                                         per_commitment_point,
618                                         counterparty_delayed_payment_base_key,
619                                         counterparty_htlc_base_key,
620                                         per_commitment_key,
621                                         input_descriptor,
622                                         amount,
623                                         htlc,
624                                         on_counterparty_tx_csv
625                                 }
626                         },
627                         1 => {
628                                 let per_commitment_point = Readable::read(reader)?;
629                                 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
630                                 let counterparty_htlc_base_key = Readable::read(reader)?;
631                                 let preimage = Readable::read(reader)?;
632                                 let htlc = Readable::read(reader)?;
633                                 InputMaterial::CounterpartyHTLC {
634                                         per_commitment_point,
635                                         counterparty_delayed_payment_base_key,
636                                         counterparty_htlc_base_key,
637                                         preimage,
638                                         htlc
639                                 }
640                         },
641                         2 => {
642                                 let preimage = Readable::read(reader)?;
643                                 let amount = Readable::read(reader)?;
644                                 InputMaterial::HolderHTLC {
645                                         preimage,
646                                         amount,
647                                 }
648                         },
649                         3 => {
650                                 InputMaterial::Funding {
651                                         funding_redeemscript: Readable::read(reader)?,
652                                 }
653                         }
654                         _ => return Err(DecodeError::InvalidValue),
655                 };
656                 Ok(input_material)
657         }
658 }
659
660 /// ClaimRequest is a descriptor structure to communicate between detection
661 /// and reaction module. They are generated by ChannelMonitor while parsing
662 /// onchain txn leaked from a channel and handed over to OnchainTxHandler which
663 /// is responsible for opportunistic aggregation, selecting and enforcing
664 /// bumping logic, building and signing transactions.
665 pub(crate) struct ClaimRequest {
666         // Block height before which claiming is exclusive to one party,
667         // after reaching it, claiming may be contentious.
668         pub(crate) absolute_timelock: u32,
669         // Timeout tx must have nLocktime set which means aggregating multiple
670         // ones must take the higher nLocktime among them to satisfy all of them.
671         // Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
672         // of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
673         // Do simplify we mark them as non-aggregable.
674         pub(crate) aggregable: bool,
675         // Basic bitcoin outpoint (txid, vout)
676         pub(crate) outpoint: BitcoinOutPoint,
677         // Following outpoint type, set of data needed to generate transaction digest
678         // and satisfy witness program.
679         pub(crate) witness_data: InputMaterial
680 }
681
682 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
683 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
684 #[derive(Clone, PartialEq)]
685 enum OnchainEvent {
686         /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
687         /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
688         /// only win from it, so it's never an OnchainEvent
689         HTLCUpdate {
690                 htlc_update: (HTLCSource, PaymentHash),
691         },
692         MaturingOutput {
693                 descriptor: SpendableOutputDescriptor,
694         },
695 }
696
697 const SERIALIZATION_VERSION: u8 = 1;
698 const MIN_SERIALIZATION_VERSION: u8 = 1;
699
700 #[cfg_attr(test, derive(PartialEq))]
701 #[derive(Clone)]
702 pub(super) enum ChannelMonitorUpdateStep {
703         LatestHolderCommitmentTXInfo {
704                 commitment_tx: HolderCommitmentTransaction,
705                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
706         },
707         LatestCounterpartyCommitmentTXInfo {
708                 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
709                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
710                 commitment_number: u64,
711                 their_revocation_point: PublicKey,
712         },
713         PaymentPreimage {
714                 payment_preimage: PaymentPreimage,
715         },
716         CommitmentSecret {
717                 idx: u64,
718                 secret: [u8; 32],
719         },
720         /// Used to indicate that the no future updates will occur, and likely that the latest holder
721         /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
722         ChannelForceClosed {
723                 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
724                 /// think we've fallen behind!
725                 should_broadcast: bool,
726         },
727 }
728
729 impl Writeable for ChannelMonitorUpdateStep {
730         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
731                 match self {
732                         &ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { ref commitment_tx, ref htlc_outputs } => {
733                                 0u8.write(w)?;
734                                 commitment_tx.write(w)?;
735                                 (htlc_outputs.len() as u64).write(w)?;
736                                 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
737                                         output.write(w)?;
738                                         signature.write(w)?;
739                                         source.write(w)?;
740                                 }
741                         }
742                         &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
743                                 1u8.write(w)?;
744                                 unsigned_commitment_tx.write(w)?;
745                                 commitment_number.write(w)?;
746                                 their_revocation_point.write(w)?;
747                                 (htlc_outputs.len() as u64).write(w)?;
748                                 for &(ref output, ref source) in htlc_outputs.iter() {
749                                         output.write(w)?;
750                                         source.as_ref().map(|b| b.as_ref()).write(w)?;
751                                 }
752                         },
753                         &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
754                                 2u8.write(w)?;
755                                 payment_preimage.write(w)?;
756                         },
757                         &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
758                                 3u8.write(w)?;
759                                 idx.write(w)?;
760                                 secret.write(w)?;
761                         },
762                         &ChannelMonitorUpdateStep::ChannelForceClosed { ref should_broadcast } => {
763                                 4u8.write(w)?;
764                                 should_broadcast.write(w)?;
765                         },
766                 }
767                 Ok(())
768         }
769 }
770 impl Readable for ChannelMonitorUpdateStep {
771         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
772                 match Readable::read(r)? {
773                         0u8 => {
774                                 Ok(ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
775                                         commitment_tx: Readable::read(r)?,
776                                         htlc_outputs: {
777                                                 let len: u64 = Readable::read(r)?;
778                                                 let mut res = Vec::new();
779                                                 for _ in 0..len {
780                                                         res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
781                                                 }
782                                                 res
783                                         },
784                                 })
785                         },
786                         1u8 => {
787                                 Ok(ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
788                                         unsigned_commitment_tx: Readable::read(r)?,
789                                         commitment_number: Readable::read(r)?,
790                                         their_revocation_point: Readable::read(r)?,
791                                         htlc_outputs: {
792                                                 let len: u64 = Readable::read(r)?;
793                                                 let mut res = Vec::new();
794                                                 for _ in 0..len {
795                                                         res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
796                                                 }
797                                                 res
798                                         },
799                                 })
800                         },
801                         2u8 => {
802                                 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
803                                         payment_preimage: Readable::read(r)?,
804                                 })
805                         },
806                         3u8 => {
807                                 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
808                                         idx: Readable::read(r)?,
809                                         secret: Readable::read(r)?,
810                                 })
811                         },
812                         4u8 => {
813                                 Ok(ChannelMonitorUpdateStep::ChannelForceClosed {
814                                         should_broadcast: Readable::read(r)?
815                                 })
816                         },
817                         _ => Err(DecodeError::InvalidValue),
818                 }
819         }
820 }
821
822 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
823 /// on-chain transactions to ensure no loss of funds occurs.
824 ///
825 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
826 /// information and are actively monitoring the chain.
827 ///
828 /// Pending Events or updated HTLCs which have not yet been read out by
829 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
830 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
831 /// gotten are fully handled before re-serializing the new state.
832 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
833         latest_update_id: u64,
834         commitment_transaction_number_obscure_factor: u64,
835
836         destination_script: Script,
837         broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
838         counterparty_payment_script: Script,
839         shutdown_script: Script,
840
841         keys: ChanSigner,
842         funding_info: (OutPoint, Script),
843         current_counterparty_commitment_txid: Option<Txid>,
844         prev_counterparty_commitment_txid: Option<Txid>,
845
846         counterparty_tx_cache: CounterpartyCommitmentTransaction,
847         funding_redeemscript: Script,
848         channel_value_satoshis: u64,
849         // first is the idx of the first of the two revocation points
850         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
851
852         on_holder_tx_csv: u16,
853
854         commitment_secrets: CounterpartyCommitmentSecrets,
855         counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
856         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
857         /// Nor can we figure out their commitment numbers without the commitment transaction they are
858         /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
859         /// commitment transactions which we find on-chain, mapping them to the commitment number which
860         /// can be used to derive the revocation key and claim the transactions.
861         counterparty_commitment_txn_on_chain: HashMap<Txid, (u64, Vec<Script>)>,
862         /// Cache used to make pruning of payment_preimages faster.
863         /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
864         /// counterparty transactions (ie should remain pretty small).
865         /// Serialized to disk but should generally not be sent to Watchtowers.
866         counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
867
868         // We store two holder commitment transactions to avoid any race conditions where we may update
869         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
870         // various monitors for one channel being out of sync, and us broadcasting a holder
871         // transaction for which we have deleted claim information on some watchtowers.
872         prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
873         current_holder_commitment_tx: HolderSignedTx,
874
875         // Used just for ChannelManager to make sure it has the latest channel data during
876         // deserialization
877         current_counterparty_commitment_number: u64,
878         // Used just for ChannelManager to make sure it has the latest channel data during
879         // deserialization
880         current_holder_commitment_number: u64,
881
882         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
883
884         pending_monitor_events: Vec<MonitorEvent>,
885         pending_events: Vec<Event>,
886
887         // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
888         // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
889         // actions when we receive a block with given height. Actions depend on OnchainEvent type.
890         onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
891
892         // If we get serialized out and re-read, we need to make sure that the chain monitoring
893         // interface knows about the TXOs that we want to be notified of spends of. We could probably
894         // be smart and derive them from the above storage fields, but its much simpler and more
895         // Obviously Correct (tm) if we just keep track of them explicitly.
896         outputs_to_watch: HashMap<Txid, Vec<Script>>,
897
898         #[cfg(test)]
899         pub onchain_tx_handler: OnchainTxHandler<ChanSigner>,
900         #[cfg(not(test))]
901         onchain_tx_handler: OnchainTxHandler<ChanSigner>,
902
903         // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
904         // channel has been force-closed. After this is set, no further holder commitment transaction
905         // updates may occur, and we panic!() if one is provided.
906         lockdown_from_offchain: bool,
907
908         // Set once we've signed a holder commitment transaction and handed it over to our
909         // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
910         // may occur, and we fail any such monitor updates.
911         //
912         // In case of update rejection due to a locally already signed commitment transaction, we
913         // nevertheless store update content to track in case of concurrent broadcast by another
914         // remote monitor out-of-order with regards to the block view.
915         holder_tx_signed: bool,
916
917         // We simply modify last_block_hash in Channel's block_connected so that serialization is
918         // consistent but hopefully the users' copy handles block_connected in a consistent way.
919         // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
920         // their last_block_hash from its state and not based on updated copies that didn't run through
921         // the full block_connected).
922         last_block_hash: BlockHash,
923         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
924 }
925
926 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
927 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
928 /// events to it, while also taking any add/update_monitor events and passing them to some remote
929 /// server(s).
930 ///
931 /// In general, you must always have at least one local copy in memory, which must never fail to
932 /// update (as it is responsible for broadcasting the latest state in case the channel is closed),
933 /// and then persist it to various on-disk locations. If, for some reason, the in-memory copy fails
934 /// to update (eg out-of-memory or some other condition), you must immediately shut down without
935 /// taking any further action such as writing the current state to disk. This should likely be
936 /// accomplished via panic!() or abort().
937 ///
938 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
939 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
940 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
941 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
942 ///
943 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
944 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
945 /// than calling these methods directly, the user should register implementors as listeners to the
946 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
947 /// all registered listeners in one go.
948 pub trait ManyChannelMonitor: Send + Sync {
949         /// The concrete type which signs for transactions and provides access to our channel public
950         /// keys.
951         type Keys: ChannelKeys;
952
953         /// Adds a monitor for the given `funding_txo`.
954         ///
955         /// Implementations must ensure that `monitor` receives block_connected calls for blocks with
956         /// the funding transaction or any spends of it, as well as any spends of outputs returned by
957         /// get_outputs_to_watch. Not doing so may result in LOST FUNDS.
958         fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr>;
959
960         /// Updates a monitor for the given `funding_txo`.
961         ///
962         /// TODO(jkczyz): Determine where this should go from e73036c6845fd3cc16479a1b497db82a5ebb3897.
963         ///
964         /// In case of distributed watchtowers deployment, even if an Err is return, the new version
965         /// must be written to disk, as state may have been stored but rejected due to a block forcing
966         /// a commitment broadcast. This storage is used to claim outputs of rejected state confirmed
967         /// onchain by another watchtower, lagging behind on block processing.
968         fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
969
970         /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
971         /// with success or failure.
972         ///
973         /// You should probably just call through to
974         /// ChannelMonitor::get_and_clear_pending_monitor_events() for each ChannelMonitor and return
975         /// the full list.
976         fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent>;
977 }
978
979 #[cfg(any(test, feature = "fuzztarget"))]
980 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
981 /// underlying object
982 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
983         fn eq(&self, other: &Self) -> bool {
984                 if self.latest_update_id != other.latest_update_id ||
985                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
986                         self.destination_script != other.destination_script ||
987                         self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
988                         self.counterparty_payment_script != other.counterparty_payment_script ||
989                         self.keys.pubkeys() != other.keys.pubkeys() ||
990                         self.funding_info != other.funding_info ||
991                         self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
992                         self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
993                         self.counterparty_tx_cache != other.counterparty_tx_cache ||
994                         self.funding_redeemscript != other.funding_redeemscript ||
995                         self.channel_value_satoshis != other.channel_value_satoshis ||
996                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
997                         self.on_holder_tx_csv != other.on_holder_tx_csv ||
998                         self.commitment_secrets != other.commitment_secrets ||
999                         self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
1000                         self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
1001                         self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
1002                         self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
1003                         self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
1004                         self.current_holder_commitment_number != other.current_holder_commitment_number ||
1005                         self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
1006                         self.payment_preimages != other.payment_preimages ||
1007                         self.pending_monitor_events != other.pending_monitor_events ||
1008                         self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
1009                         self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
1010                         self.outputs_to_watch != other.outputs_to_watch ||
1011                         self.lockdown_from_offchain != other.lockdown_from_offchain ||
1012                         self.holder_tx_signed != other.holder_tx_signed
1013                 {
1014                         false
1015                 } else {
1016                         true
1017                 }
1018         }
1019 }
1020
1021 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
1022         /// Writes this monitor into the given writer, suitable for writing to disk.
1023         ///
1024         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1025         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1026         /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
1027         /// returned block hash and the the current chain and then reconnecting blocks to get to the
1028         /// best chain) upon deserializing the object!
1029         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1030                 //TODO: We still write out all the serialization here manually instead of using the fancy
1031                 //serialization framework we have, we should migrate things over to it.
1032                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
1033                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
1034
1035                 self.latest_update_id.write(writer)?;
1036
1037                 // Set in initial Channel-object creation, so should always be set by now:
1038                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
1039
1040                 self.destination_script.write(writer)?;
1041                 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
1042                         writer.write_all(&[0; 1])?;
1043                         broadcasted_holder_revokable_script.0.write(writer)?;
1044                         broadcasted_holder_revokable_script.1.write(writer)?;
1045                         broadcasted_holder_revokable_script.2.write(writer)?;
1046                 } else {
1047                         writer.write_all(&[1; 1])?;
1048                 }
1049
1050                 self.counterparty_payment_script.write(writer)?;
1051                 self.shutdown_script.write(writer)?;
1052
1053                 self.keys.write(writer)?;
1054                 writer.write_all(&self.funding_info.0.txid[..])?;
1055                 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
1056                 self.funding_info.1.write(writer)?;
1057                 self.current_counterparty_commitment_txid.write(writer)?;
1058                 self.prev_counterparty_commitment_txid.write(writer)?;
1059
1060                 self.counterparty_tx_cache.write(writer)?;
1061                 self.funding_redeemscript.write(writer)?;
1062                 self.channel_value_satoshis.write(writer)?;
1063
1064                 match self.their_cur_revocation_points {
1065                         Some((idx, pubkey, second_option)) => {
1066                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
1067                                 writer.write_all(&pubkey.serialize())?;
1068                                 match second_option {
1069                                         Some(second_pubkey) => {
1070                                                 writer.write_all(&second_pubkey.serialize())?;
1071                                         },
1072                                         None => {
1073                                                 writer.write_all(&[0; 33])?;
1074                                         },
1075                                 }
1076                         },
1077                         None => {
1078                                 writer.write_all(&byte_utils::be48_to_array(0))?;
1079                         },
1080                 }
1081
1082                 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
1083
1084                 self.commitment_secrets.write(writer)?;
1085
1086                 macro_rules! serialize_htlc_in_commitment {
1087                         ($htlc_output: expr) => {
1088                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1089                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1090                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1091                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1092                                 $htlc_output.transaction_output_index.write(writer)?;
1093                         }
1094                 }
1095
1096                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
1097                 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
1098                         writer.write_all(&txid[..])?;
1099                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1100                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1101                                 serialize_htlc_in_commitment!(htlc_output);
1102                                 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1103                         }
1104                 }
1105
1106                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
1107                 for (ref txid, &(commitment_number, ref txouts)) in self.counterparty_commitment_txn_on_chain.iter() {
1108                         writer.write_all(&txid[..])?;
1109                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1110                         (txouts.len() as u64).write(writer)?;
1111                         for script in txouts.iter() {
1112                                 script.write(writer)?;
1113                         }
1114                 }
1115
1116                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
1117                 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1118                         writer.write_all(&payment_hash.0[..])?;
1119                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1120                 }
1121
1122                 macro_rules! serialize_holder_tx {
1123                         ($holder_tx: expr) => {
1124                                 $holder_tx.txid.write(writer)?;
1125                                 writer.write_all(&$holder_tx.revocation_key.serialize())?;
1126                                 writer.write_all(&$holder_tx.a_htlc_key.serialize())?;
1127                                 writer.write_all(&$holder_tx.b_htlc_key.serialize())?;
1128                                 writer.write_all(&$holder_tx.delayed_payment_key.serialize())?;
1129                                 writer.write_all(&$holder_tx.per_commitment_point.serialize())?;
1130
1131                                 writer.write_all(&byte_utils::be32_to_array($holder_tx.feerate_per_kw))?;
1132                                 writer.write_all(&byte_utils::be64_to_array($holder_tx.htlc_outputs.len() as u64))?;
1133                                 for &(ref htlc_output, ref sig, ref htlc_source) in $holder_tx.htlc_outputs.iter() {
1134                                         serialize_htlc_in_commitment!(htlc_output);
1135                                         if let &Some(ref their_sig) = sig {
1136                                                 1u8.write(writer)?;
1137                                                 writer.write_all(&their_sig.serialize_compact())?;
1138                                         } else {
1139                                                 0u8.write(writer)?;
1140                                         }
1141                                         htlc_source.write(writer)?;
1142                                 }
1143                         }
1144                 }
1145
1146                 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1147                         writer.write_all(&[1; 1])?;
1148                         serialize_holder_tx!(prev_holder_tx);
1149                 } else {
1150                         writer.write_all(&[0; 1])?;
1151                 }
1152
1153                 serialize_holder_tx!(self.current_holder_commitment_tx);
1154
1155                 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1156                 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1157
1158                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1159                 for payment_preimage in self.payment_preimages.values() {
1160                         writer.write_all(&payment_preimage.0[..])?;
1161                 }
1162
1163                 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
1164                 for event in self.pending_monitor_events.iter() {
1165                         match event {
1166                                 MonitorEvent::HTLCEvent(upd) => {
1167                                         0u8.write(writer)?;
1168                                         upd.write(writer)?;
1169                                 },
1170                                 MonitorEvent::CommitmentTxBroadcasted(_) => 1u8.write(writer)?
1171                         }
1172                 }
1173
1174                 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
1175                 for event in self.pending_events.iter() {
1176                         event.write(writer)?;
1177                 }
1178
1179                 self.last_block_hash.write(writer)?;
1180
1181                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1182                 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1183                         writer.write_all(&byte_utils::be32_to_array(**target))?;
1184                         writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1185                         for ev in events.iter() {
1186                                 match *ev {
1187                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1188                                                 0u8.write(writer)?;
1189                                                 htlc_update.0.write(writer)?;
1190                                                 htlc_update.1.write(writer)?;
1191                                         },
1192                                         OnchainEvent::MaturingOutput { ref descriptor } => {
1193                                                 1u8.write(writer)?;
1194                                                 descriptor.write(writer)?;
1195                                         },
1196                                 }
1197                         }
1198                 }
1199
1200                 (self.outputs_to_watch.len() as u64).write(writer)?;
1201                 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1202                         txid.write(writer)?;
1203                         (output_scripts.len() as u64).write(writer)?;
1204                         for script in output_scripts.iter() {
1205                                 script.write(writer)?;
1206                         }
1207                 }
1208                 self.onchain_tx_handler.write(writer)?;
1209
1210                 self.lockdown_from_offchain.write(writer)?;
1211                 self.holder_tx_signed.write(writer)?;
1212
1213                 Ok(())
1214         }
1215 }
1216
1217 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1218         pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1219                         on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1220                         counterparty_htlc_base_key: &PublicKey, counterparty_delayed_payment_base_key: &PublicKey,
1221                         on_holder_tx_csv: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1222                         commitment_transaction_number_obscure_factor: u64,
1223                         initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<ChanSigner> {
1224
1225                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1226                 let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
1227                 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1228                 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1229                 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1230
1231                 let counterparty_tx_cache = CounterpartyCommitmentTransaction { counterparty_delayed_payment_base_key: *counterparty_delayed_payment_base_key, counterparty_htlc_base_key: *counterparty_htlc_base_key, on_counterparty_tx_csv, per_htlc: HashMap::new() };
1232
1233                 let mut onchain_tx_handler = OnchainTxHandler::new(destination_script.clone(), keys.clone(), on_holder_tx_csv);
1234
1235                 let holder_tx_sequence = initial_holder_commitment_tx.unsigned_tx.input[0].sequence as u64;
1236                 let holder_tx_locktime = initial_holder_commitment_tx.unsigned_tx.lock_time as u64;
1237                 let holder_commitment_tx = HolderSignedTx {
1238                         txid: initial_holder_commitment_tx.txid(),
1239                         revocation_key: initial_holder_commitment_tx.keys.revocation_key,
1240                         a_htlc_key: initial_holder_commitment_tx.keys.broadcaster_htlc_key,
1241                         b_htlc_key: initial_holder_commitment_tx.keys.countersignatory_htlc_key,
1242                         delayed_payment_key: initial_holder_commitment_tx.keys.broadcaster_delayed_payment_key,
1243                         per_commitment_point: initial_holder_commitment_tx.keys.per_commitment_point,
1244                         feerate_per_kw: initial_holder_commitment_tx.feerate_per_kw,
1245                         htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1246                 };
1247                 onchain_tx_handler.provide_latest_holder_tx(initial_holder_commitment_tx);
1248
1249                 ChannelMonitor {
1250                         latest_update_id: 0,
1251                         commitment_transaction_number_obscure_factor,
1252
1253                         destination_script: destination_script.clone(),
1254                         broadcasted_holder_revokable_script: None,
1255                         counterparty_payment_script,
1256                         shutdown_script,
1257
1258                         keys,
1259                         funding_info,
1260                         current_counterparty_commitment_txid: None,
1261                         prev_counterparty_commitment_txid: None,
1262
1263                         counterparty_tx_cache,
1264                         funding_redeemscript,
1265                         channel_value_satoshis: channel_value_satoshis,
1266                         their_cur_revocation_points: None,
1267
1268                         on_holder_tx_csv,
1269
1270                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1271                         counterparty_claimable_outpoints: HashMap::new(),
1272                         counterparty_commitment_txn_on_chain: HashMap::new(),
1273                         counterparty_hash_commitment_number: HashMap::new(),
1274
1275                         prev_holder_signed_commitment_tx: None,
1276                         current_holder_commitment_tx: holder_commitment_tx,
1277                         current_counterparty_commitment_number: 1 << 48,
1278                         current_holder_commitment_number: 0xffff_ffff_ffff - ((((holder_tx_sequence & 0xffffff) << 3*8) | (holder_tx_locktime as u64 & 0xffffff)) ^ commitment_transaction_number_obscure_factor),
1279
1280                         payment_preimages: HashMap::new(),
1281                         pending_monitor_events: Vec::new(),
1282                         pending_events: Vec::new(),
1283
1284                         onchain_events_waiting_threshold_conf: HashMap::new(),
1285                         outputs_to_watch: HashMap::new(),
1286
1287                         onchain_tx_handler,
1288
1289                         lockdown_from_offchain: false,
1290                         holder_tx_signed: false,
1291
1292                         last_block_hash: Default::default(),
1293                         secp_ctx: Secp256k1::new(),
1294                 }
1295         }
1296
1297         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1298         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1299         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1300         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1301                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1302                         return Err(MonitorUpdateError("Previous secret did not match new one"));
1303                 }
1304
1305                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1306                 // events for now-revoked/fulfilled HTLCs.
1307                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1308                         for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1309                                 *source = None;
1310                         }
1311                 }
1312
1313                 if !self.payment_preimages.is_empty() {
1314                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1315                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1316                         let min_idx = self.get_min_seen_secret();
1317                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1318
1319                         self.payment_preimages.retain(|&k, _| {
1320                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1321                                         if k == htlc.payment_hash {
1322                                                 return true
1323                                         }
1324                                 }
1325                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1326                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1327                                                 if k == htlc.payment_hash {
1328                                                         return true
1329                                                 }
1330                                         }
1331                                 }
1332                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1333                                         if *cn < min_idx {
1334                                                 return true
1335                                         }
1336                                         true
1337                                 } else { false };
1338                                 if contains {
1339                                         counterparty_hash_commitment_number.remove(&k);
1340                                 }
1341                                 false
1342                         });
1343                 }
1344
1345                 Ok(())
1346         }
1347
1348         /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1349         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1350         /// possibly future revocation/preimage information) to claim outputs where possible.
1351         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1352         pub(super) fn provide_latest_counterparty_commitment_tx_info<L: Deref>(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
1353                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1354                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1355                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1356                 // timeouts)
1357                 for &(ref htlc, _) in &htlc_outputs {
1358                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1359                 }
1360
1361                 let new_txid = unsigned_commitment_tx.txid();
1362                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1363                 log_trace!(logger, "New potential counterparty commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1364                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1365                 self.current_counterparty_commitment_txid = Some(new_txid);
1366                 self.counterparty_claimable_outpoints.insert(new_txid, htlc_outputs.clone());
1367                 self.current_counterparty_commitment_number = commitment_number;
1368                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1369                 match self.their_cur_revocation_points {
1370                         Some(old_points) => {
1371                                 if old_points.0 == commitment_number + 1 {
1372                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1373                                 } else if old_points.0 == commitment_number + 2 {
1374                                         if let Some(old_second_point) = old_points.2 {
1375                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1376                                         } else {
1377                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1378                                         }
1379                                 } else {
1380                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1381                                 }
1382                         },
1383                         None => {
1384                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1385                         }
1386                 }
1387                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1388                 for htlc in htlc_outputs {
1389                         if htlc.0.transaction_output_index.is_some() {
1390                                 htlcs.push(htlc.0);
1391                         }
1392                 }
1393                 self.counterparty_tx_cache.per_htlc.insert(new_txid, htlcs);
1394         }
1395
1396         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1397         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1398         /// is important that any clones of this channel monitor (including remote clones) by kept
1399         /// up-to-date as our holder commitment transaction is updated.
1400         /// Panics if set_on_holder_tx_csv has never been called.
1401         pub(super) fn provide_latest_holder_commitment_tx_info(&mut self, commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1402                 let txid = commitment_tx.txid();
1403                 let sequence = commitment_tx.unsigned_tx.input[0].sequence as u64;
1404                 let locktime = commitment_tx.unsigned_tx.lock_time as u64;
1405                 let mut new_holder_commitment_tx = HolderSignedTx {
1406                         txid,
1407                         revocation_key: commitment_tx.keys.revocation_key,
1408                         a_htlc_key: commitment_tx.keys.broadcaster_htlc_key,
1409                         b_htlc_key: commitment_tx.keys.countersignatory_htlc_key,
1410                         delayed_payment_key: commitment_tx.keys.broadcaster_delayed_payment_key,
1411                         per_commitment_point: commitment_tx.keys.per_commitment_point,
1412                         feerate_per_kw: commitment_tx.feerate_per_kw,
1413                         htlc_outputs: htlc_outputs,
1414                 };
1415                 self.onchain_tx_handler.provide_latest_holder_tx(commitment_tx);
1416                 self.current_holder_commitment_number = 0xffff_ffff_ffff - ((((sequence & 0xffffff) << 3*8) | (locktime as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
1417                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1418                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1419                 if self.holder_tx_signed {
1420                         return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1421                 }
1422                 Ok(())
1423         }
1424
1425         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1426         /// commitment_tx_infos which contain the payment hash have been revoked.
1427         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1428                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1429         }
1430
1431         pub(super) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1432                 where B::Target: BroadcasterInterface,
1433                                         L::Target: Logger,
1434         {
1435                 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1436                         broadcaster.broadcast_transaction(tx);
1437                 }
1438                 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1439         }
1440
1441         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1442         /// itself.
1443         ///
1444         /// panics if the given update is not the next update by update_id.
1445         pub fn update_monitor<B: Deref, L: Deref>(&mut self, mut updates: ChannelMonitorUpdate, broadcaster: &B, logger: &L) -> Result<(), MonitorUpdateError>
1446                 where B::Target: BroadcasterInterface,
1447                                         L::Target: Logger,
1448         {
1449                 if self.latest_update_id + 1 != updates.update_id {
1450                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1451                 }
1452                 for update in updates.updates.drain(..) {
1453                         match update {
1454                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1455                                         if self.lockdown_from_offchain { panic!(); }
1456                                         self.provide_latest_holder_commitment_tx_info(commitment_tx, htlc_outputs)?
1457                                 },
1458                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1459                                         self.provide_latest_counterparty_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point, logger),
1460                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1461                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1462                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1463                                         self.provide_secret(idx, secret)?,
1464                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1465                                         self.lockdown_from_offchain = true;
1466                                         if should_broadcast {
1467                                                 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1468                                         } else {
1469                                                 log_error!(logger, "You have a toxic holder commitment transaction avaible in channel monitor, read comment in ChannelMonitor::get_latest_holder_commitment_txn to be informed of manual action to take");
1470                                         }
1471                                 }
1472                         }
1473                 }
1474                 self.latest_update_id = updates.update_id;
1475                 Ok(())
1476         }
1477
1478         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1479         /// ChannelMonitor.
1480         pub fn get_latest_update_id(&self) -> u64 {
1481                 self.latest_update_id
1482         }
1483
1484         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1485         pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1486                 &self.funding_info
1487         }
1488
1489         /// Gets a list of txids, with their output scripts (in the order they appear in the
1490         /// transaction), which we must learn about spends of via block_connected().
1491         ///
1492         /// (C-not exported) because we have no HashMap bindings
1493         pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<Script>> {
1494                 &self.outputs_to_watch
1495         }
1496
1497         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1498         /// Generally useful when deserializing as during normal operation the return values of
1499         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1500         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1501         ///
1502         /// (C-not exported) as there is no practical way to track lifetimes of returned values.
1503         pub fn get_monitored_outpoints(&self) -> Vec<(Txid, u32, &Script)> {
1504                 let mut res = Vec::with_capacity(self.counterparty_commitment_txn_on_chain.len() * 2);
1505                 for (ref txid, &(_, ref outputs)) in self.counterparty_commitment_txn_on_chain.iter() {
1506                         for (idx, output) in outputs.iter().enumerate() {
1507                                 res.push(((*txid).clone(), idx as u32, output));
1508                         }
1509                 }
1510                 res
1511         }
1512
1513         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1514         /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_monitor_events().
1515         pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1516                 let mut ret = Vec::new();
1517                 mem::swap(&mut ret, &mut self.pending_monitor_events);
1518                 ret
1519         }
1520
1521         /// Gets the list of pending events which were generated by previous actions, clearing the list
1522         /// in the process.
1523         ///
1524         /// This is called by ManyChannelMonitor::get_and_clear_pending_events() and is equivalent to
1525         /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1526         /// no internal locking in ChannelMonitors.
1527         pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1528                 let mut ret = Vec::new();
1529                 mem::swap(&mut ret, &mut self.pending_events);
1530                 ret
1531         }
1532
1533         /// Can only fail if idx is < get_min_seen_secret
1534         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1535                 self.commitment_secrets.get_secret(idx)
1536         }
1537
1538         pub(super) fn get_min_seen_secret(&self) -> u64 {
1539                 self.commitment_secrets.get_min_seen_secret()
1540         }
1541
1542         pub(super) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1543                 self.current_counterparty_commitment_number
1544         }
1545
1546         pub(super) fn get_cur_holder_commitment_number(&self) -> u64 {
1547                 self.current_holder_commitment_number
1548         }
1549
1550         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1551         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1552         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1553         /// HTLC-Success/HTLC-Timeout transactions.
1554         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1555         /// revoked counterparty commitment tx
1556         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<TxOut>)) where L::Target: Logger {
1557                 // Most secp and related errors trying to create keys means we have no hope of constructing
1558                 // a spend transaction...so we return no transactions to broadcast
1559                 let mut claimable_outpoints = Vec::new();
1560                 let mut watch_outputs = Vec::new();
1561
1562                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1563                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1564
1565                 macro_rules! ignore_error {
1566                         ( $thing : expr ) => {
1567                                 match $thing {
1568                                         Ok(a) => a,
1569                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1570                                 }
1571                         };
1572                 }
1573
1574                 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);
1575                 if commitment_number >= self.get_min_seen_secret() {
1576                         let secret = self.get_secret(commitment_number).unwrap();
1577                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1578                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1579                         let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().revocation_basepoint));
1580                         let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_tx_cache.counterparty_delayed_payment_base_key));
1581
1582                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_tx_cache.on_counterparty_tx_csv, &delayed_key);
1583                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1584
1585                         // First, process non-htlc outputs (to_holder & to_counterparty)
1586                         for (idx, outp) in tx.output.iter().enumerate() {
1587                                 if outp.script_pubkey == revokeable_p2wsh {
1588                                         let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: outp.value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1589                                         claimable_outpoints.push(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
1590                                 }
1591                         }
1592
1593                         // Then, try to find revoked htlc outputs
1594                         if let Some(ref per_commitment_data) = per_commitment_option {
1595                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1596                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1597                                                 if transaction_output_index as usize >= tx.output.len() ||
1598                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1599                                                         return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1600                                                 }
1601                                                 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, amount: tx.output[transaction_output_index as usize].value, htlc: Some(htlc.clone()), on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1602                                                 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1603                                         }
1604                                 }
1605                         }
1606
1607                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1608                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1609                                 // We're definitely a counterparty commitment transaction!
1610                                 log_trace!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1611                                 watch_outputs.append(&mut tx.output.clone());
1612                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1613
1614                                 macro_rules! check_htlc_fails {
1615                                         ($txid: expr, $commitment_tx: expr) => {
1616                                                 if let Some(ref outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1617                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1618                                                                 if let &Some(ref source) = source_option {
1619                                                                         log_info!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of revoked counterparty commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1620                                                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1621                                                                                 hash_map::Entry::Occupied(mut entry) => {
1622                                                                                         let e = entry.get_mut();
1623                                                                                         e.retain(|ref event| {
1624                                                                                                 match **event {
1625                                                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1626                                                                                                                 return htlc_update.0 != **source
1627                                                                                                         },
1628                                                                                                         _ => true
1629                                                                                                 }
1630                                                                                         });
1631                                                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1632                                                                                 }
1633                                                                                 hash_map::Entry::Vacant(entry) => {
1634                                                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1635                                                                                 }
1636                                                                         }
1637                                                                 }
1638                                                         }
1639                                                 }
1640                                         }
1641                                 }
1642                                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
1643                                         check_htlc_fails!(txid, "current");
1644                                 }
1645                                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1646                                         check_htlc_fails!(txid, "counterparty");
1647                                 }
1648                                 // No need to check holder commitment txn, symmetric HTLCSource must be present as per-htlc data on counterparty commitment tx
1649                         }
1650                 } else if let Some(per_commitment_data) = per_commitment_option {
1651                         // While this isn't useful yet, there is a potential race where if a counterparty
1652                         // revokes a state at the same time as the commitment transaction for that state is
1653                         // confirmed, and the watchtower receives the block before the user, the user could
1654                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1655                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1656                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1657                         // insert it here.
1658                         watch_outputs.append(&mut tx.output.clone());
1659                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1660
1661                         log_trace!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1662
1663                         macro_rules! check_htlc_fails {
1664                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1665                                         if let Some(ref latest_outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1666                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1667                                                         if let &Some(ref source) = source_option {
1668                                                                 // Check if the HTLC is present in the commitment transaction that was
1669                                                                 // broadcast, but not if it was below the dust limit, which we should
1670                                                                 // fail backwards immediately as there is no way for us to learn the
1671                                                                 // payment_preimage.
1672                                                                 // Note that if the dust limit were allowed to change between
1673                                                                 // commitment transactions we'd want to be check whether *any*
1674                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1675                                                                 // cannot currently change after channel initialization, so we don't
1676                                                                 // need to here.
1677                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1678                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1679                                                                                 continue $id;
1680                                                                         }
1681                                                                 }
1682                                                                 log_trace!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of counterparty commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1683                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1684                                                                         hash_map::Entry::Occupied(mut entry) => {
1685                                                                                 let e = entry.get_mut();
1686                                                                                 e.retain(|ref event| {
1687                                                                                         match **event {
1688                                                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1689                                                                                                         return htlc_update.0 != **source
1690                                                                                                 },
1691                                                                                                 _ => true
1692                                                                                         }
1693                                                                                 });
1694                                                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1695                                                                         }
1696                                                                         hash_map::Entry::Vacant(entry) => {
1697                                                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1698                                                                         }
1699                                                                 }
1700                                                         }
1701                                                 }
1702                                         }
1703                                 }
1704                         }
1705                         if let Some(ref txid) = self.current_counterparty_commitment_txid {
1706                                 check_htlc_fails!(txid, "current", 'current_loop);
1707                         }
1708                         if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1709                                 check_htlc_fails!(txid, "previous", 'prev_loop);
1710                         }
1711
1712                         if let Some(revocation_points) = self.their_cur_revocation_points {
1713                                 let revocation_point_option =
1714                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1715                                         else if let Some(point) = revocation_points.2.as_ref() {
1716                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1717                                         } else { None };
1718                                 if let Some(revocation_point) = revocation_point_option {
1719                                         self.counterparty_payment_script = {
1720                                                 // Note that the Network here is ignored as we immediately drop the address for the
1721                                                 // script_pubkey version
1722                                                 let payment_hash160 = WPubkeyHash::hash(&self.keys.pubkeys().payment_point.serialize());
1723                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script()
1724                                         };
1725
1726                                         // Then, try to find htlc outputs
1727                                         for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1728                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1729                                                         if transaction_output_index as usize >= tx.output.len() ||
1730                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1731                                                                 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1732                                                         }
1733                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1734                                                         let aggregable = if !htlc.offered { false } else { true };
1735                                                         if preimage.is_some() || !htlc.offered {
1736                                                                 let witness_data = InputMaterial::CounterpartyHTLC { per_commitment_point: *revocation_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, preimage, htlc: htlc.clone() };
1737                                                                 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1738                                                         }
1739                                                 }
1740                                         }
1741                                 }
1742                         }
1743                 }
1744                 (claimable_outpoints, (commitment_txid, watch_outputs))
1745         }
1746
1747         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1748         fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<ClaimRequest>, Option<(Txid, Vec<TxOut>)>) where L::Target: Logger {
1749                 let htlc_txid = tx.txid();
1750                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1751                         return (Vec::new(), None)
1752                 }
1753
1754                 macro_rules! ignore_error {
1755                         ( $thing : expr ) => {
1756                                 match $thing {
1757                                         Ok(a) => a,
1758                                         Err(_) => return (Vec::new(), None)
1759                                 }
1760                         };
1761                 }
1762
1763                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1764                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1765                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1766
1767                 log_trace!(logger, "Counterparty HTLC broadcast {}:{}", htlc_txid, 0);
1768                 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key,  per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: tx.output[0].value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv };
1769                 let claimable_outpoints = vec!(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
1770                 (claimable_outpoints, Some((htlc_txid, tx.output.clone())))
1771         }
1772
1773         fn broadcast_by_holder_state(&self, commitment_tx: &Transaction, holder_tx: &HolderSignedTx) -> (Vec<ClaimRequest>, Vec<TxOut>, Option<(Script, PublicKey, PublicKey)>) {
1774                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
1775                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
1776
1777                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
1778                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
1779
1780                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1781                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1782                                 claim_requests.push(ClaimRequest { absolute_timelock: ::std::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
1783                                         witness_data: InputMaterial::HolderHTLC {
1784                                                 preimage: if !htlc.offered {
1785                                                                 if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1786                                                                         Some(preimage.clone())
1787                                                                 } else {
1788                                                                         // We can't build an HTLC-Success transaction without the preimage
1789                                                                         continue;
1790                                                                 }
1791                                                         } else { None },
1792                                                 amount: htlc.amount_msat,
1793                                 }});
1794                                 watch_outputs.push(commitment_tx.output[transaction_output_index as usize].clone());
1795                         }
1796                 }
1797
1798                 (claim_requests, watch_outputs, broadcasted_holder_revokable_script)
1799         }
1800
1801         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1802         /// revoked using data in holder_claimable_outpoints.
1803         /// Should not be used if check_spend_revoked_transaction succeeds.
1804         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<TxOut>)) where L::Target: Logger {
1805                 let commitment_txid = tx.txid();
1806                 let mut claim_requests = Vec::new();
1807                 let mut watch_outputs = Vec::new();
1808
1809                 macro_rules! wait_threshold_conf {
1810                         ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1811                                 log_trace!(logger, "Failing HTLC with payment_hash {} from {} holder commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1812                                 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
1813                                         hash_map::Entry::Occupied(mut entry) => {
1814                                                 let e = entry.get_mut();
1815                                                 e.retain(|ref event| {
1816                                                         match **event {
1817                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1818                                                                         return htlc_update.0 != $source
1819                                                                 },
1820                                                                 _ => true
1821                                                         }
1822                                                 });
1823                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
1824                                         }
1825                                         hash_map::Entry::Vacant(entry) => {
1826                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
1827                                         }
1828                                 }
1829                         }
1830                 }
1831
1832                 macro_rules! append_onchain_update {
1833                         ($updates: expr) => {
1834                                 claim_requests = $updates.0;
1835                                 watch_outputs.append(&mut $updates.1);
1836                                 self.broadcasted_holder_revokable_script = $updates.2;
1837                         }
1838                 }
1839
1840                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1841                 let mut is_holder_tx = false;
1842
1843                 if self.current_holder_commitment_tx.txid == commitment_txid {
1844                         is_holder_tx = true;
1845                         log_trace!(logger, "Got latest holder commitment tx broadcast, searching for available HTLCs to claim");
1846                         let mut res = self.broadcast_by_holder_state(tx, &self.current_holder_commitment_tx);
1847                         append_onchain_update!(res);
1848                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1849                         if holder_tx.txid == commitment_txid {
1850                                 is_holder_tx = true;
1851                                 log_trace!(logger, "Got previous holder commitment tx broadcast, searching for available HTLCs to claim");
1852                                 let mut res = self.broadcast_by_holder_state(tx, holder_tx);
1853                                 append_onchain_update!(res);
1854                         }
1855                 }
1856
1857                 macro_rules! fail_dust_htlcs_after_threshold_conf {
1858                         ($holder_tx: expr) => {
1859                                 for &(ref htlc, _, ref source) in &$holder_tx.htlc_outputs {
1860                                         if htlc.transaction_output_index.is_none() {
1861                                                 if let &Some(ref source) = source {
1862                                                         wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
1863                                                 }
1864                                         }
1865                                 }
1866                         }
1867                 }
1868
1869                 if is_holder_tx {
1870                         fail_dust_htlcs_after_threshold_conf!(self.current_holder_commitment_tx);
1871                         if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1872                                 fail_dust_htlcs_after_threshold_conf!(holder_tx);
1873                         }
1874                 }
1875
1876                 (claim_requests, (commitment_txid, watch_outputs))
1877         }
1878
1879         /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1880         /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1881         /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1882         /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1883         /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1884         /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1885         /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1886         /// out-of-band the other node operator to coordinate with him if option is available to you.
1887         /// In any-case, choice is up to the user.
1888         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1889                 log_trace!(logger, "Getting signed latest holder commitment transaction!");
1890                 self.holder_tx_signed = true;
1891                 if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
1892                         let txid = commitment_tx.txid();
1893                         let mut res = vec![commitment_tx];
1894                         for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1895                                 if let Some(vout) = htlc.0.transaction_output_index {
1896                                         let preimage = if !htlc.0.offered {
1897                                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1898                                                                 // We can't build an HTLC-Success transaction without the preimage
1899                                                                 continue;
1900                                                         }
1901                                                 } else { None };
1902                                         if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
1903                                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
1904                                                 res.push(htlc_tx);
1905                                         }
1906                                 }
1907                         }
1908                         // 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.
1909                         // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
1910                         return res
1911                 }
1912                 Vec::new()
1913         }
1914
1915         /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1916         /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1917         /// revoked commitment transaction.
1918         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1919         pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1920                 log_trace!(logger, "Getting signed copy of latest holder commitment transaction!");
1921                 if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript) {
1922                         let txid = commitment_tx.txid();
1923                         let mut res = vec![commitment_tx];
1924                         for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1925                                 if let Some(vout) = htlc.0.transaction_output_index {
1926                                         let preimage = if !htlc.0.offered {
1927                                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1928                                                                 // We can't build an HTLC-Success transaction without the preimage
1929                                                                 continue;
1930                                                         }
1931                                                 } else { None };
1932                                         if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
1933                                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
1934                                                 res.push(htlc_tx);
1935                                         }
1936                                 }
1937                         }
1938                         return res
1939                 }
1940                 Vec::new()
1941         }
1942
1943         /// Called by SimpleManyChannelMonitor::block_connected, which implements
1944         /// ChainListener::block_connected.
1945         /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
1946         /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
1947         /// on-chain.
1948         fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txn_matched: &[(usize, &Transaction)], height: u32, broadcaster: B, fee_estimator: F, logger: L)-> Vec<(Txid, Vec<TxOut>)>
1949                 where B::Target: BroadcasterInterface,
1950                       F::Target: FeeEstimator,
1951                                         L::Target: Logger,
1952         {
1953                 for &(_, tx) in txn_matched {
1954                         let mut output_val = 0;
1955                         for out in tx.output.iter() {
1956                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1957                                 output_val += out.value;
1958                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1959                         }
1960                 }
1961
1962                 let block_hash = header.block_hash();
1963                 log_trace!(logger, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
1964
1965                 let mut watch_outputs = Vec::new();
1966                 let mut claimable_outpoints = Vec::new();
1967                 for &(_, tx) in txn_matched {
1968                         if tx.input.len() == 1 {
1969                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1970                                 // commitment transactions and HTLC transactions will all only ever have one input,
1971                                 // which is an easy way to filter out any potential non-matching txn for lazy
1972                                 // filters.
1973                                 let prevout = &tx.input[0].previous_output;
1974                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
1975                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1976                                                 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
1977                                                 if !new_outputs.1.is_empty() {
1978                                                         watch_outputs.push(new_outputs);
1979                                                 }
1980                                                 if new_outpoints.is_empty() {
1981                                                         let (mut new_outpoints, new_outputs) = self.check_spend_holder_transaction(&tx, height, &logger);
1982                                                         if !new_outputs.1.is_empty() {
1983                                                                 watch_outputs.push(new_outputs);
1984                                                         }
1985                                                         claimable_outpoints.append(&mut new_outpoints);
1986                                                 }
1987                                                 claimable_outpoints.append(&mut new_outpoints);
1988                                         }
1989                                 } else {
1990                                         if let Some(&(commitment_number, _)) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
1991                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
1992                                                 claimable_outpoints.append(&mut new_outpoints);
1993                                                 if let Some(new_outputs) = new_outputs_option {
1994                                                         watch_outputs.push(new_outputs);
1995                                                 }
1996                                         }
1997                                 }
1998                         }
1999                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2000                         // can also be resolved in a few other ways which can have more than one output. Thus,
2001                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2002                         self.is_resolving_htlc_output(&tx, height, &logger);
2003
2004                         self.is_paying_spendable_output(&tx, height, &logger);
2005                 }
2006                 let should_broadcast = self.would_broadcast_at_height(height, &logger);
2007                 if should_broadcast {
2008                         claimable_outpoints.push(ClaimRequest { absolute_timelock: height, aggregable: false, outpoint: BitcoinOutPoint { txid: self.funding_info.0.txid.clone(), vout: self.funding_info.0.index as u32 }, witness_data: InputMaterial::Funding { funding_redeemscript: self.funding_redeemscript.clone() }});
2009                 }
2010                 if should_broadcast {
2011                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
2012                         if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
2013                                 self.holder_tx_signed = true;
2014                                 let (mut new_outpoints, new_outputs, _) = self.broadcast_by_holder_state(&commitment_tx, &self.current_holder_commitment_tx);
2015                                 if !new_outputs.is_empty() {
2016                                         watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2017                                 }
2018                                 claimable_outpoints.append(&mut new_outpoints);
2019                         }
2020                 }
2021                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2022                         for ev in events {
2023                                 match ev {
2024                                         OnchainEvent::HTLCUpdate { htlc_update } => {
2025                                                 log_trace!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2026                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2027                                                         payment_hash: htlc_update.1,
2028                                                         payment_preimage: None,
2029                                                         source: htlc_update.0,
2030                                                 }));
2031                                         },
2032                                         OnchainEvent::MaturingOutput { descriptor } => {
2033                                                 log_trace!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2034                                                 self.pending_events.push(Event::SpendableOutputs {
2035                                                         outputs: vec![descriptor]
2036                                                 });
2037                                         }
2038                                 }
2039                         }
2040                 }
2041
2042                 self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, &*broadcaster, &*fee_estimator, &*logger);
2043
2044                 self.last_block_hash = block_hash;
2045                 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2046                         self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2047                 }
2048
2049                 watch_outputs
2050         }
2051
2052         fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2053                 where B::Target: BroadcasterInterface,
2054                       F::Target: FeeEstimator,
2055                       L::Target: Logger,
2056         {
2057                 let block_hash = header.block_hash();
2058                 log_trace!(logger, "Block {} at height {} disconnected", block_hash, height);
2059
2060                 if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2061                         //We may discard:
2062                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2063                         //- maturing spendable output has transaction paying us has been disconnected
2064                 }
2065
2066                 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2067
2068                 self.last_block_hash = block_hash;
2069         }
2070
2071         fn would_broadcast_at_height<L: Deref>(&self, height: u32, logger: &L) -> bool where L::Target: Logger {
2072                 // We need to consider all HTLCs which are:
2073                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
2074                 //    transactions and we'd end up in a race, or
2075                 //  * are in our latest holder commitment transaction, as this is the thing we will
2076                 //    broadcast if we go on-chain.
2077                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2078                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2079                 // to the source, and if we don't fail the channel we will have to ensure that the next
2080                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2081                 // easier to just fail the channel as this case should be rare enough anyway.
2082                 macro_rules! scan_commitment {
2083                         ($htlcs: expr, $holder_tx: expr) => {
2084                                 for ref htlc in $htlcs {
2085                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2086                                         // chain with enough room to claim the HTLC without our counterparty being able to
2087                                         // time out the HTLC first.
2088                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2089                                         // concern is being able to claim the corresponding inbound HTLC (on another
2090                                         // channel) before it expires. In fact, we don't even really care if our
2091                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2092                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2093                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2094                                         // we give ourselves a few blocks of headroom after expiration before going
2095                                         // on-chain for an expired HTLC.
2096                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2097                                         // from us until we've reached the point where we go on-chain with the
2098                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2099                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2100                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2101                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2102                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2103                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2104                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2105                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2106                                         //  The final, above, condition is checked for statically in channelmanager
2107                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2108                                         let htlc_outbound = $holder_tx == htlc.offered;
2109                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2110                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2111                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2112                                                 return true;
2113                                         }
2114                                 }
2115                         }
2116                 }
2117
2118                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2119
2120                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2121                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2122                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2123                         }
2124                 }
2125                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2126                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2127                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2128                         }
2129                 }
2130
2131                 false
2132         }
2133
2134         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2135         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2136         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2137                 'outer_loop: for input in &tx.input {
2138                         let mut payment_data = None;
2139                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2140                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2141                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2142                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2143
2144                         macro_rules! log_claim {
2145                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2146                                         // We found the output in question, but aren't failing it backwards
2147                                         // as we have no corresponding source and no valid counterparty commitment txid
2148                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2149                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2150                                         let outbound_htlc = $holder_tx == $htlc.offered;
2151                                         if ($holder_tx && revocation_sig_claim) ||
2152                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2153                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2154                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2155                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2156                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2157                                         } else {
2158                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2159                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2160                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2161                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2162                                         }
2163                                 }
2164                         }
2165
2166                         macro_rules! check_htlc_valid_counterparty {
2167                                 ($counterparty_txid: expr, $htlc_output: expr) => {
2168                                         if let Some(txid) = $counterparty_txid {
2169                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2170                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2171                                                                 if let &Some(ref source) = pending_source {
2172                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2173                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2174                                                                         break;
2175                                                                 }
2176                                                         }
2177                                                 }
2178                                         }
2179                                 }
2180                         }
2181
2182                         macro_rules! scan_commitment {
2183                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2184                                         for (ref htlc_output, source_option) in $htlcs {
2185                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2186                                                         if let Some(ref source) = source_option {
2187                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
2188                                                                 // We have a resolution of an HTLC either from one of our latest
2189                                                                 // holder commitment transactions or an unrevoked counterparty commitment
2190                                                                 // transaction. This implies we either learned a preimage, the HTLC
2191                                                                 // has timed out, or we screwed up. In any case, we should now
2192                                                                 // resolve the source HTLC with the original sender.
2193                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2194                                                         } else if !$holder_tx {
2195                                                                         check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2196                                                                 if payment_data.is_none() {
2197                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2198                                                                 }
2199                                                         }
2200                                                         if payment_data.is_none() {
2201                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
2202                                                                 continue 'outer_loop;
2203                                                         }
2204                                                 }
2205                                         }
2206                                 }
2207                         }
2208
2209                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2210                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2211                                         "our latest holder commitment tx", true);
2212                         }
2213                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2214                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2215                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2216                                                 "our previous holder commitment tx", true);
2217                                 }
2218                         }
2219                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2220                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2221                                         "counterparty commitment tx", false);
2222                         }
2223
2224                         // Check that scan_commitment, above, decided there is some source worth relaying an
2225                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2226                         if let Some((source, payment_hash)) = payment_data {
2227                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2228                                 if accepted_preimage_claim {
2229                                         if !self.pending_monitor_events.iter().any(
2230                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2231                                                 payment_preimage.0.copy_from_slice(&input.witness[3]);
2232                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2233                                                         source,
2234                                                         payment_preimage: Some(payment_preimage),
2235                                                         payment_hash
2236                                                 }));
2237                                         }
2238                                 } else if offered_preimage_claim {
2239                                         if !self.pending_monitor_events.iter().any(
2240                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2241                                                         upd.source == source
2242                                                 } else { false }) {
2243                                                 payment_preimage.0.copy_from_slice(&input.witness[1]);
2244                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2245                                                         source,
2246                                                         payment_preimage: Some(payment_preimage),
2247                                                         payment_hash
2248                                                 }));
2249                                         }
2250                                 } else {
2251                                         log_info!(logger, "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);
2252                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2253                                                 hash_map::Entry::Occupied(mut entry) => {
2254                                                         let e = entry.get_mut();
2255                                                         e.retain(|ref event| {
2256                                                                 match **event {
2257                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2258                                                                                 return htlc_update.0 != source
2259                                                                         },
2260                                                                         _ => true
2261                                                                 }
2262                                                         });
2263                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2264                                                 }
2265                                                 hash_map::Entry::Vacant(entry) => {
2266                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2267                                                 }
2268                                         }
2269                                 }
2270                         }
2271                 }
2272         }
2273
2274         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2275         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2276                 let mut spendable_output = None;
2277                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2278                         if i > ::std::u16::MAX as usize {
2279                                 // While it is possible that an output exists on chain which is greater than the
2280                                 // 2^16th output in a given transaction, this is only possible if the output is not
2281                                 // in a lightning transaction and was instead placed there by some third party who
2282                                 // wishes to give us money for no reason.
2283                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
2284                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2285                                 // scripts are not longer than one byte in length and because they are inherently
2286                                 // non-standard due to their size.
2287                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
2288                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
2289                                 // nearly a full block with garbage just to hit this case.
2290                                 continue;
2291                         }
2292                         if outp.script_pubkey == self.destination_script {
2293                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
2294                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2295                                         output: outp.clone(),
2296                                 });
2297                                 break;
2298                         } else if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2299                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2300                                         spendable_output =  Some(SpendableOutputDescriptor::DynamicOutputP2WSH {
2301                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2302                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
2303                                                 to_self_delay: self.on_holder_tx_csv,
2304                                                 output: outp.clone(),
2305                                                 key_derivation_params: self.keys.key_derivation_params(),
2306                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2307                                         });
2308                                         break;
2309                                 }
2310                         } else if self.counterparty_payment_script == outp.script_pubkey {
2311                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
2312                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2313                                         output: outp.clone(),
2314                                         key_derivation_params: self.keys.key_derivation_params(),
2315                                 });
2316                                 break;
2317                         } else if outp.script_pubkey == self.shutdown_script {
2318                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2319                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2320                                         output: outp.clone(),
2321                                 });
2322                         }
2323                 }
2324                 if let Some(spendable_output) = spendable_output {
2325                         log_trace!(logger, "Maturing {} until {}", log_spendable!(spendable_output), height + ANTI_REORG_DELAY - 1);
2326                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2327                                 hash_map::Entry::Occupied(mut entry) => {
2328                                         let e = entry.get_mut();
2329                                         e.push(OnchainEvent::MaturingOutput { descriptor: spendable_output });
2330                                 }
2331                                 hash_map::Entry::Vacant(entry) => {
2332                                         entry.insert(vec![OnchainEvent::MaturingOutput { descriptor: spendable_output }]);
2333                                 }
2334                         }
2335                 }
2336         }
2337 }
2338
2339 const MAX_ALLOC_SIZE: usize = 64*1024;
2340
2341 impl<ChanSigner: ChannelKeys + Readable> Readable for (BlockHash, ChannelMonitor<ChanSigner>) {
2342         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
2343                 macro_rules! unwrap_obj {
2344                         ($key: expr) => {
2345                                 match $key {
2346                                         Ok(res) => res,
2347                                         Err(_) => return Err(DecodeError::InvalidValue),
2348                                 }
2349                         }
2350                 }
2351
2352                 let _ver: u8 = Readable::read(reader)?;
2353                 let min_ver: u8 = Readable::read(reader)?;
2354                 if min_ver > SERIALIZATION_VERSION {
2355                         return Err(DecodeError::UnknownVersion);
2356                 }
2357
2358                 let latest_update_id: u64 = Readable::read(reader)?;
2359                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2360
2361                 let destination_script = Readable::read(reader)?;
2362                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2363                         0 => {
2364                                 let revokable_address = Readable::read(reader)?;
2365                                 let per_commitment_point = Readable::read(reader)?;
2366                                 let revokable_script = Readable::read(reader)?;
2367                                 Some((revokable_address, per_commitment_point, revokable_script))
2368                         },
2369                         1 => { None },
2370                         _ => return Err(DecodeError::InvalidValue),
2371                 };
2372                 let counterparty_payment_script = Readable::read(reader)?;
2373                 let shutdown_script = Readable::read(reader)?;
2374
2375                 let keys = Readable::read(reader)?;
2376                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2377                 // barely-init'd ChannelMonitors that we can't do anything with.
2378                 let outpoint = OutPoint {
2379                         txid: Readable::read(reader)?,
2380                         index: Readable::read(reader)?,
2381                 };
2382                 let funding_info = (outpoint, Readable::read(reader)?);
2383                 let current_counterparty_commitment_txid = Readable::read(reader)?;
2384                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2385
2386                 let counterparty_tx_cache = Readable::read(reader)?;
2387                 let funding_redeemscript = Readable::read(reader)?;
2388                 let channel_value_satoshis = Readable::read(reader)?;
2389
2390                 let their_cur_revocation_points = {
2391                         let first_idx = <U48 as Readable>::read(reader)?.0;
2392                         if first_idx == 0 {
2393                                 None
2394                         } else {
2395                                 let first_point = Readable::read(reader)?;
2396                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2397                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2398                                         Some((first_idx, first_point, None))
2399                                 } else {
2400                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2401                                 }
2402                         }
2403                 };
2404
2405                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2406
2407                 let commitment_secrets = Readable::read(reader)?;
2408
2409                 macro_rules! read_htlc_in_commitment {
2410                         () => {
2411                                 {
2412                                         let offered: bool = Readable::read(reader)?;
2413                                         let amount_msat: u64 = Readable::read(reader)?;
2414                                         let cltv_expiry: u32 = Readable::read(reader)?;
2415                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2416                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2417
2418                                         HTLCOutputInCommitment {
2419                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2420                                         }
2421                                 }
2422                         }
2423                 }
2424
2425                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2426                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2427                 for _ in 0..counterparty_claimable_outpoints_len {
2428                         let txid: Txid = Readable::read(reader)?;
2429                         let htlcs_count: u64 = Readable::read(reader)?;
2430                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2431                         for _ in 0..htlcs_count {
2432                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2433                         }
2434                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2435                                 return Err(DecodeError::InvalidValue);
2436                         }
2437                 }
2438
2439                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2440                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2441                 for _ in 0..counterparty_commitment_txn_on_chain_len {
2442                         let txid: Txid = Readable::read(reader)?;
2443                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2444                         let outputs_count = <u64 as Readable>::read(reader)?;
2445                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2446                         for _ in 0..outputs_count {
2447                                 outputs.push(Readable::read(reader)?);
2448                         }
2449                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2450                                 return Err(DecodeError::InvalidValue);
2451                         }
2452                 }
2453
2454                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2455                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2456                 for _ in 0..counterparty_hash_commitment_number_len {
2457                         let payment_hash: PaymentHash = Readable::read(reader)?;
2458                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2459                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2460                                 return Err(DecodeError::InvalidValue);
2461                         }
2462                 }
2463
2464                 macro_rules! read_holder_tx {
2465                         () => {
2466                                 {
2467                                         let txid = Readable::read(reader)?;
2468                                         let revocation_key = Readable::read(reader)?;
2469                                         let a_htlc_key = Readable::read(reader)?;
2470                                         let b_htlc_key = Readable::read(reader)?;
2471                                         let delayed_payment_key = Readable::read(reader)?;
2472                                         let per_commitment_point = Readable::read(reader)?;
2473                                         let feerate_per_kw: u32 = Readable::read(reader)?;
2474
2475                                         let htlcs_len: u64 = Readable::read(reader)?;
2476                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2477                                         for _ in 0..htlcs_len {
2478                                                 let htlc = read_htlc_in_commitment!();
2479                                                 let sigs = match <u8 as Readable>::read(reader)? {
2480                                                         0 => None,
2481                                                         1 => Some(Readable::read(reader)?),
2482                                                         _ => return Err(DecodeError::InvalidValue),
2483                                                 };
2484                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
2485                                         }
2486
2487                                         HolderSignedTx {
2488                                                 txid,
2489                                                 revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
2490                                                 htlc_outputs: htlcs
2491                                         }
2492                                 }
2493                         }
2494                 }
2495
2496                 let prev_holder_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2497                         0 => None,
2498                         1 => {
2499                                 Some(read_holder_tx!())
2500                         },
2501                         _ => return Err(DecodeError::InvalidValue),
2502                 };
2503                 let current_holder_commitment_tx = read_holder_tx!();
2504
2505                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2506                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2507
2508                 let payment_preimages_len: u64 = Readable::read(reader)?;
2509                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2510                 for _ in 0..payment_preimages_len {
2511                         let preimage: PaymentPreimage = Readable::read(reader)?;
2512                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2513                         if let Some(_) = payment_preimages.insert(hash, preimage) {
2514                                 return Err(DecodeError::InvalidValue);
2515                         }
2516                 }
2517
2518                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
2519                 let mut pending_monitor_events = Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2520                 for _ in 0..pending_monitor_events_len {
2521                         let ev = match <u8 as Readable>::read(reader)? {
2522                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
2523                                 1 => MonitorEvent::CommitmentTxBroadcasted(funding_info.0),
2524                                 _ => return Err(DecodeError::InvalidValue)
2525                         };
2526                         pending_monitor_events.push(ev);
2527                 }
2528
2529                 let pending_events_len: u64 = Readable::read(reader)?;
2530                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
2531                 for _ in 0..pending_events_len {
2532                         if let Some(event) = MaybeReadable::read(reader)? {
2533                                 pending_events.push(event);
2534                         }
2535                 }
2536
2537                 let last_block_hash: BlockHash = Readable::read(reader)?;
2538
2539                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2540                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2541                 for _ in 0..waiting_threshold_conf_len {
2542                         let height_target = Readable::read(reader)?;
2543                         let events_len: u64 = Readable::read(reader)?;
2544                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
2545                         for _ in 0..events_len {
2546                                 let ev = match <u8 as Readable>::read(reader)? {
2547                                         0 => {
2548                                                 let htlc_source = Readable::read(reader)?;
2549                                                 let hash = Readable::read(reader)?;
2550                                                 OnchainEvent::HTLCUpdate {
2551                                                         htlc_update: (htlc_source, hash)
2552                                                 }
2553                                         },
2554                                         1 => {
2555                                                 let descriptor = Readable::read(reader)?;
2556                                                 OnchainEvent::MaturingOutput {
2557                                                         descriptor
2558                                                 }
2559                                         },
2560                                         _ => return Err(DecodeError::InvalidValue),
2561                                 };
2562                                 events.push(ev);
2563                         }
2564                         onchain_events_waiting_threshold_conf.insert(height_target, events);
2565                 }
2566
2567                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2568                 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<Vec<Script>>())));
2569                 for _ in 0..outputs_to_watch_len {
2570                         let txid = Readable::read(reader)?;
2571                         let outputs_len: u64 = Readable::read(reader)?;
2572                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
2573                         for _ in 0..outputs_len {
2574                                 outputs.push(Readable::read(reader)?);
2575                         }
2576                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2577                                 return Err(DecodeError::InvalidValue);
2578                         }
2579                 }
2580                 let onchain_tx_handler = Readable::read(reader)?;
2581
2582                 let lockdown_from_offchain = Readable::read(reader)?;
2583                 let holder_tx_signed = Readable::read(reader)?;
2584
2585                 Ok((last_block_hash.clone(), ChannelMonitor {
2586                         latest_update_id,
2587                         commitment_transaction_number_obscure_factor,
2588
2589                         destination_script,
2590                         broadcasted_holder_revokable_script,
2591                         counterparty_payment_script,
2592                         shutdown_script,
2593
2594                         keys,
2595                         funding_info,
2596                         current_counterparty_commitment_txid,
2597                         prev_counterparty_commitment_txid,
2598
2599                         counterparty_tx_cache,
2600                         funding_redeemscript,
2601                         channel_value_satoshis,
2602                         their_cur_revocation_points,
2603
2604                         on_holder_tx_csv,
2605
2606                         commitment_secrets,
2607                         counterparty_claimable_outpoints,
2608                         counterparty_commitment_txn_on_chain,
2609                         counterparty_hash_commitment_number,
2610
2611                         prev_holder_signed_commitment_tx,
2612                         current_holder_commitment_tx,
2613                         current_counterparty_commitment_number,
2614                         current_holder_commitment_number,
2615
2616                         payment_preimages,
2617                         pending_monitor_events,
2618                         pending_events,
2619
2620                         onchain_events_waiting_threshold_conf,
2621                         outputs_to_watch,
2622
2623                         onchain_tx_handler,
2624
2625                         lockdown_from_offchain,
2626                         holder_tx_signed,
2627
2628                         last_block_hash,
2629                         secp_ctx: Secp256k1::new(),
2630                 }))
2631         }
2632 }
2633
2634 #[cfg(test)]
2635 mod tests {
2636         use bitcoin::blockdata::script::{Script, Builder};
2637         use bitcoin::blockdata::opcodes;
2638         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2639         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2640         use bitcoin::util::bip143;
2641         use bitcoin::hashes::Hash;
2642         use bitcoin::hashes::sha256::Hash as Sha256;
2643         use bitcoin::hashes::hex::FromHex;
2644         use bitcoin::hash_types::Txid;
2645         use hex;
2646         use chain::transaction::OutPoint;
2647         use ln::channelmanager::{PaymentPreimage, PaymentHash};
2648         use ln::channelmonitor::ChannelMonitor;
2649         use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
2650         use ln::chan_utils;
2651         use ln::chan_utils::{HTLCOutputInCommitment, HolderCommitmentTransaction};
2652         use util::test_utils::TestLogger;
2653         use bitcoin::secp256k1::key::{SecretKey,PublicKey};
2654         use bitcoin::secp256k1::Secp256k1;
2655         use std::sync::Arc;
2656         use chain::keysinterface::InMemoryChannelKeys;
2657
2658         #[test]
2659         fn test_prune_preimages() {
2660                 let secp_ctx = Secp256k1::new();
2661                 let logger = Arc::new(TestLogger::new());
2662
2663                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2664                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2665
2666                 let mut preimages = Vec::new();
2667                 {
2668                         for i in 0..20 {
2669                                 let preimage = PaymentPreimage([i; 32]);
2670                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2671                                 preimages.push((preimage, hash));
2672                         }
2673                 }
2674
2675                 macro_rules! preimages_slice_to_htlc_outputs {
2676                         ($preimages_slice: expr) => {
2677                                 {
2678                                         let mut res = Vec::new();
2679                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
2680                                                 res.push((HTLCOutputInCommitment {
2681                                                         offered: true,
2682                                                         amount_msat: 0,
2683                                                         cltv_expiry: 0,
2684                                                         payment_hash: preimage.1.clone(),
2685                                                         transaction_output_index: Some(idx as u32),
2686                                                 }, None));
2687                                         }
2688                                         res
2689                                 }
2690                         }
2691                 }
2692                 macro_rules! preimages_to_holder_htlcs {
2693                         ($preimages_slice: expr) => {
2694                                 {
2695                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2696                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2697                                         res
2698                                 }
2699                         }
2700                 }
2701
2702                 macro_rules! test_preimages_exist {
2703                         ($preimages_slice: expr, $monitor: expr) => {
2704                                 for preimage in $preimages_slice {
2705                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
2706                                 }
2707                         }
2708                 }
2709
2710                 let keys = InMemoryChannelKeys::new(
2711                         &secp_ctx,
2712                         SecretKey::from_slice(&[41; 32]).unwrap(),
2713                         SecretKey::from_slice(&[41; 32]).unwrap(),
2714                         SecretKey::from_slice(&[41; 32]).unwrap(),
2715                         SecretKey::from_slice(&[41; 32]).unwrap(),
2716                         SecretKey::from_slice(&[41; 32]).unwrap(),
2717                         [41; 32],
2718                         0,
2719                         (0, 0)
2720                 );
2721
2722                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
2723                 // old state.
2724                 let mut monitor = ChannelMonitor::new(keys,
2725                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
2726                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2727                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2728                         &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2729                         10, Script::new(), 46, 0, HolderCommitmentTransaction::dummy());
2730
2731                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
2732                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
2733                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
2734                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
2735                 monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
2736                 for &(ref preimage, ref hash) in preimages.iter() {
2737                         monitor.provide_payment_preimage(hash, preimage);
2738                 }
2739
2740                 // Now provide a secret, pruning preimages 10-15
2741                 let mut secret = [0; 32];
2742                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2743                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2744                 assert_eq!(monitor.payment_preimages.len(), 15);
2745                 test_preimages_exist!(&preimages[0..10], monitor);
2746                 test_preimages_exist!(&preimages[15..20], monitor);
2747
2748                 // Now provide a further secret, pruning preimages 15-17
2749                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2750                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2751                 assert_eq!(monitor.payment_preimages.len(), 13);
2752                 test_preimages_exist!(&preimages[0..10], monitor);
2753                 test_preimages_exist!(&preimages[17..20], monitor);
2754
2755                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
2756                 // previous commitment tx's preimages too
2757                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
2758                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2759                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2760                 assert_eq!(monitor.payment_preimages.len(), 12);
2761                 test_preimages_exist!(&preimages[0..10], monitor);
2762                 test_preimages_exist!(&preimages[18..20], monitor);
2763
2764                 // But if we do it again, we'll prune 5-10
2765                 monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
2766                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2767                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2768                 assert_eq!(monitor.payment_preimages.len(), 5);
2769                 test_preimages_exist!(&preimages[0..5], monitor);
2770         }
2771
2772         #[test]
2773         fn test_claim_txn_weight_computation() {
2774                 // We test Claim txn weight, knowing that we want expected weigth and
2775                 // not actual case to avoid sigs and time-lock delays hell variances.
2776
2777                 let secp_ctx = Secp256k1::new();
2778                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
2779                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
2780                 let mut sum_actual_sigs = 0;
2781
2782                 macro_rules! sign_input {
2783                         ($sighash_parts: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
2784                                 let htlc = HTLCOutputInCommitment {
2785                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
2786                                         amount_msat: 0,
2787                                         cltv_expiry: 2 << 16,
2788                                         payment_hash: PaymentHash([1; 32]),
2789                                         transaction_output_index: Some($idx as u32),
2790                                 };
2791                                 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) };
2792                                 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
2793                                 let sig = secp_ctx.sign(&sighash, &privkey);
2794                                 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
2795                                 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
2796                                 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
2797                                 if *$input_type == InputDescriptors::RevokedOutput {
2798                                         $sighash_parts.access_witness($idx).push(vec!(1));
2799                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
2800                                         $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
2801                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
2802                                         $sighash_parts.access_witness($idx).push(vec![0]);
2803                                 } else {
2804                                         $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
2805                                 }
2806                                 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
2807                                 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
2808                                 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
2809                                 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
2810                         }
2811                 }
2812
2813                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
2814                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
2815
2816                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
2817                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2818                 for i in 0..4 {
2819                         claim_tx.input.push(TxIn {
2820                                 previous_output: BitcoinOutPoint {
2821                                         txid,
2822                                         vout: i,
2823                                 },
2824                                 script_sig: Script::new(),
2825                                 sequence: 0xfffffffd,
2826                                 witness: Vec::new(),
2827                         });
2828                 }
2829                 claim_tx.output.push(TxOut {
2830                         script_pubkey: script_pubkey.clone(),
2831                         value: 0,
2832                 });
2833                 let base_weight = claim_tx.get_weight();
2834                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
2835                 {
2836                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2837                         for (idx, inp) in inputs_des.iter().enumerate() {
2838                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2839                         }
2840                 }
2841                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2842
2843                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
2844                 claim_tx.input.clear();
2845                 sum_actual_sigs = 0;
2846                 for i in 0..4 {
2847                         claim_tx.input.push(TxIn {
2848                                 previous_output: BitcoinOutPoint {
2849                                         txid,
2850                                         vout: i,
2851                                 },
2852                                 script_sig: Script::new(),
2853                                 sequence: 0xfffffffd,
2854                                 witness: Vec::new(),
2855                         });
2856                 }
2857                 let base_weight = claim_tx.get_weight();
2858                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
2859                 {
2860                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2861                         for (idx, inp) in inputs_des.iter().enumerate() {
2862                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2863                         }
2864                 }
2865                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2866
2867                 // Justice tx with 1 revoked HTLC-Success tx output
2868                 claim_tx.input.clear();
2869                 sum_actual_sigs = 0;
2870                 claim_tx.input.push(TxIn {
2871                         previous_output: BitcoinOutPoint {
2872                                 txid,
2873                                 vout: 0,
2874                         },
2875                         script_sig: Script::new(),
2876                         sequence: 0xfffffffd,
2877                         witness: Vec::new(),
2878                 });
2879                 let base_weight = claim_tx.get_weight();
2880                 let inputs_des = vec![InputDescriptors::RevokedOutput];
2881                 {
2882                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
2883                         for (idx, inp) in inputs_des.iter().enumerate() {
2884                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
2885                         }
2886                 }
2887                 assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
2888         }
2889
2890         // Further testing is done in the ChannelManager integration tests.
2891 }