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