Move MonitorEvent serialization to TLV-enum-upgradable from custom
[rust-lightning] / lightning / src / chain / 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 [`chain::Watch`] 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::{Block, BlockHeader};
24 use bitcoin::blockdata::transaction::{TxOut,Transaction};
25 use bitcoin::blockdata::script::{Script, Builder};
26 use bitcoin::blockdata::opcodes;
27
28 use bitcoin::hashes::Hash;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
31
32 use bitcoin::secp256k1::{Secp256k1,Signature};
33 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
34 use bitcoin::secp256k1;
35
36 use ln::{PaymentHash, PaymentPreimage};
37 use ln::msgs::DecodeError;
38 use ln::chan_utils;
39 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
40 use ln::channelmanager::HTLCSource;
41 use chain;
42 use chain::{BestBlock, WatchedOutput};
43 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
44 use chain::transaction::{OutPoint, TransactionData};
45 use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
46 use chain::onchaintx::OnchainTxHandler;
47 use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
48 use chain::Filter;
49 use util::logger::Logger;
50 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
51 use util::byte_utils;
52 use util::events::Event;
53
54 use prelude::*;
55 use core::{cmp, mem};
56 use io::{self, Error};
57 use core::ops::Deref;
58 use sync::Mutex;
59
60 /// An update generated by the underlying Channel itself which contains some new information the
61 /// ChannelMonitor should be made aware of.
62 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
63 #[derive(Clone)]
64 #[must_use]
65 pub struct ChannelMonitorUpdate {
66         pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
67         /// The sequence number of this update. Updates *must* be replayed in-order according to this
68         /// sequence number (and updates may panic if they are not). The update_id values are strictly
69         /// increasing and increase by one for each new update, with one exception specified below.
70         ///
71         /// This sequence number is also used to track up to which points updates which returned
72         /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
73         /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
74         ///
75         /// The only instance where update_id values are not strictly increasing is the case where we
76         /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
77         /// its docs for more details.
78         pub update_id: u64,
79 }
80
81 /// If:
82 ///    (1) a channel has been force closed and
83 ///    (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
84 ///        this channel's (the backward link's) broadcasted commitment transaction
85 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
86 /// with the update providing said payment preimage. No other update types are allowed after
87 /// force-close.
88 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
89
90 impl Writeable for ChannelMonitorUpdate {
91         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
92                 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
93                 self.update_id.write(w)?;
94                 (self.updates.len() as u64).write(w)?;
95                 for update_step in self.updates.iter() {
96                         update_step.write(w)?;
97                 }
98                 write_tlv_fields!(w, {});
99                 Ok(())
100         }
101 }
102 impl Readable for ChannelMonitorUpdate {
103         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
104                 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
105                 let update_id: u64 = Readable::read(r)?;
106                 let len: u64 = Readable::read(r)?;
107                 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
108                 for _ in 0..len {
109                         if let Some(upd) = MaybeReadable::read(r)? {
110                                 updates.push(upd);
111                         }
112                 }
113                 read_tlv_fields!(r, {});
114                 Ok(Self { update_id, updates })
115         }
116 }
117
118 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
119 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
120 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
121 /// corrupted.
122 /// Contains a developer-readable error message.
123 #[derive(Clone, Debug)]
124 pub struct MonitorUpdateError(pub &'static str);
125
126 /// An event to be processed by the ChannelManager.
127 #[derive(Clone, PartialEq)]
128 pub enum MonitorEvent {
129         /// A monitor event containing an HTLCUpdate.
130         HTLCEvent(HTLCUpdate),
131
132         /// A monitor event that the Channel's commitment transaction was confirmed.
133         CommitmentTxConfirmed(OutPoint),
134 }
135 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent, ;
136         (2, HTLCEvent),
137         (4, CommitmentTxConfirmed),
138 );
139
140 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
141 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
142 /// preimage claim backward will lead to loss of funds.
143 #[derive(Clone, PartialEq)]
144 pub struct HTLCUpdate {
145         pub(crate) payment_hash: PaymentHash,
146         pub(crate) payment_preimage: Option<PaymentPreimage>,
147         pub(crate) source: HTLCSource,
148         pub(crate) onchain_value_satoshis: Option<u64>,
149 }
150 impl_writeable_tlv_based!(HTLCUpdate, {
151         (0, payment_hash, required),
152         (1, onchain_value_satoshis, option),
153         (2, source, required),
154         (4, payment_preimage, option),
155 });
156
157 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
158 /// instead claiming it in its own individual transaction.
159 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
160 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
161 /// HTLC-Success transaction.
162 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
163 /// transaction confirmed (and we use it in a few more, equivalent, places).
164 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
165 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
166 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
167 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
168 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
169 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
170 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
171 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
172 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
173 /// accurate block height.
174 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
175 /// with at worst this delay, so we are not only using this value as a mercy for them but also
176 /// us as a safeguard to delay with enough time.
177 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
178 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
179 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
180 /// losing money.
181 ///
182 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
183 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
184 /// by a  [`ChannelMonitor`] may be incorrect.
185 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
186 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
187 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
188 // keep bumping another claim tx to solve the outpoint.
189 pub const ANTI_REORG_DELAY: u32 = 6;
190 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
191 /// refuse to accept a new HTLC.
192 ///
193 /// This is used for a few separate purposes:
194 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
195 ///    waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
196 ///    fail this HTLC,
197 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
198 ///    condition with the above), we will fail this HTLC without telling the user we received it,
199 /// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
200 ///    that HTLC expires within this many blocks, we will simply fail the HTLC instead.
201 ///
202 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
203 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
204 ///
205 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
206 /// in a race condition between the user connecting a block (which would fail it) and the user
207 /// providing us the preimage (which would claim it).
208 ///
209 /// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
210 /// end up force-closing the channel on us to claim it.
211 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
212
213 // TODO(devrandom) replace this with HolderCommitmentTransaction
214 #[derive(Clone, PartialEq)]
215 struct HolderSignedTx {
216         /// txid of the transaction in tx, just used to make comparison faster
217         txid: Txid,
218         revocation_key: PublicKey,
219         a_htlc_key: PublicKey,
220         b_htlc_key: PublicKey,
221         delayed_payment_key: PublicKey,
222         per_commitment_point: PublicKey,
223         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
224         to_self_value_sat: u64,
225         feerate_per_kw: u32,
226 }
227 impl_writeable_tlv_based!(HolderSignedTx, {
228         (0, txid, required),
229         // Note that this is filled in with data from OnchainTxHandler if it's missing.
230         // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
231         (1, to_self_value_sat, (default_value, u64::max_value())),
232         (2, revocation_key, required),
233         (4, a_htlc_key, required),
234         (6, b_htlc_key, required),
235         (8, delayed_payment_key, required),
236         (10, per_commitment_point, required),
237         (12, feerate_per_kw, required),
238         (14, htlc_outputs, vec_type)
239 });
240
241 /// We use this to track static counterparty commitment transaction data and to generate any
242 /// justice or 2nd-stage preimage/timeout transactions.
243 #[derive(PartialEq)]
244 struct CounterpartyCommitmentParameters {
245         counterparty_delayed_payment_base_key: PublicKey,
246         counterparty_htlc_base_key: PublicKey,
247         on_counterparty_tx_csv: u16,
248 }
249
250 impl Writeable for CounterpartyCommitmentParameters {
251         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
252                 w.write_all(&byte_utils::be64_to_array(0))?;
253                 write_tlv_fields!(w, {
254                         (0, self.counterparty_delayed_payment_base_key, required),
255                         (2, self.counterparty_htlc_base_key, required),
256                         (4, self.on_counterparty_tx_csv, required),
257                 });
258                 Ok(())
259         }
260 }
261 impl Readable for CounterpartyCommitmentParameters {
262         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
263                 let counterparty_commitment_transaction = {
264                         // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
265                         // used. Read it for compatibility.
266                         let per_htlc_len: u64 = Readable::read(r)?;
267                         for _  in 0..per_htlc_len {
268                                 let _txid: Txid = Readable::read(r)?;
269                                 let htlcs_count: u64 = Readable::read(r)?;
270                                 for _ in 0..htlcs_count {
271                                         let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
272                                 }
273                         }
274
275                         let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
276                         let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
277                         let mut on_counterparty_tx_csv: u16 = 0;
278                         read_tlv_fields!(r, {
279                                 (0, counterparty_delayed_payment_base_key, required),
280                                 (2, counterparty_htlc_base_key, required),
281                                 (4, on_counterparty_tx_csv, required),
282                         });
283                         CounterpartyCommitmentParameters {
284                                 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
285                                 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
286                                 on_counterparty_tx_csv,
287                         }
288                 };
289                 Ok(counterparty_commitment_transaction)
290         }
291 }
292
293 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
294 /// transaction causing it.
295 ///
296 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
297 #[derive(PartialEq)]
298 struct OnchainEventEntry {
299         txid: Txid,
300         height: u32,
301         event: OnchainEvent,
302 }
303
304 impl OnchainEventEntry {
305         fn confirmation_threshold(&self) -> u32 {
306                 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
307                 match self.event {
308                         OnchainEvent::MaturingOutput {
309                                 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
310                         } => {
311                                 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
312                                 // it's broadcastable when we see the previous block.
313                                 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
314                         },
315                         OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
316                         OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
317                                 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
318                                 // it's broadcastable when we see the previous block.
319                                 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
320                         },
321                         _ => {},
322                 }
323                 conf_threshold
324         }
325
326         fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
327                 best_block.height() >= self.confirmation_threshold()
328         }
329 }
330
331 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
332 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
333 #[derive(PartialEq)]
334 enum OnchainEvent {
335         /// An outbound HTLC failing after a transaction is confirmed. Used
336         ///  * when an outbound HTLC output is spent by us after the HTLC timed out
337         ///  * an outbound HTLC which was not present in the commitment transaction which appeared
338         ///    on-chain (either because it was not fully committed to or it was dust).
339         /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
340         /// appearing only as an `HTLCSpendConfirmation`, below.
341         HTLCUpdate {
342                 source: HTLCSource,
343                 payment_hash: PaymentHash,
344                 onchain_value_satoshis: Option<u64>,
345                 /// None in the second case, above, ie when there is no relevant output in the commitment
346                 /// transaction which appeared on chain.
347                 input_idx: Option<u32>,
348         },
349         MaturingOutput {
350                 descriptor: SpendableOutputDescriptor,
351         },
352         /// A spend of the funding output, either a commitment transaction or a cooperative closing
353         /// transaction.
354         FundingSpendConfirmation {
355                 /// The CSV delay for the output of the funding spend transaction (implying it is a local
356                 /// commitment transaction, and this is the delay on the to_self output).
357                 on_local_output_csv: Option<u16>,
358         },
359         /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
360         /// is constructed. This is used when
361         ///  * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
362         ///    immediately claim the HTLC on the inbound edge and track the resolution here,
363         ///  * an inbound HTLC is claimed by our counterparty (with a timeout),
364         ///  * an inbound HTLC is claimed by us (with a preimage).
365         ///  * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
366         ///    signature.
367         HTLCSpendConfirmation {
368                 input_idx: u32,
369                 /// If the claim was made by either party with a preimage, this is filled in
370                 preimage: Option<PaymentPreimage>,
371                 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
372                 /// we set this to the output CSV value which we will have to wait until to spend the
373                 /// output (and generate a SpendableOutput event).
374                 on_to_local_output_csv: Option<u16>,
375         },
376 }
377
378 impl Writeable for OnchainEventEntry {
379         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
380                 write_tlv_fields!(writer, {
381                         (0, self.txid, required),
382                         (2, self.height, required),
383                         (4, self.event, required),
384                 });
385                 Ok(())
386         }
387 }
388
389 impl MaybeReadable for OnchainEventEntry {
390         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
391                 let mut txid = Default::default();
392                 let mut height = 0;
393                 let mut event = None;
394                 read_tlv_fields!(reader, {
395                         (0, txid, required),
396                         (2, height, required),
397                         (4, event, ignorable),
398                 });
399                 if let Some(ev) = event {
400                         Ok(Some(Self { txid, height, event: ev }))
401                 } else {
402                         Ok(None)
403                 }
404         }
405 }
406
407 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
408         (0, HTLCUpdate) => {
409                 (0, source, required),
410                 (1, onchain_value_satoshis, option),
411                 (2, payment_hash, required),
412                 (3, input_idx, option),
413         },
414         (1, MaturingOutput) => {
415                 (0, descriptor, required),
416         },
417         (3, FundingSpendConfirmation) => {
418                 (0, on_local_output_csv, option),
419         },
420         (5, HTLCSpendConfirmation) => {
421                 (0, input_idx, required),
422                 (2, preimage, option),
423                 (4, on_to_local_output_csv, option),
424         },
425
426 );
427
428 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
429 #[derive(Clone)]
430 pub(crate) enum ChannelMonitorUpdateStep {
431         LatestHolderCommitmentTXInfo {
432                 commitment_tx: HolderCommitmentTransaction,
433                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
434         },
435         LatestCounterpartyCommitmentTXInfo {
436                 commitment_txid: Txid,
437                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
438                 commitment_number: u64,
439                 their_revocation_point: PublicKey,
440         },
441         PaymentPreimage {
442                 payment_preimage: PaymentPreimage,
443         },
444         CommitmentSecret {
445                 idx: u64,
446                 secret: [u8; 32],
447         },
448         /// Used to indicate that the no future updates will occur, and likely that the latest holder
449         /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
450         ChannelForceClosed {
451                 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
452                 /// think we've fallen behind!
453                 should_broadcast: bool,
454         },
455         ShutdownScript {
456                 scriptpubkey: Script,
457         },
458 }
459
460 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
461         (0, LatestHolderCommitmentTXInfo) => {
462                 (0, commitment_tx, required),
463                 (2, htlc_outputs, vec_type),
464         },
465         (1, LatestCounterpartyCommitmentTXInfo) => {
466                 (0, commitment_txid, required),
467                 (2, commitment_number, required),
468                 (4, their_revocation_point, required),
469                 (6, htlc_outputs, vec_type),
470         },
471         (2, PaymentPreimage) => {
472                 (0, payment_preimage, required),
473         },
474         (3, CommitmentSecret) => {
475                 (0, idx, required),
476                 (2, secret, required),
477         },
478         (4, ChannelForceClosed) => {
479                 (0, should_broadcast, required),
480         },
481         (5, ShutdownScript) => {
482                 (0, scriptpubkey, required),
483         },
484 );
485
486 /// Details about the balance(s) available for spending once the channel appears on chain.
487 ///
488 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
489 /// be provided.
490 #[derive(Clone, Debug, PartialEq, Eq)]
491 #[cfg_attr(test, derive(PartialOrd, Ord))]
492 pub enum Balance {
493         /// The channel is not yet closed (or the commitment or closing transaction has not yet
494         /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
495         /// force-closed now.
496         ClaimableOnChannelClose {
497                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
498                 /// required to do so.
499                 claimable_amount_satoshis: u64,
500         },
501         /// The channel has been closed, and the given balance is ours but awaiting confirmations until
502         /// we consider it spendable.
503         ClaimableAwaitingConfirmations {
504                 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
505                 /// were spent in broadcasting the transaction.
506                 claimable_amount_satoshis: u64,
507                 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
508                 /// amount.
509                 confirmation_height: u32,
510         },
511         /// The channel has been closed, and the given balance should be ours but awaiting spending
512         /// transaction confirmation. If the spending transaction does not confirm in time, it is
513         /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
514         ///
515         /// Once the spending transaction confirms, before it has reached enough confirmations to be
516         /// considered safe from chain reorganizations, the balance will instead be provided via
517         /// [`Balance::ClaimableAwaitingConfirmations`].
518         ContentiousClaimable {
519                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
520                 /// required to do so.
521                 claimable_amount_satoshis: u64,
522                 /// The height at which the counterparty may be able to claim the balance if we have not
523                 /// done so.
524                 timeout_height: u32,
525         },
526         /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
527         /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
528         /// likely to be claimed by our counterparty before we do.
529         MaybeClaimableHTLCAwaitingTimeout {
530                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
531                 /// required to do so.
532                 claimable_amount_satoshis: u64,
533                 /// The height at which we will be able to claim the balance if our counterparty has not
534                 /// done so.
535                 claimable_height: u32,
536         },
537 }
538
539 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
540 #[derive(PartialEq)]
541 struct IrrevocablyResolvedHTLC {
542         input_idx: u32,
543         /// Only set if the HTLC claim was ours using a payment preimage
544         payment_preimage: Option<PaymentPreimage>,
545 }
546
547 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
548         (0, input_idx, required),
549         (2, payment_preimage, option),
550 });
551
552 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
553 /// on-chain transactions to ensure no loss of funds occurs.
554 ///
555 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
556 /// information and are actively monitoring the chain.
557 ///
558 /// Pending Events or updated HTLCs which have not yet been read out by
559 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
560 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
561 /// gotten are fully handled before re-serializing the new state.
562 ///
563 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
564 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
565 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
566 /// returned block hash and the the current chain and then reconnecting blocks to get to the
567 /// best chain) upon deserializing the object!
568 pub struct ChannelMonitor<Signer: Sign> {
569         #[cfg(test)]
570         pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
571         #[cfg(not(test))]
572         inner: Mutex<ChannelMonitorImpl<Signer>>,
573 }
574
575 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
576         latest_update_id: u64,
577         commitment_transaction_number_obscure_factor: u64,
578
579         destination_script: Script,
580         broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
581         counterparty_payment_script: Script,
582         shutdown_script: Option<Script>,
583
584         channel_keys_id: [u8; 32],
585         holder_revocation_basepoint: PublicKey,
586         funding_info: (OutPoint, Script),
587         current_counterparty_commitment_txid: Option<Txid>,
588         prev_counterparty_commitment_txid: Option<Txid>,
589
590         counterparty_commitment_params: CounterpartyCommitmentParameters,
591         funding_redeemscript: Script,
592         channel_value_satoshis: u64,
593         // first is the idx of the first of the two revocation points
594         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
595
596         on_holder_tx_csv: u16,
597
598         commitment_secrets: CounterpartyCommitmentSecrets,
599         /// The set of outpoints in each counterparty commitment transaction. We always need at least
600         /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
601         /// transaction broadcast as we need to be able to construct the witness script in all cases.
602         counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
603         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
604         /// Nor can we figure out their commitment numbers without the commitment transaction they are
605         /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
606         /// commitment transactions which we find on-chain, mapping them to the commitment number which
607         /// can be used to derive the revocation key and claim the transactions.
608         counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
609         /// Cache used to make pruning of payment_preimages faster.
610         /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
611         /// counterparty transactions (ie should remain pretty small).
612         /// Serialized to disk but should generally not be sent to Watchtowers.
613         counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
614
615         // We store two holder commitment transactions to avoid any race conditions where we may update
616         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
617         // various monitors for one channel being out of sync, and us broadcasting a holder
618         // transaction for which we have deleted claim information on some watchtowers.
619         prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
620         current_holder_commitment_tx: HolderSignedTx,
621
622         // Used just for ChannelManager to make sure it has the latest channel data during
623         // deserialization
624         current_counterparty_commitment_number: u64,
625         // Used just for ChannelManager to make sure it has the latest channel data during
626         // deserialization
627         current_holder_commitment_number: u64,
628
629         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
630
631         pending_monitor_events: Vec<MonitorEvent>,
632         pending_events: Vec<Event>,
633
634         // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
635         // which to take actions once they reach enough confirmations. Each entry includes the
636         // transaction's id and the height when the transaction was confirmed on chain.
637         onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
638
639         // If we get serialized out and re-read, we need to make sure that the chain monitoring
640         // interface knows about the TXOs that we want to be notified of spends of. We could probably
641         // be smart and derive them from the above storage fields, but its much simpler and more
642         // Obviously Correct (tm) if we just keep track of them explicitly.
643         outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
644
645         #[cfg(test)]
646         pub onchain_tx_handler: OnchainTxHandler<Signer>,
647         #[cfg(not(test))]
648         onchain_tx_handler: OnchainTxHandler<Signer>,
649
650         // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
651         // channel has been force-closed. After this is set, no further holder commitment transaction
652         // updates may occur, and we panic!() if one is provided.
653         lockdown_from_offchain: bool,
654
655         // Set once we've signed a holder commitment transaction and handed it over to our
656         // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
657         // may occur, and we fail any such monitor updates.
658         //
659         // In case of update rejection due to a locally already signed commitment transaction, we
660         // nevertheless store update content to track in case of concurrent broadcast by another
661         // remote monitor out-of-order with regards to the block view.
662         holder_tx_signed: bool,
663
664         funding_spend_confirmed: Option<Txid>,
665         /// The set of HTLCs which have been either claimed or failed on chain and have reached
666         /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
667         /// spending CSV for revocable outputs).
668         htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
669
670         // We simply modify best_block in Channel's block_connected so that serialization is
671         // consistent but hopefully the users' copy handles block_connected in a consistent way.
672         // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
673         // their best_block from its state and not based on updated copies that didn't run through
674         // the full block_connected).
675         best_block: BestBlock,
676
677         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
678 }
679
680 /// Transaction outputs to watch for on-chain spends.
681 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
682
683 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
684 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
685 /// underlying object
686 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
687         fn eq(&self, other: &Self) -> bool {
688                 let inner = self.inner.lock().unwrap();
689                 let other = other.inner.lock().unwrap();
690                 inner.eq(&other)
691         }
692 }
693
694 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
695 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
696 /// underlying object
697 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
698         fn eq(&self, other: &Self) -> bool {
699                 if self.latest_update_id != other.latest_update_id ||
700                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
701                         self.destination_script != other.destination_script ||
702                         self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
703                         self.counterparty_payment_script != other.counterparty_payment_script ||
704                         self.channel_keys_id != other.channel_keys_id ||
705                         self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
706                         self.funding_info != other.funding_info ||
707                         self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
708                         self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
709                         self.counterparty_commitment_params != other.counterparty_commitment_params ||
710                         self.funding_redeemscript != other.funding_redeemscript ||
711                         self.channel_value_satoshis != other.channel_value_satoshis ||
712                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
713                         self.on_holder_tx_csv != other.on_holder_tx_csv ||
714                         self.commitment_secrets != other.commitment_secrets ||
715                         self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
716                         self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
717                         self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
718                         self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
719                         self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
720                         self.current_holder_commitment_number != other.current_holder_commitment_number ||
721                         self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
722                         self.payment_preimages != other.payment_preimages ||
723                         self.pending_monitor_events != other.pending_monitor_events ||
724                         self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
725                         self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
726                         self.outputs_to_watch != other.outputs_to_watch ||
727                         self.lockdown_from_offchain != other.lockdown_from_offchain ||
728                         self.holder_tx_signed != other.holder_tx_signed ||
729                         self.funding_spend_confirmed != other.funding_spend_confirmed ||
730                         self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
731                 {
732                         false
733                 } else {
734                         true
735                 }
736         }
737 }
738
739 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
740         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
741                 self.inner.lock().unwrap().write(writer)
742         }
743 }
744
745 // These are also used for ChannelMonitorUpdate, above.
746 const SERIALIZATION_VERSION: u8 = 1;
747 const MIN_SERIALIZATION_VERSION: u8 = 1;
748
749 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
750         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
751                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
752
753                 self.latest_update_id.write(writer)?;
754
755                 // Set in initial Channel-object creation, so should always be set by now:
756                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
757
758                 self.destination_script.write(writer)?;
759                 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
760                         writer.write_all(&[0; 1])?;
761                         broadcasted_holder_revokable_script.0.write(writer)?;
762                         broadcasted_holder_revokable_script.1.write(writer)?;
763                         broadcasted_holder_revokable_script.2.write(writer)?;
764                 } else {
765                         writer.write_all(&[1; 1])?;
766                 }
767
768                 self.counterparty_payment_script.write(writer)?;
769                 match &self.shutdown_script {
770                         Some(script) => script.write(writer)?,
771                         None => Script::new().write(writer)?,
772                 }
773
774                 self.channel_keys_id.write(writer)?;
775                 self.holder_revocation_basepoint.write(writer)?;
776                 writer.write_all(&self.funding_info.0.txid[..])?;
777                 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
778                 self.funding_info.1.write(writer)?;
779                 self.current_counterparty_commitment_txid.write(writer)?;
780                 self.prev_counterparty_commitment_txid.write(writer)?;
781
782                 self.counterparty_commitment_params.write(writer)?;
783                 self.funding_redeemscript.write(writer)?;
784                 self.channel_value_satoshis.write(writer)?;
785
786                 match self.their_cur_revocation_points {
787                         Some((idx, pubkey, second_option)) => {
788                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
789                                 writer.write_all(&pubkey.serialize())?;
790                                 match second_option {
791                                         Some(second_pubkey) => {
792                                                 writer.write_all(&second_pubkey.serialize())?;
793                                         },
794                                         None => {
795                                                 writer.write_all(&[0; 33])?;
796                                         },
797                                 }
798                         },
799                         None => {
800                                 writer.write_all(&byte_utils::be48_to_array(0))?;
801                         },
802                 }
803
804                 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
805
806                 self.commitment_secrets.write(writer)?;
807
808                 macro_rules! serialize_htlc_in_commitment {
809                         ($htlc_output: expr) => {
810                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
811                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
812                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
813                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
814                                 $htlc_output.transaction_output_index.write(writer)?;
815                         }
816                 }
817
818                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
819                 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
820                         writer.write_all(&txid[..])?;
821                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
822                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
823                                 serialize_htlc_in_commitment!(htlc_output);
824                                 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
825                         }
826                 }
827
828                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
829                 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
830                         writer.write_all(&txid[..])?;
831                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
832                 }
833
834                 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
835                 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
836                         writer.write_all(&payment_hash.0[..])?;
837                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
838                 }
839
840                 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
841                         writer.write_all(&[1; 1])?;
842                         prev_holder_tx.write(writer)?;
843                 } else {
844                         writer.write_all(&[0; 1])?;
845                 }
846
847                 self.current_holder_commitment_tx.write(writer)?;
848
849                 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
850                 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
851
852                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
853                 for payment_preimage in self.payment_preimages.values() {
854                         writer.write_all(&payment_preimage.0[..])?;
855                 }
856
857                 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
858                 for event in self.pending_monitor_events.iter() {
859                         match event {
860                                 MonitorEvent::HTLCEvent(upd) => {
861                                         0u8.write(writer)?;
862                                         upd.write(writer)?;
863                                 },
864                                 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?
865                         }
866                 }
867
868                 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
869                 for event in self.pending_events.iter() {
870                         event.write(writer)?;
871                 }
872
873                 self.best_block.block_hash().write(writer)?;
874                 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
875
876                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
877                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
878                         entry.write(writer)?;
879                 }
880
881                 (self.outputs_to_watch.len() as u64).write(writer)?;
882                 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
883                         txid.write(writer)?;
884                         (idx_scripts.len() as u64).write(writer)?;
885                         for (idx, script) in idx_scripts.iter() {
886                                 idx.write(writer)?;
887                                 script.write(writer)?;
888                         }
889                 }
890                 self.onchain_tx_handler.write(writer)?;
891
892                 self.lockdown_from_offchain.write(writer)?;
893                 self.holder_tx_signed.write(writer)?;
894
895                 write_tlv_fields!(writer, {
896                         (1, self.funding_spend_confirmed, option),
897                         (3, self.htlcs_resolved_on_chain, vec_type),
898                         (5, self.pending_monitor_events, vec_type),
899                 });
900
901                 Ok(())
902         }
903 }
904
905 impl<Signer: Sign> ChannelMonitor<Signer> {
906         pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
907                           on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
908                           channel_parameters: &ChannelTransactionParameters,
909                           funding_redeemscript: Script, channel_value_satoshis: u64,
910                           commitment_transaction_number_obscure_factor: u64,
911                           initial_holder_commitment_tx: HolderCommitmentTransaction,
912                           best_block: BestBlock) -> ChannelMonitor<Signer> {
913
914                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
915                 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
916                 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
917
918                 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
919                 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
920                 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
921                 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
922
923                 let channel_keys_id = keys.channel_keys_id();
924                 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
925
926                 // block for Rust 1.34 compat
927                 let (holder_commitment_tx, current_holder_commitment_number) = {
928                         let trusted_tx = initial_holder_commitment_tx.trust();
929                         let txid = trusted_tx.txid();
930
931                         let tx_keys = trusted_tx.keys();
932                         let holder_commitment_tx = HolderSignedTx {
933                                 txid,
934                                 revocation_key: tx_keys.revocation_key,
935                                 a_htlc_key: tx_keys.broadcaster_htlc_key,
936                                 b_htlc_key: tx_keys.countersignatory_htlc_key,
937                                 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
938                                 per_commitment_point: tx_keys.per_commitment_point,
939                                 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
940                                 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
941                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
942                         };
943                         (holder_commitment_tx, trusted_tx.commitment_number())
944                 };
945
946                 let onchain_tx_handler =
947                         OnchainTxHandler::new(destination_script.clone(), keys,
948                         channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
949
950                 let mut outputs_to_watch = HashMap::new();
951                 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
952
953                 ChannelMonitor {
954                         inner: Mutex::new(ChannelMonitorImpl {
955                                 latest_update_id: 0,
956                                 commitment_transaction_number_obscure_factor,
957
958                                 destination_script: destination_script.clone(),
959                                 broadcasted_holder_revokable_script: None,
960                                 counterparty_payment_script,
961                                 shutdown_script,
962
963                                 channel_keys_id,
964                                 holder_revocation_basepoint,
965                                 funding_info,
966                                 current_counterparty_commitment_txid: None,
967                                 prev_counterparty_commitment_txid: None,
968
969                                 counterparty_commitment_params,
970                                 funding_redeemscript,
971                                 channel_value_satoshis,
972                                 their_cur_revocation_points: None,
973
974                                 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
975
976                                 commitment_secrets: CounterpartyCommitmentSecrets::new(),
977                                 counterparty_claimable_outpoints: HashMap::new(),
978                                 counterparty_commitment_txn_on_chain: HashMap::new(),
979                                 counterparty_hash_commitment_number: HashMap::new(),
980
981                                 prev_holder_signed_commitment_tx: None,
982                                 current_holder_commitment_tx: holder_commitment_tx,
983                                 current_counterparty_commitment_number: 1 << 48,
984                                 current_holder_commitment_number,
985
986                                 payment_preimages: HashMap::new(),
987                                 pending_monitor_events: Vec::new(),
988                                 pending_events: Vec::new(),
989
990                                 onchain_events_awaiting_threshold_conf: Vec::new(),
991                                 outputs_to_watch,
992
993                                 onchain_tx_handler,
994
995                                 lockdown_from_offchain: false,
996                                 holder_tx_signed: false,
997                                 funding_spend_confirmed: None,
998                                 htlcs_resolved_on_chain: Vec::new(),
999
1000                                 best_block,
1001
1002                                 secp_ctx,
1003                         }),
1004                 }
1005         }
1006
1007         #[cfg(test)]
1008         fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1009                 self.inner.lock().unwrap().provide_secret(idx, secret)
1010         }
1011
1012         /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1013         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1014         /// possibly future revocation/preimage information) to claim outputs where possible.
1015         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1016         pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1017                 &self,
1018                 txid: Txid,
1019                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1020                 commitment_number: u64,
1021                 their_revocation_point: PublicKey,
1022                 logger: &L,
1023         ) where L::Target: Logger {
1024                 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1025                         txid, htlc_outputs, commitment_number, their_revocation_point, logger)
1026         }
1027
1028         #[cfg(test)]
1029         fn provide_latest_holder_commitment_tx(
1030                 &self,
1031                 holder_commitment_tx: HolderCommitmentTransaction,
1032                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1033         ) -> Result<(), MonitorUpdateError> {
1034                 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
1035                         holder_commitment_tx, htlc_outputs)
1036         }
1037
1038         #[cfg(test)]
1039         pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1040                 &self,
1041                 payment_hash: &PaymentHash,
1042                 payment_preimage: &PaymentPreimage,
1043                 broadcaster: &B,
1044                 fee_estimator: &F,
1045                 logger: &L,
1046         ) where
1047                 B::Target: BroadcasterInterface,
1048                 F::Target: FeeEstimator,
1049                 L::Target: Logger,
1050         {
1051                 self.inner.lock().unwrap().provide_payment_preimage(
1052                         payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1053         }
1054
1055         pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1056                 &self,
1057                 broadcaster: &B,
1058                 logger: &L,
1059         ) where
1060                 B::Target: BroadcasterInterface,
1061                 L::Target: Logger,
1062         {
1063                 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1064         }
1065
1066         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1067         /// itself.
1068         ///
1069         /// panics if the given update is not the next update by update_id.
1070         pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1071                 &self,
1072                 updates: &ChannelMonitorUpdate,
1073                 broadcaster: &B,
1074                 fee_estimator: &F,
1075                 logger: &L,
1076         ) -> Result<(), MonitorUpdateError>
1077         where
1078                 B::Target: BroadcasterInterface,
1079                 F::Target: FeeEstimator,
1080                 L::Target: Logger,
1081         {
1082                 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1083         }
1084
1085         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1086         /// ChannelMonitor.
1087         pub fn get_latest_update_id(&self) -> u64 {
1088                 self.inner.lock().unwrap().get_latest_update_id()
1089         }
1090
1091         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1092         pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1093                 self.inner.lock().unwrap().get_funding_txo().clone()
1094         }
1095
1096         /// Gets a list of txids, with their output scripts (in the order they appear in the
1097         /// transaction), which we must learn about spends of via block_connected().
1098         pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1099                 self.inner.lock().unwrap().get_outputs_to_watch()
1100                         .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1101         }
1102
1103         /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1104         /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1105         /// have been registered.
1106         pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1107                 let lock = self.inner.lock().unwrap();
1108                 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1109                 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1110                         for (index, script_pubkey) in outputs.iter() {
1111                                 assert!(*index <= u16::max_value() as u32);
1112                                 filter.register_output(WatchedOutput {
1113                                         block_hash: None,
1114                                         outpoint: OutPoint { txid: *txid, index: *index as u16 },
1115                                         script_pubkey: script_pubkey.clone(),
1116                                 });
1117                         }
1118                 }
1119         }
1120
1121         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1122         /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1123         pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1124                 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1125         }
1126
1127         /// Gets the list of pending events which were generated by previous actions, clearing the list
1128         /// in the process.
1129         ///
1130         /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1131         /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1132         /// no internal locking in ChannelMonitors.
1133         pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1134                 self.inner.lock().unwrap().get_and_clear_pending_events()
1135         }
1136
1137         pub(crate) fn get_min_seen_secret(&self) -> u64 {
1138                 self.inner.lock().unwrap().get_min_seen_secret()
1139         }
1140
1141         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1142                 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1143         }
1144
1145         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1146                 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1147         }
1148
1149         /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1150         /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1151         /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1152         /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1153         /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1154         /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1155         /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1156         /// out-of-band the other node operator to coordinate with him if option is available to you.
1157         /// In any-case, choice is up to the user.
1158         pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1159         where L::Target: Logger {
1160                 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1161         }
1162
1163         /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1164         /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1165         /// revoked commitment transaction.
1166         #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1167         pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1168         where L::Target: Logger {
1169                 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1170         }
1171
1172         /// Processes transactions in a newly connected block, which may result in any of the following:
1173         /// - update the monitor's state against resolved HTLCs
1174         /// - punish the counterparty in the case of seeing a revoked commitment transaction
1175         /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1176         /// - detect settled outputs for later spending
1177         /// - schedule and bump any in-flight claims
1178         ///
1179         /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1180         /// [`get_outputs_to_watch`].
1181         ///
1182         /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1183         pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1184                 &self,
1185                 header: &BlockHeader,
1186                 txdata: &TransactionData,
1187                 height: u32,
1188                 broadcaster: B,
1189                 fee_estimator: F,
1190                 logger: L,
1191         ) -> Vec<TransactionOutputs>
1192         where
1193                 B::Target: BroadcasterInterface,
1194                 F::Target: FeeEstimator,
1195                 L::Target: Logger,
1196         {
1197                 self.inner.lock().unwrap().block_connected(
1198                         header, txdata, height, broadcaster, fee_estimator, logger)
1199         }
1200
1201         /// Determines if the disconnected block contained any transactions of interest and updates
1202         /// appropriately.
1203         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1204                 &self,
1205                 header: &BlockHeader,
1206                 height: u32,
1207                 broadcaster: B,
1208                 fee_estimator: F,
1209                 logger: L,
1210         ) where
1211                 B::Target: BroadcasterInterface,
1212                 F::Target: FeeEstimator,
1213                 L::Target: Logger,
1214         {
1215                 self.inner.lock().unwrap().block_disconnected(
1216                         header, height, broadcaster, fee_estimator, logger)
1217         }
1218
1219         /// Processes transactions confirmed in a block with the given header and height, returning new
1220         /// outputs to watch. See [`block_connected`] for details.
1221         ///
1222         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1223         /// blocks. See [`chain::Confirm`] for calling expectations.
1224         ///
1225         /// [`block_connected`]: Self::block_connected
1226         pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1227                 &self,
1228                 header: &BlockHeader,
1229                 txdata: &TransactionData,
1230                 height: u32,
1231                 broadcaster: B,
1232                 fee_estimator: F,
1233                 logger: L,
1234         ) -> Vec<TransactionOutputs>
1235         where
1236                 B::Target: BroadcasterInterface,
1237                 F::Target: FeeEstimator,
1238                 L::Target: Logger,
1239         {
1240                 self.inner.lock().unwrap().transactions_confirmed(
1241                         header, txdata, height, broadcaster, fee_estimator, logger)
1242         }
1243
1244         /// Processes a transaction that was reorganized out of the chain.
1245         ///
1246         /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1247         /// than blocks. See [`chain::Confirm`] for calling expectations.
1248         ///
1249         /// [`block_disconnected`]: Self::block_disconnected
1250         pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1251                 &self,
1252                 txid: &Txid,
1253                 broadcaster: B,
1254                 fee_estimator: F,
1255                 logger: L,
1256         ) where
1257                 B::Target: BroadcasterInterface,
1258                 F::Target: FeeEstimator,
1259                 L::Target: Logger,
1260         {
1261                 self.inner.lock().unwrap().transaction_unconfirmed(
1262                         txid, broadcaster, fee_estimator, logger);
1263         }
1264
1265         /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1266         /// [`block_connected`] for details.
1267         ///
1268         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1269         /// blocks. See [`chain::Confirm`] for calling expectations.
1270         ///
1271         /// [`block_connected`]: Self::block_connected
1272         pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1273                 &self,
1274                 header: &BlockHeader,
1275                 height: u32,
1276                 broadcaster: B,
1277                 fee_estimator: F,
1278                 logger: L,
1279         ) -> Vec<TransactionOutputs>
1280         where
1281                 B::Target: BroadcasterInterface,
1282                 F::Target: FeeEstimator,
1283                 L::Target: Logger,
1284         {
1285                 self.inner.lock().unwrap().best_block_updated(
1286                         header, height, broadcaster, fee_estimator, logger)
1287         }
1288
1289         /// Returns the set of txids that should be monitored for re-organization out of the chain.
1290         pub fn get_relevant_txids(&self) -> Vec<Txid> {
1291                 let inner = self.inner.lock().unwrap();
1292                 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1293                         .iter()
1294                         .map(|entry| entry.txid)
1295                         .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1296                         .collect();
1297                 txids.sort_unstable();
1298                 txids.dedup();
1299                 txids
1300         }
1301
1302         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1303         /// [`chain::Confirm`] interfaces.
1304         pub fn current_best_block(&self) -> BestBlock {
1305                 self.inner.lock().unwrap().best_block.clone()
1306         }
1307
1308         /// Gets the balances in this channel which are either claimable by us if we were to
1309         /// force-close the channel now or which are claimable on-chain (possibly awaiting
1310         /// confirmation).
1311         ///
1312         /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1313         /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1314         /// balance, or until our counterparty has claimed the balance and accrued several
1315         /// confirmations on the claim transaction.
1316         ///
1317         /// Note that the balances available when you or your counterparty have broadcasted revoked
1318         /// state(s) may not be fully captured here.
1319         // TODO, fix that ^
1320         ///
1321         /// See [`Balance`] for additional details on the types of claimable balances which
1322         /// may be returned here and their meanings.
1323         pub fn get_claimable_balances(&self) -> Vec<Balance> {
1324                 let mut res = Vec::new();
1325                 let us = self.inner.lock().unwrap();
1326
1327                 let mut confirmed_txid = us.funding_spend_confirmed;
1328                 let mut pending_commitment_tx_conf_thresh = None;
1329                 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1330                         if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1331                                 Some((event.txid, event.confirmation_threshold()))
1332                         } else { None }
1333                 });
1334                 if let Some((txid, conf_thresh)) = funding_spend_pending {
1335                         debug_assert!(us.funding_spend_confirmed.is_none(),
1336                                 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1337                         confirmed_txid = Some(txid);
1338                         pending_commitment_tx_conf_thresh = Some(conf_thresh);
1339                 }
1340
1341                 macro_rules! walk_htlcs {
1342                         ($holder_commitment: expr, $htlc_iter: expr) => {
1343                                 for htlc in $htlc_iter {
1344                                         if let Some(htlc_input_idx) = htlc.transaction_output_index {
1345                                                 if us.htlcs_resolved_on_chain.iter().any(|v| v.input_idx == htlc_input_idx) {
1346                                                         assert!(us.funding_spend_confirmed.is_some());
1347                                                 } else if htlc.offered == $holder_commitment {
1348                                                         // If the payment was outbound, check if there's an HTLCUpdate
1349                                                         // indicating we have spent this HTLC with a timeout, claiming it back
1350                                                         // and awaiting confirmations on it.
1351                                                         let htlc_update_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1352                                                                 if let OnchainEvent::HTLCUpdate { input_idx: Some(input_idx), .. } = event.event {
1353                                                                         if input_idx == htlc_input_idx { Some(event.confirmation_threshold()) } else { None }
1354                                                                 } else { None }
1355                                                         });
1356                                                         if let Some(conf_thresh) = htlc_update_pending {
1357                                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1358                                                                         claimable_amount_satoshis: htlc.amount_msat / 1000,
1359                                                                         confirmation_height: conf_thresh,
1360                                                                 });
1361                                                         } else {
1362                                                                 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1363                                                                         claimable_amount_satoshis: htlc.amount_msat / 1000,
1364                                                                         claimable_height: htlc.cltv_expiry,
1365                                                                 });
1366                                                         }
1367                                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1368                                                         // Otherwise (the payment was inbound), only expose it as claimable if
1369                                                         // we know the preimage.
1370                                                         // Note that if there is a pending claim, but it did not use the
1371                                                         // preimage, we lost funds to our counterparty! We will then continue
1372                                                         // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1373                                                         let htlc_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1374                                                                 if let OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } = event.event {
1375                                                                         if input_idx == htlc_input_idx {
1376                                                                                 Some((event.confirmation_threshold(), preimage.is_some()))
1377                                                                         } else { None }
1378                                                                 } else { None }
1379                                                         });
1380                                                         if let Some((conf_thresh, true)) = htlc_spend_pending {
1381                                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1382                                                                         claimable_amount_satoshis: htlc.amount_msat / 1000,
1383                                                                         confirmation_height: conf_thresh,
1384                                                                 });
1385                                                         } else {
1386                                                                 res.push(Balance::ContentiousClaimable {
1387                                                                         claimable_amount_satoshis: htlc.amount_msat / 1000,
1388                                                                         timeout_height: htlc.cltv_expiry,
1389                                                                 });
1390                                                         }
1391                                                 }
1392                                         }
1393                                 }
1394                         }
1395                 }
1396
1397                 if let Some(txid) = confirmed_txid {
1398                         let mut found_commitment_tx = false;
1399                         if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1400                                 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1401                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1402                                         if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1403                                                 if let OnchainEvent::MaturingOutput {
1404                                                         descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1405                                                 } = &event.event {
1406                                                         Some(descriptor.output.value)
1407                                                 } else { None }
1408                                         }) {
1409                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1410                                                         claimable_amount_satoshis: value,
1411                                                         confirmation_height: conf_thresh,
1412                                                 });
1413                                         } else {
1414                                                 // If a counterparty commitment transaction is awaiting confirmation, we
1415                                                 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1416                                                 // confirmation with the same height or have never met our dust amount.
1417                                         }
1418                                 }
1419                                 found_commitment_tx = true;
1420                         } else if txid == us.current_holder_commitment_tx.txid {
1421                                 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1422                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1423                                         res.push(Balance::ClaimableAwaitingConfirmations {
1424                                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1425                                                 confirmation_height: conf_thresh,
1426                                         });
1427                                 }
1428                                 found_commitment_tx = true;
1429                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1430                                 if txid == prev_commitment.txid {
1431                                         walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1432                                         if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1433                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1434                                                         claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1435                                                         confirmation_height: conf_thresh,
1436                                                 });
1437                                         }
1438                                         found_commitment_tx = true;
1439                                 }
1440                         }
1441                         if !found_commitment_tx {
1442                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1443                                         // We blindly assume this is a cooperative close transaction here, and that
1444                                         // neither us nor our counterparty misbehaved. At worst we've under-estimated
1445                                         // the amount we can claim as we'll punish a misbehaving counterparty.
1446                                         res.push(Balance::ClaimableAwaitingConfirmations {
1447                                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1448                                                 confirmation_height: conf_thresh,
1449                                         });
1450                                 }
1451                         }
1452                         // TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1453                         // outputs.
1454                 } else {
1455                         let mut claimable_inbound_htlc_value_sat = 0;
1456                         for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1457                                 if htlc.transaction_output_index.is_none() { continue; }
1458                                 if htlc.offered {
1459                                         res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1460                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1461                                                 claimable_height: htlc.cltv_expiry,
1462                                         });
1463                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1464                                         claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1465                                 }
1466                         }
1467                         res.push(Balance::ClaimableOnChannelClose {
1468                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1469                         });
1470                 }
1471
1472                 res
1473         }
1474 }
1475
1476 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1477 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1478 /// after ANTI_REORG_DELAY blocks.
1479 ///
1480 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1481 /// are the commitment transactions which are generated by us. The off-chain state machine in
1482 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1483 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1484 /// included in a remote commitment transaction are failed back if they are not present in the
1485 /// broadcasted commitment transaction.
1486 ///
1487 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1488 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1489 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1490 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1491 macro_rules! fail_unbroadcast_htlcs {
1492         ($self: expr, $commitment_tx_type: expr, $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1493                 macro_rules! check_htlc_fails {
1494                         ($txid: expr, $commitment_tx: expr) => {
1495                                 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1496                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1497                                                 if let &Some(ref source) = source_option {
1498                                                         // Check if the HTLC is present in the commitment transaction that was
1499                                                         // broadcast, but not if it was below the dust limit, which we should
1500                                                         // fail backwards immediately as there is no way for us to learn the
1501                                                         // payment_preimage.
1502                                                         // Note that if the dust limit were allowed to change between
1503                                                         // commitment transactions we'd want to be check whether *any*
1504                                                         // broadcastable commitment transaction has the HTLC in it, but it
1505                                                         // cannot currently change after channel initialization, so we don't
1506                                                         // need to here.
1507                                                         let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1508                                                         let mut matched_htlc = false;
1509                                                         for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1510                                                                 if broadcast_htlc.transaction_output_index.is_some() && Some(&**source) == *broadcast_source {
1511                                                                         matched_htlc = true;
1512                                                                         break;
1513                                                                 }
1514                                                         }
1515                                                         if matched_htlc { continue; }
1516                                                         $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1517                                                                 if entry.height != $commitment_tx_conf_height { return true; }
1518                                                                 match entry.event {
1519                                                                         OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1520                                                                                 *update_source != **source
1521                                                                         },
1522                                                                         _ => true,
1523                                                                 }
1524                                                         });
1525                                                         let entry = OnchainEventEntry {
1526                                                                 txid: *$txid,
1527                                                                 height: $commitment_tx_conf_height,
1528                                                                 event: OnchainEvent::HTLCUpdate {
1529                                                                         source: (**source).clone(),
1530                                                                         payment_hash: htlc.payment_hash.clone(),
1531                                                                         onchain_value_satoshis: Some(htlc.amount_msat / 1000),
1532                                                                         input_idx: None,
1533                                                                 },
1534                                                         };
1535                                                         log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction, waiting for confirmation (at height {})",
1536                                                                 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type, entry.confirmation_threshold());
1537                                                         $self.onchain_events_awaiting_threshold_conf.push(entry);
1538                                                 }
1539                                         }
1540                                 }
1541                         }
1542                 }
1543                 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1544                         check_htlc_fails!(txid, "current");
1545                 }
1546                 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1547                         check_htlc_fails!(txid, "previous");
1548                 }
1549         } }
1550 }
1551
1552 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1553         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1554         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1555         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1556         fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1557                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1558                         return Err(MonitorUpdateError("Previous secret did not match new one"));
1559                 }
1560
1561                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1562                 // events for now-revoked/fulfilled HTLCs.
1563                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1564                         for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1565                                 *source = None;
1566                         }
1567                 }
1568
1569                 if !self.payment_preimages.is_empty() {
1570                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1571                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1572                         let min_idx = self.get_min_seen_secret();
1573                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1574
1575                         self.payment_preimages.retain(|&k, _| {
1576                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1577                                         if k == htlc.payment_hash {
1578                                                 return true
1579                                         }
1580                                 }
1581                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1582                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1583                                                 if k == htlc.payment_hash {
1584                                                         return true
1585                                                 }
1586                                         }
1587                                 }
1588                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1589                                         if *cn < min_idx {
1590                                                 return true
1591                                         }
1592                                         true
1593                                 } else { false };
1594                                 if contains {
1595                                         counterparty_hash_commitment_number.remove(&k);
1596                                 }
1597                                 false
1598                         });
1599                 }
1600
1601                 Ok(())
1602         }
1603
1604         pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
1605                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1606                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1607                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1608                 // timeouts)
1609                 for &(ref htlc, _) in &htlc_outputs {
1610                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1611                 }
1612
1613                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1614                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1615                 self.current_counterparty_commitment_txid = Some(txid);
1616                 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1617                 self.current_counterparty_commitment_number = commitment_number;
1618                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1619                 match self.their_cur_revocation_points {
1620                         Some(old_points) => {
1621                                 if old_points.0 == commitment_number + 1 {
1622                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1623                                 } else if old_points.0 == commitment_number + 2 {
1624                                         if let Some(old_second_point) = old_points.2 {
1625                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1626                                         } else {
1627                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1628                                         }
1629                                 } else {
1630                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1631                                 }
1632                         },
1633                         None => {
1634                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1635                         }
1636                 }
1637                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1638                 for htlc in htlc_outputs {
1639                         if htlc.0.transaction_output_index.is_some() {
1640                                 htlcs.push(htlc.0);
1641                         }
1642                 }
1643         }
1644
1645         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1646         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1647         /// is important that any clones of this channel monitor (including remote clones) by kept
1648         /// up-to-date as our holder commitment transaction is updated.
1649         /// Panics if set_on_holder_tx_csv has never been called.
1650         fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1651                 // block for Rust 1.34 compat
1652                 let mut new_holder_commitment_tx = {
1653                         let trusted_tx = holder_commitment_tx.trust();
1654                         let txid = trusted_tx.txid();
1655                         let tx_keys = trusted_tx.keys();
1656                         self.current_holder_commitment_number = trusted_tx.commitment_number();
1657                         HolderSignedTx {
1658                                 txid,
1659                                 revocation_key: tx_keys.revocation_key,
1660                                 a_htlc_key: tx_keys.broadcaster_htlc_key,
1661                                 b_htlc_key: tx_keys.countersignatory_htlc_key,
1662                                 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1663                                 per_commitment_point: tx_keys.per_commitment_point,
1664                                 htlc_outputs,
1665                                 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1666                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
1667                         }
1668                 };
1669                 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1670                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1671                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1672                 if self.holder_tx_signed {
1673                         return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1674                 }
1675                 Ok(())
1676         }
1677
1678         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1679         /// commitment_tx_infos which contain the payment hash have been revoked.
1680         fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &F, logger: &L)
1681         where B::Target: BroadcasterInterface,
1682                     F::Target: FeeEstimator,
1683                     L::Target: Logger,
1684         {
1685                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1686
1687                 // If the channel is force closed, try to claim the output from this preimage.
1688                 // First check if a counterparty commitment transaction has been broadcasted:
1689                 macro_rules! claim_htlcs {
1690                         ($commitment_number: expr, $txid: expr) => {
1691                                 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1692                                 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1693                         }
1694                 }
1695                 if let Some(txid) = self.current_counterparty_commitment_txid {
1696                         if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1697                                 claim_htlcs!(*commitment_number, txid);
1698                                 return;
1699                         }
1700                 }
1701                 if let Some(txid) = self.prev_counterparty_commitment_txid {
1702                         if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1703                                 claim_htlcs!(*commitment_number, txid);
1704                                 return;
1705                         }
1706                 }
1707
1708                 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1709                 // claiming the HTLC output from each of the holder commitment transactions.
1710                 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1711                 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1712                 // holder commitment transactions.
1713                 if self.broadcasted_holder_revokable_script.is_some() {
1714                         // Assume that the broadcasted commitment transaction confirmed in the current best
1715                         // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1716                         // transactions.
1717                         let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1718                         self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1719                         if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1720                                 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1721                                 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1722                         }
1723                 }
1724         }
1725
1726         pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1727                 where B::Target: BroadcasterInterface,
1728                                         L::Target: Logger,
1729         {
1730                 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1731                         log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1732                         broadcaster.broadcast_transaction(tx);
1733                 }
1734                 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
1735         }
1736
1737         pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
1738         where B::Target: BroadcasterInterface,
1739                     F::Target: FeeEstimator,
1740                     L::Target: Logger,
1741         {
1742                 // ChannelMonitor updates may be applied after force close if we receive a
1743                 // preimage for a broadcasted commitment transaction HTLC output that we'd
1744                 // like to claim on-chain. If this is the case, we no longer have guaranteed
1745                 // access to the monitor's update ID, so we use a sentinel value instead.
1746                 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1747                         match updates.updates[0] {
1748                                 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1749                                 _ => panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage"),
1750                         }
1751                         assert_eq!(updates.updates.len(), 1);
1752                 } else if self.latest_update_id + 1 != updates.update_id {
1753                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1754                 }
1755                 for update in updates.updates.iter() {
1756                         match update {
1757                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1758                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1759                                         if self.lockdown_from_offchain { panic!(); }
1760                                         self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
1761                                 }
1762                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1763                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1764                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1765                                 },
1766                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1767                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1768                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1769                                 },
1770                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1771                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1772                                         self.provide_secret(*idx, *secret)?
1773                                 },
1774                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1775                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1776                                         self.lockdown_from_offchain = true;
1777                                         if *should_broadcast {
1778                                                 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1779                                         } else if !self.holder_tx_signed {
1780                                                 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");
1781                                         } else {
1782                                                 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
1783                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1784                                                 // shouldn't print the scary warning above.
1785                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1786                                         }
1787                                 },
1788                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
1789                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
1790                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
1791                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
1792                                         }
1793                                 },
1794                         }
1795                 }
1796                 self.latest_update_id = updates.update_id;
1797                 Ok(())
1798         }
1799
1800         pub fn get_latest_update_id(&self) -> u64 {
1801                 self.latest_update_id
1802         }
1803
1804         pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1805                 &self.funding_info
1806         }
1807
1808         pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1809                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1810                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1811                 // its trivial to do, double-check that here.
1812                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1813                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1814                 }
1815                 &self.outputs_to_watch
1816         }
1817
1818         pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1819                 let mut ret = Vec::new();
1820                 mem::swap(&mut ret, &mut self.pending_monitor_events);
1821                 ret
1822         }
1823
1824         pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1825                 let mut ret = Vec::new();
1826                 mem::swap(&mut ret, &mut self.pending_events);
1827                 ret
1828         }
1829
1830         /// Can only fail if idx is < get_min_seen_secret
1831         fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1832                 self.commitment_secrets.get_secret(idx)
1833         }
1834
1835         pub(crate) fn get_min_seen_secret(&self) -> u64 {
1836                 self.commitment_secrets.get_min_seen_secret()
1837         }
1838
1839         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1840                 self.current_counterparty_commitment_number
1841         }
1842
1843         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1844                 self.current_holder_commitment_number
1845         }
1846
1847         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1848         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1849         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1850         /// HTLC-Success/HTLC-Timeout transactions.
1851         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1852         /// revoked counterparty commitment tx
1853         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1854                 // Most secp and related errors trying to create keys means we have no hope of constructing
1855                 // a spend transaction...so we return no transactions to broadcast
1856                 let mut claimable_outpoints = Vec::new();
1857                 let mut watch_outputs = Vec::new();
1858
1859                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1860                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1861
1862                 macro_rules! ignore_error {
1863                         ( $thing : expr ) => {
1864                                 match $thing {
1865                                         Ok(a) => a,
1866                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1867                                 }
1868                         };
1869                 }
1870
1871                 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);
1872                 if commitment_number >= self.get_min_seen_secret() {
1873                         let secret = self.get_secret(commitment_number).unwrap();
1874                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1875                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1876                         let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
1877                         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_commitment_params.counterparty_delayed_payment_base_key));
1878
1879                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
1880                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1881
1882                         // First, process non-htlc outputs (to_holder & to_counterparty)
1883                         for (idx, outp) in tx.output.iter().enumerate() {
1884                                 if outp.script_pubkey == revokeable_p2wsh {
1885                                         let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv);
1886                                         let justice_package = PackageTemplate::build_package(commitment_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
1887                                         claimable_outpoints.push(justice_package);
1888                                 }
1889                         }
1890
1891                         // Then, try to find revoked htlc outputs
1892                         if let Some(ref per_commitment_data) = per_commitment_option {
1893                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1894                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1895                                                 if transaction_output_index as usize >= tx.output.len() ||
1896                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1897                                                         return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1898                                                 }
1899                                                 let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone());
1900                                                 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
1901                                                 claimable_outpoints.push(justice_package);
1902                                         }
1903                                 }
1904                         }
1905
1906                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1907                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1908                                 // We're definitely a counterparty commitment transaction!
1909                                 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1910                                 for (idx, outp) in tx.output.iter().enumerate() {
1911                                         watch_outputs.push((idx as u32, outp.clone()));
1912                                 }
1913                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1914
1915                                 fail_unbroadcast_htlcs!(self, "revoked counterparty", height, [].iter().map(|a| *a), logger);
1916                         }
1917                 } else if let Some(per_commitment_data) = per_commitment_option {
1918                         // While this isn't useful yet, there is a potential race where if a counterparty
1919                         // revokes a state at the same time as the commitment transaction for that state is
1920                         // confirmed, and the watchtower receives the block before the user, the user could
1921                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1922                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1923                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1924                         // insert it here.
1925                         for (idx, outp) in tx.output.iter().enumerate() {
1926                                 watch_outputs.push((idx as u32, outp.clone()));
1927                         }
1928                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1929
1930                         log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1931                         fail_unbroadcast_htlcs!(self, "counterparty", height, per_commitment_data.iter().map(|(a, b)| (a, b.as_ref().map(|b| b.as_ref()))), logger);
1932
1933                         let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
1934                         for req in htlc_claim_reqs {
1935                                 claimable_outpoints.push(req);
1936                         }
1937
1938                 }
1939                 (claimable_outpoints, (commitment_txid, watch_outputs))
1940         }
1941
1942         fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
1943                 let mut claimable_outpoints = Vec::new();
1944                 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
1945                         if let Some(revocation_points) = self.their_cur_revocation_points {
1946                                 let revocation_point_option =
1947                                         // If the counterparty commitment tx is the latest valid state, use their latest
1948                                         // per-commitment point
1949                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1950                                         else if let Some(point) = revocation_points.2.as_ref() {
1951                                                 // If counterparty commitment tx is the state previous to the latest valid state, use
1952                                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
1953                                                 // them to temporarily have two valid commitment txns from our viewpoint)
1954                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1955                                         } else { None };
1956                                 if let Some(revocation_point) = revocation_point_option {
1957                                         for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
1958                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1959                                                         if let Some(transaction) = tx {
1960                                                                 if transaction_output_index as usize >= transaction.output.len() ||
1961                                                                         transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1962                                                                                 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
1963                                                                         }
1964                                                         }
1965                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1966                                                         if preimage.is_some() || !htlc.offered {
1967                                                                 let counterparty_htlc_outp = if htlc.offered { PackageSolvingData::CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput::build(*revocation_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, preimage.unwrap(), htlc.clone())) } else { PackageSolvingData::CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput::build(*revocation_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, htlc.clone())) };
1968                                                                 let aggregation = if !htlc.offered { false } else { true };
1969                                                                 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
1970                                                                 claimable_outpoints.push(counterparty_package);
1971                                                         }
1972                                                 }
1973                                         }
1974                                 }
1975                         }
1976                 }
1977                 claimable_outpoints
1978         }
1979
1980         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1981         fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
1982                 let htlc_txid = tx.txid();
1983                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1984                         return (Vec::new(), None)
1985                 }
1986
1987                 macro_rules! ignore_error {
1988                         ( $thing : expr ) => {
1989                                 match $thing {
1990                                         Ok(a) => a,
1991                                         Err(_) => return (Vec::new(), None)
1992                                 }
1993                         };
1994                 }
1995
1996                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1997                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1998                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1999
2000                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2001                 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, tx.output[0].value, self.counterparty_commitment_params.on_counterparty_tx_csv);
2002                 let justice_package = PackageTemplate::build_package(htlc_txid, 0, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
2003                 let claimable_outpoints = vec!(justice_package);
2004                 let outputs = vec![(0, tx.output[0].clone())];
2005                 (claimable_outpoints, Some((htlc_txid, outputs)))
2006         }
2007
2008         // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2009         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2010         // script so we can detect whether a holder transaction has been seen on-chain.
2011         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2012                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2013
2014                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2015                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2016
2017                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2018                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2019                                 let htlc_output = if htlc.offered {
2020                                                 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2021                                         } else {
2022                                                 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2023                                                         preimage.clone()
2024                                                 } else {
2025                                                         // We can't build an HTLC-Success transaction without the preimage
2026                                                         continue;
2027                                                 };
2028                                                 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2029                                         };
2030                                 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2031                                 claim_requests.push(htlc_package);
2032                         }
2033                 }
2034
2035                 (claim_requests, broadcasted_holder_revokable_script)
2036         }
2037
2038         // Returns holder HTLC outputs to watch and react to in case of spending.
2039         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2040                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2041                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2042                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2043                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2044                         }
2045                 }
2046                 watch_outputs
2047         }
2048
2049         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2050         /// revoked using data in holder_claimable_outpoints.
2051         /// Should not be used if check_spend_revoked_transaction succeeds.
2052         /// Returns None unless the transaction is definitely one of our commitment transactions.
2053         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2054                 let commitment_txid = tx.txid();
2055                 let mut claim_requests = Vec::new();
2056                 let mut watch_outputs = Vec::new();
2057
2058                 macro_rules! append_onchain_update {
2059                         ($updates: expr, $to_watch: expr) => {
2060                                 claim_requests = $updates.0;
2061                                 self.broadcasted_holder_revokable_script = $updates.1;
2062                                 watch_outputs.append(&mut $to_watch);
2063                         }
2064                 }
2065
2066                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2067                 let mut is_holder_tx = false;
2068
2069                 if self.current_holder_commitment_tx.txid == commitment_txid {
2070                         is_holder_tx = true;
2071                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2072                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2073                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2074                         append_onchain_update!(res, to_watch);
2075                         fail_unbroadcast_htlcs!(self, "latest holder", height, self.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2076                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2077                         if holder_tx.txid == commitment_txid {
2078                                 is_holder_tx = true;
2079                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2080                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2081                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2082                                 append_onchain_update!(res, to_watch);
2083                                 fail_unbroadcast_htlcs!(self, "previous holder", height, holder_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2084                         }
2085                 }
2086
2087                 if is_holder_tx {
2088                         Some((claim_requests, (commitment_txid, watch_outputs)))
2089                 } else {
2090                         None
2091                 }
2092         }
2093
2094         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2095                 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2096                 self.holder_tx_signed = true;
2097                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2098                 let txid = commitment_tx.txid();
2099                 let mut holder_transactions = vec![commitment_tx];
2100                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2101                         if let Some(vout) = htlc.0.transaction_output_index {
2102                                 let preimage = if !htlc.0.offered {
2103                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2104                                                 // We can't build an HTLC-Success transaction without the preimage
2105                                                 continue;
2106                                         }
2107                                 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2108                                         // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2109                                         // current locktime requirements on-chain. We will broadcast them in
2110                                         // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2111                                         // Note that we add + 1 as transactions are broadcastable when they can be
2112                                         // confirmed in the next block.
2113                                         continue;
2114                                 } else { None };
2115                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2116                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2117                                         holder_transactions.push(htlc_tx);
2118                                 }
2119                         }
2120                 }
2121                 // 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.
2122                 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2123                 holder_transactions
2124         }
2125
2126         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2127         /// Note that this includes possibly-locktimed-in-the-future transactions!
2128         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2129                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2130                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2131                 let txid = commitment_tx.txid();
2132                 let mut holder_transactions = vec![commitment_tx];
2133                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2134                         if let Some(vout) = htlc.0.transaction_output_index {
2135                                 let preimage = if !htlc.0.offered {
2136                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2137                                                 // We can't build an HTLC-Success transaction without the preimage
2138                                                 continue;
2139                                         }
2140                                 } else { None };
2141                                 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2142                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2143                                         holder_transactions.push(htlc_tx);
2144                                 }
2145                         }
2146                 }
2147                 holder_transactions
2148         }
2149
2150         pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L) -> Vec<TransactionOutputs>
2151                 where B::Target: BroadcasterInterface,
2152                       F::Target: FeeEstimator,
2153                                         L::Target: Logger,
2154         {
2155                 let block_hash = header.block_hash();
2156                 self.best_block = BestBlock::new(block_hash, height);
2157
2158                 self.transactions_confirmed(header, txdata, height, broadcaster, fee_estimator, logger)
2159         }
2160
2161         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2162                 &mut self,
2163                 header: &BlockHeader,
2164                 height: u32,
2165                 broadcaster: B,
2166                 fee_estimator: F,
2167                 logger: L,
2168         ) -> Vec<TransactionOutputs>
2169         where
2170                 B::Target: BroadcasterInterface,
2171                 F::Target: FeeEstimator,
2172                 L::Target: Logger,
2173         {
2174                 let block_hash = header.block_hash();
2175
2176                 if height > self.best_block.height() {
2177                         self.best_block = BestBlock::new(block_hash, height);
2178                         self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2179                 } else if block_hash != self.best_block.block_hash() {
2180                         self.best_block = BestBlock::new(block_hash, height);
2181                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2182                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2183                         Vec::new()
2184                 } else { Vec::new() }
2185         }
2186
2187         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2188                 &mut self,
2189                 header: &BlockHeader,
2190                 txdata: &TransactionData,
2191                 height: u32,
2192                 broadcaster: B,
2193                 fee_estimator: F,
2194                 logger: L,
2195         ) -> Vec<TransactionOutputs>
2196         where
2197                 B::Target: BroadcasterInterface,
2198                 F::Target: FeeEstimator,
2199                 L::Target: Logger,
2200         {
2201                 let txn_matched = self.filter_block(txdata);
2202                 for tx in &txn_matched {
2203                         let mut output_val = 0;
2204                         for out in tx.output.iter() {
2205                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2206                                 output_val += out.value;
2207                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2208                         }
2209                 }
2210
2211                 let block_hash = header.block_hash();
2212
2213                 let mut watch_outputs = Vec::new();
2214                 let mut claimable_outpoints = Vec::new();
2215                 for tx in &txn_matched {
2216                         if tx.input.len() == 1 {
2217                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2218                                 // commitment transactions and HTLC transactions will all only ever have one input,
2219                                 // which is an easy way to filter out any potential non-matching txn for lazy
2220                                 // filters.
2221                                 let prevout = &tx.input[0].previous_output;
2222                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2223                                         let mut balance_spendable_csv = None;
2224                                         log_info!(logger, "Channel closed by funding output spend in txid {}.", log_bytes!(tx.txid()));
2225                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2226                                                 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2227                                                 if !new_outputs.1.is_empty() {
2228                                                         watch_outputs.push(new_outputs);
2229                                                 }
2230                                                 claimable_outpoints.append(&mut new_outpoints);
2231                                                 if new_outpoints.is_empty() {
2232                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2233                                                                 if !new_outputs.1.is_empty() {
2234                                                                         watch_outputs.push(new_outputs);
2235                                                                 }
2236                                                                 claimable_outpoints.append(&mut new_outpoints);
2237                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
2238                                                         }
2239                                                 }
2240                                         }
2241                                         let txid = tx.txid();
2242                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2243                                                 txid,
2244                                                 height: height,
2245                                                 event: OnchainEvent::FundingSpendConfirmation {
2246                                                         on_local_output_csv: balance_spendable_csv,
2247                                                 },
2248                                         });
2249                                 } else {
2250                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2251                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2252                                                 claimable_outpoints.append(&mut new_outpoints);
2253                                                 if let Some(new_outputs) = new_outputs_option {
2254                                                         watch_outputs.push(new_outputs);
2255                                                 }
2256                                         }
2257                                 }
2258                         }
2259                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2260                         // can also be resolved in a few other ways which can have more than one output. Thus,
2261                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2262                         self.is_resolving_htlc_output(&tx, height, &logger);
2263
2264                         self.is_paying_spendable_output(&tx, height, &logger);
2265                 }
2266
2267                 if height > self.best_block.height() {
2268                         self.best_block = BestBlock::new(block_hash, height);
2269                 }
2270
2271                 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2272         }
2273
2274         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2275         /// `self.best_block` before calling if a new best blockchain tip is available. More
2276         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2277         /// complexity especially in `OnchainTx::update_claims_view`.
2278         ///
2279         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2280         /// confirmed at, even if it is not the current best height.
2281         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2282                 &mut self,
2283                 conf_height: u32,
2284                 txn_matched: Vec<&Transaction>,
2285                 mut watch_outputs: Vec<TransactionOutputs>,
2286                 mut claimable_outpoints: Vec<PackageTemplate>,
2287                 broadcaster: &B,
2288                 fee_estimator: &F,
2289                 logger: &L,
2290         ) -> Vec<TransactionOutputs>
2291         where
2292                 B::Target: BroadcasterInterface,
2293                 F::Target: FeeEstimator,
2294                 L::Target: Logger,
2295         {
2296                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2297                 debug_assert!(self.best_block.height() >= conf_height);
2298
2299                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2300                 if should_broadcast {
2301                         let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2302                         let commitment_package = PackageTemplate::build_package(self.funding_info.0.txid.clone(), self.funding_info.0.index as u32, PackageSolvingData::HolderFundingOutput(funding_outp), self.best_block.height(), false, self.best_block.height());
2303                         claimable_outpoints.push(commitment_package);
2304                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2305                         let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2306                         self.holder_tx_signed = true;
2307                         // Because we're broadcasting a commitment transaction, we should construct the package
2308                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2309                         // "not yet confirmed" things as discardable, so we cannot do that here.
2310                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2311                         let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2312                         if !new_outputs.is_empty() {
2313                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2314                         }
2315                         claimable_outpoints.append(&mut new_outpoints);
2316                 }
2317
2318                 // Find which on-chain events have reached their confirmation threshold.
2319                 let onchain_events_awaiting_threshold_conf =
2320                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2321                 let mut onchain_events_reaching_threshold_conf = Vec::new();
2322                 for entry in onchain_events_awaiting_threshold_conf {
2323                         if entry.has_reached_confirmation_threshold(&self.best_block) {
2324                                 onchain_events_reaching_threshold_conf.push(entry);
2325                         } else {
2326                                 self.onchain_events_awaiting_threshold_conf.push(entry);
2327                         }
2328                 }
2329
2330                 // Used to check for duplicate HTLC resolutions.
2331                 #[cfg(debug_assertions)]
2332                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2333                         .iter()
2334                         .filter_map(|entry| match &entry.event {
2335                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2336                                 _ => None,
2337                         })
2338                         .collect();
2339                 #[cfg(debug_assertions)]
2340                 let mut matured_htlcs = Vec::new();
2341
2342                 // Produce actionable events from on-chain events having reached their threshold.
2343                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2344                         match entry.event {
2345                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, onchain_value_satoshis, input_idx } => {
2346                                         // Check for duplicate HTLC resolutions.
2347                                         #[cfg(debug_assertions)]
2348                                         {
2349                                                 debug_assert!(
2350                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2351                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
2352                                                          call either transaction_unconfirmed for the conflicting transaction \
2353                                                          or block_disconnected for a block containing it.");
2354                                                 debug_assert!(
2355                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2356                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
2357                                                          call either transaction_unconfirmed for the conflicting transaction \
2358                                                          or block_disconnected for a block containing it.");
2359                                                 matured_htlcs.push(source.clone());
2360                                         }
2361
2362                                         log_debug!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!(payment_hash.0));
2363                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2364                                                 payment_hash,
2365                                                 payment_preimage: None,
2366                                                 source: source.clone(),
2367                                                 onchain_value_satoshis,
2368                                         }));
2369                                         if let Some(idx) = input_idx {
2370                                                 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx: idx, payment_preimage: None });
2371                                         }
2372                                 },
2373                                 OnchainEvent::MaturingOutput { descriptor } => {
2374                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2375                                         self.pending_events.push(Event::SpendableOutputs {
2376                                                 outputs: vec![descriptor]
2377                                         });
2378                                 },
2379                                 OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } => {
2380                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx, payment_preimage: preimage });
2381                                 },
2382                                 OnchainEvent::FundingSpendConfirmation { .. } => {
2383                                         self.funding_spend_confirmed = Some(entry.txid);
2384                                 },
2385                         }
2386                 }
2387
2388                 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2389
2390                 // Determine new outputs to watch by comparing against previously known outputs to watch,
2391                 // updating the latter in the process.
2392                 watch_outputs.retain(|&(ref txid, ref txouts)| {
2393                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2394                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2395                 });
2396                 #[cfg(test)]
2397                 {
2398                         // If we see a transaction for which we registered outputs previously,
2399                         // make sure the registered scriptpubkey at the expected index match
2400                         // the actual transaction output one. We failed this case before #653.
2401                         for tx in &txn_matched {
2402                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2403                                         for idx_and_script in outputs.iter() {
2404                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
2405                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2406                                         }
2407                                 }
2408                         }
2409                 }
2410                 watch_outputs
2411         }
2412
2413         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2414                 where B::Target: BroadcasterInterface,
2415                       F::Target: FeeEstimator,
2416                       L::Target: Logger,
2417         {
2418                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2419
2420                 //We may discard:
2421                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2422                 //- maturing spendable output has transaction paying us has been disconnected
2423                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2424
2425                 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2426
2427                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2428         }
2429
2430         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2431                 &mut self,
2432                 txid: &Txid,
2433                 broadcaster: B,
2434                 fee_estimator: F,
2435                 logger: L,
2436         ) where
2437                 B::Target: BroadcasterInterface,
2438                 F::Target: FeeEstimator,
2439                 L::Target: Logger,
2440         {
2441                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.txid != *txid);
2442                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2443         }
2444
2445         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2446         /// transactions thereof.
2447         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2448                 let mut matched_txn = HashSet::new();
2449                 txdata.iter().filter(|&&(_, tx)| {
2450                         let mut matches = self.spends_watched_output(tx);
2451                         for input in tx.input.iter() {
2452                                 if matches { break; }
2453                                 if matched_txn.contains(&input.previous_output.txid) {
2454                                         matches = true;
2455                                 }
2456                         }
2457                         if matches {
2458                                 matched_txn.insert(tx.txid());
2459                         }
2460                         matches
2461                 }).map(|(_, tx)| *tx).collect()
2462         }
2463
2464         /// Checks if a given transaction spends any watched outputs.
2465         fn spends_watched_output(&self, tx: &Transaction) -> bool {
2466                 for input in tx.input.iter() {
2467                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2468                                 for (idx, _script_pubkey) in outputs.iter() {
2469                                         if *idx == input.previous_output.vout {
2470                                                 #[cfg(test)]
2471                                                 {
2472                                                         // If the expected script is a known type, check that the witness
2473                                                         // appears to be spending the correct type (ie that the match would
2474                                                         // actually succeed in BIP 158/159-style filters).
2475                                                         if _script_pubkey.is_v0_p2wsh() {
2476                                                                 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2477                                                         } else if _script_pubkey.is_v0_p2wpkh() {
2478                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2479                                                         } else { panic!(); }
2480                                                 }
2481                                                 return true;
2482                                         }
2483                                 }
2484                         }
2485                 }
2486
2487                 false
2488         }
2489
2490         fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2491                 // We need to consider all HTLCs which are:
2492                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
2493                 //    transactions and we'd end up in a race, or
2494                 //  * are in our latest holder commitment transaction, as this is the thing we will
2495                 //    broadcast if we go on-chain.
2496                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2497                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2498                 // to the source, and if we don't fail the channel we will have to ensure that the next
2499                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2500                 // easier to just fail the channel as this case should be rare enough anyway.
2501                 let height = self.best_block.height();
2502                 macro_rules! scan_commitment {
2503                         ($htlcs: expr, $holder_tx: expr) => {
2504                                 for ref htlc in $htlcs {
2505                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2506                                         // chain with enough room to claim the HTLC without our counterparty being able to
2507                                         // time out the HTLC first.
2508                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2509                                         // concern is being able to claim the corresponding inbound HTLC (on another
2510                                         // channel) before it expires. In fact, we don't even really care if our
2511                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2512                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2513                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2514                                         // we give ourselves a few blocks of headroom after expiration before going
2515                                         // on-chain for an expired HTLC.
2516                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2517                                         // from us until we've reached the point where we go on-chain with the
2518                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2519                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2520                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2521                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2522                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2523                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2524                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2525                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2526                                         //  The final, above, condition is checked for statically in channelmanager
2527                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2528                                         let htlc_outbound = $holder_tx == htlc.offered;
2529                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2530                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2531                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2532                                                 return true;
2533                                         }
2534                                 }
2535                         }
2536                 }
2537
2538                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2539
2540                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2541                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2542                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2543                         }
2544                 }
2545                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2546                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2547                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2548                         }
2549                 }
2550
2551                 false
2552         }
2553
2554         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2555         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2556         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2557                 'outer_loop: for input in &tx.input {
2558                         let mut payment_data = None;
2559                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2560                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2561                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2562                         #[cfg(not(fuzzing))]
2563                         let accepted_timeout_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2564                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && !revocation_sig_claim;
2565                         #[cfg(not(fuzzing))]
2566                         let offered_timeout_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::OfferedHTLC);
2567
2568                         let mut payment_preimage = PaymentPreimage([0; 32]);
2569                         if accepted_preimage_claim {
2570                                 payment_preimage.0.copy_from_slice(&input.witness[3]);
2571                         } else if offered_preimage_claim {
2572                                 payment_preimage.0.copy_from_slice(&input.witness[1]);
2573                         }
2574
2575                         macro_rules! log_claim {
2576                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2577                                         let outbound_htlc = $holder_tx == $htlc.offered;
2578                                         // HTLCs must either be claimed by a matching script type or through the
2579                                         // revocation path:
2580                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2581                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2582                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2583                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2584                                         // Further, only exactly one of the possible spend paths should have been
2585                                         // matched by any HTLC spend:
2586                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2587                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2588                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2589                                                          revocation_sig_claim as u8, 1);
2590                                         if ($holder_tx && revocation_sig_claim) ||
2591                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2592                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2593                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2594                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2595                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2596                                         } else {
2597                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2598                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2599                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2600                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2601                                         }
2602                                 }
2603                         }
2604
2605                         macro_rules! check_htlc_valid_counterparty {
2606                                 ($counterparty_txid: expr, $htlc_output: expr) => {
2607                                         if let Some(txid) = $counterparty_txid {
2608                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2609                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2610                                                                 if let &Some(ref source) = pending_source {
2611                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2612                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2613                                                                         break;
2614                                                                 }
2615                                                         }
2616                                                 }
2617                                         }
2618                                 }
2619                         }
2620
2621                         macro_rules! scan_commitment {
2622                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2623                                         for (ref htlc_output, source_option) in $htlcs {
2624                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2625                                                         if let Some(ref source) = source_option {
2626                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
2627                                                                 // We have a resolution of an HTLC either from one of our latest
2628                                                                 // holder commitment transactions or an unrevoked counterparty commitment
2629                                                                 // transaction. This implies we either learned a preimage, the HTLC
2630                                                                 // has timed out, or we screwed up. In any case, we should now
2631                                                                 // resolve the source HTLC with the original sender.
2632                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2633                                                         } else if !$holder_tx {
2634                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2635                                                                 if payment_data.is_none() {
2636                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2637                                                                 }
2638                                                         }
2639                                                         if payment_data.is_none() {
2640                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
2641                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
2642                                                                 if !outbound_htlc || revocation_sig_claim {
2643                                                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2644                                                                                 txid: tx.txid(), height,
2645                                                                                 event: OnchainEvent::HTLCSpendConfirmation {
2646                                                                                         input_idx: input.previous_output.vout,
2647                                                                                         preimage: if accepted_preimage_claim || offered_preimage_claim {
2648                                                                                                 Some(payment_preimage) } else { None },
2649                                                                                         // If this is a payment to us (!outbound_htlc, above),
2650                                                                                         // wait for the CSV delay before dropping the HTLC from
2651                                                                                         // claimable balance if the claim was an HTLC-Success
2652                                                                                         // transaction.
2653                                                                                         on_to_local_output_csv: if accepted_preimage_claim {
2654                                                                                                 Some(self.on_holder_tx_csv) } else { None },
2655                                                                                 },
2656                                                                         });
2657                                                                 } else {
2658                                                                         // Outbound claims should always have payment_data, unless
2659                                                                         // we've already failed the HTLC as the commitment transaction
2660                                                                         // which was broadcasted was revoked. In that case, we should
2661                                                                         // spend the HTLC output here immediately, and expose that fact
2662                                                                         // as a Balance, something which we do not yet do.
2663                                                                         // TODO: Track the above as claimable!
2664                                                                 }
2665                                                                 continue 'outer_loop;
2666                                                         }
2667                                                 }
2668                                         }
2669                                 }
2670                         }
2671
2672                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2673                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2674                                         "our latest holder commitment tx", true);
2675                         }
2676                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2677                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2678                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2679                                                 "our previous holder commitment tx", true);
2680                                 }
2681                         }
2682                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2683                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2684                                         "counterparty commitment tx", false);
2685                         }
2686
2687                         // Check that scan_commitment, above, decided there is some source worth relaying an
2688                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2689                         if let Some((source, payment_hash, amount_msat)) = payment_data {
2690                                 if accepted_preimage_claim {
2691                                         if !self.pending_monitor_events.iter().any(
2692                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2693                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2694                                                         txid: tx.txid(),
2695                                                         height,
2696                                                         event: OnchainEvent::HTLCSpendConfirmation {
2697                                                                 input_idx: input.previous_output.vout,
2698                                                                 preimage: Some(payment_preimage),
2699                                                                 on_to_local_output_csv: None,
2700                                                         },
2701                                                 });
2702                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2703                                                         source,
2704                                                         payment_preimage: Some(payment_preimage),
2705                                                         payment_hash,
2706                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2707                                                 }));
2708                                         }
2709                                 } else if offered_preimage_claim {
2710                                         if !self.pending_monitor_events.iter().any(
2711                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2712                                                         upd.source == source
2713                                                 } else { false }) {
2714                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2715                                                         txid: tx.txid(),
2716                                                         height,
2717                                                         event: OnchainEvent::HTLCSpendConfirmation {
2718                                                                 input_idx: input.previous_output.vout,
2719                                                                 preimage: Some(payment_preimage),
2720                                                                 on_to_local_output_csv: None,
2721                                                         },
2722                                                 });
2723                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2724                                                         source,
2725                                                         payment_preimage: Some(payment_preimage),
2726                                                         payment_hash,
2727                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2728                                                 }));
2729                                         }
2730                                 } else {
2731                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2732                                                 if entry.height != height { return true; }
2733                                                 match entry.event {
2734                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
2735                                                                 *htlc_source != source
2736                                                         },
2737                                                         _ => true,
2738                                                 }
2739                                         });
2740                                         let entry = OnchainEventEntry {
2741                                                 txid: tx.txid(),
2742                                                 height,
2743                                                 event: OnchainEvent::HTLCUpdate {
2744                                                         source, payment_hash,
2745                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2746                                                         input_idx: Some(input.previous_output.vout),
2747                                                 },
2748                                         };
2749                                         log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", log_bytes!(payment_hash.0), entry.confirmation_threshold());
2750                                         self.onchain_events_awaiting_threshold_conf.push(entry);
2751                                 }
2752                         }
2753                 }
2754         }
2755
2756         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2757         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2758                 let mut spendable_output = None;
2759                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2760                         if i > ::core::u16::MAX as usize {
2761                                 // While it is possible that an output exists on chain which is greater than the
2762                                 // 2^16th output in a given transaction, this is only possible if the output is not
2763                                 // in a lightning transaction and was instead placed there by some third party who
2764                                 // wishes to give us money for no reason.
2765                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
2766                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2767                                 // scripts are not longer than one byte in length and because they are inherently
2768                                 // non-standard due to their size.
2769                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
2770                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
2771                                 // nearly a full block with garbage just to hit this case.
2772                                 continue;
2773                         }
2774                         if outp.script_pubkey == self.destination_script {
2775                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
2776                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2777                                         output: outp.clone(),
2778                                 });
2779                                 break;
2780                         }
2781                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2782                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2783                                         spendable_output =  Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2784                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2785                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
2786                                                 to_self_delay: self.on_holder_tx_csv,
2787                                                 output: outp.clone(),
2788                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2789                                                 channel_keys_id: self.channel_keys_id,
2790                                                 channel_value_satoshis: self.channel_value_satoshis,
2791                                         }));
2792                                         break;
2793                                 }
2794                         }
2795                         if self.counterparty_payment_script == outp.script_pubkey {
2796                                 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2797                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2798                                         output: outp.clone(),
2799                                         channel_keys_id: self.channel_keys_id,
2800                                         channel_value_satoshis: self.channel_value_satoshis,
2801                                 }));
2802                                 break;
2803                         }
2804                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
2805                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2806                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2807                                         output: outp.clone(),
2808                                 });
2809                                 break;
2810                         }
2811                 }
2812                 if let Some(spendable_output) = spendable_output {
2813                         let entry = OnchainEventEntry {
2814                                 txid: tx.txid(),
2815                                 height: height,
2816                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2817                         };
2818                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2819                         self.onchain_events_awaiting_threshold_conf.push(entry);
2820                 }
2821         }
2822 }
2823
2824 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2825 where
2826         T::Target: BroadcasterInterface,
2827         F::Target: FeeEstimator,
2828         L::Target: Logger,
2829 {
2830         fn block_connected(&self, block: &Block, height: u32) {
2831                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2832                 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2833         }
2834
2835         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2836                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2837         }
2838 }
2839
2840 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
2841 where
2842         T::Target: BroadcasterInterface,
2843         F::Target: FeeEstimator,
2844         L::Target: Logger,
2845 {
2846         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
2847                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
2848         }
2849
2850         fn transaction_unconfirmed(&self, txid: &Txid) {
2851                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
2852         }
2853
2854         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
2855                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
2856         }
2857
2858         fn get_relevant_txids(&self) -> Vec<Txid> {
2859                 self.0.get_relevant_txids()
2860         }
2861 }
2862
2863 const MAX_ALLOC_SIZE: usize = 64*1024;
2864
2865 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
2866                 for (BlockHash, ChannelMonitor<Signer>) {
2867         fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
2868                 macro_rules! unwrap_obj {
2869                         ($key: expr) => {
2870                                 match $key {
2871                                         Ok(res) => res,
2872                                         Err(_) => return Err(DecodeError::InvalidValue),
2873                                 }
2874                         }
2875                 }
2876
2877                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
2878
2879                 let latest_update_id: u64 = Readable::read(reader)?;
2880                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2881
2882                 let destination_script = Readable::read(reader)?;
2883                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2884                         0 => {
2885                                 let revokable_address = Readable::read(reader)?;
2886                                 let per_commitment_point = Readable::read(reader)?;
2887                                 let revokable_script = Readable::read(reader)?;
2888                                 Some((revokable_address, per_commitment_point, revokable_script))
2889                         },
2890                         1 => { None },
2891                         _ => return Err(DecodeError::InvalidValue),
2892                 };
2893                 let counterparty_payment_script = Readable::read(reader)?;
2894                 let shutdown_script = {
2895                         let script = <Script as Readable>::read(reader)?;
2896                         if script.is_empty() { None } else { Some(script) }
2897                 };
2898
2899                 let channel_keys_id = Readable::read(reader)?;
2900                 let holder_revocation_basepoint = Readable::read(reader)?;
2901                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2902                 // barely-init'd ChannelMonitors that we can't do anything with.
2903                 let outpoint = OutPoint {
2904                         txid: Readable::read(reader)?,
2905                         index: Readable::read(reader)?,
2906                 };
2907                 let funding_info = (outpoint, Readable::read(reader)?);
2908                 let current_counterparty_commitment_txid = Readable::read(reader)?;
2909                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2910
2911                 let counterparty_commitment_params = Readable::read(reader)?;
2912                 let funding_redeemscript = Readable::read(reader)?;
2913                 let channel_value_satoshis = Readable::read(reader)?;
2914
2915                 let their_cur_revocation_points = {
2916                         let first_idx = <U48 as Readable>::read(reader)?.0;
2917                         if first_idx == 0 {
2918                                 None
2919                         } else {
2920                                 let first_point = Readable::read(reader)?;
2921                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2922                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2923                                         Some((first_idx, first_point, None))
2924                                 } else {
2925                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2926                                 }
2927                         }
2928                 };
2929
2930                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2931
2932                 let commitment_secrets = Readable::read(reader)?;
2933
2934                 macro_rules! read_htlc_in_commitment {
2935                         () => {
2936                                 {
2937                                         let offered: bool = Readable::read(reader)?;
2938                                         let amount_msat: u64 = Readable::read(reader)?;
2939                                         let cltv_expiry: u32 = Readable::read(reader)?;
2940                                         let payment_hash: PaymentHash = Readable::read(reader)?;
2941                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
2942
2943                                         HTLCOutputInCommitment {
2944                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2945                                         }
2946                                 }
2947                         }
2948                 }
2949
2950                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2951                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2952                 for _ in 0..counterparty_claimable_outpoints_len {
2953                         let txid: Txid = Readable::read(reader)?;
2954                         let htlcs_count: u64 = Readable::read(reader)?;
2955                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2956                         for _ in 0..htlcs_count {
2957                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2958                         }
2959                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2960                                 return Err(DecodeError::InvalidValue);
2961                         }
2962                 }
2963
2964                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2965                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2966                 for _ in 0..counterparty_commitment_txn_on_chain_len {
2967                         let txid: Txid = Readable::read(reader)?;
2968                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2969                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
2970                                 return Err(DecodeError::InvalidValue);
2971                         }
2972                 }
2973
2974                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2975                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2976                 for _ in 0..counterparty_hash_commitment_number_len {
2977                         let payment_hash: PaymentHash = Readable::read(reader)?;
2978                         let commitment_number = <U48 as Readable>::read(reader)?.0;
2979                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2980                                 return Err(DecodeError::InvalidValue);
2981                         }
2982                 }
2983
2984                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
2985                         match <u8 as Readable>::read(reader)? {
2986                                 0 => None,
2987                                 1 => {
2988                                         Some(Readable::read(reader)?)
2989                                 },
2990                                 _ => return Err(DecodeError::InvalidValue),
2991                         };
2992                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
2993
2994                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2995                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2996
2997                 let payment_preimages_len: u64 = Readable::read(reader)?;
2998                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2999                 for _ in 0..payment_preimages_len {
3000                         let preimage: PaymentPreimage = Readable::read(reader)?;
3001                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3002                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3003                                 return Err(DecodeError::InvalidValue);
3004                         }
3005                 }
3006
3007                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3008                 let mut pending_monitor_events = Some(
3009                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3010                 for _ in 0..pending_monitor_events_len {
3011                         let ev = match <u8 as Readable>::read(reader)? {
3012                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3013                                 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3014                                 _ => return Err(DecodeError::InvalidValue)
3015                         };
3016                         pending_monitor_events.as_mut().unwrap().push(ev);
3017                 }
3018
3019                 let pending_events_len: u64 = Readable::read(reader)?;
3020                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3021                 for _ in 0..pending_events_len {
3022                         if let Some(event) = MaybeReadable::read(reader)? {
3023                                 pending_events.push(event);
3024                         }
3025                 }
3026
3027                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3028
3029                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3030                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3031                 for _ in 0..waiting_threshold_conf_len {
3032                         if let Some(val) = MaybeReadable::read(reader)? {
3033                                 onchain_events_awaiting_threshold_conf.push(val);
3034                         }
3035                 }
3036
3037                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3038                 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::<u32>() + mem::size_of::<Vec<Script>>())));
3039                 for _ in 0..outputs_to_watch_len {
3040                         let txid = Readable::read(reader)?;
3041                         let outputs_len: u64 = Readable::read(reader)?;
3042                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3043                         for _ in 0..outputs_len {
3044                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3045                         }
3046                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3047                                 return Err(DecodeError::InvalidValue);
3048                         }
3049                 }
3050                 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3051
3052                 let lockdown_from_offchain = Readable::read(reader)?;
3053                 let holder_tx_signed = Readable::read(reader)?;
3054
3055                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3056                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3057                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3058                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3059                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3060                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3061                                 return Err(DecodeError::InvalidValue);
3062                         }
3063                 }
3064
3065                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3066                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3067                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3068                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3069                         return Err(DecodeError::InvalidValue);
3070                 }
3071
3072                 let mut funding_spend_confirmed = None;
3073                 let mut htlcs_resolved_on_chain = Some(Vec::new());
3074                 read_tlv_fields!(reader, {
3075                         (1, funding_spend_confirmed, option),
3076                         (3, htlcs_resolved_on_chain, vec_type),
3077                         (5, pending_monitor_events, vec_type),
3078                 });
3079
3080                 let mut secp_ctx = Secp256k1::new();
3081                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3082
3083                 Ok((best_block.block_hash(), ChannelMonitor {
3084                         inner: Mutex::new(ChannelMonitorImpl {
3085                                 latest_update_id,
3086                                 commitment_transaction_number_obscure_factor,
3087
3088                                 destination_script,
3089                                 broadcasted_holder_revokable_script,
3090                                 counterparty_payment_script,
3091                                 shutdown_script,
3092
3093                                 channel_keys_id,
3094                                 holder_revocation_basepoint,
3095                                 funding_info,
3096                                 current_counterparty_commitment_txid,
3097                                 prev_counterparty_commitment_txid,
3098
3099                                 counterparty_commitment_params,
3100                                 funding_redeemscript,
3101                                 channel_value_satoshis,
3102                                 their_cur_revocation_points,
3103
3104                                 on_holder_tx_csv,
3105
3106                                 commitment_secrets,
3107                                 counterparty_claimable_outpoints,
3108                                 counterparty_commitment_txn_on_chain,
3109                                 counterparty_hash_commitment_number,
3110
3111                                 prev_holder_signed_commitment_tx,
3112                                 current_holder_commitment_tx,
3113                                 current_counterparty_commitment_number,
3114                                 current_holder_commitment_number,
3115
3116                                 payment_preimages,
3117                                 pending_monitor_events: pending_monitor_events.unwrap(),
3118                                 pending_events,
3119
3120                                 onchain_events_awaiting_threshold_conf,
3121                                 outputs_to_watch,
3122
3123                                 onchain_tx_handler,
3124
3125                                 lockdown_from_offchain,
3126                                 holder_tx_signed,
3127                                 funding_spend_confirmed,
3128                                 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3129
3130                                 best_block,
3131
3132                                 secp_ctx,
3133                         }),
3134                 }))
3135         }
3136 }
3137
3138 #[cfg(test)]
3139 mod tests {
3140         use bitcoin::blockdata::script::{Script, Builder};
3141         use bitcoin::blockdata::opcodes;
3142         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3143         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3144         use bitcoin::util::bip143;
3145         use bitcoin::hashes::Hash;
3146         use bitcoin::hashes::sha256::Hash as Sha256;
3147         use bitcoin::hashes::hex::FromHex;
3148         use bitcoin::hash_types::Txid;
3149         use bitcoin::network::constants::Network;
3150         use hex;
3151         use chain::BestBlock;
3152         use chain::channelmonitor::ChannelMonitor;
3153         use chain::package::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
3154         use chain::transaction::OutPoint;
3155         use ln::{PaymentPreimage, PaymentHash};
3156         use ln::chan_utils;
3157         use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3158         use ln::script::ShutdownScript;
3159         use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3160         use bitcoin::secp256k1::key::{SecretKey,PublicKey};
3161         use bitcoin::secp256k1::Secp256k1;
3162         use sync::{Arc, Mutex};
3163         use chain::keysinterface::InMemorySigner;
3164         use prelude::*;
3165
3166         #[test]
3167         fn test_prune_preimages() {
3168                 let secp_ctx = Secp256k1::new();
3169                 let logger = Arc::new(TestLogger::new());
3170                 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3171                 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: Mutex::new(253) });
3172
3173                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3174                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3175
3176                 let mut preimages = Vec::new();
3177                 {
3178                         for i in 0..20 {
3179                                 let preimage = PaymentPreimage([i; 32]);
3180                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3181                                 preimages.push((preimage, hash));
3182                         }
3183                 }
3184
3185                 macro_rules! preimages_slice_to_htlc_outputs {
3186                         ($preimages_slice: expr) => {
3187                                 {
3188                                         let mut res = Vec::new();
3189                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3190                                                 res.push((HTLCOutputInCommitment {
3191                                                         offered: true,
3192                                                         amount_msat: 0,
3193                                                         cltv_expiry: 0,
3194                                                         payment_hash: preimage.1.clone(),
3195                                                         transaction_output_index: Some(idx as u32),
3196                                                 }, None));
3197                                         }
3198                                         res
3199                                 }
3200                         }
3201                 }
3202                 macro_rules! preimages_to_holder_htlcs {
3203                         ($preimages_slice: expr) => {
3204                                 {
3205                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3206                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3207                                         res
3208                                 }
3209                         }
3210                 }
3211
3212                 macro_rules! test_preimages_exist {
3213                         ($preimages_slice: expr, $monitor: expr) => {
3214                                 for preimage in $preimages_slice {
3215                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3216                                 }
3217                         }
3218                 }
3219
3220                 let keys = InMemorySigner::new(
3221                         &secp_ctx,
3222                         SecretKey::from_slice(&[41; 32]).unwrap(),
3223                         SecretKey::from_slice(&[41; 32]).unwrap(),
3224                         SecretKey::from_slice(&[41; 32]).unwrap(),
3225                         SecretKey::from_slice(&[41; 32]).unwrap(),
3226                         SecretKey::from_slice(&[41; 32]).unwrap(),
3227                         [41; 32],
3228                         0,
3229                         [0; 32]
3230                 );
3231
3232                 let counterparty_pubkeys = ChannelPublicKeys {
3233                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3234                         revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3235                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3236                         delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3237                         htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3238                 };
3239                 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
3240                 let channel_parameters = ChannelTransactionParameters {
3241                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3242                         holder_selected_contest_delay: 66,
3243                         is_outbound_from_holder: true,
3244                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3245                                 pubkeys: counterparty_pubkeys,
3246                                 selected_contest_delay: 67,
3247                         }),
3248                         funding_outpoint: Some(funding_outpoint),
3249                 };
3250                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3251                 // old state.
3252                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3253                 let best_block = BestBlock::from_genesis(Network::Testnet);
3254                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3255                                                   Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3256                                                   (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3257                                                   &channel_parameters,
3258                                                   Script::new(), 46, 0,
3259                                                   HolderCommitmentTransaction::dummy(), best_block);
3260
3261                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3262                 let dummy_txid = dummy_tx.txid();
3263                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3264                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3265                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3266                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3267                 for &(ref preimage, ref hash) in preimages.iter() {
3268                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
3269                 }
3270
3271                 // Now provide a secret, pruning preimages 10-15
3272                 let mut secret = [0; 32];
3273                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3274                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3275                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3276                 test_preimages_exist!(&preimages[0..10], monitor);
3277                 test_preimages_exist!(&preimages[15..20], monitor);
3278
3279                 // Now provide a further secret, pruning preimages 15-17
3280                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3281                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3282                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3283                 test_preimages_exist!(&preimages[0..10], monitor);
3284                 test_preimages_exist!(&preimages[17..20], monitor);
3285
3286                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3287                 // previous commitment tx's preimages too
3288                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3289                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3290                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3291                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3292                 test_preimages_exist!(&preimages[0..10], monitor);
3293                 test_preimages_exist!(&preimages[18..20], monitor);
3294
3295                 // But if we do it again, we'll prune 5-10
3296                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3297                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3298                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3299                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3300                 test_preimages_exist!(&preimages[0..5], monitor);
3301         }
3302
3303         #[test]
3304         fn test_claim_txn_weight_computation() {
3305                 // We test Claim txn weight, knowing that we want expected weigth and
3306                 // not actual case to avoid sigs and time-lock delays hell variances.
3307
3308                 let secp_ctx = Secp256k1::new();
3309                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3310                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3311                 let mut sum_actual_sigs = 0;
3312
3313                 macro_rules! sign_input {
3314                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr) => {
3315                                 let htlc = HTLCOutputInCommitment {
3316                                         offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
3317                                         amount_msat: 0,
3318                                         cltv_expiry: 2 << 16,
3319                                         payment_hash: PaymentHash([1; 32]),
3320                                         transaction_output_index: Some($idx as u32),
3321                                 };
3322                                 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
3323                                 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3324                                 let sig = secp_ctx.sign(&sighash, &privkey);
3325                                 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3326                                 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3327                                 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3328                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
3329                                         $sighash_parts.access_witness($idx).push(vec!(1));
3330                                 } else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
3331                                         $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3332                                 } else if *$weight == WEIGHT_RECEIVED_HTLC {
3333                                         $sighash_parts.access_witness($idx).push(vec![0]);
3334                                 } else {
3335                                         $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3336                                 }
3337                                 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3338                                 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3339                                 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3340                                 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3341                         }
3342                 }
3343
3344                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3345                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3346
3347                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3348                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3349                 for i in 0..4 {
3350                         claim_tx.input.push(TxIn {
3351                                 previous_output: BitcoinOutPoint {
3352                                         txid,
3353                                         vout: i,
3354                                 },
3355                                 script_sig: Script::new(),
3356                                 sequence: 0xfffffffd,
3357                                 witness: Vec::new(),
3358                         });
3359                 }
3360                 claim_tx.output.push(TxOut {
3361                         script_pubkey: script_pubkey.clone(),
3362                         value: 0,
3363                 });
3364                 let base_weight = claim_tx.get_weight();
3365                 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3366                 let mut inputs_total_weight = 2; // count segwit flags
3367                 {
3368                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3369                         for (idx, inp) in inputs_weight.iter().enumerate() {
3370                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3371                                 inputs_total_weight += inp;
3372                         }
3373                 }
3374                 assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3375
3376                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3377                 claim_tx.input.clear();
3378                 sum_actual_sigs = 0;
3379                 for i in 0..4 {
3380                         claim_tx.input.push(TxIn {
3381                                 previous_output: BitcoinOutPoint {
3382                                         txid,
3383                                         vout: i,
3384                                 },
3385                                 script_sig: Script::new(),
3386                                 sequence: 0xfffffffd,
3387                                 witness: Vec::new(),
3388                         });
3389                 }
3390                 let base_weight = claim_tx.get_weight();
3391                 let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3392                 let mut inputs_total_weight = 2; // count segwit flags
3393                 {
3394                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3395                         for (idx, inp) in inputs_weight.iter().enumerate() {
3396                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3397                                 inputs_total_weight += inp;
3398                         }
3399                 }
3400                 assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3401
3402                 // Justice tx with 1 revoked HTLC-Success tx output
3403                 claim_tx.input.clear();
3404                 sum_actual_sigs = 0;
3405                 claim_tx.input.push(TxIn {
3406                         previous_output: BitcoinOutPoint {
3407                                 txid,
3408                                 vout: 0,
3409                         },
3410                         script_sig: Script::new(),
3411                         sequence: 0xfffffffd,
3412                         witness: Vec::new(),
3413                 });
3414                 let base_weight = claim_tx.get_weight();
3415                 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3416                 let mut inputs_total_weight = 2; // count segwit flags
3417                 {
3418                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3419                         for (idx, inp) in inputs_weight.iter().enumerate() {
3420                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3421                                 inputs_total_weight += inp;
3422                         }
3423                 }
3424                 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3425         }
3426
3427         // Further testing is done in the ChannelManager integration tests.
3428 }