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