Merge pull request #2795 from TheBlueMatt/2023-11-robuster-chan-to-peer
[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::Header;
24 use bitcoin::blockdata::transaction::{OutPoint as BitcoinOutPoint, TxOut, Transaction};
25 use bitcoin::blockdata::script::{Script, ScriptBuf};
26
27 use bitcoin::hashes::Hash;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hash_types::{Txid, BlockHash};
30
31 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
32 use bitcoin::secp256k1::{SecretKey, PublicKey};
33 use bitcoin::secp256k1;
34 use bitcoin::sighash::EcdsaSighashType;
35
36 use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
37 use crate::ln::{PaymentHash, PaymentPreimage, ChannelId};
38 use crate::ln::msgs::DecodeError;
39 use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint};
40 use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys};
41 use crate::ln::channelmanager::{HTLCSource, SentHTLCId};
42 use crate::chain;
43 use crate::chain::{BestBlock, WatchedOutput};
44 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
45 use crate::chain::transaction::{OutPoint, TransactionData};
46 use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::WriteableEcdsaChannelSigner, SignerProvider, EntropySource};
47 use crate::chain::onchaintx::{ClaimEvent, OnchainTxHandler};
48 use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
49 use crate::chain::Filter;
50 use crate::util::logger::{Logger, Record};
51 use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48};
52 use crate::util::byte_utils;
53 use crate::events::{Event, EventHandler};
54 use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent};
55
56 use crate::prelude::*;
57 use core::{cmp, mem};
58 use crate::io::{self, Error};
59 use core::convert::TryInto;
60 use core::ops::Deref;
61 use crate::sync::{Mutex, LockTestExt};
62
63 /// An update generated by the underlying channel itself which contains some new information the
64 /// [`ChannelMonitor`] should be made aware of.
65 ///
66 /// Because this represents only a small number of updates to the underlying state, it is generally
67 /// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction
68 /// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment
69 /// transaction), a single update may reach upwards of 1 MiB in serialized size.
70 #[derive(Clone, Debug, PartialEq, Eq)]
71 #[must_use]
72 pub struct ChannelMonitorUpdate {
73         pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
74         /// Historically, [`ChannelMonitor`]s didn't know their counterparty node id. However,
75         /// `ChannelManager` really wants to know it so that it can easily look up the corresponding
76         /// channel. For now, this results in a temporary map in `ChannelManager` to look up channels
77         /// by only the funding outpoint.
78         ///
79         /// To eventually remove that, we repeat the counterparty node id here so that we can upgrade
80         /// `ChannelMonitor`s to become aware of the counterparty node id if they were generated prior
81         /// to when it was stored directly in them.
82         pub(crate) counterparty_node_id: Option<PublicKey>,
83         /// The sequence number of this update. Updates *must* be replayed in-order according to this
84         /// sequence number (and updates may panic if they are not). The update_id values are strictly
85         /// increasing and increase by one for each new update, with two exceptions specified below.
86         ///
87         /// This sequence number is also used to track up to which points updates which returned
88         /// [`ChannelMonitorUpdateStatus::InProgress`] have been applied to all copies of a given
89         /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
90         ///
91         /// The only instances we allow where update_id values are not strictly increasing have a
92         /// special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. This update ID is used for updates that
93         /// will force close the channel by broadcasting the latest commitment transaction or
94         /// special post-force-close updates, like providing preimages necessary to claim outputs on the
95         /// broadcast commitment transaction. See its docs for more details.
96         ///
97         /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
98         pub update_id: u64,
99 }
100
101 /// The update ID used for a [`ChannelMonitorUpdate`] that is either:
102 ///
103 ///     (1) attempting to force close the channel by broadcasting our latest commitment transaction or
104 ///     (2) providing a preimage (after the channel has been force closed) from a forward link that
105 ///             allows us to spend an HTLC output on this channel's (the backward link's) broadcasted
106 ///             commitment transaction.
107 ///
108 /// No other [`ChannelMonitorUpdate`]s are allowed after force-close.
109 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
110
111 impl Writeable for ChannelMonitorUpdate {
112         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
113                 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
114                 self.update_id.write(w)?;
115                 (self.updates.len() as u64).write(w)?;
116                 for update_step in self.updates.iter() {
117                         update_step.write(w)?;
118                 }
119                 write_tlv_fields!(w, {
120                         (1, self.counterparty_node_id, option),
121                 });
122                 Ok(())
123         }
124 }
125 impl Readable for ChannelMonitorUpdate {
126         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
127                 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
128                 let update_id: u64 = Readable::read(r)?;
129                 let len: u64 = Readable::read(r)?;
130                 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
131                 for _ in 0..len {
132                         if let Some(upd) = MaybeReadable::read(r)? {
133                                 updates.push(upd);
134                         }
135                 }
136                 let mut counterparty_node_id = None;
137                 read_tlv_fields!(r, {
138                         (1, counterparty_node_id, option),
139                 });
140                 Ok(Self { update_id, counterparty_node_id, updates })
141         }
142 }
143
144 /// An event to be processed by the ChannelManager.
145 #[derive(Clone, PartialEq, Eq)]
146 pub enum MonitorEvent {
147         /// A monitor event containing an HTLCUpdate.
148         HTLCEvent(HTLCUpdate),
149
150         /// Indicates we broadcasted the channel's latest commitment transaction and thus closed the
151         /// channel.
152         HolderForceClosed(OutPoint),
153
154         /// Indicates a [`ChannelMonitor`] update has completed. See
155         /// [`ChannelMonitorUpdateStatus::InProgress`] for more information on how this is used.
156         ///
157         /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
158         Completed {
159                 /// The funding outpoint of the [`ChannelMonitor`] that was updated
160                 funding_txo: OutPoint,
161                 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
162                 /// [`ChannelMonitor::get_latest_update_id`].
163                 ///
164                 /// Note that this should only be set to a given update's ID if all previous updates for the
165                 /// same [`ChannelMonitor`] have been applied and persisted.
166                 monitor_update_id: u64,
167         },
168 }
169 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
170         // Note that Completed is currently never serialized to disk as it is generated only in
171         // ChainMonitor.
172         (0, Completed) => {
173                 (0, funding_txo, required),
174                 (2, monitor_update_id, required),
175         },
176 ;
177         (2, HTLCEvent),
178         (4, HolderForceClosed),
179         // 6 was `UpdateFailed` until LDK 0.0.117
180 );
181
182 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
183 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
184 /// preimage claim backward will lead to loss of funds.
185 #[derive(Clone, PartialEq, Eq)]
186 pub struct HTLCUpdate {
187         pub(crate) payment_hash: PaymentHash,
188         pub(crate) payment_preimage: Option<PaymentPreimage>,
189         pub(crate) source: HTLCSource,
190         pub(crate) htlc_value_satoshis: Option<u64>,
191 }
192 impl_writeable_tlv_based!(HTLCUpdate, {
193         (0, payment_hash, required),
194         (1, htlc_value_satoshis, option),
195         (2, source, required),
196         (4, payment_preimage, option),
197 });
198
199 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
200 /// instead claiming it in its own individual transaction.
201 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
202 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
203 /// HTLC-Success transaction.
204 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
205 /// transaction confirmed (and we use it in a few more, equivalent, places).
206 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
207 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
208 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
209 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
210 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
211 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
212 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
213 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
214 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
215 /// accurate block height.
216 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
217 /// with at worst this delay, so we are not only using this value as a mercy for them but also
218 /// us as a safeguard to delay with enough time.
219 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
220 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
221 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
222 /// losing money.
223 ///
224 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
225 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
226 /// by a  [`ChannelMonitor`] may be incorrect.
227 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
228 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
229 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
230 // keep bumping another claim tx to solve the outpoint.
231 pub const ANTI_REORG_DELAY: u32 = 6;
232 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
233 /// refuse to accept a new HTLC.
234 ///
235 /// This is used for a few separate purposes:
236 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
237 ///    waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
238 ///    fail this HTLC,
239 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
240 ///    condition with the above), we will fail this HTLC without telling the user we received it,
241 ///
242 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
243 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
244 ///
245 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
246 /// in a race condition between the user connecting a block (which would fail it) and the user
247 /// providing us the preimage (which would claim it).
248 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
249
250 // TODO(devrandom) replace this with HolderCommitmentTransaction
251 #[derive(Clone, PartialEq, Eq)]
252 struct HolderSignedTx {
253         /// txid of the transaction in tx, just used to make comparison faster
254         txid: Txid,
255         revocation_key: RevocationKey,
256         a_htlc_key: HtlcKey,
257         b_htlc_key: HtlcKey,
258         delayed_payment_key: DelayedPaymentKey,
259         per_commitment_point: PublicKey,
260         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
261         to_self_value_sat: u64,
262         feerate_per_kw: u32,
263 }
264 impl_writeable_tlv_based!(HolderSignedTx, {
265         (0, txid, required),
266         // Note that this is filled in with data from OnchainTxHandler if it's missing.
267         // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
268         (1, to_self_value_sat, (default_value, u64::max_value())),
269         (2, revocation_key, required),
270         (4, a_htlc_key, required),
271         (6, b_htlc_key, required),
272         (8, delayed_payment_key, required),
273         (10, per_commitment_point, required),
274         (12, feerate_per_kw, required),
275         (14, htlc_outputs, required_vec)
276 });
277
278 impl HolderSignedTx {
279         fn non_dust_htlcs(&self) -> Vec<HTLCOutputInCommitment> {
280                 self.htlc_outputs.iter().filter_map(|(htlc, _, _)| {
281                         if let Some(_) = htlc.transaction_output_index {
282                                 Some(htlc.clone())
283                         } else {
284                                 None
285                         }
286                 })
287                 .collect()
288         }
289 }
290
291 /// We use this to track static counterparty commitment transaction data and to generate any
292 /// justice or 2nd-stage preimage/timeout transactions.
293 #[derive(Clone, PartialEq, Eq)]
294 struct CounterpartyCommitmentParameters {
295         counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
296         counterparty_htlc_base_key: HtlcBasepoint,
297         on_counterparty_tx_csv: u16,
298 }
299
300 impl Writeable for CounterpartyCommitmentParameters {
301         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
302                 w.write_all(&(0 as u64).to_be_bytes())?;
303                 write_tlv_fields!(w, {
304                         (0, self.counterparty_delayed_payment_base_key, required),
305                         (2, self.counterparty_htlc_base_key, required),
306                         (4, self.on_counterparty_tx_csv, required),
307                 });
308                 Ok(())
309         }
310 }
311 impl Readable for CounterpartyCommitmentParameters {
312         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
313                 let counterparty_commitment_transaction = {
314                         // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
315                         // used. Read it for compatibility.
316                         let per_htlc_len: u64 = Readable::read(r)?;
317                         for _  in 0..per_htlc_len {
318                                 let _txid: Txid = Readable::read(r)?;
319                                 let htlcs_count: u64 = Readable::read(r)?;
320                                 for _ in 0..htlcs_count {
321                                         let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
322                                 }
323                         }
324
325                         let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
326                         let mut counterparty_htlc_base_key = RequiredWrapper(None);
327                         let mut on_counterparty_tx_csv: u16 = 0;
328                         read_tlv_fields!(r, {
329                                 (0, counterparty_delayed_payment_base_key, required),
330                                 (2, counterparty_htlc_base_key, required),
331                                 (4, on_counterparty_tx_csv, required),
332                         });
333                         CounterpartyCommitmentParameters {
334                                 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
335                                 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
336                                 on_counterparty_tx_csv,
337                         }
338                 };
339                 Ok(counterparty_commitment_transaction)
340         }
341 }
342
343 /// An entry for an [`OnchainEvent`], stating the block height and hash when the event was
344 /// observed, as well as the transaction causing it.
345 ///
346 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
347 #[derive(Clone, PartialEq, Eq)]
348 struct OnchainEventEntry {
349         txid: Txid,
350         height: u32,
351         block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
352         event: OnchainEvent,
353         transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
354 }
355
356 impl OnchainEventEntry {
357         fn confirmation_threshold(&self) -> u32 {
358                 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
359                 match self.event {
360                         OnchainEvent::MaturingOutput {
361                                 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
362                         } => {
363                                 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
364                                 // it's broadcastable when we see the previous block.
365                                 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
366                         },
367                         OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
368                         OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
369                                 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
370                                 // it's broadcastable when we see the previous block.
371                                 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
372                         },
373                         _ => {},
374                 }
375                 conf_threshold
376         }
377
378         fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
379                 best_block.height() >= self.confirmation_threshold()
380         }
381 }
382
383 /// The (output index, sats value) for the counterparty's output in a commitment transaction.
384 ///
385 /// This was added as an `Option` in 0.0.110.
386 type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>;
387
388 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
389 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
390 #[derive(Clone, PartialEq, Eq)]
391 enum OnchainEvent {
392         /// An outbound HTLC failing after a transaction is confirmed. Used
393         ///  * when an outbound HTLC output is spent by us after the HTLC timed out
394         ///  * an outbound HTLC which was not present in the commitment transaction which appeared
395         ///    on-chain (either because it was not fully committed to or it was dust).
396         /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
397         /// appearing only as an `HTLCSpendConfirmation`, below.
398         HTLCUpdate {
399                 source: HTLCSource,
400                 payment_hash: PaymentHash,
401                 htlc_value_satoshis: Option<u64>,
402                 /// None in the second case, above, ie when there is no relevant output in the commitment
403                 /// transaction which appeared on chain.
404                 commitment_tx_output_idx: Option<u32>,
405         },
406         /// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the
407         /// [`SpendableOutputDescriptor`].
408         MaturingOutput {
409                 descriptor: SpendableOutputDescriptor,
410         },
411         /// A spend of the funding output, either a commitment transaction or a cooperative closing
412         /// transaction.
413         FundingSpendConfirmation {
414                 /// The CSV delay for the output of the funding spend transaction (implying it is a local
415                 /// commitment transaction, and this is the delay on the to_self output).
416                 on_local_output_csv: Option<u16>,
417                 /// If the funding spend transaction was a known remote commitment transaction, we track
418                 /// the output index and amount of the counterparty's `to_self` output here.
419                 ///
420                 /// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
421                 /// counterparty output.
422                 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
423         },
424         /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
425         /// is constructed. This is used when
426         ///  * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
427         ///    immediately claim the HTLC on the inbound edge and track the resolution here,
428         ///  * an inbound HTLC is claimed by our counterparty (with a timeout),
429         ///  * an inbound HTLC is claimed by us (with a preimage).
430         ///  * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
431         ///    signature.
432         ///  * a revoked-state HTLC transaction was broadcasted, which was claimed by an
433         ///    HTLC-Success/HTLC-Failure transaction (and is still claimable with a revocation
434         ///    signature).
435         HTLCSpendConfirmation {
436                 commitment_tx_output_idx: u32,
437                 /// If the claim was made by either party with a preimage, this is filled in
438                 preimage: Option<PaymentPreimage>,
439                 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
440                 /// we set this to the output CSV value which we will have to wait until to spend the
441                 /// output (and generate a SpendableOutput event).
442                 on_to_local_output_csv: Option<u16>,
443         },
444 }
445
446 impl Writeable for OnchainEventEntry {
447         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
448                 write_tlv_fields!(writer, {
449                         (0, self.txid, required),
450                         (1, self.transaction, option),
451                         (2, self.height, required),
452                         (3, self.block_hash, option),
453                         (4, self.event, required),
454                 });
455                 Ok(())
456         }
457 }
458
459 impl MaybeReadable for OnchainEventEntry {
460         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
461                 let mut txid = Txid::all_zeros();
462                 let mut transaction = None;
463                 let mut block_hash = None;
464                 let mut height = 0;
465                 let mut event = UpgradableRequired(None);
466                 read_tlv_fields!(reader, {
467                         (0, txid, required),
468                         (1, transaction, option),
469                         (2, height, required),
470                         (3, block_hash, option),
471                         (4, event, upgradable_required),
472                 });
473                 Ok(Some(Self { txid, transaction, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
474         }
475 }
476
477 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
478         (0, HTLCUpdate) => {
479                 (0, source, required),
480                 (1, htlc_value_satoshis, option),
481                 (2, payment_hash, required),
482                 (3, commitment_tx_output_idx, option),
483         },
484         (1, MaturingOutput) => {
485                 (0, descriptor, required),
486         },
487         (3, FundingSpendConfirmation) => {
488                 (0, on_local_output_csv, option),
489                 (1, commitment_tx_to_counterparty_output, option),
490         },
491         (5, HTLCSpendConfirmation) => {
492                 (0, commitment_tx_output_idx, required),
493                 (2, preimage, option),
494                 (4, on_to_local_output_csv, option),
495         },
496
497 );
498
499 #[derive(Clone, Debug, PartialEq, Eq)]
500 pub(crate) enum ChannelMonitorUpdateStep {
501         LatestHolderCommitmentTXInfo {
502                 commitment_tx: HolderCommitmentTransaction,
503                 /// Note that LDK after 0.0.115 supports this only containing dust HTLCs (implying the
504                 /// `Signature` field is never filled in). At that point, non-dust HTLCs are implied by the
505                 /// HTLC fields in `commitment_tx` and the sources passed via `nondust_htlc_sources`.
506                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
507                 claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
508                 nondust_htlc_sources: Vec<HTLCSource>,
509         },
510         LatestCounterpartyCommitmentTXInfo {
511                 commitment_txid: Txid,
512                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
513                 commitment_number: u64,
514                 their_per_commitment_point: PublicKey,
515                 feerate_per_kw: Option<u32>,
516                 to_broadcaster_value_sat: Option<u64>,
517                 to_countersignatory_value_sat: Option<u64>,
518         },
519         PaymentPreimage {
520                 payment_preimage: PaymentPreimage,
521         },
522         CommitmentSecret {
523                 idx: u64,
524                 secret: [u8; 32],
525         },
526         /// Used to indicate that the no future updates will occur, and likely that the latest holder
527         /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
528         ChannelForceClosed {
529                 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
530                 /// think we've fallen behind!
531                 should_broadcast: bool,
532         },
533         ShutdownScript {
534                 scriptpubkey: ScriptBuf,
535         },
536 }
537
538 impl ChannelMonitorUpdateStep {
539         fn variant_name(&self) -> &'static str {
540                 match self {
541                         ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
542                         ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
543                         ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
544                         ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
545                         ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
546                         ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
547                 }
548         }
549 }
550
551 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
552         (0, LatestHolderCommitmentTXInfo) => {
553                 (0, commitment_tx, required),
554                 (1, claimed_htlcs, optional_vec),
555                 (2, htlc_outputs, required_vec),
556                 (4, nondust_htlc_sources, optional_vec),
557         },
558         (1, LatestCounterpartyCommitmentTXInfo) => {
559                 (0, commitment_txid, required),
560                 (1, feerate_per_kw, option),
561                 (2, commitment_number, required),
562                 (3, to_broadcaster_value_sat, option),
563                 (4, their_per_commitment_point, required),
564                 (5, to_countersignatory_value_sat, option),
565                 (6, htlc_outputs, required_vec),
566         },
567         (2, PaymentPreimage) => {
568                 (0, payment_preimage, required),
569         },
570         (3, CommitmentSecret) => {
571                 (0, idx, required),
572                 (2, secret, required),
573         },
574         (4, ChannelForceClosed) => {
575                 (0, should_broadcast, required),
576         },
577         (5, ShutdownScript) => {
578                 (0, scriptpubkey, required),
579         },
580 );
581
582 /// Details about the balance(s) available for spending once the channel appears on chain.
583 ///
584 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
585 /// be provided.
586 #[derive(Clone, Debug, PartialEq, Eq)]
587 #[cfg_attr(test, derive(PartialOrd, Ord))]
588 pub enum Balance {
589         /// The channel is not yet closed (or the commitment or closing transaction has not yet
590         /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
591         /// force-closed now.
592         ClaimableOnChannelClose {
593                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
594                 /// required to do so.
595                 amount_satoshis: u64,
596         },
597         /// The channel has been closed, and the given balance is ours but awaiting confirmations until
598         /// we consider it spendable.
599         ClaimableAwaitingConfirmations {
600                 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
601                 /// were spent in broadcasting the transaction.
602                 amount_satoshis: u64,
603                 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
604                 /// amount.
605                 confirmation_height: u32,
606         },
607         /// The channel has been closed, and the given balance should be ours but awaiting spending
608         /// transaction confirmation. If the spending transaction does not confirm in time, it is
609         /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
610         ///
611         /// Once the spending transaction confirms, before it has reached enough confirmations to be
612         /// considered safe from chain reorganizations, the balance will instead be provided via
613         /// [`Balance::ClaimableAwaitingConfirmations`].
614         ContentiousClaimable {
615                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
616                 /// required to do so.
617                 amount_satoshis: u64,
618                 /// The height at which the counterparty may be able to claim the balance if we have not
619                 /// done so.
620                 timeout_height: u32,
621                 /// The payment hash that locks this HTLC.
622                 payment_hash: PaymentHash,
623                 /// The preimage that can be used to claim this HTLC.
624                 payment_preimage: PaymentPreimage,
625         },
626         /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
627         /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
628         /// likely to be claimed by our counterparty before we do.
629         MaybeTimeoutClaimableHTLC {
630                 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
631                 /// which will be required to do so.
632                 amount_satoshis: u64,
633                 /// The height at which we will be able to claim the balance if our counterparty has not
634                 /// done so.
635                 claimable_height: u32,
636                 /// The payment hash whose preimage our counterparty needs to claim this HTLC.
637                 payment_hash: PaymentHash,
638         },
639         /// HTLCs which we received from our counterparty which are claimable with a preimage which we
640         /// do not currently have. This will only be claimable if we receive the preimage from the node
641         /// to which we forwarded this HTLC before the timeout.
642         MaybePreimageClaimableHTLC {
643                 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
644                 /// which will be required to do so.
645                 amount_satoshis: u64,
646                 /// The height at which our counterparty will be able to claim the balance if we have not
647                 /// yet received the preimage and claimed it ourselves.
648                 expiry_height: u32,
649                 /// The payment hash whose preimage we need to claim this HTLC.
650                 payment_hash: PaymentHash,
651         },
652         /// The channel has been closed, and our counterparty broadcasted a revoked commitment
653         /// transaction.
654         ///
655         /// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
656         /// following amount.
657         CounterpartyRevokedOutputClaimable {
658                 /// The amount, in satoshis, of the output which we can claim.
659                 ///
660                 /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
661                 /// were already spent.
662                 amount_satoshis: u64,
663         },
664 }
665
666 impl Balance {
667         /// The amount claimable, in satoshis. This excludes balances that we are unsure if we are able
668         /// to claim, this is because we are waiting for a preimage or for a timeout to expire. For more
669         /// information on these balances see [`Balance::MaybeTimeoutClaimableHTLC`] and
670         /// [`Balance::MaybePreimageClaimableHTLC`].
671         ///
672         /// On-chain fees required to claim the balance are not included in this amount.
673         pub fn claimable_amount_satoshis(&self) -> u64 {
674                 match self {
675                         Balance::ClaimableOnChannelClose { amount_satoshis, .. }|
676                         Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
677                         Balance::ContentiousClaimable { amount_satoshis, .. }|
678                         Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
679                                 => *amount_satoshis,
680                         Balance::MaybeTimeoutClaimableHTLC { .. }|
681                         Balance::MaybePreimageClaimableHTLC { .. }
682                                 => 0,
683                 }
684         }
685 }
686
687 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
688 #[derive(Clone, PartialEq, Eq)]
689 struct IrrevocablyResolvedHTLC {
690         commitment_tx_output_idx: Option<u32>,
691         /// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC
692         /// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
693         /// transaction.
694         resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
695         resolving_tx: Option<Transaction>,
696         /// Only set if the HTLC claim was ours using a payment preimage
697         payment_preimage: Option<PaymentPreimage>,
698 }
699
700 // In LDK versions prior to 0.0.111 commitment_tx_output_idx was not Option-al and
701 // IrrevocablyResolvedHTLC objects only existed for non-dust HTLCs. This was a bug, but to maintain
702 // backwards compatibility we must ensure we always write out a commitment_tx_output_idx field,
703 // using `u32::max_value()` as a sentinal to indicate the HTLC was dust.
704 impl Writeable for IrrevocablyResolvedHTLC {
705         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
706                 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::max_value());
707                 write_tlv_fields!(writer, {
708                         (0, mapped_commitment_tx_output_idx, required),
709                         (1, self.resolving_txid, option),
710                         (2, self.payment_preimage, option),
711                         (3, self.resolving_tx, option),
712                 });
713                 Ok(())
714         }
715 }
716
717 impl Readable for IrrevocablyResolvedHTLC {
718         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
719                 let mut mapped_commitment_tx_output_idx = 0;
720                 let mut resolving_txid = None;
721                 let mut payment_preimage = None;
722                 let mut resolving_tx = None;
723                 read_tlv_fields!(reader, {
724                         (0, mapped_commitment_tx_output_idx, required),
725                         (1, resolving_txid, option),
726                         (2, payment_preimage, option),
727                         (3, resolving_tx, option),
728                 });
729                 Ok(Self {
730                         commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::max_value() { None } else { Some(mapped_commitment_tx_output_idx) },
731                         resolving_txid,
732                         payment_preimage,
733                         resolving_tx,
734                 })
735         }
736 }
737
738 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
739 /// on-chain transactions to ensure no loss of funds occurs.
740 ///
741 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
742 /// information and are actively monitoring the chain.
743 ///
744 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
745 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
746 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
747 /// returned block hash and the the current chain and then reconnecting blocks to get to the
748 /// best chain) upon deserializing the object!
749 pub struct ChannelMonitor<Signer: WriteableEcdsaChannelSigner> {
750         #[cfg(test)]
751         pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
752         #[cfg(not(test))]
753         pub(super) inner: Mutex<ChannelMonitorImpl<Signer>>,
754 }
755
756 impl<Signer: WriteableEcdsaChannelSigner> Clone for ChannelMonitor<Signer> where Signer: Clone {
757         fn clone(&self) -> Self {
758                 let inner = self.inner.lock().unwrap().clone();
759                 ChannelMonitor::from_impl(inner)
760         }
761 }
762
763 #[derive(Clone, PartialEq)]
764 pub(crate) struct ChannelMonitorImpl<Signer: WriteableEcdsaChannelSigner> {
765         latest_update_id: u64,
766         commitment_transaction_number_obscure_factor: u64,
767
768         destination_script: ScriptBuf,
769         broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
770         counterparty_payment_script: ScriptBuf,
771         shutdown_script: Option<ScriptBuf>,
772
773         channel_keys_id: [u8; 32],
774         holder_revocation_basepoint: RevocationBasepoint,
775         funding_info: (OutPoint, ScriptBuf),
776         current_counterparty_commitment_txid: Option<Txid>,
777         prev_counterparty_commitment_txid: Option<Txid>,
778
779         counterparty_commitment_params: CounterpartyCommitmentParameters,
780         funding_redeemscript: ScriptBuf,
781         channel_value_satoshis: u64,
782         // first is the idx of the first of the two per-commitment points
783         their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
784
785         on_holder_tx_csv: u16,
786
787         commitment_secrets: CounterpartyCommitmentSecrets,
788         /// The set of outpoints in each counterparty commitment transaction. We always need at least
789         /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
790         /// transaction broadcast as we need to be able to construct the witness script in all cases.
791         counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
792         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
793         /// Nor can we figure out their commitment numbers without the commitment transaction they are
794         /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
795         /// commitment transactions which we find on-chain, mapping them to the commitment number which
796         /// can be used to derive the revocation key and claim the transactions.
797         counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
798         /// Cache used to make pruning of payment_preimages faster.
799         /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
800         /// counterparty transactions (ie should remain pretty small).
801         /// Serialized to disk but should generally not be sent to Watchtowers.
802         counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
803
804         counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
805
806         // We store two holder commitment transactions to avoid any race conditions where we may update
807         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
808         // various monitors for one channel being out of sync, and us broadcasting a holder
809         // transaction for which we have deleted claim information on some watchtowers.
810         prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
811         current_holder_commitment_tx: HolderSignedTx,
812
813         // Used just for ChannelManager to make sure it has the latest channel data during
814         // deserialization
815         current_counterparty_commitment_number: u64,
816         // Used just for ChannelManager to make sure it has the latest channel data during
817         // deserialization
818         current_holder_commitment_number: u64,
819
820         /// The set of payment hashes from inbound payments for which we know the preimage. Payment
821         /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
822         /// remote commitment transactions are automatically removed when commitment transactions are
823         /// revoked.
824         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
825
826         // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
827         // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
828         // presumably user implementations thereof as well) where we update the in-memory channel
829         // object, then before the persistence finishes (as it's all under a read-lock), we return
830         // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
831         // the pre-event state here, but have processed the event in the `ChannelManager`.
832         // Note that because the `event_lock` in `ChainMonitor` is only taken in
833         // block/transaction-connected events and *not* during block/transaction-disconnected events,
834         // we further MUST NOT generate events during block/transaction-disconnection.
835         pending_monitor_events: Vec<MonitorEvent>,
836
837         pub(super) pending_events: Vec<Event>,
838         pub(super) is_processing_pending_events: bool,
839
840         // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
841         // which to take actions once they reach enough confirmations. Each entry includes the
842         // transaction's id and the height when the transaction was confirmed on chain.
843         onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
844
845         // If we get serialized out and re-read, we need to make sure that the chain monitoring
846         // interface knows about the TXOs that we want to be notified of spends of. We could probably
847         // be smart and derive them from the above storage fields, but its much simpler and more
848         // Obviously Correct (tm) if we just keep track of them explicitly.
849         outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
850
851         #[cfg(test)]
852         pub onchain_tx_handler: OnchainTxHandler<Signer>,
853         #[cfg(not(test))]
854         onchain_tx_handler: OnchainTxHandler<Signer>,
855
856         // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
857         // channel has been force-closed. After this is set, no further holder commitment transaction
858         // updates may occur, and we panic!() if one is provided.
859         lockdown_from_offchain: bool,
860
861         // Set once we've signed a holder commitment transaction and handed it over to our
862         // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
863         // may occur, and we fail any such monitor updates.
864         //
865         // In case of update rejection due to a locally already signed commitment transaction, we
866         // nevertheless store update content to track in case of concurrent broadcast by another
867         // remote monitor out-of-order with regards to the block view.
868         holder_tx_signed: bool,
869
870         // If a spend of the funding output is seen, we set this to true and reject any further
871         // updates. This prevents any further changes in the offchain state no matter the order
872         // of block connection between ChannelMonitors and the ChannelManager.
873         funding_spend_seen: bool,
874
875         /// Set to `Some` of the confirmed transaction spending the funding input of the channel after
876         /// reaching `ANTI_REORG_DELAY` confirmations.
877         funding_spend_confirmed: Option<Txid>,
878
879         confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
880         /// The set of HTLCs which have been either claimed or failed on chain and have reached
881         /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
882         /// spending CSV for revocable outputs).
883         htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
884
885         /// The set of `SpendableOutput` events which we have already passed upstream to be claimed.
886         /// These are tracked explicitly to ensure that we don't generate the same events redundantly
887         /// if users duplicatively confirm old transactions. Specifically for transactions claiming a
888         /// revoked remote outpoint we otherwise have no tracking at all once they've reached
889         /// [`ANTI_REORG_DELAY`], so we have to track them here.
890         spendable_txids_confirmed: Vec<Txid>,
891
892         // We simply modify best_block in Channel's block_connected so that serialization is
893         // consistent but hopefully the users' copy handles block_connected in a consistent way.
894         // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
895         // their best_block from its state and not based on updated copies that didn't run through
896         // the full block_connected).
897         best_block: BestBlock,
898
899         /// The node_id of our counterparty
900         counterparty_node_id: Option<PublicKey>,
901
902         /// Initial counterparty commmitment data needed to recreate the commitment tx
903         /// in the persistence pipeline for third-party watchtowers. This will only be present on
904         /// monitors created after 0.0.117.
905         ///
906         /// Ordering of tuple data: (their_per_commitment_point, feerate_per_kw, to_broadcaster_sats,
907         /// to_countersignatory_sats)
908         initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
909 }
910
911 /// Transaction outputs to watch for on-chain spends.
912 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
913
914 impl<Signer: WriteableEcdsaChannelSigner> PartialEq for ChannelMonitor<Signer> where Signer: PartialEq {
915         fn eq(&self, other: &Self) -> bool {
916                 // We need some kind of total lockorder. Absent a better idea, we sort by position in
917                 // memory and take locks in that order (assuming that we can't move within memory while a
918                 // lock is held).
919                 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
920                 let a = if ord { self.inner.unsafe_well_ordered_double_lock_self() } else { other.inner.unsafe_well_ordered_double_lock_self() };
921                 let b = if ord { other.inner.unsafe_well_ordered_double_lock_self() } else { self.inner.unsafe_well_ordered_double_lock_self() };
922                 a.eq(&b)
923         }
924 }
925
926 impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
927         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
928                 self.inner.lock().unwrap().write(writer)
929         }
930 }
931
932 // These are also used for ChannelMonitorUpdate, above.
933 const SERIALIZATION_VERSION: u8 = 1;
934 const MIN_SERIALIZATION_VERSION: u8 = 1;
935
936 impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
937         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
938                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
939
940                 self.latest_update_id.write(writer)?;
941
942                 // Set in initial Channel-object creation, so should always be set by now:
943                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
944
945                 self.destination_script.write(writer)?;
946                 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
947                         writer.write_all(&[0; 1])?;
948                         broadcasted_holder_revokable_script.0.write(writer)?;
949                         broadcasted_holder_revokable_script.1.write(writer)?;
950                         broadcasted_holder_revokable_script.2.write(writer)?;
951                 } else {
952                         writer.write_all(&[1; 1])?;
953                 }
954
955                 self.counterparty_payment_script.write(writer)?;
956                 match &self.shutdown_script {
957                         Some(script) => script.write(writer)?,
958                         None => ScriptBuf::new().write(writer)?,
959                 }
960
961                 self.channel_keys_id.write(writer)?;
962                 self.holder_revocation_basepoint.write(writer)?;
963                 writer.write_all(&self.funding_info.0.txid[..])?;
964                 writer.write_all(&self.funding_info.0.index.to_be_bytes())?;
965                 self.funding_info.1.write(writer)?;
966                 self.current_counterparty_commitment_txid.write(writer)?;
967                 self.prev_counterparty_commitment_txid.write(writer)?;
968
969                 self.counterparty_commitment_params.write(writer)?;
970                 self.funding_redeemscript.write(writer)?;
971                 self.channel_value_satoshis.write(writer)?;
972
973                 match self.their_cur_per_commitment_points {
974                         Some((idx, pubkey, second_option)) => {
975                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
976                                 writer.write_all(&pubkey.serialize())?;
977                                 match second_option {
978                                         Some(second_pubkey) => {
979                                                 writer.write_all(&second_pubkey.serialize())?;
980                                         },
981                                         None => {
982                                                 writer.write_all(&[0; 33])?;
983                                         },
984                                 }
985                         },
986                         None => {
987                                 writer.write_all(&byte_utils::be48_to_array(0))?;
988                         },
989                 }
990
991                 writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?;
992
993                 self.commitment_secrets.write(writer)?;
994
995                 macro_rules! serialize_htlc_in_commitment {
996                         ($htlc_output: expr) => {
997                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
998                                 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
999                                 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1000                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1001                                 $htlc_output.transaction_output_index.write(writer)?;
1002                         }
1003                 }
1004
1005                 writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?;
1006                 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
1007                         writer.write_all(&txid[..])?;
1008                         writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1009                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1010                                 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
1011                                                 || Some(**txid) == self.prev_counterparty_commitment_txid,
1012                                         "HTLC Sources for all revoked commitment transactions should be none!");
1013                                 serialize_htlc_in_commitment!(htlc_output);
1014                                 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1015                         }
1016                 }
1017
1018                 writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?;
1019                 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
1020                         writer.write_all(&txid[..])?;
1021                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1022                 }
1023
1024                 writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?;
1025                 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1026                         writer.write_all(&payment_hash.0[..])?;
1027                         writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1028                 }
1029
1030                 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1031                         writer.write_all(&[1; 1])?;
1032                         prev_holder_tx.write(writer)?;
1033                 } else {
1034                         writer.write_all(&[0; 1])?;
1035                 }
1036
1037                 self.current_holder_commitment_tx.write(writer)?;
1038
1039                 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1040                 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1041
1042                 writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?;
1043                 for payment_preimage in self.payment_preimages.values() {
1044                         writer.write_all(&payment_preimage.0[..])?;
1045                 }
1046
1047                 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
1048                         MonitorEvent::HTLCEvent(_) => true,
1049                         MonitorEvent::HolderForceClosed(_) => true,
1050                         _ => false,
1051                 }).count() as u64).to_be_bytes())?;
1052                 for event in self.pending_monitor_events.iter() {
1053                         match event {
1054                                 MonitorEvent::HTLCEvent(upd) => {
1055                                         0u8.write(writer)?;
1056                                         upd.write(writer)?;
1057                                 },
1058                                 MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1059                                 _ => {}, // Covered in the TLV writes below
1060                         }
1061                 }
1062
1063                 writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?;
1064                 for event in self.pending_events.iter() {
1065                         event.write(writer)?;
1066                 }
1067
1068                 self.best_block.block_hash().write(writer)?;
1069                 writer.write_all(&self.best_block.height().to_be_bytes())?;
1070
1071                 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
1072                 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
1073                         entry.write(writer)?;
1074                 }
1075
1076                 (self.outputs_to_watch.len() as u64).write(writer)?;
1077                 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
1078                         txid.write(writer)?;
1079                         (idx_scripts.len() as u64).write(writer)?;
1080                         for (idx, script) in idx_scripts.iter() {
1081                                 idx.write(writer)?;
1082                                 script.write(writer)?;
1083                         }
1084                 }
1085                 self.onchain_tx_handler.write(writer)?;
1086
1087                 self.lockdown_from_offchain.write(writer)?;
1088                 self.holder_tx_signed.write(writer)?;
1089
1090                 write_tlv_fields!(writer, {
1091                         (1, self.funding_spend_confirmed, option),
1092                         (3, self.htlcs_resolved_on_chain, required_vec),
1093                         (5, self.pending_monitor_events, required_vec),
1094                         (7, self.funding_spend_seen, required),
1095                         (9, self.counterparty_node_id, option),
1096                         (11, self.confirmed_commitment_tx_counterparty_output, option),
1097                         (13, self.spendable_txids_confirmed, required_vec),
1098                         (15, self.counterparty_fulfilled_htlcs, required),
1099                         (17, self.initial_counterparty_commitment_info, option),
1100                 });
1101
1102                 Ok(())
1103         }
1104 }
1105
1106 macro_rules! _process_events_body {
1107         ($self_opt: expr, $event_to_handle: expr, $handle_event: expr) => {
1108                 loop {
1109                         let (pending_events, repeated_events);
1110                         if let Some(us) = $self_opt {
1111                                 let mut inner = us.inner.lock().unwrap();
1112                                 if inner.is_processing_pending_events {
1113                                         break;
1114                                 }
1115                                 inner.is_processing_pending_events = true;
1116
1117                                 pending_events = inner.pending_events.clone();
1118                                 repeated_events = inner.get_repeated_events();
1119                         } else { break; }
1120                         let num_events = pending_events.len();
1121
1122                         for event in pending_events.into_iter().chain(repeated_events.into_iter()) {
1123                                 $event_to_handle = event;
1124                                 $handle_event;
1125                         }
1126
1127                         if let Some(us) = $self_opt {
1128                                 let mut inner = us.inner.lock().unwrap();
1129                                 inner.pending_events.drain(..num_events);
1130                                 inner.is_processing_pending_events = false;
1131                                 if !inner.pending_events.is_empty() {
1132                                         // If there's more events to process, go ahead and do so.
1133                                         continue;
1134                                 }
1135                         }
1136                         break;
1137                 }
1138         }
1139 }
1140 pub(super) use _process_events_body as process_events_body;
1141
1142 pub(crate) struct WithChannelMonitor<'a, L: Deref> where L::Target: Logger {
1143         logger: &'a L,
1144         peer_id: Option<PublicKey>,
1145         channel_id: Option<ChannelId>,
1146 }
1147
1148 impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger {
1149         fn log(&self, mut record: Record) {
1150                 record.peer_id = self.peer_id;
1151                 record.channel_id = self.channel_id;
1152                 self.logger.log(record)
1153         }
1154 }
1155
1156 impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger {
1157         pub(crate) fn from<S: WriteableEcdsaChannelSigner>(logger: &'a L, monitor: &ChannelMonitor<S>) -> Self {
1158                 Self::from_impl(logger, &*monitor.inner.lock().unwrap())
1159         }
1160
1161         pub(crate) fn from_impl<S: WriteableEcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>) -> Self {
1162                 let peer_id = monitor_impl.counterparty_node_id;
1163                 let channel_id = Some(monitor_impl.funding_info.0.to_channel_id());
1164                 WithChannelMonitor {
1165                         logger, peer_id, channel_id,
1166                 }
1167         }
1168 }
1169
1170 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1171         /// For lockorder enforcement purposes, we need to have a single site which constructs the
1172         /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1173         /// PartialEq implementation) we may decide a lockorder violation has occurred.
1174         fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1175                 ChannelMonitor { inner: Mutex::new(imp) }
1176         }
1177
1178         pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1179                           on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, ScriptBuf),
1180                           channel_parameters: &ChannelTransactionParameters,
1181                           funding_redeemscript: ScriptBuf, channel_value_satoshis: u64,
1182                           commitment_transaction_number_obscure_factor: u64,
1183                           initial_holder_commitment_tx: HolderCommitmentTransaction,
1184                           best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
1185
1186                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1187                 let counterparty_payment_script = chan_utils::get_counterparty_payment_script(
1188                         &channel_parameters.channel_type_features, &keys.pubkeys().payment_point
1189                 );
1190
1191                 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1192                 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1193                 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1194                 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1195
1196                 let channel_keys_id = keys.channel_keys_id();
1197                 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1198
1199                 // block for Rust 1.34 compat
1200                 let (holder_commitment_tx, current_holder_commitment_number) = {
1201                         let trusted_tx = initial_holder_commitment_tx.trust();
1202                         let txid = trusted_tx.txid();
1203
1204                         let tx_keys = trusted_tx.keys();
1205                         let holder_commitment_tx = HolderSignedTx {
1206                                 txid,
1207                                 revocation_key: tx_keys.revocation_key,
1208                                 a_htlc_key: tx_keys.broadcaster_htlc_key,
1209                                 b_htlc_key: tx_keys.countersignatory_htlc_key,
1210                                 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1211                                 per_commitment_point: tx_keys.per_commitment_point,
1212                                 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1213                                 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1214                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
1215                         };
1216                         (holder_commitment_tx, trusted_tx.commitment_number())
1217                 };
1218
1219                 let onchain_tx_handler = OnchainTxHandler::new(
1220                         channel_value_satoshis, channel_keys_id, destination_script.into(), keys,
1221                         channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx
1222                 );
1223
1224                 let mut outputs_to_watch = HashMap::new();
1225                 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1226
1227                 Self::from_impl(ChannelMonitorImpl {
1228                         latest_update_id: 0,
1229                         commitment_transaction_number_obscure_factor,
1230
1231                         destination_script: destination_script.into(),
1232                         broadcasted_holder_revokable_script: None,
1233                         counterparty_payment_script,
1234                         shutdown_script,
1235
1236                         channel_keys_id,
1237                         holder_revocation_basepoint,
1238                         funding_info,
1239                         current_counterparty_commitment_txid: None,
1240                         prev_counterparty_commitment_txid: None,
1241
1242                         counterparty_commitment_params,
1243                         funding_redeemscript,
1244                         channel_value_satoshis,
1245                         their_cur_per_commitment_points: None,
1246
1247                         on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1248
1249                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1250                         counterparty_claimable_outpoints: HashMap::new(),
1251                         counterparty_commitment_txn_on_chain: HashMap::new(),
1252                         counterparty_hash_commitment_number: HashMap::new(),
1253                         counterparty_fulfilled_htlcs: HashMap::new(),
1254
1255                         prev_holder_signed_commitment_tx: None,
1256                         current_holder_commitment_tx: holder_commitment_tx,
1257                         current_counterparty_commitment_number: 1 << 48,
1258                         current_holder_commitment_number,
1259
1260                         payment_preimages: HashMap::new(),
1261                         pending_monitor_events: Vec::new(),
1262                         pending_events: Vec::new(),
1263                         is_processing_pending_events: false,
1264
1265                         onchain_events_awaiting_threshold_conf: Vec::new(),
1266                         outputs_to_watch,
1267
1268                         onchain_tx_handler,
1269
1270                         lockdown_from_offchain: false,
1271                         holder_tx_signed: false,
1272                         funding_spend_seen: false,
1273                         funding_spend_confirmed: None,
1274                         confirmed_commitment_tx_counterparty_output: None,
1275                         htlcs_resolved_on_chain: Vec::new(),
1276                         spendable_txids_confirmed: Vec::new(),
1277
1278                         best_block,
1279                         counterparty_node_id: Some(counterparty_node_id),
1280                         initial_counterparty_commitment_info: None,
1281                 })
1282         }
1283
1284         #[cfg(test)]
1285         fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1286                 self.inner.lock().unwrap().provide_secret(idx, secret)
1287         }
1288
1289         /// A variant of `Self::provide_latest_counterparty_commitment_tx` used to provide
1290         /// additional information to the monitor to store in order to recreate the initial
1291         /// counterparty commitment transaction during persistence (mainly for use in third-party
1292         /// watchtowers).
1293         ///
1294         /// This is used to provide the counterparty commitment information directly to the monitor
1295         /// before the initial persistence of a new channel.
1296         pub(crate) fn provide_initial_counterparty_commitment_tx<L: Deref>(
1297                 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1298                 commitment_number: u64, their_cur_per_commitment_point: PublicKey, feerate_per_kw: u32,
1299                 to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, logger: &L,
1300         )
1301         where L::Target: Logger
1302         {
1303                 let mut inner = self.inner.lock().unwrap();
1304                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1305                 inner.provide_initial_counterparty_commitment_tx(txid,
1306                         htlc_outputs, commitment_number, their_cur_per_commitment_point, feerate_per_kw,
1307                         to_broadcaster_value_sat, to_countersignatory_value_sat, &logger);
1308         }
1309
1310         /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1311         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1312         /// possibly future revocation/preimage information) to claim outputs where possible.
1313         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1314         #[cfg(test)]
1315         fn provide_latest_counterparty_commitment_tx<L: Deref>(
1316                 &self,
1317                 txid: Txid,
1318                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1319                 commitment_number: u64,
1320                 their_per_commitment_point: PublicKey,
1321                 logger: &L,
1322         ) where L::Target: Logger {
1323                 let mut inner = self.inner.lock().unwrap();
1324                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1325                 inner.provide_latest_counterparty_commitment_tx(
1326                         txid, htlc_outputs, commitment_number, their_per_commitment_point, &logger)
1327         }
1328
1329         #[cfg(test)]
1330         fn provide_latest_holder_commitment_tx(
1331                 &self, holder_commitment_tx: HolderCommitmentTransaction,
1332                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1333         ) -> Result<(), ()> {
1334                 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new()).map_err(|_| ())
1335         }
1336
1337         /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1338         /// off-chain state with a new commitment transaction.
1339         pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1340                 &self,
1341                 payment_hash: &PaymentHash,
1342                 payment_preimage: &PaymentPreimage,
1343                 broadcaster: &B,
1344                 fee_estimator: &LowerBoundedFeeEstimator<F>,
1345                 logger: &L,
1346         ) where
1347                 B::Target: BroadcasterInterface,
1348                 F::Target: FeeEstimator,
1349                 L::Target: Logger,
1350         {
1351                 let mut inner = self.inner.lock().unwrap();
1352                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1353                 inner.provide_payment_preimage(
1354                         payment_hash, payment_preimage, broadcaster, fee_estimator, &logger)
1355         }
1356
1357         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1358         /// itself.
1359         ///
1360         /// panics if the given update is not the next update by update_id.
1361         pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1362                 &self,
1363                 updates: &ChannelMonitorUpdate,
1364                 broadcaster: &B,
1365                 fee_estimator: &F,
1366                 logger: &L,
1367         ) -> Result<(), ()>
1368         where
1369                 B::Target: BroadcasterInterface,
1370                 F::Target: FeeEstimator,
1371                 L::Target: Logger,
1372         {
1373                 let mut inner = self.inner.lock().unwrap();
1374                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1375                 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
1376         }
1377
1378         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1379         /// ChannelMonitor.
1380         pub fn get_latest_update_id(&self) -> u64 {
1381                 self.inner.lock().unwrap().get_latest_update_id()
1382         }
1383
1384         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1385         pub fn get_funding_txo(&self) -> (OutPoint, ScriptBuf) {
1386                 self.inner.lock().unwrap().get_funding_txo().clone()
1387         }
1388
1389         /// Gets a list of txids, with their output scripts (in the order they appear in the
1390         /// transaction), which we must learn about spends of via block_connected().
1391         pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
1392                 self.inner.lock().unwrap().get_outputs_to_watch()
1393                         .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1394         }
1395
1396         /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1397         /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1398         /// have been registered.
1399         pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L) 
1400         where 
1401                 F::Target: chain::Filter, L::Target: Logger,
1402         {
1403                 let lock = self.inner.lock().unwrap();
1404                 let logger = WithChannelMonitor::from_impl(logger, &*lock);
1405                 log_trace!(&logger, "Registering funding outpoint {}", &lock.get_funding_txo().0);
1406                 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1407                 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1408                         for (index, script_pubkey) in outputs.iter() {
1409                                 assert!(*index <= u16::max_value() as u32);
1410                                 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
1411                                 log_trace!(logger, "Registering outpoint {} with the filter for monitoring spends", outpoint);
1412                                 filter.register_output(WatchedOutput {
1413                                         block_hash: None,
1414                                         outpoint,
1415                                         script_pubkey: script_pubkey.clone(),
1416                                 });
1417                         }
1418                 }
1419         }
1420
1421         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1422         /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1423         pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1424                 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1425         }
1426
1427         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
1428         ///
1429         /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
1430         /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
1431         /// within each channel. As the confirmation of a commitment transaction may be critical to the
1432         /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
1433         /// environment with spotty connections, like on mobile.
1434         ///
1435         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
1436         /// order to handle these events.
1437         ///
1438         /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
1439         /// [`BumpTransaction`]: crate::events::Event::BumpTransaction
1440         pub fn process_pending_events<H: Deref>(&self, handler: &H) where H::Target: EventHandler {
1441                 let mut ev;
1442                 process_events_body!(Some(self), ev, handler.handle_event(ev));
1443         }
1444
1445         /// Processes any events asynchronously.
1446         ///
1447         /// See [`Self::process_pending_events`] for more information.
1448         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
1449                 &self, handler: &H
1450         ) {
1451                 let mut ev;
1452                 process_events_body!(Some(self), ev, { handler(ev).await });
1453         }
1454
1455         #[cfg(test)]
1456         pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1457                 let mut ret = Vec::new();
1458                 let mut lck = self.inner.lock().unwrap();
1459                 mem::swap(&mut ret, &mut lck.pending_events);
1460                 ret.append(&mut lck.get_repeated_events());
1461                 ret
1462         }
1463
1464         /// Gets the counterparty's initial commitment transaction. The returned commitment
1465         /// transaction is unsigned. This is intended to be called during the initial persistence of
1466         /// the monitor (inside an implementation of [`Persist::persist_new_channel`]), to allow for
1467         /// watchtowers in the persistence pipeline to have enough data to form justice transactions.
1468         ///
1469         /// This is similar to [`Self::counterparty_commitment_txs_from_update`], except
1470         /// that for the initial commitment transaction, we don't have a corresponding update.
1471         ///
1472         /// This will only return `Some` for channel monitors that have been created after upgrading
1473         /// to LDK 0.0.117+.
1474         ///
1475         /// [`Persist::persist_new_channel`]: crate::chain::chainmonitor::Persist::persist_new_channel
1476         pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
1477                 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
1478         }
1479
1480         /// Gets all of the counterparty commitment transactions provided by the given update. This
1481         /// may be empty if the update doesn't include any new counterparty commitments. Returned
1482         /// commitment transactions are unsigned.
1483         ///
1484         /// This is provided so that watchtower clients in the persistence pipeline are able to build
1485         /// justice transactions for each counterparty commitment upon each update. It's intended to be
1486         /// used within an implementation of [`Persist::update_persisted_channel`], which is provided
1487         /// with a monitor and an update. Once revoked, signing a justice transaction can be done using
1488         /// [`Self::sign_to_local_justice_tx`].
1489         ///
1490         /// It is expected that a watchtower client may use this method to retrieve the latest counterparty
1491         /// commitment transaction(s), and then hold the necessary data until a later update in which
1492         /// the monitor has been updated with the corresponding revocation data, at which point the
1493         /// monitor can sign the justice transaction.
1494         ///
1495         /// This will only return a non-empty list for monitor updates that have been created after
1496         /// upgrading to LDK 0.0.117+. Note that no restriction lies on the monitors themselves, which
1497         /// may have been created prior to upgrading.
1498         ///
1499         /// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel
1500         pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
1501                 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
1502         }
1503
1504         /// Wrapper around [`EcdsaChannelSigner::sign_justice_revoked_output`] to make
1505         /// signing the justice transaction easier for implementors of
1506         /// [`chain::chainmonitor::Persist`]. On success this method returns the provided transaction
1507         /// signing the input at `input_idx`. This method will only produce a valid signature for
1508         /// a transaction spending the `to_local` output of a commitment transaction, i.e. this cannot
1509         /// be used for revoked HTLC outputs.
1510         ///
1511         /// `Value` is the value of the output being spent by the input at `input_idx`, committed
1512         /// in the BIP 143 signature.
1513         ///
1514         /// This method will only succeed if this monitor has received the revocation secret for the
1515         /// provided `commitment_number`. If a commitment number is provided that does not correspond
1516         /// to the commitment transaction being revoked, this will return a signed transaction, but
1517         /// the signature will not be valid.
1518         ///
1519         /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_justice_revoked_output
1520         /// [`Persist`]: crate::chain::chainmonitor::Persist
1521         pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
1522                 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
1523         }
1524
1525         pub(crate) fn get_min_seen_secret(&self) -> u64 {
1526                 self.inner.lock().unwrap().get_min_seen_secret()
1527         }
1528
1529         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1530                 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1531         }
1532
1533         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1534                 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1535         }
1536
1537         /// Gets the `node_id` of the counterparty for this channel.
1538         ///
1539         /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1540         /// otherwise.
1541         pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1542                 self.inner.lock().unwrap().counterparty_node_id
1543         }
1544
1545         /// Used by [`ChannelManager`] deserialization to broadcast the latest holder state if its copy
1546         /// of the channel state was out-of-date.
1547         ///
1548         /// You may also use this to broadcast the latest local commitment transaction, either because
1549         /// a monitor update failed or because we've fallen behind (i.e. we've received proof that our
1550         /// counterparty side knows a revocation secret we gave them that they shouldn't know).
1551         ///
1552         /// Broadcasting these transactions in the second case is UNSAFE, as they allow counterparty
1553         /// side to punish you. Nevertheless you may want to broadcast them if counterparty doesn't
1554         /// close channel with their commitment transaction after a substantial amount of time. Best
1555         /// may be to contact the other node operator out-of-band to coordinate other options available
1556         /// to you.
1557         ///
1558         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1559         pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1560         where L::Target: Logger {
1561                 let mut inner = self.inner.lock().unwrap();
1562                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1563                 inner.get_latest_holder_commitment_txn(&logger)
1564         }
1565
1566         /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1567         /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1568         /// revoked commitment transaction.
1569         #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1570         pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1571         where L::Target: Logger {
1572                 let mut inner = self.inner.lock().unwrap();
1573                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1574                 inner.unsafe_get_latest_holder_commitment_txn(&logger)
1575         }
1576
1577         /// Processes transactions in a newly connected block, which may result in any of the following:
1578         /// - update the monitor's state against resolved HTLCs
1579         /// - punish the counterparty in the case of seeing a revoked commitment transaction
1580         /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1581         /// - detect settled outputs for later spending
1582         /// - schedule and bump any in-flight claims
1583         ///
1584         /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1585         /// [`get_outputs_to_watch`].
1586         ///
1587         /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1588         pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1589                 &self,
1590                 header: &Header,
1591                 txdata: &TransactionData,
1592                 height: u32,
1593                 broadcaster: B,
1594                 fee_estimator: F,
1595                 logger: &L,
1596         ) -> Vec<TransactionOutputs>
1597         where
1598                 B::Target: BroadcasterInterface,
1599                 F::Target: FeeEstimator,
1600                 L::Target: Logger,
1601         {
1602                 let mut inner = self.inner.lock().unwrap();
1603                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1604                 inner.block_connected(
1605                         header, txdata, height, broadcaster, fee_estimator, &logger)
1606         }
1607
1608         /// Determines if the disconnected block contained any transactions of interest and updates
1609         /// appropriately.
1610         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1611                 &self,
1612                 header: &Header,
1613                 height: u32,
1614                 broadcaster: B,
1615                 fee_estimator: F,
1616                 logger: &L,
1617         ) where
1618                 B::Target: BroadcasterInterface,
1619                 F::Target: FeeEstimator,
1620                 L::Target: Logger,
1621         {
1622                 let mut inner = self.inner.lock().unwrap();
1623                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1624                 inner.block_disconnected(
1625                         header, height, broadcaster, fee_estimator, &logger)
1626         }
1627
1628         /// Processes transactions confirmed in a block with the given header and height, returning new
1629         /// outputs to watch. See [`block_connected`] for details.
1630         ///
1631         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1632         /// blocks. See [`chain::Confirm`] for calling expectations.
1633         ///
1634         /// [`block_connected`]: Self::block_connected
1635         pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1636                 &self,
1637                 header: &Header,
1638                 txdata: &TransactionData,
1639                 height: u32,
1640                 broadcaster: B,
1641                 fee_estimator: F,
1642                 logger: &L,
1643         ) -> Vec<TransactionOutputs>
1644         where
1645                 B::Target: BroadcasterInterface,
1646                 F::Target: FeeEstimator,
1647                 L::Target: Logger,
1648         {
1649                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1650                 let mut inner = self.inner.lock().unwrap();
1651                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1652                 inner.transactions_confirmed(
1653                         header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
1654         }
1655
1656         /// Processes a transaction that was reorganized out of the chain.
1657         ///
1658         /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1659         /// than blocks. See [`chain::Confirm`] for calling expectations.
1660         ///
1661         /// [`block_disconnected`]: Self::block_disconnected
1662         pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1663                 &self,
1664                 txid: &Txid,
1665                 broadcaster: B,
1666                 fee_estimator: F,
1667                 logger: &L,
1668         ) where
1669                 B::Target: BroadcasterInterface,
1670                 F::Target: FeeEstimator,
1671                 L::Target: Logger,
1672         {
1673                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1674                 let mut inner = self.inner.lock().unwrap();
1675                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1676                 inner.transaction_unconfirmed(
1677                         txid, broadcaster, &bounded_fee_estimator, &logger
1678                 );
1679         }
1680
1681         /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1682         /// [`block_connected`] for details.
1683         ///
1684         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1685         /// blocks. See [`chain::Confirm`] for calling expectations.
1686         ///
1687         /// [`block_connected`]: Self::block_connected
1688         pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1689                 &self,
1690                 header: &Header,
1691                 height: u32,
1692                 broadcaster: B,
1693                 fee_estimator: F,
1694                 logger: &L,
1695         ) -> Vec<TransactionOutputs>
1696         where
1697                 B::Target: BroadcasterInterface,
1698                 F::Target: FeeEstimator,
1699                 L::Target: Logger,
1700         {
1701                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1702                 let mut inner = self.inner.lock().unwrap();
1703                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1704                 inner.best_block_updated(
1705                         header, height, broadcaster, &bounded_fee_estimator, &logger
1706                 )
1707         }
1708
1709         /// Returns the set of txids that should be monitored for re-organization out of the chain.
1710         pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
1711                 let inner = self.inner.lock().unwrap();
1712                 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
1713                         .iter()
1714                         .map(|entry| (entry.txid, entry.height, entry.block_hash))
1715                         .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1716                         .collect();
1717                 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
1718                 txids.dedup_by_key(|(txid, _, _)| *txid);
1719                 txids
1720         }
1721
1722         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1723         /// [`chain::Confirm`] interfaces.
1724         pub fn current_best_block(&self) -> BestBlock {
1725                 self.inner.lock().unwrap().best_block.clone()
1726         }
1727
1728         /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
1729         /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
1730         /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
1731         /// invoking this every 30 seconds, or lower if running in an environment with spotty
1732         /// connections, like on mobile.
1733         pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
1734                 &self, broadcaster: B, fee_estimator: F, logger: &L,
1735         )
1736         where
1737                 B::Target: BroadcasterInterface,
1738                 F::Target: FeeEstimator,
1739                 L::Target: Logger,
1740         {
1741                 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1742                 let mut inner = self.inner.lock().unwrap();
1743                 let logger = WithChannelMonitor::from_impl(logger, &*inner);
1744                 let current_height = inner.best_block.height;
1745                 inner.onchain_tx_handler.rebroadcast_pending_claims(
1746                         current_height, &broadcaster, &fee_estimator, &logger,
1747                 );
1748         }
1749
1750         /// Returns the descriptors for relevant outputs (i.e., those that we can spend) within the
1751         /// transaction if they exist and the transaction has at least [`ANTI_REORG_DELAY`]
1752         /// confirmations. For [`SpendableOutputDescriptor::DelayedPaymentOutput`] descriptors to be
1753         /// returned, the transaction must have at least `max(ANTI_REORG_DELAY, to_self_delay)`
1754         /// confirmations.
1755         ///
1756         /// Descriptors returned by this method are primarily exposed via [`Event::SpendableOutputs`]
1757         /// once they are no longer under reorg risk. This method serves as a way to retrieve these
1758         /// descriptors at a later time, either for historical purposes, or to replay any
1759         /// missed/unhandled descriptors. For the purpose of gathering historical records, if the
1760         /// channel close has fully resolved (i.e., [`ChannelMonitor::get_claimable_balances`] returns
1761         /// an empty set), you can retrieve all spendable outputs by providing all descendant spending
1762         /// transactions starting from the channel's funding transaction and going down three levels.
1763         ///
1764         /// `tx` is a transaction we'll scan the outputs of. Any transaction can be provided. If any
1765         /// outputs which can be spent by us are found, at least one descriptor is returned.
1766         ///
1767         /// `confirmation_height` must be the height of the block in which `tx` was included in.
1768         pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
1769                 let inner = self.inner.lock().unwrap();
1770                 let current_height = inner.best_block.height;
1771                 let mut spendable_outputs = inner.get_spendable_outputs(tx);
1772                 spendable_outputs.retain(|descriptor| {
1773                         let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
1774                         if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
1775                                 conf_threshold = cmp::min(conf_threshold,
1776                                         current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
1777                         }
1778                         conf_threshold >= confirmation_height
1779                 });
1780                 spendable_outputs
1781         }
1782
1783         #[cfg(test)]
1784         pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
1785                 self.inner.lock().unwrap().counterparty_payment_script.clone()
1786         }
1787
1788         #[cfg(test)]
1789         pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
1790                 self.inner.lock().unwrap().counterparty_payment_script = script;
1791         }
1792 }
1793
1794 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
1795         /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1796         /// to one `Balance` for the HTLC.
1797         fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1798                 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1799         -> Option<Balance> {
1800                 let htlc_commitment_tx_output_idx =
1801                         if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1802
1803                 let mut htlc_spend_txid_opt = None;
1804                 let mut htlc_spend_tx_opt = None;
1805                 let mut holder_timeout_spend_pending = None;
1806                 let mut htlc_spend_pending = None;
1807                 let mut holder_delayed_output_pending = None;
1808                 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1809                         match event.event {
1810                                 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1811                                 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1812                                         debug_assert!(htlc_spend_txid_opt.is_none());
1813                                         htlc_spend_txid_opt = Some(&event.txid);
1814                                         debug_assert!(htlc_spend_tx_opt.is_none());
1815                                         htlc_spend_tx_opt = event.transaction.as_ref();
1816                                         debug_assert!(holder_timeout_spend_pending.is_none());
1817                                         debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1818                                         holder_timeout_spend_pending = Some(event.confirmation_threshold());
1819                                 },
1820                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1821                                 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1822                                         debug_assert!(htlc_spend_txid_opt.is_none());
1823                                         htlc_spend_txid_opt = Some(&event.txid);
1824                                         debug_assert!(htlc_spend_tx_opt.is_none());
1825                                         htlc_spend_tx_opt = event.transaction.as_ref();
1826                                         debug_assert!(htlc_spend_pending.is_none());
1827                                         htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1828                                 },
1829                                 OnchainEvent::MaturingOutput {
1830                                         descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1831                                 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
1832                                         .any(|(input_idx, inp)|
1833                                                  Some(inp.previous_output.txid) == confirmed_txid &&
1834                                                         inp.previous_output.vout == htlc_commitment_tx_output_idx &&
1835                                                                 // A maturing output for an HTLC claim will always be at the same
1836                                                                 // index as the HTLC input. This is true pre-anchors, as there's
1837                                                                 // only 1 input and 1 output. This is also true post-anchors,
1838                                                                 // because we have a SIGHASH_SINGLE|ANYONECANPAY signature from our
1839                                                                 // channel counterparty.
1840                                                                 descriptor.outpoint.index as usize == input_idx
1841                                         ))
1842                                         .unwrap_or(false)
1843                                 => {
1844                                         debug_assert!(holder_delayed_output_pending.is_none());
1845                                         holder_delayed_output_pending = Some(event.confirmation_threshold());
1846                                 },
1847                                 _ => {},
1848                         }
1849                 }
1850                 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1851                         .find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
1852                                 debug_assert!(htlc_spend_txid_opt.is_none());
1853                                 htlc_spend_txid_opt = v.resolving_txid.as_ref();
1854                                 debug_assert!(htlc_spend_tx_opt.is_none());
1855                                 htlc_spend_tx_opt = v.resolving_tx.as_ref();
1856                                 true
1857                         } else { false });
1858                 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1859
1860                 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
1861                 let htlc_output_to_spend =
1862                         if let Some(txid) = htlc_spend_txid_opt {
1863                                 // Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
1864                                 // are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
1865                                 // locate the correct output by ensuring its adjacent input spends the HTLC output
1866                                 // in the commitment.
1867                                 if let Some(ref tx) = htlc_spend_tx_opt {
1868                                         let htlc_input_idx_opt = tx.input.iter().enumerate()
1869                                                 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
1870                                                 .map(|(idx, _)| idx as u32);
1871                                         debug_assert!(htlc_input_idx_opt.is_some());
1872                                         BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
1873                                 } else {
1874                                         debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
1875                                         BitcoinOutPoint::new(*txid, 0)
1876                                 }
1877                         } else {
1878                                 htlc_commitment_outpoint
1879                         };
1880                 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1881
1882                 if let Some(conf_thresh) = holder_delayed_output_pending {
1883                         debug_assert!(holder_commitment);
1884                         return Some(Balance::ClaimableAwaitingConfirmations {
1885                                 amount_satoshis: htlc.amount_msat / 1000,
1886                                 confirmation_height: conf_thresh,
1887                         });
1888                 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
1889                         // Funding transaction spends should be fully confirmed by the time any
1890                         // HTLC transactions are resolved, unless we're talking about a holder
1891                         // commitment tx, whose resolution is delayed until the CSV timeout is
1892                         // reached, even though HTLCs may be resolved after only
1893                         // ANTI_REORG_DELAY confirmations.
1894                         debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
1895                 } else if counterparty_revoked_commitment {
1896                         let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1897                                 if let OnchainEvent::MaturingOutput {
1898                                         descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1899                                 } = &event.event {
1900                                         if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1901                                                 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1902                                                         tx.txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
1903                                                 } else {
1904                                                         Some(inp.previous_output.txid) == confirmed_txid &&
1905                                                                 inp.previous_output.vout == htlc_commitment_tx_output_idx
1906                                                 }
1907                                         })).unwrap_or(false) {
1908                                                 Some(())
1909                                         } else { None }
1910                                 } else { None }
1911                         });
1912                         if htlc_output_claim_pending.is_some() {
1913                                 // We already push `Balance`s onto the `res` list for every
1914                                 // `StaticOutput` in a `MaturingOutput` in the revoked
1915                                 // counterparty commitment transaction case generally, so don't
1916                                 // need to do so again here.
1917                         } else {
1918                                 debug_assert!(holder_timeout_spend_pending.is_none(),
1919                                         "HTLCUpdate OnchainEvents should never appear for preimage claims");
1920                                 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1921                                         "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1922                                 return Some(Balance::CounterpartyRevokedOutputClaimable {
1923                                         amount_satoshis: htlc.amount_msat / 1000,
1924                                 });
1925                         }
1926                 } else if htlc.offered == holder_commitment {
1927                         // If the payment was outbound, check if there's an HTLCUpdate
1928                         // indicating we have spent this HTLC with a timeout, claiming it back
1929                         // and awaiting confirmations on it.
1930                         if let Some(conf_thresh) = holder_timeout_spend_pending {
1931                                 return Some(Balance::ClaimableAwaitingConfirmations {
1932                                         amount_satoshis: htlc.amount_msat / 1000,
1933                                         confirmation_height: conf_thresh,
1934                                 });
1935                         } else {
1936                                 return Some(Balance::MaybeTimeoutClaimableHTLC {
1937                                         amount_satoshis: htlc.amount_msat / 1000,
1938                                         claimable_height: htlc.cltv_expiry,
1939                                         payment_hash: htlc.payment_hash,
1940                                 });
1941                         }
1942                 } else if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1943                         // Otherwise (the payment was inbound), only expose it as claimable if
1944                         // we know the preimage.
1945                         // Note that if there is a pending claim, but it did not use the
1946                         // preimage, we lost funds to our counterparty! We will then continue
1947                         // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1948                         debug_assert!(holder_timeout_spend_pending.is_none());
1949                         if let Some((conf_thresh, true)) = htlc_spend_pending {
1950                                 return Some(Balance::ClaimableAwaitingConfirmations {
1951                                         amount_satoshis: htlc.amount_msat / 1000,
1952                                         confirmation_height: conf_thresh,
1953                                 });
1954                         } else {
1955                                 return Some(Balance::ContentiousClaimable {
1956                                         amount_satoshis: htlc.amount_msat / 1000,
1957                                         timeout_height: htlc.cltv_expiry,
1958                                         payment_hash: htlc.payment_hash,
1959                                         payment_preimage: *payment_preimage,
1960                                 });
1961                         }
1962                 } else if htlc_resolved.is_none() {
1963                         return Some(Balance::MaybePreimageClaimableHTLC {
1964                                 amount_satoshis: htlc.amount_msat / 1000,
1965                                 expiry_height: htlc.cltv_expiry,
1966                                 payment_hash: htlc.payment_hash,
1967                         });
1968                 }
1969                 None
1970         }
1971 }
1972
1973 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1974         /// Gets the balances in this channel which are either claimable by us if we were to
1975         /// force-close the channel now or which are claimable on-chain (possibly awaiting
1976         /// confirmation).
1977         ///
1978         /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1979         /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1980         /// balance, or until our counterparty has claimed the balance and accrued several
1981         /// confirmations on the claim transaction.
1982         ///
1983         /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1984         /// LDK prior to 0.0.111, not all or excess balances may be included.
1985         ///
1986         /// See [`Balance`] for additional details on the types of claimable balances which
1987         /// may be returned here and their meanings.
1988         pub fn get_claimable_balances(&self) -> Vec<Balance> {
1989                 let mut res = Vec::new();
1990                 let us = self.inner.lock().unwrap();
1991
1992                 let mut confirmed_txid = us.funding_spend_confirmed;
1993                 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
1994                 let mut pending_commitment_tx_conf_thresh = None;
1995                 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1996                         if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1997                                 event.event
1998                         {
1999                                 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2000                                 Some((event.txid, event.confirmation_threshold()))
2001                         } else { None }
2002                 });
2003                 if let Some((txid, conf_thresh)) = funding_spend_pending {
2004                         debug_assert!(us.funding_spend_confirmed.is_none(),
2005                                 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2006                         confirmed_txid = Some(txid);
2007                         pending_commitment_tx_conf_thresh = Some(conf_thresh);
2008                 }
2009
2010                 macro_rules! walk_htlcs {
2011                         ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2012                                 for htlc in $htlc_iter {
2013                                         if htlc.transaction_output_index.is_some() {
2014
2015                                                 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
2016                                                         res.push(bal);
2017                                                 }
2018                                         }
2019                                 }
2020                         }
2021                 }
2022
2023                 if let Some(txid) = confirmed_txid {
2024                         let mut found_commitment_tx = false;
2025                         if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
2026                                 // First look for the to_remote output back to us.
2027                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2028                                         if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2029                                                 if let OnchainEvent::MaturingOutput {
2030                                                         descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2031                                                 } = &event.event {
2032                                                         Some(descriptor.output.value)
2033                                                 } else { None }
2034                                         }) {
2035                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2036                                                         amount_satoshis: value,
2037                                                         confirmation_height: conf_thresh,
2038                                                 });
2039                                         } else {
2040                                                 // If a counterparty commitment transaction is awaiting confirmation, we
2041                                                 // should either have a StaticPaymentOutput MaturingOutput event awaiting
2042                                                 // confirmation with the same height or have never met our dust amount.
2043                                         }
2044                                 }
2045                                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2046                                         walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2047                                 } else {
2048                                         walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2049                                         // The counterparty broadcasted a revoked state!
2050                                         // Look for any StaticOutputs first, generating claimable balances for those.
2051                                         // If any match the confirmed counterparty revoked to_self output, skip
2052                                         // generating a CounterpartyRevokedOutputClaimable.
2053                                         let mut spent_counterparty_output = false;
2054                                         for event in us.onchain_events_awaiting_threshold_conf.iter() {
2055                                                 if let OnchainEvent::MaturingOutput {
2056                                                         descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
2057                                                 } = &event.event {
2058                                                         res.push(Balance::ClaimableAwaitingConfirmations {
2059                                                                 amount_satoshis: output.value,
2060                                                                 confirmation_height: event.confirmation_threshold(),
2061                                                         });
2062                                                         if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
2063                                                                 if event.transaction.as_ref().map(|tx|
2064                                                                         tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
2065                                                                 ).unwrap_or(false) {
2066                                                                         spent_counterparty_output = true;
2067                                                                 }
2068                                                         }
2069                                                 }
2070                                         }
2071
2072                                         if spent_counterparty_output {
2073                                         } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
2074                                                 let output_spendable = us.onchain_tx_handler
2075                                                         .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
2076                                                 if output_spendable {
2077                                                         res.push(Balance::CounterpartyRevokedOutputClaimable {
2078                                                                 amount_satoshis: amt,
2079                                                         });
2080                                                 }
2081                                         } else {
2082                                                 // Counterparty output is missing, either it was broadcasted on a
2083                                                 // previous version of LDK or the counterparty hadn't met dust.
2084                                         }
2085                                 }
2086                                 found_commitment_tx = true;
2087                         } else if txid == us.current_holder_commitment_tx.txid {
2088                                 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
2089                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2090                                         res.push(Balance::ClaimableAwaitingConfirmations {
2091                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2092                                                 confirmation_height: conf_thresh,
2093                                         });
2094                                 }
2095                                 found_commitment_tx = true;
2096                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2097                                 if txid == prev_commitment.txid {
2098                                         walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
2099                                         if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2100                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2101                                                         amount_satoshis: prev_commitment.to_self_value_sat,
2102                                                         confirmation_height: conf_thresh,
2103                                                 });
2104                                         }
2105                                         found_commitment_tx = true;
2106                                 }
2107                         }
2108                         if !found_commitment_tx {
2109                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2110                                         // We blindly assume this is a cooperative close transaction here, and that
2111                                         // neither us nor our counterparty misbehaved. At worst we've under-estimated
2112                                         // the amount we can claim as we'll punish a misbehaving counterparty.
2113                                         res.push(Balance::ClaimableAwaitingConfirmations {
2114                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2115                                                 confirmation_height: conf_thresh,
2116                                         });
2117                                 }
2118                         }
2119                 } else {
2120                         let mut claimable_inbound_htlc_value_sat = 0;
2121                         for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
2122                                 if htlc.transaction_output_index.is_none() { continue; }
2123                                 if htlc.offered {
2124                                         res.push(Balance::MaybeTimeoutClaimableHTLC {
2125                                                 amount_satoshis: htlc.amount_msat / 1000,
2126                                                 claimable_height: htlc.cltv_expiry,
2127                                                 payment_hash: htlc.payment_hash,
2128                                         });
2129                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
2130                                         claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
2131                                 } else {
2132                                         // As long as the HTLC is still in our latest commitment state, treat
2133                                         // it as potentially claimable, even if it has long-since expired.
2134                                         res.push(Balance::MaybePreimageClaimableHTLC {
2135                                                 amount_satoshis: htlc.amount_msat / 1000,
2136                                                 expiry_height: htlc.cltv_expiry,
2137                                                 payment_hash: htlc.payment_hash,
2138                                         });
2139                                 }
2140                         }
2141                         res.push(Balance::ClaimableOnChannelClose {
2142                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
2143                         });
2144                 }
2145
2146                 res
2147         }
2148
2149         /// Gets the set of outbound HTLCs which can be (or have been) resolved by this
2150         /// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
2151         /// to the `ChannelManager` having been persisted.
2152         ///
2153         /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes
2154         /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
2155         /// event from this `ChannelMonitor`).
2156         pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2157                 let mut res = HashMap::new();
2158                 // Just examine the available counterparty commitment transactions. See docs on
2159                 // `fail_unbroadcast_htlcs`, below, for justification.
2160                 let us = self.inner.lock().unwrap();
2161                 macro_rules! walk_counterparty_commitment {
2162                         ($txid: expr) => {
2163                                 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
2164                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2165                                                 if let &Some(ref source) = source_option {
2166                                                         res.insert((**source).clone(), (htlc.clone(),
2167                                                                 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned()));
2168                                                 }
2169                                         }
2170                                 }
2171                         }
2172                 }
2173                 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2174                         walk_counterparty_commitment!(txid);
2175                 }
2176                 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2177                         walk_counterparty_commitment!(txid);
2178                 }
2179                 res
2180         }
2181
2182         /// Gets the set of outbound HTLCs which are pending resolution in this channel or which were
2183         /// resolved with a preimage from our counterparty.
2184         ///
2185         /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
2186         ///
2187         /// Currently, the preimage is unused, however if it is present in the relevant internal state
2188         /// an HTLC is always included even if it has been resolved.
2189         pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2190                 let us = self.inner.lock().unwrap();
2191                 // We're only concerned with the confirmation count of HTLC transactions, and don't
2192                 // actually care how many confirmations a commitment transaction may or may not have. Thus,
2193                 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
2194                 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2195                         us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2196                                 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2197                                         Some(event.txid)
2198                                 } else { None }
2199                         })
2200                 });
2201
2202                 if confirmed_txid.is_none() {
2203                         // If we have not seen a commitment transaction on-chain (ie the channel is not yet
2204                         // closed), just get the full set.
2205                         mem::drop(us);
2206                         return self.get_all_current_outbound_htlcs();
2207                 }
2208
2209                 let mut res = HashMap::new();
2210                 macro_rules! walk_htlcs {
2211                         ($holder_commitment: expr, $htlc_iter: expr) => {
2212                                 for (htlc, source) in $htlc_iter {
2213                                         if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc.transaction_output_index) {
2214                                                 // We should assert that funding_spend_confirmed is_some() here, but we
2215                                                 // have some unit tests which violate HTLC transaction CSVs entirely and
2216                                                 // would fail.
2217                                                 // TODO: Once tests all connect transactions at consensus-valid times, we
2218                                                 // should assert here like we do in `get_claimable_balances`.
2219                                         } else if htlc.offered == $holder_commitment {
2220                                                 // If the payment was outbound, check if there's an HTLCUpdate
2221                                                 // indicating we have spent this HTLC with a timeout, claiming it back
2222                                                 // and awaiting confirmations on it.
2223                                                 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2224                                                         if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
2225                                                                 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
2226                                                                 // before considering it "no longer pending" - this matches when we
2227                                                                 // provide the ChannelManager an HTLC failure event.
2228                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
2229                                                                         us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
2230                                                         } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
2231                                                                 // If the HTLC was fulfilled with a preimage, we consider the HTLC
2232                                                                 // immediately non-pending, matching when we provide ChannelManager
2233                                                                 // the preimage.
2234                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index
2235                                                         } else { false }
2236                                                 });
2237                                                 let counterparty_resolved_preimage_opt =
2238                                                         us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned();
2239                                                 if !htlc_update_confd || counterparty_resolved_preimage_opt.is_some() {
2240                                                         res.insert(source.clone(), (htlc.clone(), counterparty_resolved_preimage_opt));
2241                                                 }
2242                                         }
2243                                 }
2244                         }
2245                 }
2246
2247                 let txid = confirmed_txid.unwrap();
2248                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2249                         walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
2250                                 if let &Some(ref source) = b {
2251                                         Some((a, &**source))
2252                                 } else { None }
2253                         }));
2254                 } else if txid == us.current_holder_commitment_tx.txid {
2255                         walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
2256                                 if let Some(source) = c { Some((a, source)) } else { None }
2257                         }));
2258                 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2259                         if txid == prev_commitment.txid {
2260                                 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
2261                                         if let Some(source) = c { Some((a, source)) } else { None }
2262                                 }));
2263                         }
2264                 }
2265
2266                 res
2267         }
2268
2269         pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
2270                 self.inner.lock().unwrap().payment_preimages.clone()
2271         }
2272 }
2273
2274 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
2275 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
2276 /// after ANTI_REORG_DELAY blocks.
2277 ///
2278 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
2279 /// are the commitment transactions which are generated by us. The off-chain state machine in
2280 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
2281 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
2282 /// included in a remote commitment transaction are failed back if they are not present in the
2283 /// broadcasted commitment transaction.
2284 ///
2285 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
2286 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
2287 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
2288 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
2289 macro_rules! fail_unbroadcast_htlcs {
2290         ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2291          $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2292                 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
2293
2294                 macro_rules! check_htlc_fails {
2295                         ($txid: expr, $commitment_tx: expr) => {
2296                                 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
2297                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2298                                                 if let &Some(ref source) = source_option {
2299                                                         // Check if the HTLC is present in the commitment transaction that was
2300                                                         // broadcast, but not if it was below the dust limit, which we should
2301                                                         // fail backwards immediately as there is no way for us to learn the
2302                                                         // payment_preimage.
2303                                                         // Note that if the dust limit were allowed to change between
2304                                                         // commitment transactions we'd want to be check whether *any*
2305                                                         // broadcastable commitment transaction has the HTLC in it, but it
2306                                                         // cannot currently change after channel initialization, so we don't
2307                                                         // need to here.
2308                                                         let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2309
2310                                                         let mut matched_htlc = false;
2311                                                         for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2312                                                                 if broadcast_htlc.transaction_output_index.is_some() &&
2313                                                                         (Some(&**source) == *broadcast_source ||
2314                                                                          (broadcast_source.is_none() &&
2315                                                                           broadcast_htlc.payment_hash == htlc.payment_hash &&
2316                                                                           broadcast_htlc.amount_msat == htlc.amount_msat)) {
2317                                                                         matched_htlc = true;
2318                                                                         break;
2319                                                                 }
2320                                                         }
2321                                                         if matched_htlc { continue; }
2322                                                         if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2323                                                                 continue;
2324                                                         }
2325                                                         $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2326                                                                 if entry.height != $commitment_tx_conf_height { return true; }
2327                                                                 match entry.event {
2328                                                                         OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2329                                                                                 *update_source != **source
2330                                                                         },
2331                                                                         _ => true,
2332                                                                 }
2333                                                         });
2334                                                         let entry = OnchainEventEntry {
2335                                                                 txid: $commitment_txid_confirmed,
2336                                                                 transaction: Some($commitment_tx_confirmed.clone()),
2337                                                                 height: $commitment_tx_conf_height,
2338                                                                 block_hash: Some(*$commitment_tx_conf_hash),
2339                                                                 event: OnchainEvent::HTLCUpdate {
2340                                                                         source: (**source).clone(),
2341                                                                         payment_hash: htlc.payment_hash.clone(),
2342                                                                         htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2343                                                                         commitment_tx_output_idx: None,
2344                                                                 },
2345                                                         };
2346                                                         log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2347                                                                 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2348                                                                 $commitment_txid_confirmed, entry.confirmation_threshold());
2349                                                         $self.onchain_events_awaiting_threshold_conf.push(entry);
2350                                                 }
2351                                         }
2352                                 }
2353                         }
2354                 }
2355                 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2356                         check_htlc_fails!(txid, "current");
2357                 }
2358                 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2359                         check_htlc_fails!(txid, "previous");
2360                 }
2361         } }
2362 }
2363
2364 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
2365 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
2366 // in-line tests later.
2367
2368 #[cfg(test)]
2369 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2370         use bitcoin::blockdata::opcodes;
2371         let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2372         ret[131] = opcodes::all::OP_DROP.to_u8();
2373         ret[132] = opcodes::all::OP_DROP.to_u8();
2374         ret[133] = opcodes::all::OP_DROP.to_u8();
2375         ret[134] = opcodes::all::OP_DROP.to_u8();
2376         ret[135] = opcodes::OP_TRUE.to_u8();
2377         Vec::from(&ret[..])
2378 }
2379
2380 #[cfg(test)]
2381 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2382         vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2383 }
2384
2385 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2386         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
2387         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
2388         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
2389         fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2390                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2391                         return Err("Previous secret did not match new one");
2392                 }
2393
2394                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
2395                 // events for now-revoked/fulfilled HTLCs.
2396                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2397                         if self.current_counterparty_commitment_txid.unwrap() != txid {
2398                                 let cur_claimables = self.counterparty_claimable_outpoints.get(
2399                                         &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2400                                 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2401                                         if let Some(source) = source_opt {
2402                                                 if !cur_claimables.iter()
2403                                                         .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2404                                                 {
2405                                                         self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2406                                                 }
2407                                         }
2408                                 }
2409                                 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2410                                         *source_opt = None;
2411                                 }
2412                         } else {
2413                                 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2414                         }
2415                 }
2416
2417                 if !self.payment_preimages.is_empty() {
2418                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2419                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2420                         let min_idx = self.get_min_seen_secret();
2421                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2422
2423                         self.payment_preimages.retain(|&k, _| {
2424                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2425                                         if k == htlc.payment_hash {
2426                                                 return true
2427                                         }
2428                                 }
2429                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2430                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2431                                                 if k == htlc.payment_hash {
2432                                                         return true
2433                                                 }
2434                                         }
2435                                 }
2436                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2437                                         if *cn < min_idx {
2438                                                 return true
2439                                         }
2440                                         true
2441                                 } else { false };
2442                                 if contains {
2443                                         counterparty_hash_commitment_number.remove(&k);
2444                                 }
2445                                 false
2446                         });
2447                 }
2448
2449                 Ok(())
2450         }
2451
2452         fn provide_initial_counterparty_commitment_tx<L: Deref>(
2453                 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2454                 commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32,
2455                 to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor<L>,
2456         ) where L::Target: Logger {
2457                 self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(),
2458                         feerate_per_kw, to_broadcaster_value, to_countersignatory_value));
2459
2460                 #[cfg(debug_assertions)] {
2461                         let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
2462                         debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), txid);
2463                 }
2464
2465                 self.provide_latest_counterparty_commitment_tx(txid, htlc_outputs, commitment_number,
2466                                 their_per_commitment_point, logger);
2467         }
2468
2469         fn provide_latest_counterparty_commitment_tx<L: Deref>(
2470                 &mut self, txid: Txid,
2471                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2472                 commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor<L>,
2473         ) where L::Target: Logger {
2474                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2475                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2476                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2477                 // timeouts)
2478                 for &(ref htlc, _) in &htlc_outputs {
2479                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2480                 }
2481
2482                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2483                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2484                 self.current_counterparty_commitment_txid = Some(txid);
2485                 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2486                 self.current_counterparty_commitment_number = commitment_number;
2487                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2488                 match self.their_cur_per_commitment_points {
2489                         Some(old_points) => {
2490                                 if old_points.0 == commitment_number + 1 {
2491                                         self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2492                                 } else if old_points.0 == commitment_number + 2 {
2493                                         if let Some(old_second_point) = old_points.2 {
2494                                                 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2495                                         } else {
2496                                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2497                                         }
2498                                 } else {
2499                                         self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2500                                 }
2501                         },
2502                         None => {
2503                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2504                         }
2505                 }
2506                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2507                 for htlc in htlc_outputs {
2508                         if htlc.0.transaction_output_index.is_some() {
2509                                 htlcs.push(htlc.0);
2510                         }
2511                 }
2512         }
2513
2514         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2515         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2516         /// is important that any clones of this channel monitor (including remote clones) by kept
2517         /// up-to-date as our holder commitment transaction is updated.
2518         /// Panics if set_on_holder_tx_csv has never been called.
2519         fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, mut htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], nondust_htlc_sources: Vec<HTLCSource>) -> Result<(), &'static str> {
2520                 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
2521                         // If we have non-dust HTLCs in htlc_outputs, ensure they match the HTLCs in the
2522                         // `holder_commitment_tx`. In the future, we'll no longer provide the redundant data
2523                         // and just pass in source data via `nondust_htlc_sources`.
2524                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
2525                         for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
2526                                 debug_assert_eq!(a, b);
2527                         }
2528                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
2529                         for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
2530                                 debug_assert_eq!(a, b);
2531                         }
2532                         debug_assert!(nondust_htlc_sources.is_empty());
2533                 } else {
2534                         // If we don't have any non-dust HTLCs in htlc_outputs, assume they were all passed via
2535                         // `nondust_htlc_sources`, building up the final htlc_outputs by combining
2536                         // `nondust_htlc_sources` and the `holder_commitment_tx`
2537                         #[cfg(debug_assertions)] {
2538                                 let mut prev = -1;
2539                                 for htlc in holder_commitment_tx.trust().htlcs().iter() {
2540                                         assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
2541                                         prev = htlc.transaction_output_index.unwrap() as i32;
2542                                 }
2543                         }
2544                         debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
2545                         debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
2546                         debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
2547
2548                         let mut sources_iter = nondust_htlc_sources.into_iter();
2549
2550                         for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
2551                                 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
2552                         {
2553                                 if htlc.offered {
2554                                         let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
2555                                         #[cfg(debug_assertions)] {
2556                                                 assert!(source.possibly_matches_output(htlc));
2557                                         }
2558                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
2559                                 } else {
2560                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
2561                                 }
2562                         }
2563                         debug_assert!(sources_iter.next().is_none());
2564                 }
2565
2566                 let trusted_tx = holder_commitment_tx.trust();
2567                 let txid = trusted_tx.txid();
2568                 let tx_keys = trusted_tx.keys();
2569                 self.current_holder_commitment_number = trusted_tx.commitment_number();
2570                 let mut new_holder_commitment_tx = HolderSignedTx {
2571                         txid,
2572                         revocation_key: tx_keys.revocation_key,
2573                         a_htlc_key: tx_keys.broadcaster_htlc_key,
2574                         b_htlc_key: tx_keys.countersignatory_htlc_key,
2575                         delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2576                         per_commitment_point: tx_keys.per_commitment_point,
2577                         htlc_outputs,
2578                         to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2579                         feerate_per_kw: trusted_tx.feerate_per_kw(),
2580                 };
2581                 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2582                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2583                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2584                 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2585                         #[cfg(debug_assertions)] {
2586                                 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
2587                                                 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2588                                 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
2589                                         if let Some(source) = source_opt {
2590                                                 SentHTLCId::from_source(source) == *claimed_htlc_id
2591                                         } else { false }
2592                                 }));
2593                         }
2594                         self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
2595                 }
2596                 if self.holder_tx_signed {
2597                         return Err("Latest holder commitment signed has already been signed, update is rejected");
2598                 }
2599                 Ok(())
2600         }
2601
2602         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2603         /// commitment_tx_infos which contain the payment hash have been revoked.
2604         fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2605                 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2606                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
2607         where B::Target: BroadcasterInterface,
2608                     F::Target: FeeEstimator,
2609                     L::Target: Logger,
2610         {
2611                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2612
2613                 let confirmed_spend_txid = self.funding_spend_confirmed.or_else(|| {
2614                         self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
2615                                 OnchainEvent::FundingSpendConfirmation { .. } => Some(event.txid),
2616                                 _ => None,
2617                         })
2618                 });
2619                 let confirmed_spend_txid = if let Some(txid) = confirmed_spend_txid {
2620                         txid
2621                 } else {
2622                         return;
2623                 };
2624
2625                 // If the channel is force closed, try to claim the output from this preimage.
2626                 // First check if a counterparty commitment transaction has been broadcasted:
2627                 macro_rules! claim_htlcs {
2628                         ($commitment_number: expr, $txid: expr) => {
2629                                 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2630                                 self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2631                         }
2632                 }
2633                 if let Some(txid) = self.current_counterparty_commitment_txid {
2634                         if txid == confirmed_spend_txid {
2635                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2636                                         claim_htlcs!(*commitment_number, txid);
2637                                 } else {
2638                                         debug_assert!(false);
2639                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2640                                 }
2641                                 return;
2642                         }
2643                 }
2644                 if let Some(txid) = self.prev_counterparty_commitment_txid {
2645                         if txid == confirmed_spend_txid {
2646                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2647                                         claim_htlcs!(*commitment_number, txid);
2648                                 } else {
2649                                         debug_assert!(false);
2650                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2651                                 }
2652                                 return;
2653                         }
2654                 }
2655
2656                 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2657                 // claiming the HTLC output from each of the holder commitment transactions.
2658                 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2659                 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2660                 // holder commitment transactions.
2661                 if self.broadcasted_holder_revokable_script.is_some() {
2662                         let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
2663                                 Some(&self.current_holder_commitment_tx)
2664                         } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
2665                                 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
2666                                         Some(prev_holder_commitment_tx)
2667                                 } else {
2668                                         None
2669                                 }
2670                         } else {
2671                                 None
2672                         };
2673                         if let Some(holder_commitment_tx) = holder_commitment_tx {
2674                                 // Assume that the broadcasted commitment transaction confirmed in the current best
2675                                 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2676                                 // transactions.
2677                                 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height());
2678                                 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2679                         }
2680                 }
2681         }
2682
2683         fn generate_claimable_outpoints_and_watch_outputs(&mut self) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
2684                 let funding_outp = HolderFundingOutput::build(
2685                         self.funding_redeemscript.clone(),
2686                         self.channel_value_satoshis,
2687                         self.onchain_tx_handler.channel_type_features().clone()
2688                 );
2689                 let commitment_package = PackageTemplate::build_package(
2690                         self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
2691                         PackageSolvingData::HolderFundingOutput(funding_outp),
2692                         self.best_block.height(), self.best_block.height()
2693                 );
2694                 let mut claimable_outpoints = vec![commitment_package];
2695                 self.pending_monitor_events.push(MonitorEvent::HolderForceClosed(self.funding_info.0));
2696                 // Although we aren't signing the transaction directly here, the transaction will be signed
2697                 // in the claim that is queued to OnchainTxHandler. We set holder_tx_signed here to reject
2698                 // new channel updates.
2699                 self.holder_tx_signed = true;
2700                 let mut watch_outputs = Vec::new();
2701                 // We can't broadcast our HTLC transactions while the commitment transaction is
2702                 // unconfirmed. We'll delay doing so until we detect the confirmed commitment in
2703                 // `transactions_confirmed`.
2704                 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
2705                         // Because we're broadcasting a commitment transaction, we should construct the package
2706                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2707                         // "not yet confirmed" things as discardable, so we cannot do that here.
2708                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
2709                                 &self.current_holder_commitment_tx, self.best_block.height()
2710                         );
2711                         let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
2712                         let new_outputs = self.get_broadcasted_holder_watch_outputs(
2713                                 &self.current_holder_commitment_tx, &unsigned_commitment_tx
2714                         );
2715                         if !new_outputs.is_empty() {
2716                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2717                         }
2718                         claimable_outpoints.append(&mut new_outpoints);
2719                 }
2720                 (claimable_outpoints, watch_outputs)
2721         }
2722
2723         pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
2724                 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
2725         )
2726         where
2727                 B::Target: BroadcasterInterface,
2728                 F::Target: FeeEstimator,
2729                 L::Target: Logger,
2730         {
2731                 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs();
2732                 self.onchain_tx_handler.update_claims_view_from_requests(
2733                         claimable_outpoints, self.best_block.height(), self.best_block.height(), broadcaster,
2734                         fee_estimator, logger
2735                 );
2736         }
2737
2738         fn update_monitor<B: Deref, F: Deref, L: Deref>(
2739                 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
2740         ) -> Result<(), ()>
2741         where B::Target: BroadcasterInterface,
2742                 F::Target: FeeEstimator,
2743                 L::Target: Logger,
2744         {
2745                 if self.latest_update_id == CLOSED_CHANNEL_UPDATE_ID && updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2746                         log_info!(logger, "Applying post-force-closed update to monitor {} with {} change(s).",
2747                                 log_funding_info!(self), updates.updates.len());
2748                 } else if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2749                         log_info!(logger, "Applying force close update to monitor {} with {} change(s).",
2750                                 log_funding_info!(self), updates.updates.len());
2751                 } else {
2752                         log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
2753                                 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2754                 }
2755
2756                 if updates.counterparty_node_id.is_some() {
2757                         if self.counterparty_node_id.is_none() {
2758                                 self.counterparty_node_id = updates.counterparty_node_id;
2759                         } else {
2760                                 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
2761                         }
2762                 }
2763
2764                 // ChannelMonitor updates may be applied after force close if we receive a preimage for a
2765                 // broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
2766                 // is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
2767                 // sentinel value instead.
2768                 //
2769                 // The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
2770                 // thinks the channel needs to have its commitment transaction broadcast, so we'll allow
2771                 // them as well.
2772                 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2773                         assert_eq!(updates.updates.len(), 1);
2774                         match updates.updates[0] {
2775                                 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
2776                                 // We should have already seen a `ChannelForceClosed` update if we're trying to
2777                                 // provide a preimage at this point.
2778                                 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
2779                                         debug_assert_eq!(self.latest_update_id, CLOSED_CHANNEL_UPDATE_ID),
2780                                 _ => {
2781                                         log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2782                                         panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2783                                 },
2784                         }
2785                 } else if self.latest_update_id + 1 != updates.update_id {
2786                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2787                 }
2788                 let mut ret = Ok(());
2789                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
2790                 for update in updates.updates.iter() {
2791                         match update {
2792                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
2793                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2794                                         if self.lockdown_from_offchain { panic!(); }
2795                                         if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone()) {
2796                                                 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2797                                                 log_error!(logger, "    {}", e);
2798                                                 ret = Err(());
2799                                         }
2800                                 }
2801                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
2802                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2803                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2804                                 },
2805                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2806                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2807                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2808                                 },
2809                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2810                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2811                                         if let Err(e) = self.provide_secret(*idx, *secret) {
2812                                                 debug_assert!(false, "Latest counterparty commitment secret was invalid");
2813                                                 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2814                                                 log_error!(logger, "    {}", e);
2815                                                 ret = Err(());
2816                                         }
2817                                 },
2818                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2819                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2820                                         self.lockdown_from_offchain = true;
2821                                         if *should_broadcast {
2822                                                 // There's no need to broadcast our commitment transaction if we've seen one
2823                                                 // confirmed (even with 1 confirmation) as it'll be rejected as
2824                                                 // duplicate/conflicting.
2825                                                 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
2826                                                         self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
2827                                                                 OnchainEvent::FundingSpendConfirmation { .. } => true,
2828                                                                 _ => false,
2829                                                         }).is_some();
2830                                                 if detected_funding_spend {
2831                                                         log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
2832                                                         continue;
2833                                                 }
2834                                                 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
2835                                         } else if !self.holder_tx_signed {
2836                                                 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
2837                                                 log_error!(logger, "    in channel monitor for channel {}!", &self.funding_info.0.to_channel_id());
2838                                                 log_error!(logger, "    Read the docs for ChannelMonitor::get_latest_holder_commitment_txn and take manual action!");
2839                                         } else {
2840                                                 // If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
2841                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2842                                                 // shouldn't print the scary warning above.
2843                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2844                                         }
2845                                 },
2846                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2847                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2848                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2849                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2850                                         }
2851                                 },
2852                         }
2853                 }
2854
2855                 #[cfg(debug_assertions)] {
2856                         self.counterparty_commitment_txs_from_update(updates);
2857                 }
2858
2859                 // If the updates succeeded and we were in an already closed channel state, then there's no
2860                 // need to refuse any updates we expect to receive afer seeing a confirmed commitment.
2861                 if ret.is_ok() && updates.update_id == CLOSED_CHANNEL_UPDATE_ID && self.latest_update_id == updates.update_id {
2862                         return Ok(());
2863                 }
2864
2865                 self.latest_update_id = updates.update_id;
2866
2867                 // Refuse updates after we've detected a spend onchain, but only if we haven't processed a
2868                 // force closed monitor update yet.
2869                 if ret.is_ok() && self.funding_spend_seen && self.latest_update_id != CLOSED_CHANNEL_UPDATE_ID {
2870                         log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2871                         Err(())
2872                 } else { ret }
2873         }
2874
2875         fn get_latest_update_id(&self) -> u64 {
2876                 self.latest_update_id
2877         }
2878
2879         fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
2880                 &self.funding_info
2881         }
2882
2883         fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
2884                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2885                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2886                 // its trivial to do, double-check that here.
2887                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2888                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2889                 }
2890                 &self.outputs_to_watch
2891         }
2892
2893         fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2894                 let mut ret = Vec::new();
2895                 mem::swap(&mut ret, &mut self.pending_monitor_events);
2896                 ret
2897         }
2898
2899         /// Gets the set of events that are repeated regularly (e.g. those which RBF bump
2900         /// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
2901         /// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
2902         pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
2903                 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
2904                 let mut ret = Vec::with_capacity(pending_claim_events.len());
2905                 for (claim_id, claim_event) in pending_claim_events {
2906                         match claim_event {
2907                                 ClaimEvent::BumpCommitment {
2908                                         package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
2909                                 } => {
2910                                         let commitment_txid = commitment_tx.txid();
2911                                         debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
2912                                         let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
2913                                         let commitment_tx_fee_satoshis = self.channel_value_satoshis -
2914                                                 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value);
2915                                         ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
2916                                                 claim_id,
2917                                                 package_target_feerate_sat_per_1000_weight,
2918                                                 commitment_tx,
2919                                                 commitment_tx_fee_satoshis,
2920                                                 anchor_descriptor: AnchorDescriptor {
2921                                                         channel_derivation_parameters: ChannelDerivationParameters {
2922                                                                 keys_id: self.channel_keys_id,
2923                                                                 value_satoshis: self.channel_value_satoshis,
2924                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
2925                                                         },
2926                                                         outpoint: BitcoinOutPoint {
2927                                                                 txid: commitment_txid,
2928                                                                 vout: anchor_output_idx,
2929                                                         },
2930                                                 },
2931                                                 pending_htlcs,
2932                                         }));
2933                                 },
2934                                 ClaimEvent::BumpHTLC {
2935                                         target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
2936                                 } => {
2937                                         let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
2938                                         for htlc in htlcs {
2939                                                 htlc_descriptors.push(HTLCDescriptor {
2940                                                         channel_derivation_parameters: ChannelDerivationParameters {
2941                                                                 keys_id: self.channel_keys_id,
2942                                                                 value_satoshis: self.channel_value_satoshis,
2943                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
2944                                                         },
2945                                                         commitment_txid: htlc.commitment_txid,
2946                                                         per_commitment_number: htlc.per_commitment_number,
2947                                                         per_commitment_point: self.onchain_tx_handler.signer.get_per_commitment_point(
2948                                                                 htlc.per_commitment_number, &self.onchain_tx_handler.secp_ctx,
2949                                                         ),
2950                                                         feerate_per_kw: 0,
2951                                                         htlc: htlc.htlc,
2952                                                         preimage: htlc.preimage,
2953                                                         counterparty_sig: htlc.counterparty_sig,
2954                                                 });
2955                                         }
2956                                         ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
2957                                                 claim_id,
2958                                                 target_feerate_sat_per_1000_weight,
2959                                                 htlc_descriptors,
2960                                                 tx_lock_time,
2961                                         }));
2962                                 }
2963                         }
2964                 }
2965                 ret
2966         }
2967
2968         fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
2969                 let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
2970                         to_countersignatory_value) = self.initial_counterparty_commitment_info?;
2971                 let htlc_outputs = vec![];
2972
2973                 let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
2974                         &their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
2975                         feerate_per_kw, htlc_outputs);
2976                 Some(commitment_tx)
2977         }
2978
2979         fn build_counterparty_commitment_tx(
2980                 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
2981                 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
2982                 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
2983         ) -> CommitmentTransaction {
2984                 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
2985                         .counterparty_parameters.as_ref().unwrap().pubkeys;
2986                 let countersignatory_keys =
2987                         &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
2988
2989                 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
2990                 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
2991                 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
2992                         &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
2993                 let channel_parameters =
2994                         &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
2995
2996                 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
2997                         to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
2998                         countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
2999                         channel_parameters)
3000         }
3001
3002         fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3003                 update.updates.iter().filter_map(|update| {
3004                         match update {
3005                                 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3006                                         ref htlc_outputs, commitment_number, their_per_commitment_point,
3007                                         feerate_per_kw: Some(feerate_per_kw),
3008                                         to_broadcaster_value_sat: Some(to_broadcaster_value),
3009                                         to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3010
3011                                         let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3012                                                 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3013                                         }).collect::<Vec<_>>();
3014
3015                                         let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3016                                                         &their_per_commitment_point, to_broadcaster_value,
3017                                                         to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3018
3019                                         debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3020
3021                                         Some(commitment_tx)
3022                                 },
3023                                 _ => None,
3024                         }
3025                 }).collect()
3026         }
3027
3028         fn sign_to_local_justice_tx(
3029                 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3030         ) -> Result<Transaction, ()> {
3031                 let secret = self.get_secret(commitment_number).ok_or(())?;
3032                 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3033                 let their_per_commitment_point = PublicKey::from_secret_key(
3034                         &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3035
3036                 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3037                         &self.holder_revocation_basepoint, &their_per_commitment_point);
3038                 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3039                         &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3040                 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3041                         self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3042
3043                 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3044                         &justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3045                 justice_tx.input[input_idx].witness.push_bitcoin_signature(&sig.serialize_der(), EcdsaSighashType::All);
3046                 justice_tx.input[input_idx].witness.push(&[1u8]);
3047                 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3048                 Ok(justice_tx)
3049         }
3050
3051         /// Can only fail if idx is < get_min_seen_secret
3052         fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3053                 self.commitment_secrets.get_secret(idx)
3054         }
3055
3056         fn get_min_seen_secret(&self) -> u64 {
3057                 self.commitment_secrets.get_min_seen_secret()
3058         }
3059
3060         fn get_cur_counterparty_commitment_number(&self) -> u64 {
3061                 self.current_counterparty_commitment_number
3062         }
3063
3064         fn get_cur_holder_commitment_number(&self) -> u64 {
3065                 self.current_holder_commitment_number
3066         }
3067
3068         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
3069         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
3070         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
3071         /// HTLC-Success/HTLC-Timeout transactions.
3072         ///
3073         /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
3074         /// general information about the output that is to the counterparty in the commitment
3075         /// transaction.
3076         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3077                 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
3078         where L::Target: Logger {
3079                 // Most secp and related errors trying to create keys means we have no hope of constructing
3080                 // a spend transaction...so we return no transactions to broadcast
3081                 let mut claimable_outpoints = Vec::new();
3082                 let mut watch_outputs = Vec::new();
3083                 let mut to_counterparty_output_info = None;
3084
3085                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
3086                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3087
3088                 macro_rules! ignore_error {
3089                         ( $thing : expr ) => {
3090                                 match $thing {
3091                                         Ok(a) => a,
3092                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
3093                                 }
3094                         };
3095                 }
3096
3097                 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (tx.lock_time.to_consensus_u32() as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
3098                 if commitment_number >= self.get_min_seen_secret() {
3099                         let secret = self.get_secret(commitment_number).unwrap();
3100                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3101                         let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3102                         let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point,);
3103                         let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key));
3104
3105                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3106                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
3107
3108                         // First, process non-htlc outputs (to_holder & to_counterparty)
3109                         for (idx, outp) in tx.output.iter().enumerate() {
3110                                 if outp.script_pubkey == revokeable_p2wsh {
3111                                         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, self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
3112                                         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, height);
3113                                         claimable_outpoints.push(justice_package);
3114                                         to_counterparty_output_info =
3115                                                 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3116                                 }
3117                         }
3118
3119                         // Then, try to find revoked htlc outputs
3120                         if let Some(ref per_commitment_data) = per_commitment_option {
3121                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
3122                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3123                                                 if transaction_output_index as usize >= tx.output.len() ||
3124                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
3125                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
3126                                                         return (claimable_outpoints, (commitment_txid, watch_outputs),
3127                                                                 to_counterparty_output_info);
3128                                                 }
3129                                                 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.channel_type_features);
3130                                                 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, height);
3131                                                 claimable_outpoints.push(justice_package);
3132                                         }
3133                                 }
3134                         }
3135
3136                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
3137                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
3138                                 // We're definitely a counterparty commitment transaction!
3139                                 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
3140                                 for (idx, outp) in tx.output.iter().enumerate() {
3141                                         watch_outputs.push((idx as u32, outp.clone()));
3142                                 }
3143                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3144
3145                                 if let Some(per_commitment_data) = per_commitment_option {
3146                                         fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3147                                                 block_hash, per_commitment_data.iter().map(|(htlc, htlc_source)|
3148                                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3149                                                 ), logger);
3150                                 } else {
3151                                         debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
3152                                         fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3153                                                 block_hash, [].iter().map(|reference| *reference), logger);
3154                                 }
3155                         }
3156                 } else if let Some(per_commitment_data) = per_commitment_option {
3157                         // While this isn't useful yet, there is a potential race where if a counterparty
3158                         // revokes a state at the same time as the commitment transaction for that state is
3159                         // confirmed, and the watchtower receives the block before the user, the user could
3160                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
3161                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
3162                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
3163                         // insert it here.
3164                         for (idx, outp) in tx.output.iter().enumerate() {
3165                                 watch_outputs.push((idx as u32, outp.clone()));
3166                         }
3167                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3168
3169                         log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3170                         fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3171                                 per_commitment_data.iter().map(|(htlc, htlc_source)|
3172                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3173                                 ), logger);
3174
3175                         let (htlc_claim_reqs, counterparty_output_info) =
3176                                 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
3177                         to_counterparty_output_info = counterparty_output_info;
3178                         for req in htlc_claim_reqs {
3179                                 claimable_outpoints.push(req);
3180                         }
3181
3182                 }
3183                 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
3184         }
3185
3186         /// Returns the HTLC claim package templates and the counterparty output info
3187         fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
3188         -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3189                 let mut claimable_outpoints = Vec::new();
3190                 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3191
3192                 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
3193                         Some(outputs) => outputs,
3194                         None => return (claimable_outpoints, to_counterparty_output_info),
3195                 };
3196                 let per_commitment_points = match self.their_cur_per_commitment_points {
3197                         Some(points) => points,
3198                         None => return (claimable_outpoints, to_counterparty_output_info),
3199                 };
3200
3201                 let per_commitment_point =
3202                         // If the counterparty commitment tx is the latest valid state, use their latest
3203                         // per-commitment point
3204                         if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
3205                         else if let Some(point) = per_commitment_points.2.as_ref() {
3206                                 // If counterparty commitment tx is the state previous to the latest valid state, use
3207                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
3208                                 // them to temporarily have two valid commitment txns from our viewpoint)
3209                                 if per_commitment_points.0 == commitment_number + 1 {
3210                                         point
3211                                 } else { return (claimable_outpoints, to_counterparty_output_info); }
3212                         } else { return (claimable_outpoints, to_counterparty_output_info); };
3213
3214                 if let Some(transaction) = tx {
3215                         let revocation_pubkey = RevocationKey::from_basepoint(
3216                                 &self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point);
3217
3218                         let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point);
3219
3220                         let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3221                                 self.counterparty_commitment_params.on_counterparty_tx_csv,
3222                                 &delayed_key).to_v0_p2wsh();
3223                         for (idx, outp) in transaction.output.iter().enumerate() {
3224                                 if outp.script_pubkey == revokeable_p2wsh {
3225                                         to_counterparty_output_info =
3226                                                 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3227                                 }
3228                         }
3229                 }
3230
3231                 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
3232                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3233                                 if let Some(transaction) = tx {
3234                                         if transaction_output_index as usize >= transaction.output.len() ||
3235                                                 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
3236                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
3237                                                         return (claimable_outpoints, to_counterparty_output_info);
3238                                                 }
3239                                 }
3240                                 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
3241                                 if preimage.is_some() || !htlc.offered {
3242                                         let counterparty_htlc_outp = if htlc.offered {
3243                                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(
3244                                                         CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
3245                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3246                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
3247                                                                 preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3248                                         } else {
3249                                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(
3250                                                         CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
3251                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3252                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
3253                                                                 htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3254                                         };
3255                                         let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry, 0);
3256                                         claimable_outpoints.push(counterparty_package);
3257                                 }
3258                         }
3259                 }
3260
3261                 (claimable_outpoints, to_counterparty_output_info)
3262         }
3263
3264         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
3265         fn check_spend_counterparty_htlc<L: Deref>(
3266                 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3267         ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3268                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3269                 let per_commitment_key = match SecretKey::from_slice(&secret) {
3270                         Ok(key) => key,
3271                         Err(_) => return (Vec::new(), None)
3272                 };
3273                 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3274
3275                 let htlc_txid = tx.txid();
3276                 let mut claimable_outpoints = vec![];
3277                 let mut outputs_to_watch = None;
3278                 // Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
3279                 // with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
3280                 // counterparty can now aggregate multiple HTLCs into a single transaction thanks to
3281                 // `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
3282                 // confirmed revoked HTLC transaction (for more details, see
3283                 // https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
3284                 //
3285                 // We make sure we're not vulnerable to this case by checking all inputs of the transaction,
3286                 // and claim those which spend the commitment transaction, have a witness of 5 elements, and
3287                 // have a corresponding output at the same index within the transaction.
3288                 for (idx, input) in tx.input.iter().enumerate() {
3289                         if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3290                                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3291                                 let revk_outp = RevokedOutput::build(
3292                                         per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3293                                         self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3294                                         tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3295                                         false
3296                                 );
3297                                 let justice_package = PackageTemplate::build_package(
3298                                         htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3299                                         height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, height
3300                                 );
3301                                 claimable_outpoints.push(justice_package);
3302                                 if outputs_to_watch.is_none() {
3303                                         outputs_to_watch = Some((htlc_txid, vec![]));
3304                                 }
3305                                 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3306                         }
3307                 }
3308                 (claimable_outpoints, outputs_to_watch)
3309         }
3310
3311         // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
3312         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
3313         // script so we can detect whether a holder transaction has been seen on-chain.
3314         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3315                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3316
3317                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3318                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3319
3320                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3321                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3322                                 let htlc_output = if htlc.offered {
3323                                         let htlc_output = HolderHTLCOutput::build_offered(
3324                                                 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone()
3325                                         );
3326                                         htlc_output
3327                                 } else {
3328                                         let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
3329                                                 preimage.clone()
3330                                         } else {
3331                                                 // We can't build an HTLC-Success transaction without the preimage
3332                                                 continue;
3333                                         };
3334                                         let htlc_output = HolderHTLCOutput::build_accepted(
3335                                                 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone()
3336                                         );
3337                                         htlc_output
3338                                 };
3339                                 let htlc_package = PackageTemplate::build_package(
3340                                         holder_tx.txid, transaction_output_index,
3341                                         PackageSolvingData::HolderHTLCOutput(htlc_output),
3342                                         htlc.cltv_expiry, conf_height
3343                                 );
3344                                 claim_requests.push(htlc_package);
3345                         }
3346                 }
3347
3348                 (claim_requests, broadcasted_holder_revokable_script)
3349         }
3350
3351         // Returns holder HTLC outputs to watch and react to in case of spending.
3352         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3353                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3354                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3355                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3356                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3357                         }
3358                 }
3359                 watch_outputs
3360         }
3361
3362         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
3363         /// revoked using data in holder_claimable_outpoints.
3364         /// Should not be used if check_spend_revoked_transaction succeeds.
3365         /// Returns None unless the transaction is definitely one of our commitment transactions.
3366         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
3367                 let commitment_txid = tx.txid();
3368                 let mut claim_requests = Vec::new();
3369                 let mut watch_outputs = Vec::new();
3370
3371                 macro_rules! append_onchain_update {
3372                         ($updates: expr, $to_watch: expr) => {
3373                                 claim_requests = $updates.0;
3374                                 self.broadcasted_holder_revokable_script = $updates.1;
3375                                 watch_outputs.append(&mut $to_watch);
3376                         }
3377                 }
3378
3379                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
3380                 let mut is_holder_tx = false;
3381
3382                 if self.current_holder_commitment_tx.txid == commitment_txid {
3383                         is_holder_tx = true;
3384                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3385                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3386                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3387                         append_onchain_update!(res, to_watch);
3388                         fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3389                                 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3390                                 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3391                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3392                         if holder_tx.txid == commitment_txid {
3393                                 is_holder_tx = true;
3394                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3395                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
3396                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3397                                 append_onchain_update!(res, to_watch);
3398                                 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3399                                         holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3400                                         logger);
3401                         }
3402                 }
3403
3404                 if is_holder_tx {
3405                         Some((claim_requests, (commitment_txid, watch_outputs)))
3406                 } else {
3407                         None
3408                 }
3409         }
3410
3411         /// Cancels any existing pending claims for a commitment that previously confirmed and has now
3412         /// been replaced by another.
3413         pub fn cancel_prev_commitment_claims<L: Deref>(
3414                 &mut self, logger: &L, confirmed_commitment_txid: &Txid
3415         ) where L::Target: Logger {
3416                 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
3417                         // Cancel any pending claims for counterparty commitments we've seen confirm.
3418                         if counterparty_commitment_txid == confirmed_commitment_txid {
3419                                 continue;
3420                         }
3421                         for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
3422                                 log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
3423                                         counterparty_commitment_txid);
3424                                 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
3425                                 if let Some(vout) = htlc.transaction_output_index {
3426                                         outpoint.vout = vout;
3427                                         self.onchain_tx_handler.abandon_claim(&outpoint);
3428                                 }
3429                         }
3430                 }
3431                 if self.holder_tx_signed {
3432                         // If we've signed, we may have broadcast either commitment (prev or current), and
3433                         // attempted to claim from it immediately without waiting for a confirmation.
3434                         if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
3435                                 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3436                                         self.current_holder_commitment_tx.txid);
3437                                 let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
3438                                 for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
3439                                         if let Some(vout) = htlc.transaction_output_index {
3440                                                 outpoint.vout = vout;
3441                                                 self.onchain_tx_handler.abandon_claim(&outpoint);
3442                                         }
3443                                 }
3444                         }
3445                         if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3446                                 if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
3447                                         log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3448                                                 prev_holder_commitment_tx.txid);
3449                                         let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
3450                                         for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
3451                                                 if let Some(vout) = htlc.transaction_output_index {
3452                                                         outpoint.vout = vout;
3453                                                         self.onchain_tx_handler.abandon_claim(&outpoint);
3454                                                 }
3455                                         }
3456                                 }
3457                         }
3458                 } else {
3459                         // No previous claim.
3460                 }
3461         }
3462
3463         fn get_latest_holder_commitment_txn<L: Deref>(
3464                 &mut self, logger: &WithChannelMonitor<L>,
3465         ) -> Vec<Transaction> where L::Target: Logger {
3466                 log_debug!(logger, "Getting signed latest holder commitment transaction!");
3467                 self.holder_tx_signed = true;
3468                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
3469                 let txid = commitment_tx.txid();
3470                 let mut holder_transactions = vec![commitment_tx];
3471                 // When anchor outputs are present, the HTLC transactions are only valid once the commitment
3472                 // transaction confirms.
3473                 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3474                         return holder_transactions;
3475                 }
3476                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3477                         if let Some(vout) = htlc.0.transaction_output_index {
3478                                 let preimage = if !htlc.0.offered {
3479                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3480                                                 // We can't build an HTLC-Success transaction without the preimage
3481                                                 continue;
3482                                         }
3483                                 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
3484                                         // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
3485                                         // current locktime requirements on-chain. We will broadcast them in
3486                                         // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
3487                                         // Note that we add + 1 as transactions are broadcastable when they can be
3488                                         // confirmed in the next block.
3489                                         continue;
3490                                 } else { None };
3491                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
3492                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
3493                                         holder_transactions.push(htlc_tx);
3494                                 }
3495                         }
3496                 }
3497                 // 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.
3498                 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
3499                 holder_transactions
3500         }
3501
3502         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3503         /// Note that this includes possibly-locktimed-in-the-future transactions!
3504         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
3505                 &mut self, logger: &WithChannelMonitor<L>
3506         ) -> Vec<Transaction> where L::Target: Logger {
3507                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3508                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3509                 let txid = commitment_tx.txid();
3510                 let mut holder_transactions = vec![commitment_tx];
3511                 // When anchor outputs are present, the HTLC transactions are only final once the commitment
3512                 // transaction confirms due to the CSV 1 encumberance.
3513                 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3514                         return holder_transactions;
3515                 }
3516                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3517                         if let Some(vout) = htlc.0.transaction_output_index {
3518                                 let preimage = if !htlc.0.offered {
3519                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3520                                                 // We can't build an HTLC-Success transaction without the preimage
3521                                                 continue;
3522                                         }
3523                                 } else { None };
3524                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
3525                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
3526                                         holder_transactions.push(htlc_tx);
3527                                 }
3528                         }
3529                 }
3530                 holder_transactions
3531         }
3532
3533         fn block_connected<B: Deref, F: Deref, L: Deref>(
3534                 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
3535                 fee_estimator: F, logger: &WithChannelMonitor<L>,
3536         ) -> Vec<TransactionOutputs>
3537                 where B::Target: BroadcasterInterface,
3538                         F::Target: FeeEstimator,
3539                         L::Target: Logger,
3540         {
3541                 let block_hash = header.block_hash();
3542                 self.best_block = BestBlock::new(block_hash, height);
3543
3544                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3545                 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3546         }
3547
3548         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3549                 &mut self,
3550                 header: &Header,
3551                 height: u32,
3552                 broadcaster: B,
3553                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3554                 logger: &WithChannelMonitor<L>,
3555         ) -> Vec<TransactionOutputs>
3556         where
3557                 B::Target: BroadcasterInterface,
3558                 F::Target: FeeEstimator,
3559                 L::Target: Logger,
3560         {
3561                 let block_hash = header.block_hash();
3562
3563                 if height > self.best_block.height() {
3564                         self.best_block = BestBlock::new(block_hash, height);
3565                         log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
3566                         self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
3567                 } else if block_hash != self.best_block.block_hash() {
3568                         self.best_block = BestBlock::new(block_hash, height);
3569                         log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
3570                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3571                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
3572                         Vec::new()
3573                 } else { Vec::new() }
3574         }
3575
3576         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3577                 &mut self,
3578                 header: &Header,
3579                 txdata: &TransactionData,
3580                 height: u32,
3581                 broadcaster: B,
3582                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3583                 logger: &WithChannelMonitor<L>,
3584         ) -> Vec<TransactionOutputs>
3585         where
3586                 B::Target: BroadcasterInterface,
3587                 F::Target: FeeEstimator,
3588                 L::Target: Logger,
3589         {
3590                 let txn_matched = self.filter_block(txdata);
3591                 for tx in &txn_matched {
3592                         let mut output_val = 0;
3593                         for out in tx.output.iter() {
3594                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3595                                 output_val += out.value;
3596                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3597                         }
3598                 }
3599
3600                 let block_hash = header.block_hash();
3601
3602                 let mut watch_outputs = Vec::new();
3603                 let mut claimable_outpoints = Vec::new();
3604                 'tx_iter: for tx in &txn_matched {
3605                         let txid = tx.txid();
3606                         log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
3607                         // If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
3608                         if Some(txid) == self.funding_spend_confirmed {
3609                                 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
3610                                 continue 'tx_iter;
3611                         }
3612                         for ev in self.onchain_events_awaiting_threshold_conf.iter() {
3613                                 if ev.txid == txid {
3614                                         if let Some(conf_hash) = ev.block_hash {
3615                                                 assert_eq!(header.block_hash(), conf_hash,
3616                                                         "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
3617                                                         This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
3618                                         }
3619                                         log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
3620                                         continue 'tx_iter;
3621                                 }
3622                         }
3623                         for htlc in self.htlcs_resolved_on_chain.iter() {
3624                                 if Some(txid) == htlc.resolving_txid {
3625                                         log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
3626                                         continue 'tx_iter;
3627                                 }
3628                         }
3629                         for spendable_txid in self.spendable_txids_confirmed.iter() {
3630                                 if txid == *spendable_txid {
3631                                         log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
3632                                         continue 'tx_iter;
3633                                 }
3634                         }
3635
3636                         if tx.input.len() == 1 {
3637                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
3638                                 // commitment transactions and HTLC transactions will all only ever have one input
3639                                 // (except for HTLC transactions for channels with anchor outputs), which is an easy
3640                                 // way to filter out any potential non-matching txn for lazy filters.
3641                                 let prevout = &tx.input[0].previous_output;
3642                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
3643                                         let mut balance_spendable_csv = None;
3644                                         log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
3645                                                 &self.funding_info.0.to_channel_id(), txid);
3646                                         self.funding_spend_seen = true;
3647                                         let mut commitment_tx_to_counterparty_output = None;
3648                                         if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
3649                                                 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
3650                                                         self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
3651                                                 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
3652                                                 if !new_outputs.1.is_empty() {
3653                                                         watch_outputs.push(new_outputs);
3654                                                 }
3655                                                 claimable_outpoints.append(&mut new_outpoints);
3656                                                 if new_outpoints.is_empty() {
3657                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
3658                                                                 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
3659                                                                         "A commitment transaction matched as both a counterparty and local commitment tx?");
3660                                                                 if !new_outputs.1.is_empty() {
3661                                                                         watch_outputs.push(new_outputs);
3662                                                                 }
3663                                                                 claimable_outpoints.append(&mut new_outpoints);
3664                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
3665                                                         }
3666                                                 }
3667                                         }
3668                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3669                                                 txid,
3670                                                 transaction: Some((*tx).clone()),
3671                                                 height,
3672                                                 block_hash: Some(block_hash),
3673                                                 event: OnchainEvent::FundingSpendConfirmation {
3674                                                         on_local_output_csv: balance_spendable_csv,
3675                                                         commitment_tx_to_counterparty_output,
3676                                                 },
3677                                         });
3678                                         // Now that we've detected a confirmed commitment transaction, attempt to cancel
3679                                         // pending claims for any commitments that were previously confirmed such that
3680                                         // we don't continue claiming inputs that no longer exist.
3681                                         self.cancel_prev_commitment_claims(&logger, &txid);
3682                                 }
3683                         }
3684                         if tx.input.len() >= 1 {
3685                                 // While all commitment transactions have one input, HTLC transactions may have more
3686                                 // if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
3687                                 // other ways which can have more than one output.
3688                                 for tx_input in &tx.input {
3689                                         let commitment_txid = tx_input.previous_output.txid;
3690                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
3691                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
3692                                                         &tx, commitment_number, &commitment_txid, height, &logger
3693                                                 );
3694                                                 claimable_outpoints.append(&mut new_outpoints);
3695                                                 if let Some(new_outputs) = new_outputs_option {
3696                                                         watch_outputs.push(new_outputs);
3697                                                 }
3698                                                 // Since there may be multiple HTLCs for this channel (all spending the
3699                                                 // same commitment tx) being claimed by the counterparty within the same
3700                                                 // transaction, and `check_spend_counterparty_htlc` already checks all the
3701                                                 // ones relevant to this channel, we can safely break from our loop.
3702                                                 break;
3703                                         }
3704                                 }
3705                                 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
3706
3707                                 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
3708                         }
3709                 }
3710
3711                 if height > self.best_block.height() {
3712                         self.best_block = BestBlock::new(block_hash, height);
3713                 }
3714
3715                 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
3716         }
3717
3718         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
3719         /// `self.best_block` before calling if a new best blockchain tip is available. More
3720         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
3721         /// complexity especially in
3722         /// `OnchainTx::update_claims_view_from_requests`/`OnchainTx::update_claims_view_from_matched_txn`.
3723         ///
3724         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
3725         /// confirmed at, even if it is not the current best height.
3726         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
3727                 &mut self,
3728                 conf_height: u32,
3729                 conf_hash: BlockHash,
3730                 txn_matched: Vec<&Transaction>,
3731                 mut watch_outputs: Vec<TransactionOutputs>,
3732                 mut claimable_outpoints: Vec<PackageTemplate>,
3733                 broadcaster: &B,
3734                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3735                 logger: &WithChannelMonitor<L>,
3736         ) -> Vec<TransactionOutputs>
3737         where
3738                 B::Target: BroadcasterInterface,
3739                 F::Target: FeeEstimator,
3740                 L::Target: Logger,
3741         {
3742                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
3743                 debug_assert!(self.best_block.height() >= conf_height);
3744
3745                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
3746                 if should_broadcast {
3747                         let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs();
3748                         claimable_outpoints.append(&mut new_outpoints);
3749                         watch_outputs.append(&mut new_outputs);
3750                 }
3751
3752                 // Find which on-chain events have reached their confirmation threshold.
3753                 let onchain_events_awaiting_threshold_conf =
3754                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
3755                 let mut onchain_events_reaching_threshold_conf = Vec::new();
3756                 for entry in onchain_events_awaiting_threshold_conf {
3757                         if entry.has_reached_confirmation_threshold(&self.best_block) {
3758                                 onchain_events_reaching_threshold_conf.push(entry);
3759                         } else {
3760                                 self.onchain_events_awaiting_threshold_conf.push(entry);
3761                         }
3762                 }
3763
3764                 // Used to check for duplicate HTLC resolutions.
3765                 #[cfg(debug_assertions)]
3766                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
3767                         .iter()
3768                         .filter_map(|entry| match &entry.event {
3769                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
3770                                 _ => None,
3771                         })
3772                         .collect();
3773                 #[cfg(debug_assertions)]
3774                 let mut matured_htlcs = Vec::new();
3775
3776                 // Produce actionable events from on-chain events having reached their threshold.
3777                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
3778                         match entry.event {
3779                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
3780                                         // Check for duplicate HTLC resolutions.
3781                                         #[cfg(debug_assertions)]
3782                                         {
3783                                                 debug_assert!(
3784                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
3785                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
3786                                                          call either transaction_unconfirmed for the conflicting transaction \
3787                                                          or block_disconnected for a block containing it.");
3788                                                 debug_assert!(
3789                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
3790                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
3791                                                          call either transaction_unconfirmed for the conflicting transaction \
3792                                                          or block_disconnected for a block containing it.");
3793                                                 matured_htlcs.push(source.clone());
3794                                         }
3795
3796                                         log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
3797                                                 &payment_hash, entry.txid);
3798                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3799                                                 payment_hash,
3800                                                 payment_preimage: None,
3801                                                 source: source.clone(),
3802                                                 htlc_value_satoshis,
3803                                         }));
3804                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3805                                                 commitment_tx_output_idx,
3806                                                 resolving_txid: Some(entry.txid),
3807                                                 resolving_tx: entry.transaction,
3808                                                 payment_preimage: None,
3809                                         });
3810                                 },
3811                                 OnchainEvent::MaturingOutput { descriptor } => {
3812                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
3813                                         self.pending_events.push(Event::SpendableOutputs {
3814                                                 outputs: vec![descriptor],
3815                                                 channel_id: Some(self.funding_info.0.to_channel_id()),
3816                                         });
3817                                         self.spendable_txids_confirmed.push(entry.txid);
3818                                 },
3819                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
3820                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3821                                                 commitment_tx_output_idx: Some(commitment_tx_output_idx),
3822                                                 resolving_txid: Some(entry.txid),
3823                                                 resolving_tx: entry.transaction,
3824                                                 payment_preimage: preimage,
3825                                         });
3826                                 },
3827                                 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
3828                                         self.funding_spend_confirmed = Some(entry.txid);
3829                                         self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
3830                                 },
3831                         }
3832                 }
3833
3834                 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
3835                 self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height(), broadcaster, fee_estimator, logger);
3836
3837                 // Determine new outputs to watch by comparing against previously known outputs to watch,
3838                 // updating the latter in the process.
3839                 watch_outputs.retain(|&(ref txid, ref txouts)| {
3840                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
3841                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
3842                 });
3843                 #[cfg(test)]
3844                 {
3845                         // If we see a transaction for which we registered outputs previously,
3846                         // make sure the registered scriptpubkey at the expected index match
3847                         // the actual transaction output one. We failed this case before #653.
3848                         for tx in &txn_matched {
3849                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
3850                                         for idx_and_script in outputs.iter() {
3851                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
3852                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
3853                                         }
3854                                 }
3855                         }
3856                 }
3857                 watch_outputs
3858         }
3859
3860         fn block_disconnected<B: Deref, F: Deref, L: Deref>(
3861                 &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
3862         ) where B::Target: BroadcasterInterface,
3863                 F::Target: FeeEstimator,
3864                 L::Target: Logger,
3865         {
3866                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
3867
3868                 //We may discard:
3869                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
3870                 //- maturing spendable output has transaction paying us has been disconnected
3871                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
3872
3873                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3874                 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
3875
3876                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
3877         }
3878
3879         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
3880                 &mut self,
3881                 txid: &Txid,
3882                 broadcaster: B,
3883                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3884                 logger: &WithChannelMonitor<L>,
3885         ) where
3886                 B::Target: BroadcasterInterface,
3887                 F::Target: FeeEstimator,
3888                 L::Target: Logger,
3889         {
3890                 let mut removed_height = None;
3891                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
3892                         if entry.txid == *txid {
3893                                 removed_height = Some(entry.height);
3894                                 break;
3895                         }
3896                 }
3897
3898                 if let Some(removed_height) = removed_height {
3899                         log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
3900                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
3901                                 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
3902                                 false
3903                         } else { true });
3904                 }
3905
3906                 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
3907
3908                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
3909         }
3910
3911         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
3912         /// transactions thereof.
3913         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
3914                 let mut matched_txn = HashSet::new();
3915                 txdata.iter().filter(|&&(_, tx)| {
3916                         let mut matches = self.spends_watched_output(tx);
3917                         for input in tx.input.iter() {
3918                                 if matches { break; }
3919                                 if matched_txn.contains(&input.previous_output.txid) {
3920                                         matches = true;
3921                                 }
3922                         }
3923                         if matches {
3924                                 matched_txn.insert(tx.txid());
3925                         }
3926                         matches
3927                 }).map(|(_, tx)| *tx).collect()
3928         }
3929
3930         /// Checks if a given transaction spends any watched outputs.
3931         fn spends_watched_output(&self, tx: &Transaction) -> bool {
3932                 for input in tx.input.iter() {
3933                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
3934                                 for (idx, _script_pubkey) in outputs.iter() {
3935                                         if *idx == input.previous_output.vout {
3936                                                 #[cfg(test)]
3937                                                 {
3938                                                         // If the expected script is a known type, check that the witness
3939                                                         // appears to be spending the correct type (ie that the match would
3940                                                         // actually succeed in BIP 158/159-style filters).
3941                                                         if _script_pubkey.is_v0_p2wsh() {
3942                                                                 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
3943                                                                         // In at least one test we use a deliberately bogus witness
3944                                                                         // script which hit an old panic. Thus, we check for that here
3945                                                                         // and avoid the assert if its the expected bogus script.
3946                                                                         return true;
3947                                                                 }
3948
3949                                                                 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
3950                                                         } else if _script_pubkey.is_v0_p2wpkh() {
3951                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
3952                                                         } else { panic!(); }
3953                                                 }
3954                                                 return true;
3955                                         }
3956                                 }
3957                         }
3958                 }
3959
3960                 false
3961         }
3962
3963         fn should_broadcast_holder_commitment_txn<L: Deref>(
3964                 &self, logger: &WithChannelMonitor<L>
3965         ) -> bool where L::Target: Logger {
3966                 // There's no need to broadcast our commitment transaction if we've seen one confirmed (even
3967                 // with 1 confirmation) as it'll be rejected as duplicate/conflicting.
3968                 if self.funding_spend_confirmed.is_some() ||
3969                         self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
3970                                 OnchainEvent::FundingSpendConfirmation { .. } => true,
3971                                 _ => false,
3972                         }).is_some()
3973                 {
3974                         return false;
3975                 }
3976                 // We need to consider all HTLCs which are:
3977                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
3978                 //    transactions and we'd end up in a race, or
3979                 //  * are in our latest holder commitment transaction, as this is the thing we will
3980                 //    broadcast if we go on-chain.
3981                 // Note that we consider HTLCs which were below dust threshold here - while they don't
3982                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
3983                 // to the source, and if we don't fail the channel we will have to ensure that the next
3984                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
3985                 // easier to just fail the channel as this case should be rare enough anyway.
3986                 let height = self.best_block.height();
3987                 macro_rules! scan_commitment {
3988                         ($htlcs: expr, $holder_tx: expr) => {
3989                                 for ref htlc in $htlcs {
3990                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
3991                                         // chain with enough room to claim the HTLC without our counterparty being able to
3992                                         // time out the HTLC first.
3993                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
3994                                         // concern is being able to claim the corresponding inbound HTLC (on another
3995                                         // channel) before it expires. In fact, we don't even really care if our
3996                                         // counterparty here claims such an outbound HTLC after it expired as long as we
3997                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
3998                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
3999                                         // we give ourselves a few blocks of headroom after expiration before going
4000                                         // on-chain for an expired HTLC.
4001                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
4002                                         // from us until we've reached the point where we go on-chain with the
4003                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
4004                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
4005                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
4006                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
4007                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
4008                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
4009                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
4010                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
4011                                         //  The final, above, condition is checked for statically in channelmanager
4012                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
4013                                         let htlc_outbound = $holder_tx == htlc.offered;
4014                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4015                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4016                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4017                                                 return true;
4018                                         }
4019                                 }
4020                         }
4021                 }
4022
4023                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4024
4025                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
4026                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4027                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4028                         }
4029                 }
4030                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4031                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4032                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4033                         }
4034                 }
4035
4036                 false
4037         }
4038
4039         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
4040         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
4041         fn is_resolving_htlc_output<L: Deref>(
4042                 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4043         ) where L::Target: Logger {
4044                 'outer_loop: for input in &tx.input {
4045                         let mut payment_data = None;
4046                         let htlc_claim = HTLCClaim::from_witness(&input.witness);
4047                         let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4048                         let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4049                         #[cfg(not(fuzzing))]
4050                         let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4051                         let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4052                         #[cfg(not(fuzzing))]
4053                         let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4054
4055                         let mut payment_preimage = PaymentPreimage([0; 32]);
4056                         if offered_preimage_claim || accepted_preimage_claim {
4057                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4058                         }
4059
4060                         macro_rules! log_claim {
4061                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4062                                         let outbound_htlc = $holder_tx == $htlc.offered;
4063                                         // HTLCs must either be claimed by a matching script type or through the
4064                                         // revocation path:
4065                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4066                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4067                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4068                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4069                                         // Further, only exactly one of the possible spend paths should have been
4070                                         // matched by any HTLC spend:
4071                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4072                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4073                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4074                                                          revocation_sig_claim as u8, 1);
4075                                         if ($holder_tx && revocation_sig_claim) ||
4076                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4077                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
4078                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
4079                                                         if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4080                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
4081                                         } else {
4082                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4083                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
4084                                                         if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4085                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4086                                         }
4087                                 }
4088                         }
4089
4090                         macro_rules! check_htlc_valid_counterparty {
4091                                 ($counterparty_txid: expr, $htlc_output: expr) => {
4092                                         if let Some(txid) = $counterparty_txid {
4093                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
4094                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4095                                                                 if let &Some(ref source) = pending_source {
4096                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4097                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4098                                                                         break;
4099                                                                 }
4100                                                         }
4101                                                 }
4102                                         }
4103                                 }
4104                         }
4105
4106                         macro_rules! scan_commitment {
4107                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4108                                         for (ref htlc_output, source_option) in $htlcs {
4109                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4110                                                         if let Some(ref source) = source_option {
4111                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
4112                                                                 // We have a resolution of an HTLC either from one of our latest
4113                                                                 // holder commitment transactions or an unrevoked counterparty commitment
4114                                                                 // transaction. This implies we either learned a preimage, the HTLC
4115                                                                 // has timed out, or we screwed up. In any case, we should now
4116                                                                 // resolve the source HTLC with the original sender.
4117                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4118                                                         } else if !$holder_tx {
4119                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
4120                                                                 if payment_data.is_none() {
4121                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
4122                                                                 }
4123                                                         }
4124                                                         if payment_data.is_none() {
4125                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
4126                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
4127                                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4128                                                                         txid: tx.txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4129                                                                         event: OnchainEvent::HTLCSpendConfirmation {
4130                                                                                 commitment_tx_output_idx: input.previous_output.vout,
4131                                                                                 preimage: if accepted_preimage_claim || offered_preimage_claim {
4132                                                                                         Some(payment_preimage) } else { None },
4133                                                                                 // If this is a payment to us (ie !outbound_htlc), wait for
4134                                                                                 // the CSV delay before dropping the HTLC from claimable
4135                                                                                 // balance if the claim was an HTLC-Success transaction (ie
4136                                                                                 // accepted_preimage_claim).
4137                                                                                 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4138                                                                                         Some(self.on_holder_tx_csv) } else { None },
4139                                                                         },
4140                                                                 });
4141                                                                 continue 'outer_loop;
4142                                                         }
4143                                                 }
4144                                         }
4145                                 }
4146                         }
4147
4148                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4149                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4150                                         "our latest holder commitment tx", true);
4151                         }
4152                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4153                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4154                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4155                                                 "our previous holder commitment tx", true);
4156                                 }
4157                         }
4158                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4159                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
4160                                         "counterparty commitment tx", false);
4161                         }
4162
4163                         // Check that scan_commitment, above, decided there is some source worth relaying an
4164                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
4165                         if let Some((source, payment_hash, amount_msat)) = payment_data {
4166                                 if accepted_preimage_claim {
4167                                         if !self.pending_monitor_events.iter().any(
4168                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4169                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4170                                                         txid: tx.txid(),
4171                                                         height,
4172                                                         block_hash: Some(*block_hash),
4173                                                         transaction: Some(tx.clone()),
4174                                                         event: OnchainEvent::HTLCSpendConfirmation {
4175                                                                 commitment_tx_output_idx: input.previous_output.vout,
4176                                                                 preimage: Some(payment_preimage),
4177                                                                 on_to_local_output_csv: None,
4178                                                         },
4179                                                 });
4180                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4181                                                         source,
4182                                                         payment_preimage: Some(payment_preimage),
4183                                                         payment_hash,
4184                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4185                                                 }));
4186                                         }
4187                                 } else if offered_preimage_claim {
4188                                         if !self.pending_monitor_events.iter().any(
4189                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4190                                                         upd.source == source
4191                                                 } else { false }) {
4192                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4193                                                         txid: tx.txid(),
4194                                                         transaction: Some(tx.clone()),
4195                                                         height,
4196                                                         block_hash: Some(*block_hash),
4197                                                         event: OnchainEvent::HTLCSpendConfirmation {
4198                                                                 commitment_tx_output_idx: input.previous_output.vout,
4199                                                                 preimage: Some(payment_preimage),
4200                                                                 on_to_local_output_csv: None,
4201                                                         },
4202                                                 });
4203                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4204                                                         source,
4205                                                         payment_preimage: Some(payment_preimage),
4206                                                         payment_hash,
4207                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4208                                                 }));
4209                                         }
4210                                 } else {
4211                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4212                                                 if entry.height != height { return true; }
4213                                                 match entry.event {
4214                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4215                                                                 *htlc_source != source
4216                                                         },
4217                                                         _ => true,
4218                                                 }
4219                                         });
4220                                         let entry = OnchainEventEntry {
4221                                                 txid: tx.txid(),
4222                                                 transaction: Some(tx.clone()),
4223                                                 height,
4224                                                 block_hash: Some(*block_hash),
4225                                                 event: OnchainEvent::HTLCUpdate {
4226                                                         source, payment_hash,
4227                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4228                                                         commitment_tx_output_idx: Some(input.previous_output.vout),
4229                                                 },
4230                                         };
4231                                         log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4232                                         self.onchain_events_awaiting_threshold_conf.push(entry);
4233                                 }
4234                         }
4235                 }
4236         }
4237
4238         fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4239                 let mut spendable_outputs = Vec::new();
4240                 for (i, outp) in tx.output.iter().enumerate() {
4241                         if outp.script_pubkey == self.destination_script {
4242                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4243                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4244                                         output: outp.clone(),
4245                                         channel_keys_id: Some(self.channel_keys_id),
4246                                 });
4247                         }
4248                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4249                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4250                                         spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4251                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4252                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
4253                                                 to_self_delay: self.on_holder_tx_csv,
4254                                                 output: outp.clone(),
4255                                                 revocation_pubkey: broadcasted_holder_revokable_script.2,
4256                                                 channel_keys_id: self.channel_keys_id,
4257                                                 channel_value_satoshis: self.channel_value_satoshis,
4258                                         }));
4259                                 }
4260                         }
4261                         if self.counterparty_payment_script == outp.script_pubkey {
4262                                 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4263                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4264                                         output: outp.clone(),
4265                                         channel_keys_id: self.channel_keys_id,
4266                                         channel_value_satoshis: self.channel_value_satoshis,
4267                                         channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4268                                 }));
4269                         }
4270                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4271                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4272                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4273                                         output: outp.clone(),
4274                                         channel_keys_id: Some(self.channel_keys_id),
4275                                 });
4276                         }
4277                 }
4278                 spendable_outputs
4279         }
4280
4281         /// Checks if the confirmed transaction is paying funds back to some address we can assume to
4282         /// own.
4283         fn check_tx_and_push_spendable_outputs<L: Deref>(
4284                 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4285         ) where L::Target: Logger {
4286                 for spendable_output in self.get_spendable_outputs(tx) {
4287                         let entry = OnchainEventEntry {
4288                                 txid: tx.txid(),
4289                                 transaction: Some(tx.clone()),
4290                                 height,
4291                                 block_hash: Some(*block_hash),
4292                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4293                         };
4294                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4295                         self.onchain_events_awaiting_threshold_conf.push(entry);
4296                 }
4297         }
4298 }
4299
4300 impl<Signer: WriteableEcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4301 where
4302         T::Target: BroadcasterInterface,
4303         F::Target: FeeEstimator,
4304         L::Target: Logger,
4305 {
4306         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4307                 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4308         }
4309
4310         fn block_disconnected(&self, header: &Header, height: u32) {
4311                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4312         }
4313 }
4314
4315 impl<Signer: WriteableEcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4316 where
4317         M: Deref<Target = ChannelMonitor<Signer>>,
4318         T::Target: BroadcasterInterface,
4319         F::Target: FeeEstimator,
4320         L::Target: Logger,
4321 {
4322         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4323                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4324         }
4325
4326         fn transaction_unconfirmed(&self, txid: &Txid) {
4327                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4328         }
4329
4330         fn best_block_updated(&self, header: &Header, height: u32) {
4331                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4332         }
4333
4334         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4335                 self.0.get_relevant_txids()
4336         }
4337 }
4338
4339 const MAX_ALLOC_SIZE: usize = 64*1024;
4340
4341 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4342                 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4343         fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4344                 macro_rules! unwrap_obj {
4345                         ($key: expr) => {
4346                                 match $key {
4347                                         Ok(res) => res,
4348                                         Err(_) => return Err(DecodeError::InvalidValue),
4349                                 }
4350                         }
4351                 }
4352
4353                 let (entropy_source, signer_provider) = args;
4354
4355                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4356
4357                 let latest_update_id: u64 = Readable::read(reader)?;
4358                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4359
4360                 let destination_script = Readable::read(reader)?;
4361                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4362                         0 => {
4363                                 let revokable_address = Readable::read(reader)?;
4364                                 let per_commitment_point = Readable::read(reader)?;
4365                                 let revokable_script = Readable::read(reader)?;
4366                                 Some((revokable_address, per_commitment_point, revokable_script))
4367                         },
4368                         1 => { None },
4369                         _ => return Err(DecodeError::InvalidValue),
4370                 };
4371                 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4372                 let shutdown_script = {
4373                         let script = <ScriptBuf as Readable>::read(reader)?;
4374                         if script.is_empty() { None } else { Some(script) }
4375                 };
4376
4377                 let channel_keys_id = Readable::read(reader)?;
4378                 let holder_revocation_basepoint = Readable::read(reader)?;
4379                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
4380                 // barely-init'd ChannelMonitors that we can't do anything with.
4381                 let outpoint = OutPoint {
4382                         txid: Readable::read(reader)?,
4383                         index: Readable::read(reader)?,
4384                 };
4385                 let funding_info = (outpoint, Readable::read(reader)?);
4386                 let current_counterparty_commitment_txid = Readable::read(reader)?;
4387                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4388
4389                 let counterparty_commitment_params = Readable::read(reader)?;
4390                 let funding_redeemscript = Readable::read(reader)?;
4391                 let channel_value_satoshis = Readable::read(reader)?;
4392
4393                 let their_cur_per_commitment_points = {
4394                         let first_idx = <U48 as Readable>::read(reader)?.0;
4395                         if first_idx == 0 {
4396                                 None
4397                         } else {
4398                                 let first_point = Readable::read(reader)?;
4399                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4400                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4401                                         Some((first_idx, first_point, None))
4402                                 } else {
4403                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4404                                 }
4405                         }
4406                 };
4407
4408                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4409
4410                 let commitment_secrets = Readable::read(reader)?;
4411
4412                 macro_rules! read_htlc_in_commitment {
4413                         () => {
4414                                 {
4415                                         let offered: bool = Readable::read(reader)?;
4416                                         let amount_msat: u64 = Readable::read(reader)?;
4417                                         let cltv_expiry: u32 = Readable::read(reader)?;
4418                                         let payment_hash: PaymentHash = Readable::read(reader)?;
4419                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
4420
4421                                         HTLCOutputInCommitment {
4422                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4423                                         }
4424                                 }
4425                         }
4426                 }
4427
4428                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4429                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4430                 for _ in 0..counterparty_claimable_outpoints_len {
4431                         let txid: Txid = Readable::read(reader)?;
4432                         let htlcs_count: u64 = Readable::read(reader)?;
4433                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4434                         for _ in 0..htlcs_count {
4435                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4436                         }
4437                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
4438                                 return Err(DecodeError::InvalidValue);
4439                         }
4440                 }
4441
4442                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4443                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
4444                 for _ in 0..counterparty_commitment_txn_on_chain_len {
4445                         let txid: Txid = Readable::read(reader)?;
4446                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4447                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
4448                                 return Err(DecodeError::InvalidValue);
4449                         }
4450                 }
4451
4452                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4453                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4454                 for _ in 0..counterparty_hash_commitment_number_len {
4455                         let payment_hash: PaymentHash = Readable::read(reader)?;
4456                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4457                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
4458                                 return Err(DecodeError::InvalidValue);
4459                         }
4460                 }
4461
4462                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4463                         match <u8 as Readable>::read(reader)? {
4464                                 0 => None,
4465                                 1 => {
4466                                         Some(Readable::read(reader)?)
4467                                 },
4468                                 _ => return Err(DecodeError::InvalidValue),
4469                         };
4470                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4471
4472                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4473                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4474
4475                 let payment_preimages_len: u64 = Readable::read(reader)?;
4476                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4477                 for _ in 0..payment_preimages_len {
4478                         let preimage: PaymentPreimage = Readable::read(reader)?;
4479                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4480                         if let Some(_) = payment_preimages.insert(hash, preimage) {
4481                                 return Err(DecodeError::InvalidValue);
4482                         }
4483                 }
4484
4485                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4486                 let mut pending_monitor_events = Some(
4487                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4488                 for _ in 0..pending_monitor_events_len {
4489                         let ev = match <u8 as Readable>::read(reader)? {
4490                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4491                                 1 => MonitorEvent::HolderForceClosed(funding_info.0),
4492                                 _ => return Err(DecodeError::InvalidValue)
4493                         };
4494                         pending_monitor_events.as_mut().unwrap().push(ev);
4495                 }
4496
4497                 let pending_events_len: u64 = Readable::read(reader)?;
4498                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4499                 for _ in 0..pending_events_len {
4500                         if let Some(event) = MaybeReadable::read(reader)? {
4501                                 pending_events.push(event);
4502                         }
4503                 }
4504
4505                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4506
4507                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4508                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4509                 for _ in 0..waiting_threshold_conf_len {
4510                         if let Some(val) = MaybeReadable::read(reader)? {
4511                                 onchain_events_awaiting_threshold_conf.push(val);
4512                         }
4513                 }
4514
4515                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4516                 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<ScriptBuf>>())));
4517                 for _ in 0..outputs_to_watch_len {
4518                         let txid = Readable::read(reader)?;
4519                         let outputs_len: u64 = Readable::read(reader)?;
4520                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
4521                         for _ in 0..outputs_len {
4522                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
4523                         }
4524                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
4525                                 return Err(DecodeError::InvalidValue);
4526                         }
4527                 }
4528                 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
4529                         reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
4530                 )?;
4531
4532                 let lockdown_from_offchain = Readable::read(reader)?;
4533                 let holder_tx_signed = Readable::read(reader)?;
4534
4535                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
4536                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
4537                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
4538                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
4539                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
4540                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
4541                                 return Err(DecodeError::InvalidValue);
4542                         }
4543                 }
4544
4545                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
4546                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
4547                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
4548                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
4549                         return Err(DecodeError::InvalidValue);
4550                 }
4551
4552                 let mut funding_spend_confirmed = None;
4553                 let mut htlcs_resolved_on_chain = Some(Vec::new());
4554                 let mut funding_spend_seen = Some(false);
4555                 let mut counterparty_node_id = None;
4556                 let mut confirmed_commitment_tx_counterparty_output = None;
4557                 let mut spendable_txids_confirmed = Some(Vec::new());
4558                 let mut counterparty_fulfilled_htlcs = Some(HashMap::new());
4559                 let mut initial_counterparty_commitment_info = None;
4560                 read_tlv_fields!(reader, {
4561                         (1, funding_spend_confirmed, option),
4562                         (3, htlcs_resolved_on_chain, optional_vec),
4563                         (5, pending_monitor_events, optional_vec),
4564                         (7, funding_spend_seen, option),
4565                         (9, counterparty_node_id, option),
4566                         (11, confirmed_commitment_tx_counterparty_output, option),
4567                         (13, spendable_txids_confirmed, optional_vec),
4568                         (15, counterparty_fulfilled_htlcs, option),
4569                         (17, initial_counterparty_commitment_info, option),
4570                 });
4571
4572                 // Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
4573                 // wrong `counterparty_payment_script` was being tracked. Fix it now on deserialization to
4574                 // give them a chance to recognize the spendable output.
4575                 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
4576                         counterparty_payment_script.is_v0_p2wpkh()
4577                 {
4578                         let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
4579                         counterparty_payment_script =
4580                                 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_v0_p2wsh();
4581                 }
4582
4583                 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
4584                         latest_update_id,
4585                         commitment_transaction_number_obscure_factor,
4586
4587                         destination_script,
4588                         broadcasted_holder_revokable_script,
4589                         counterparty_payment_script,
4590                         shutdown_script,
4591
4592                         channel_keys_id,
4593                         holder_revocation_basepoint,
4594                         funding_info,
4595                         current_counterparty_commitment_txid,
4596                         prev_counterparty_commitment_txid,
4597
4598                         counterparty_commitment_params,
4599                         funding_redeemscript,
4600                         channel_value_satoshis,
4601                         their_cur_per_commitment_points,
4602
4603                         on_holder_tx_csv,
4604
4605                         commitment_secrets,
4606                         counterparty_claimable_outpoints,
4607                         counterparty_commitment_txn_on_chain,
4608                         counterparty_hash_commitment_number,
4609                         counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
4610
4611                         prev_holder_signed_commitment_tx,
4612                         current_holder_commitment_tx,
4613                         current_counterparty_commitment_number,
4614                         current_holder_commitment_number,
4615
4616                         payment_preimages,
4617                         pending_monitor_events: pending_monitor_events.unwrap(),
4618                         pending_events,
4619                         is_processing_pending_events: false,
4620
4621                         onchain_events_awaiting_threshold_conf,
4622                         outputs_to_watch,
4623
4624                         onchain_tx_handler,
4625
4626                         lockdown_from_offchain,
4627                         holder_tx_signed,
4628                         funding_spend_seen: funding_spend_seen.unwrap(),
4629                         funding_spend_confirmed,
4630                         confirmed_commitment_tx_counterparty_output,
4631                         htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
4632                         spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
4633
4634                         best_block,
4635                         counterparty_node_id,
4636                         initial_counterparty_commitment_info,
4637                 })))
4638         }
4639 }
4640
4641 #[cfg(test)]
4642 mod tests {
4643         use bitcoin::blockdata::locktime::absolute::LockTime;
4644         use bitcoin::blockdata::script::{ScriptBuf, Builder};
4645         use bitcoin::blockdata::opcodes;
4646         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut};
4647         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
4648         use bitcoin::sighash;
4649         use bitcoin::sighash::EcdsaSighashType;
4650         use bitcoin::hashes::Hash;
4651         use bitcoin::hashes::sha256::Hash as Sha256;
4652         use bitcoin::hashes::hex::FromHex;
4653         use bitcoin::hash_types::{BlockHash, Txid};
4654         use bitcoin::network::constants::Network;
4655         use bitcoin::secp256k1::{SecretKey,PublicKey};
4656         use bitcoin::secp256k1::Secp256k1;
4657         use bitcoin::{Sequence, Witness};
4658
4659         use crate::chain::chaininterface::LowerBoundedFeeEstimator;
4660
4661         use super::ChannelMonitorUpdateStep;
4662         use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
4663         use crate::chain::{BestBlock, Confirm};
4664         use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
4665         use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
4666         use crate::chain::transaction::OutPoint;
4667         use crate::sign::InMemorySigner;
4668         use crate::ln::{PaymentPreimage, PaymentHash};
4669         use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
4670         use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
4671         use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
4672         use crate::ln::functional_test_utils::*;
4673         use crate::ln::script::ShutdownScript;
4674         use crate::util::errors::APIError;
4675         use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
4676         use crate::util::ser::{ReadableArgs, Writeable};
4677         use crate::util::logger::Logger;
4678         use crate::sync::{Arc, Mutex};
4679         use crate::io;
4680         use crate::ln::features::ChannelTypeFeatures;
4681         use crate::prelude::*;
4682
4683         use std::str::FromStr;
4684
4685         fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
4686                 // Previously, monitor updates were allowed freely even after a funding-spend transaction
4687                 // confirmed. This would allow a race condition where we could receive a payment (including
4688                 // the counterparty revoking their broadcasted state!) and accept it without recourse as
4689                 // long as the ChannelMonitor receives the block first, the full commitment update dance
4690                 // occurs after the block is connected, and before the ChannelManager receives the block.
4691                 // Obviously this is an incredibly contrived race given the counterparty would be risking
4692                 // their full channel balance for it, but its worth fixing nonetheless as it makes the
4693                 // potential ChannelMonitor states simpler to reason about.
4694                 //
4695                 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
4696                 // updates is handled correctly in such conditions.
4697                 let chanmon_cfgs = create_chanmon_cfgs(3);
4698                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4699                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4700                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4701                 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
4702                 create_announced_chan_between_nodes(&nodes, 1, 2);
4703
4704                 // Rebalance somewhat
4705                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
4706
4707                 // First route two payments for testing at the end
4708                 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4709                 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4710
4711                 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
4712                 assert_eq!(local_txn.len(), 1);
4713                 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
4714                 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
4715                 check_spends!(remote_txn[1], remote_txn[0]);
4716                 check_spends!(remote_txn[2], remote_txn[0]);
4717                 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
4718
4719                 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
4720                 // channel is now closed, but the ChannelManager doesn't know that yet.
4721                 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
4722                 let conf_height = nodes[0].best_block_info().1 + 1;
4723                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
4724                         &[(0, broadcast_tx)], conf_height);
4725
4726                 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
4727                                                 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
4728                                                 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
4729
4730                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
4731                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
4732                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
4733                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash,
4734                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4735                         ), false, APIError::MonitorUpdateInProgress, {});
4736                 check_added_monitors!(nodes[1], 1);
4737
4738                 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
4739                 // and provides the claim preimages for the two pending HTLCs. The first update generates
4740                 // an error, but the point of this test is to ensure the later updates are still applied.
4741                 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
4742                 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
4743                 assert_eq!(replay_update.updates.len(), 1);
4744                 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
4745                 } else { panic!(); }
4746                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
4747                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
4748
4749                 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
4750                 assert!(
4751                         pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
4752                         .is_err());
4753                 // Even though we error'd on the first update, we should still have generated an HTLC claim
4754                 // transaction
4755                 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4756                 assert!(txn_broadcasted.len() >= 2);
4757                 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
4758                         assert_eq!(tx.input.len(), 1);
4759                         tx.input[0].previous_output.txid == broadcast_tx.txid()
4760                 }).collect::<Vec<_>>();
4761                 assert_eq!(htlc_txn.len(), 2);
4762                 check_spends!(htlc_txn[0], broadcast_tx);
4763                 check_spends!(htlc_txn[1], broadcast_tx);
4764         }
4765         #[test]
4766         fn test_funding_spend_refuses_updates() {
4767                 do_test_funding_spend_refuses_updates(true);
4768                 do_test_funding_spend_refuses_updates(false);
4769         }
4770
4771         #[test]
4772         fn test_prune_preimages() {
4773                 let secp_ctx = Secp256k1::new();
4774                 let logger = Arc::new(TestLogger::new());
4775                 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
4776                 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4777
4778                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4779
4780                 let mut preimages = Vec::new();
4781                 {
4782                         for i in 0..20 {
4783                                 let preimage = PaymentPreimage([i; 32]);
4784                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4785                                 preimages.push((preimage, hash));
4786                         }
4787                 }
4788
4789                 macro_rules! preimages_slice_to_htlcs {
4790                         ($preimages_slice: expr) => {
4791                                 {
4792                                         let mut res = Vec::new();
4793                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
4794                                                 res.push((HTLCOutputInCommitment {
4795                                                         offered: true,
4796                                                         amount_msat: 0,
4797                                                         cltv_expiry: 0,
4798                                                         payment_hash: preimage.1.clone(),
4799                                                         transaction_output_index: Some(idx as u32),
4800                                                 }, ()));
4801                                         }
4802                                         res
4803                                 }
4804                         }
4805                 }
4806                 macro_rules! preimages_slice_to_htlc_outputs {
4807                         ($preimages_slice: expr) => {
4808                                 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
4809                         }
4810                 }
4811                 let dummy_sig = crate::util::crypto::sign(&secp_ctx,
4812                         &bitcoin::secp256k1::Message::from_slice(&[42; 32]).unwrap(),
4813                         &SecretKey::from_slice(&[42; 32]).unwrap());
4814
4815                 macro_rules! test_preimages_exist {
4816                         ($preimages_slice: expr, $monitor: expr) => {
4817                                 for preimage in $preimages_slice {
4818                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
4819                                 }
4820                         }
4821                 }
4822
4823                 let keys = InMemorySigner::new(
4824                         &secp_ctx,
4825                         SecretKey::from_slice(&[41; 32]).unwrap(),
4826                         SecretKey::from_slice(&[41; 32]).unwrap(),
4827                         SecretKey::from_slice(&[41; 32]).unwrap(),
4828                         SecretKey::from_slice(&[41; 32]).unwrap(),
4829                         SecretKey::from_slice(&[41; 32]).unwrap(),
4830                         [41; 32],
4831                         0,
4832                         [0; 32],
4833                         [0; 32],
4834                 );
4835
4836                 let counterparty_pubkeys = ChannelPublicKeys {
4837                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
4838                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
4839                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
4840                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
4841                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
4842                 };
4843                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
4844                 let channel_parameters = ChannelTransactionParameters {
4845                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
4846                         holder_selected_contest_delay: 66,
4847                         is_outbound_from_holder: true,
4848                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
4849                                 pubkeys: counterparty_pubkeys,
4850                                 selected_contest_delay: 67,
4851                         }),
4852                         funding_outpoint: Some(funding_outpoint),
4853                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
4854                 };
4855                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
4856                 // old state.
4857                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4858                 let best_block = BestBlock::from_network(Network::Testnet);
4859                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
4860                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
4861                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
4862                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
4863                         best_block, dummy_key);
4864
4865                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
4866                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4867
4868                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
4869                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4870                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
4871                         preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
4872                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
4873                         preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
4874                 for &(ref preimage, ref hash) in preimages.iter() {
4875                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
4876                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
4877                 }
4878
4879                 // Now provide a secret, pruning preimages 10-15
4880                 let mut secret = [0; 32];
4881                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
4882                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
4883                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
4884                 test_preimages_exist!(&preimages[0..10], monitor);
4885                 test_preimages_exist!(&preimages[15..20], monitor);
4886
4887                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
4888                         preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
4889
4890                 // Now provide a further secret, pruning preimages 15-17
4891                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
4892                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
4893                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
4894                 test_preimages_exist!(&preimages[0..10], monitor);
4895                 test_preimages_exist!(&preimages[17..20], monitor);
4896
4897                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
4898                         preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
4899
4900                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
4901                 // previous commitment tx's preimages too
4902                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
4903                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4904                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
4905                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4906                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
4907                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
4908                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
4909                 test_preimages_exist!(&preimages[0..10], monitor);
4910                 test_preimages_exist!(&preimages[18..20], monitor);
4911
4912                 // But if we do it again, we'll prune 5-10
4913                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
4914                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4915                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
4916                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4917                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
4918                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
4919                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
4920                 test_preimages_exist!(&preimages[0..5], monitor);
4921         }
4922
4923         #[test]
4924         fn test_claim_txn_weight_computation() {
4925                 // We test Claim txn weight, knowing that we want expected weigth and
4926                 // not actual case to avoid sigs and time-lock delays hell variances.
4927
4928                 let secp_ctx = Secp256k1::new();
4929                 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
4930                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
4931
4932                 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
4933                 macro_rules! sign_input {
4934                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
4935                                 let htlc = HTLCOutputInCommitment {
4936                                         offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
4937                                         amount_msat: 0,
4938                                         cltv_expiry: 2 << 16,
4939                                         payment_hash: PaymentHash([1; 32]),
4940                                         transaction_output_index: Some($idx as u32),
4941                                 };
4942                                 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey), 256, &DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(pubkey), &pubkey)) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey)) };
4943                                 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
4944                                 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
4945                                 let mut ser_sig = sig.serialize_der().to_vec();
4946                                 ser_sig.push(EcdsaSighashType::All as u8);
4947                                 $sum_actual_sigs += ser_sig.len() as u64;
4948                                 let witness = $sighash_parts.witness_mut($idx).unwrap();
4949                                 witness.push(ser_sig);
4950                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
4951                                         witness.push(vec!(1));
4952                                 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
4953                                         witness.push(pubkey.clone().serialize().to_vec());
4954                                 } else if *$weight == weight_received_htlc($opt_anchors) {
4955                                         witness.push(vec![0]);
4956                                 } else {
4957                                         witness.push(PaymentPreimage([1; 32]).0.to_vec());
4958                                 }
4959                                 witness.push(redeem_script.into_bytes());
4960                                 let witness = witness.to_vec();
4961                                 println!("witness[0] {}", witness[0].len());
4962                                 println!("witness[1] {}", witness[1].len());
4963                                 println!("witness[2] {}", witness[2].len());
4964                         }
4965                 }
4966
4967                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
4968                 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
4969
4970                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
4971                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
4972                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
4973                         let mut sum_actual_sigs = 0;
4974                         for i in 0..4 {
4975                                 claim_tx.input.push(TxIn {
4976                                         previous_output: BitcoinOutPoint {
4977                                                 txid,
4978                                                 vout: i,
4979                                         },
4980                                         script_sig: ScriptBuf::new(),
4981                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4982                                         witness: Witness::new(),
4983                                 });
4984                         }
4985                         claim_tx.output.push(TxOut {
4986                                 script_pubkey: script_pubkey.clone(),
4987                                 value: 0,
4988                         });
4989                         let base_weight = claim_tx.weight().to_wu();
4990                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(channel_type_features), weight_revoked_offered_htlc(channel_type_features), weight_revoked_received_htlc(channel_type_features)];
4991                         let mut inputs_total_weight = 2; // count segwit flags
4992                         {
4993                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4994                                 for (idx, inp) in inputs_weight.iter().enumerate() {
4995                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
4996                                         inputs_total_weight += inp;
4997                                 }
4998                         }
4999                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5000                 }
5001
5002                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
5003                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5004                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5005                         let mut sum_actual_sigs = 0;
5006                         for i in 0..4 {
5007                                 claim_tx.input.push(TxIn {
5008                                         previous_output: BitcoinOutPoint {
5009                                                 txid,
5010                                                 vout: i,
5011                                         },
5012                                         script_sig: ScriptBuf::new(),
5013                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5014                                         witness: Witness::new(),
5015                                 });
5016                         }
5017                         claim_tx.output.push(TxOut {
5018                                 script_pubkey: script_pubkey.clone(),
5019                                 value: 0,
5020                         });
5021                         let base_weight = claim_tx.weight().to_wu();
5022                         let inputs_weight = vec![weight_offered_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features)];
5023                         let mut inputs_total_weight = 2; // count segwit flags
5024                         {
5025                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5026                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5027                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5028                                         inputs_total_weight += inp;
5029                                 }
5030                         }
5031                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5032                 }
5033
5034                 // Justice tx with 1 revoked HTLC-Success tx output
5035                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5036                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5037                         let mut sum_actual_sigs = 0;
5038                         claim_tx.input.push(TxIn {
5039                                 previous_output: BitcoinOutPoint {
5040                                         txid,
5041                                         vout: 0,
5042                                 },
5043                                 script_sig: ScriptBuf::new(),
5044                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5045                                 witness: Witness::new(),
5046                         });
5047                         claim_tx.output.push(TxOut {
5048                                 script_pubkey: script_pubkey.clone(),
5049                                 value: 0,
5050                         });
5051                         let base_weight = claim_tx.weight().to_wu();
5052                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5053                         let mut inputs_total_weight = 2; // count segwit flags
5054                         {
5055                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5056                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5057                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5058                                         inputs_total_weight += inp;
5059                                 }
5060                         }
5061                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_isg */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5062                 }
5063         }
5064
5065         #[test]
5066         fn test_with_channel_monitor_impl_logger() {
5067                 let secp_ctx = Secp256k1::new();
5068                 let logger = Arc::new(TestLogger::new());
5069
5070                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5071
5072                 let keys = InMemorySigner::new(
5073                         &secp_ctx,
5074                         SecretKey::from_slice(&[41; 32]).unwrap(),
5075                         SecretKey::from_slice(&[41; 32]).unwrap(),
5076                         SecretKey::from_slice(&[41; 32]).unwrap(),
5077                         SecretKey::from_slice(&[41; 32]).unwrap(),
5078                         SecretKey::from_slice(&[41; 32]).unwrap(),
5079                         [41; 32],
5080                         0,
5081                         [0; 32],
5082                         [0; 32],
5083                 );
5084
5085                 let counterparty_pubkeys = ChannelPublicKeys {
5086                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5087                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5088                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5089                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5090                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5091                 };
5092                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
5093                 let channel_parameters = ChannelTransactionParameters {
5094                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5095                         holder_selected_contest_delay: 66,
5096                         is_outbound_from_holder: true,
5097                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5098                                 pubkeys: counterparty_pubkeys,
5099                                 selected_contest_delay: 67,
5100                         }),
5101                         funding_outpoint: Some(funding_outpoint),
5102                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5103                 };
5104                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5105                 let best_block = BestBlock::from_network(Network::Testnet);
5106                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5107                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5108                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5109                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5110                         best_block, dummy_key);
5111
5112                 let chan_id = monitor.inner.lock().unwrap().funding_info.0.to_channel_id().clone();
5113                 let context_logger = WithChannelMonitor::from(&logger, &monitor);
5114                 log_error!(context_logger, "This is an error");
5115                 log_warn!(context_logger, "This is an error");
5116                 log_debug!(context_logger, "This is an error");
5117                 log_trace!(context_logger, "This is an error");
5118                 log_gossip!(context_logger, "This is an error");
5119                 log_info!(context_logger, "This is an error");
5120                 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5121         }
5122         // Further testing is done in the ChannelManager integration tests.
5123 }