Log when a ChannelMonitor's claimable balances set goes empty
[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         /// 4032 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                 const BLOCKS_THRESHOLD: u32 = 4032; // ~four weeks
1882                 match (inner.balances_empty_height, is_all_funds_claimed) {
1883                         (Some(balances_empty_height), true) => {
1884                                 // Claimed all funds, check if reached the blocks threshold.
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                                 log_debug!(logger,
1901                                         "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
1902                                         inner.get_funding_txo().0, BLOCKS_THRESHOLD);
1903                                 inner.balances_empty_height = Some(current_height);
1904                                 false
1905                         },
1906                         (None, false) => {
1907                                 // Have funds to claim.
1908                                 false
1909                         },
1910                 }
1911         }
1912
1913         #[cfg(test)]
1914         pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
1915                 self.inner.lock().unwrap().counterparty_payment_script.clone()
1916         }
1917
1918         #[cfg(test)]
1919         pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
1920                 self.inner.lock().unwrap().counterparty_payment_script = script;
1921         }
1922
1923         #[cfg(test)]
1924         pub fn do_signer_call<F: FnMut(&Signer) -> ()>(&self, mut f: F) {
1925                 let inner = self.inner.lock().unwrap();
1926                 f(&inner.onchain_tx_handler.signer);
1927         }
1928 }
1929
1930 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
1931         /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1932         /// to one `Balance` for the HTLC.
1933         fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1934                 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1935         -> Option<Balance> {
1936                 let htlc_commitment_tx_output_idx =
1937                         if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1938
1939                 let mut htlc_spend_txid_opt = None;
1940                 let mut htlc_spend_tx_opt = None;
1941                 let mut holder_timeout_spend_pending = None;
1942                 let mut htlc_spend_pending = None;
1943                 let mut holder_delayed_output_pending = None;
1944                 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1945                         match event.event {
1946                                 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1947                                 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1948                                         debug_assert!(htlc_spend_txid_opt.is_none());
1949                                         htlc_spend_txid_opt = Some(&event.txid);
1950                                         debug_assert!(htlc_spend_tx_opt.is_none());
1951                                         htlc_spend_tx_opt = event.transaction.as_ref();
1952                                         debug_assert!(holder_timeout_spend_pending.is_none());
1953                                         debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1954                                         holder_timeout_spend_pending = Some(event.confirmation_threshold());
1955                                 },
1956                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1957                                 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1958                                         debug_assert!(htlc_spend_txid_opt.is_none());
1959                                         htlc_spend_txid_opt = Some(&event.txid);
1960                                         debug_assert!(htlc_spend_tx_opt.is_none());
1961                                         htlc_spend_tx_opt = event.transaction.as_ref();
1962                                         debug_assert!(htlc_spend_pending.is_none());
1963                                         htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1964                                 },
1965                                 OnchainEvent::MaturingOutput {
1966                                         descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1967                                 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
1968                                         .any(|(input_idx, inp)|
1969                                                  Some(inp.previous_output.txid) == confirmed_txid &&
1970                                                         inp.previous_output.vout == htlc_commitment_tx_output_idx &&
1971                                                                 // A maturing output for an HTLC claim will always be at the same
1972                                                                 // index as the HTLC input. This is true pre-anchors, as there's
1973                                                                 // only 1 input and 1 output. This is also true post-anchors,
1974                                                                 // because we have a SIGHASH_SINGLE|ANYONECANPAY signature from our
1975                                                                 // channel counterparty.
1976                                                                 descriptor.outpoint.index as usize == input_idx
1977                                         ))
1978                                         .unwrap_or(false)
1979                                 => {
1980                                         debug_assert!(holder_delayed_output_pending.is_none());
1981                                         holder_delayed_output_pending = Some(event.confirmation_threshold());
1982                                 },
1983                                 _ => {},
1984                         }
1985                 }
1986                 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1987                         .find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
1988                                 debug_assert!(htlc_spend_txid_opt.is_none());
1989                                 htlc_spend_txid_opt = v.resolving_txid.as_ref();
1990                                 debug_assert!(htlc_spend_tx_opt.is_none());
1991                                 htlc_spend_tx_opt = v.resolving_tx.as_ref();
1992                                 true
1993                         } else { false });
1994                 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1995
1996                 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
1997                 let htlc_output_to_spend =
1998                         if let Some(txid) = htlc_spend_txid_opt {
1999                                 // Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
2000                                 // are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
2001                                 // locate the correct output by ensuring its adjacent input spends the HTLC output
2002                                 // in the commitment.
2003                                 if let Some(ref tx) = htlc_spend_tx_opt {
2004                                         let htlc_input_idx_opt = tx.input.iter().enumerate()
2005                                                 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2006                                                 .map(|(idx, _)| idx as u32);
2007                                         debug_assert!(htlc_input_idx_opt.is_some());
2008                                         BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2009                                 } else {
2010                                         debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2011                                         BitcoinOutPoint::new(*txid, 0)
2012                                 }
2013                         } else {
2014                                 htlc_commitment_outpoint
2015                         };
2016                 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2017
2018                 if let Some(conf_thresh) = holder_delayed_output_pending {
2019                         debug_assert!(holder_commitment);
2020                         return Some(Balance::ClaimableAwaitingConfirmations {
2021                                 amount_satoshis: htlc.amount_msat / 1000,
2022                                 confirmation_height: conf_thresh,
2023                         });
2024                 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
2025                         // Funding transaction spends should be fully confirmed by the time any
2026                         // HTLC transactions are resolved, unless we're talking about a holder
2027                         // commitment tx, whose resolution is delayed until the CSV timeout is
2028                         // reached, even though HTLCs may be resolved after only
2029                         // ANTI_REORG_DELAY confirmations.
2030                         debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2031                 } else if counterparty_revoked_commitment {
2032                         let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2033                                 if let OnchainEvent::MaturingOutput {
2034                                         descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2035                                 } = &event.event {
2036                                         if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2037                                                 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2038                                                         tx.txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2039                                                 } else {
2040                                                         Some(inp.previous_output.txid) == confirmed_txid &&
2041                                                                 inp.previous_output.vout == htlc_commitment_tx_output_idx
2042                                                 }
2043                                         })).unwrap_or(false) {
2044                                                 Some(())
2045                                         } else { None }
2046                                 } else { None }
2047                         });
2048                         if htlc_output_claim_pending.is_some() {
2049                                 // We already push `Balance`s onto the `res` list for every
2050                                 // `StaticOutput` in a `MaturingOutput` in the revoked
2051                                 // counterparty commitment transaction case generally, so don't
2052                                 // need to do so again here.
2053                         } else {
2054                                 debug_assert!(holder_timeout_spend_pending.is_none(),
2055                                         "HTLCUpdate OnchainEvents should never appear for preimage claims");
2056                                 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2057                                         "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2058                                 return Some(Balance::CounterpartyRevokedOutputClaimable {
2059                                         amount_satoshis: htlc.amount_msat / 1000,
2060                                 });
2061                         }
2062                 } else if htlc.offered == holder_commitment {
2063                         // If the payment was outbound, check if there's an HTLCUpdate
2064                         // indicating we have spent this HTLC with a timeout, claiming it back
2065                         // and awaiting confirmations on it.
2066                         if let Some(conf_thresh) = holder_timeout_spend_pending {
2067                                 return Some(Balance::ClaimableAwaitingConfirmations {
2068                                         amount_satoshis: htlc.amount_msat / 1000,
2069                                         confirmation_height: conf_thresh,
2070                                 });
2071                         } else {
2072                                 return Some(Balance::MaybeTimeoutClaimableHTLC {
2073                                         amount_satoshis: htlc.amount_msat / 1000,
2074                                         claimable_height: htlc.cltv_expiry,
2075                                         payment_hash: htlc.payment_hash,
2076                                 });
2077                         }
2078                 } else if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2079                         // Otherwise (the payment was inbound), only expose it as claimable if
2080                         // we know the preimage.
2081                         // Note that if there is a pending claim, but it did not use the
2082                         // preimage, we lost funds to our counterparty! We will then continue
2083                         // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
2084                         debug_assert!(holder_timeout_spend_pending.is_none());
2085                         if let Some((conf_thresh, true)) = htlc_spend_pending {
2086                                 return Some(Balance::ClaimableAwaitingConfirmations {
2087                                         amount_satoshis: htlc.amount_msat / 1000,
2088                                         confirmation_height: conf_thresh,
2089                                 });
2090                         } else {
2091                                 return Some(Balance::ContentiousClaimable {
2092                                         amount_satoshis: htlc.amount_msat / 1000,
2093                                         timeout_height: htlc.cltv_expiry,
2094                                         payment_hash: htlc.payment_hash,
2095                                         payment_preimage: *payment_preimage,
2096                                 });
2097                         }
2098                 } else if htlc_resolved.is_none() {
2099                         return Some(Balance::MaybePreimageClaimableHTLC {
2100                                 amount_satoshis: htlc.amount_msat / 1000,
2101                                 expiry_height: htlc.cltv_expiry,
2102                                 payment_hash: htlc.payment_hash,
2103                         });
2104                 }
2105                 None
2106         }
2107 }
2108
2109 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
2110         /// Gets the balances in this channel which are either claimable by us if we were to
2111         /// force-close the channel now or which are claimable on-chain (possibly awaiting
2112         /// confirmation).
2113         ///
2114         /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
2115         /// included here until an [`Event::SpendableOutputs`] event has been generated for the
2116         /// balance, or until our counterparty has claimed the balance and accrued several
2117         /// confirmations on the claim transaction.
2118         ///
2119         /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
2120         /// LDK prior to 0.0.111, not all or excess balances may be included.
2121         ///
2122         /// See [`Balance`] for additional details on the types of claimable balances which
2123         /// may be returned here and their meanings.
2124         pub fn get_claimable_balances(&self) -> Vec<Balance> {
2125                 let mut res = Vec::new();
2126                 let us = self.inner.lock().unwrap();
2127
2128                 let mut confirmed_txid = us.funding_spend_confirmed;
2129                 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2130                 let mut pending_commitment_tx_conf_thresh = None;
2131                 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2132                         if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2133                                 event.event
2134                         {
2135                                 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2136                                 Some((event.txid, event.confirmation_threshold()))
2137                         } else { None }
2138                 });
2139                 if let Some((txid, conf_thresh)) = funding_spend_pending {
2140                         debug_assert!(us.funding_spend_confirmed.is_none(),
2141                                 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2142                         confirmed_txid = Some(txid);
2143                         pending_commitment_tx_conf_thresh = Some(conf_thresh);
2144                 }
2145
2146                 macro_rules! walk_htlcs {
2147                         ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2148                                 for htlc in $htlc_iter {
2149                                         if htlc.transaction_output_index.is_some() {
2150
2151                                                 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
2152                                                         res.push(bal);
2153                                                 }
2154                                         }
2155                                 }
2156                         }
2157                 }
2158
2159                 if let Some(txid) = confirmed_txid {
2160                         let mut found_commitment_tx = false;
2161                         if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
2162                                 // First look for the to_remote output back to us.
2163                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2164                                         if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2165                                                 if let OnchainEvent::MaturingOutput {
2166                                                         descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2167                                                 } = &event.event {
2168                                                         Some(descriptor.output.value)
2169                                                 } else { None }
2170                                         }) {
2171                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2172                                                         amount_satoshis: value,
2173                                                         confirmation_height: conf_thresh,
2174                                                 });
2175                                         } else {
2176                                                 // If a counterparty commitment transaction is awaiting confirmation, we
2177                                                 // should either have a StaticPaymentOutput MaturingOutput event awaiting
2178                                                 // confirmation with the same height or have never met our dust amount.
2179                                         }
2180                                 }
2181                                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2182                                         walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2183                                 } else {
2184                                         walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2185                                         // The counterparty broadcasted a revoked state!
2186                                         // Look for any StaticOutputs first, generating claimable balances for those.
2187                                         // If any match the confirmed counterparty revoked to_self output, skip
2188                                         // generating a CounterpartyRevokedOutputClaimable.
2189                                         let mut spent_counterparty_output = false;
2190                                         for event in us.onchain_events_awaiting_threshold_conf.iter() {
2191                                                 if let OnchainEvent::MaturingOutput {
2192                                                         descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
2193                                                 } = &event.event {
2194                                                         res.push(Balance::ClaimableAwaitingConfirmations {
2195                                                                 amount_satoshis: output.value,
2196                                                                 confirmation_height: event.confirmation_threshold(),
2197                                                         });
2198                                                         if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
2199                                                                 if event.transaction.as_ref().map(|tx|
2200                                                                         tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
2201                                                                 ).unwrap_or(false) {
2202                                                                         spent_counterparty_output = true;
2203                                                                 }
2204                                                         }
2205                                                 }
2206                                         }
2207
2208                                         if spent_counterparty_output {
2209                                         } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
2210                                                 let output_spendable = us.onchain_tx_handler
2211                                                         .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
2212                                                 if output_spendable {
2213                                                         res.push(Balance::CounterpartyRevokedOutputClaimable {
2214                                                                 amount_satoshis: amt,
2215                                                         });
2216                                                 }
2217                                         } else {
2218                                                 // Counterparty output is missing, either it was broadcasted on a
2219                                                 // previous version of LDK or the counterparty hadn't met dust.
2220                                         }
2221                                 }
2222                                 found_commitment_tx = true;
2223                         } else if txid == us.current_holder_commitment_tx.txid {
2224                                 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
2225                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2226                                         res.push(Balance::ClaimableAwaitingConfirmations {
2227                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2228                                                 confirmation_height: conf_thresh,
2229                                         });
2230                                 }
2231                                 found_commitment_tx = true;
2232                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2233                                 if txid == prev_commitment.txid {
2234                                         walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
2235                                         if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2236                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2237                                                         amount_satoshis: prev_commitment.to_self_value_sat,
2238                                                         confirmation_height: conf_thresh,
2239                                                 });
2240                                         }
2241                                         found_commitment_tx = true;
2242                                 }
2243                         }
2244                         if !found_commitment_tx {
2245                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2246                                         // We blindly assume this is a cooperative close transaction here, and that
2247                                         // neither us nor our counterparty misbehaved. At worst we've under-estimated
2248                                         // the amount we can claim as we'll punish a misbehaving counterparty.
2249                                         res.push(Balance::ClaimableAwaitingConfirmations {
2250                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2251                                                 confirmation_height: conf_thresh,
2252                                         });
2253                                 }
2254                         }
2255                 } else {
2256                         let mut claimable_inbound_htlc_value_sat = 0;
2257                         for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
2258                                 if htlc.transaction_output_index.is_none() { continue; }
2259                                 if htlc.offered {
2260                                         res.push(Balance::MaybeTimeoutClaimableHTLC {
2261                                                 amount_satoshis: htlc.amount_msat / 1000,
2262                                                 claimable_height: htlc.cltv_expiry,
2263                                                 payment_hash: htlc.payment_hash,
2264                                         });
2265                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
2266                                         claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
2267                                 } else {
2268                                         // As long as the HTLC is still in our latest commitment state, treat
2269                                         // it as potentially claimable, even if it has long-since expired.
2270                                         res.push(Balance::MaybePreimageClaimableHTLC {
2271                                                 amount_satoshis: htlc.amount_msat / 1000,
2272                                                 expiry_height: htlc.cltv_expiry,
2273                                                 payment_hash: htlc.payment_hash,
2274                                         });
2275                                 }
2276                         }
2277                         res.push(Balance::ClaimableOnChannelClose {
2278                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
2279                         });
2280                 }
2281
2282                 res
2283         }
2284
2285         /// Gets the set of outbound HTLCs which can be (or have been) resolved by this
2286         /// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
2287         /// to the `ChannelManager` having been persisted.
2288         ///
2289         /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes
2290         /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
2291         /// event from this `ChannelMonitor`).
2292         pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2293                 let mut res = new_hash_map();
2294                 // Just examine the available counterparty commitment transactions. See docs on
2295                 // `fail_unbroadcast_htlcs`, below, for justification.
2296                 let us = self.inner.lock().unwrap();
2297                 macro_rules! walk_counterparty_commitment {
2298                         ($txid: expr) => {
2299                                 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
2300                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2301                                                 if let &Some(ref source) = source_option {
2302                                                         res.insert((**source).clone(), (htlc.clone(),
2303                                                                 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned()));
2304                                                 }
2305                                         }
2306                                 }
2307                         }
2308                 }
2309                 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2310                         walk_counterparty_commitment!(txid);
2311                 }
2312                 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2313                         walk_counterparty_commitment!(txid);
2314                 }
2315                 res
2316         }
2317
2318         /// Gets the set of outbound HTLCs which are pending resolution in this channel or which were
2319         /// resolved with a preimage from our counterparty.
2320         ///
2321         /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
2322         ///
2323         /// Currently, the preimage is unused, however if it is present in the relevant internal state
2324         /// an HTLC is always included even if it has been resolved.
2325         pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2326                 let us = self.inner.lock().unwrap();
2327                 // We're only concerned with the confirmation count of HTLC transactions, and don't
2328                 // actually care how many confirmations a commitment transaction may or may not have. Thus,
2329                 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
2330                 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2331                         us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2332                                 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2333                                         Some(event.txid)
2334                                 } else { None }
2335                         })
2336                 });
2337
2338                 if confirmed_txid.is_none() {
2339                         // If we have not seen a commitment transaction on-chain (ie the channel is not yet
2340                         // closed), just get the full set.
2341                         mem::drop(us);
2342                         return self.get_all_current_outbound_htlcs();
2343                 }
2344
2345                 let mut res = new_hash_map();
2346                 macro_rules! walk_htlcs {
2347                         ($holder_commitment: expr, $htlc_iter: expr) => {
2348                                 for (htlc, source) in $htlc_iter {
2349                                         if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc.transaction_output_index) {
2350                                                 // We should assert that funding_spend_confirmed is_some() here, but we
2351                                                 // have some unit tests which violate HTLC transaction CSVs entirely and
2352                                                 // would fail.
2353                                                 // TODO: Once tests all connect transactions at consensus-valid times, we
2354                                                 // should assert here like we do in `get_claimable_balances`.
2355                                         } else if htlc.offered == $holder_commitment {
2356                                                 // If the payment was outbound, check if there's an HTLCUpdate
2357                                                 // indicating we have spent this HTLC with a timeout, claiming it back
2358                                                 // and awaiting confirmations on it.
2359                                                 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2360                                                         if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
2361                                                                 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
2362                                                                 // before considering it "no longer pending" - this matches when we
2363                                                                 // provide the ChannelManager an HTLC failure event.
2364                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
2365                                                                         us.best_block.height >= event.height + ANTI_REORG_DELAY - 1
2366                                                         } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
2367                                                                 // If the HTLC was fulfilled with a preimage, we consider the HTLC
2368                                                                 // immediately non-pending, matching when we provide ChannelManager
2369                                                                 // the preimage.
2370                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index
2371                                                         } else { false }
2372                                                 });
2373                                                 let counterparty_resolved_preimage_opt =
2374                                                         us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned();
2375                                                 if !htlc_update_confd || counterparty_resolved_preimage_opt.is_some() {
2376                                                         res.insert(source.clone(), (htlc.clone(), counterparty_resolved_preimage_opt));
2377                                                 }
2378                                         }
2379                                 }
2380                         }
2381                 }
2382
2383                 let txid = confirmed_txid.unwrap();
2384                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2385                         walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
2386                                 if let &Some(ref source) = b {
2387                                         Some((a, &**source))
2388                                 } else { None }
2389                         }));
2390                 } else if txid == us.current_holder_commitment_tx.txid {
2391                         walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
2392                                 if let Some(source) = c { Some((a, source)) } else { None }
2393                         }));
2394                 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2395                         if txid == prev_commitment.txid {
2396                                 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
2397                                         if let Some(source) = c { Some((a, source)) } else { None }
2398                                 }));
2399                         }
2400                 }
2401
2402                 res
2403         }
2404
2405         pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
2406                 self.inner.lock().unwrap().payment_preimages.clone()
2407         }
2408 }
2409
2410 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
2411 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
2412 /// after ANTI_REORG_DELAY blocks.
2413 ///
2414 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
2415 /// are the commitment transactions which are generated by us. The off-chain state machine in
2416 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
2417 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
2418 /// included in a remote commitment transaction are failed back if they are not present in the
2419 /// broadcasted commitment transaction.
2420 ///
2421 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
2422 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
2423 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
2424 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
2425 macro_rules! fail_unbroadcast_htlcs {
2426         ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2427          $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2428                 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
2429
2430                 macro_rules! check_htlc_fails {
2431                         ($txid: expr, $commitment_tx: expr) => {
2432                                 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
2433                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2434                                                 if let &Some(ref source) = source_option {
2435                                                         // Check if the HTLC is present in the commitment transaction that was
2436                                                         // broadcast, but not if it was below the dust limit, which we should
2437                                                         // fail backwards immediately as there is no way for us to learn the
2438                                                         // payment_preimage.
2439                                                         // Note that if the dust limit were allowed to change between
2440                                                         // commitment transactions we'd want to be check whether *any*
2441                                                         // broadcastable commitment transaction has the HTLC in it, but it
2442                                                         // cannot currently change after channel initialization, so we don't
2443                                                         // need to here.
2444                                                         let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2445
2446                                                         let mut matched_htlc = false;
2447                                                         for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2448                                                                 if broadcast_htlc.transaction_output_index.is_some() &&
2449                                                                         (Some(&**source) == *broadcast_source ||
2450                                                                          (broadcast_source.is_none() &&
2451                                                                           broadcast_htlc.payment_hash == htlc.payment_hash &&
2452                                                                           broadcast_htlc.amount_msat == htlc.amount_msat)) {
2453                                                                         matched_htlc = true;
2454                                                                         break;
2455                                                                 }
2456                                                         }
2457                                                         if matched_htlc { continue; }
2458                                                         if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2459                                                                 continue;
2460                                                         }
2461                                                         $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2462                                                                 if entry.height != $commitment_tx_conf_height { return true; }
2463                                                                 match entry.event {
2464                                                                         OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2465                                                                                 *update_source != **source
2466                                                                         },
2467                                                                         _ => true,
2468                                                                 }
2469                                                         });
2470                                                         let entry = OnchainEventEntry {
2471                                                                 txid: $commitment_txid_confirmed,
2472                                                                 transaction: Some($commitment_tx_confirmed.clone()),
2473                                                                 height: $commitment_tx_conf_height,
2474                                                                 block_hash: Some(*$commitment_tx_conf_hash),
2475                                                                 event: OnchainEvent::HTLCUpdate {
2476                                                                         source: (**source).clone(),
2477                                                                         payment_hash: htlc.payment_hash.clone(),
2478                                                                         htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2479                                                                         commitment_tx_output_idx: None,
2480                                                                 },
2481                                                         };
2482                                                         log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2483                                                                 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2484                                                                 $commitment_txid_confirmed, entry.confirmation_threshold());
2485                                                         $self.onchain_events_awaiting_threshold_conf.push(entry);
2486                                                 }
2487                                         }
2488                                 }
2489                         }
2490                 }
2491                 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2492                         check_htlc_fails!(txid, "current");
2493                 }
2494                 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2495                         check_htlc_fails!(txid, "previous");
2496                 }
2497         } }
2498 }
2499
2500 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
2501 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
2502 // in-line tests later.
2503
2504 #[cfg(test)]
2505 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2506         use bitcoin::blockdata::opcodes;
2507         let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2508         ret[131] = opcodes::all::OP_DROP.to_u8();
2509         ret[132] = opcodes::all::OP_DROP.to_u8();
2510         ret[133] = opcodes::all::OP_DROP.to_u8();
2511         ret[134] = opcodes::all::OP_DROP.to_u8();
2512         ret[135] = opcodes::OP_TRUE.to_u8();
2513         Vec::from(&ret[..])
2514 }
2515
2516 #[cfg(test)]
2517 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2518         vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2519 }
2520
2521 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2522         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
2523         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
2524         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
2525         fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2526                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2527                         return Err("Previous secret did not match new one");
2528                 }
2529
2530                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
2531                 // events for now-revoked/fulfilled HTLCs.
2532                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2533                         if self.current_counterparty_commitment_txid.unwrap() != txid {
2534                                 let cur_claimables = self.counterparty_claimable_outpoints.get(
2535                                         &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2536                                 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2537                                         if let Some(source) = source_opt {
2538                                                 if !cur_claimables.iter()
2539                                                         .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2540                                                 {
2541                                                         self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2542                                                 }
2543                                         }
2544                                 }
2545                                 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2546                                         *source_opt = None;
2547                                 }
2548                         } else {
2549                                 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2550                         }
2551                 }
2552
2553                 if !self.payment_preimages.is_empty() {
2554                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2555                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2556                         let min_idx = self.get_min_seen_secret();
2557                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2558
2559                         self.payment_preimages.retain(|&k, _| {
2560                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2561                                         if k == htlc.payment_hash {
2562                                                 return true
2563                                         }
2564                                 }
2565                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2566                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2567                                                 if k == htlc.payment_hash {
2568                                                         return true
2569                                                 }
2570                                         }
2571                                 }
2572                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2573                                         if *cn < min_idx {
2574                                                 return true
2575                                         }
2576                                         true
2577                                 } else { false };
2578                                 if contains {
2579                                         counterparty_hash_commitment_number.remove(&k);
2580                                 }
2581                                 false
2582                         });
2583                 }
2584
2585                 Ok(())
2586         }
2587
2588         fn provide_initial_counterparty_commitment_tx<L: Deref>(
2589                 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2590                 commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32,
2591                 to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor<L>,
2592         ) where L::Target: Logger {
2593                 self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(),
2594                         feerate_per_kw, to_broadcaster_value, to_countersignatory_value));
2595
2596                 #[cfg(debug_assertions)] {
2597                         let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
2598                         debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), txid);
2599                 }
2600
2601                 self.provide_latest_counterparty_commitment_tx(txid, htlc_outputs, commitment_number,
2602                                 their_per_commitment_point, logger);
2603         }
2604
2605         fn provide_latest_counterparty_commitment_tx<L: Deref>(
2606                 &mut self, txid: Txid,
2607                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2608                 commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor<L>,
2609         ) where L::Target: Logger {
2610                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2611                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2612                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2613                 // timeouts)
2614                 for &(ref htlc, _) in &htlc_outputs {
2615                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2616                 }
2617
2618                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2619                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2620                 self.current_counterparty_commitment_txid = Some(txid);
2621                 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2622                 self.current_counterparty_commitment_number = commitment_number;
2623                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2624                 match self.their_cur_per_commitment_points {
2625                         Some(old_points) => {
2626                                 if old_points.0 == commitment_number + 1 {
2627                                         self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2628                                 } else if old_points.0 == commitment_number + 2 {
2629                                         if let Some(old_second_point) = old_points.2 {
2630                                                 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2631                                         } else {
2632                                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2633                                         }
2634                                 } else {
2635                                         self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2636                                 }
2637                         },
2638                         None => {
2639                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2640                         }
2641                 }
2642                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2643                 for htlc in htlc_outputs {
2644                         if htlc.0.transaction_output_index.is_some() {
2645                                 htlcs.push(htlc.0);
2646                         }
2647                 }
2648         }
2649
2650         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2651         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2652         /// is important that any clones of this channel monitor (including remote clones) by kept
2653         /// up-to-date as our holder commitment transaction is updated.
2654         /// Panics if set_on_holder_tx_csv has never been called.
2655         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> {
2656                 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
2657                         // If we have non-dust HTLCs in htlc_outputs, ensure they match the HTLCs in the
2658                         // `holder_commitment_tx`. In the future, we'll no longer provide the redundant data
2659                         // and just pass in source data via `nondust_htlc_sources`.
2660                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
2661                         for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
2662                                 debug_assert_eq!(a, b);
2663                         }
2664                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
2665                         for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
2666                                 debug_assert_eq!(a, b);
2667                         }
2668                         debug_assert!(nondust_htlc_sources.is_empty());
2669                 } else {
2670                         // If we don't have any non-dust HTLCs in htlc_outputs, assume they were all passed via
2671                         // `nondust_htlc_sources`, building up the final htlc_outputs by combining
2672                         // `nondust_htlc_sources` and the `holder_commitment_tx`
2673                         #[cfg(debug_assertions)] {
2674                                 let mut prev = -1;
2675                                 for htlc in holder_commitment_tx.trust().htlcs().iter() {
2676                                         assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
2677                                         prev = htlc.transaction_output_index.unwrap() as i32;
2678                                 }
2679                         }
2680                         debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
2681                         debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
2682                         debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
2683
2684                         let mut sources_iter = nondust_htlc_sources.into_iter();
2685
2686                         for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
2687                                 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
2688                         {
2689                                 if htlc.offered {
2690                                         let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
2691                                         #[cfg(debug_assertions)] {
2692                                                 assert!(source.possibly_matches_output(htlc));
2693                                         }
2694                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
2695                                 } else {
2696                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
2697                                 }
2698                         }
2699                         debug_assert!(sources_iter.next().is_none());
2700                 }
2701
2702                 let trusted_tx = holder_commitment_tx.trust();
2703                 let txid = trusted_tx.txid();
2704                 let tx_keys = trusted_tx.keys();
2705                 self.current_holder_commitment_number = trusted_tx.commitment_number();
2706                 let mut new_holder_commitment_tx = HolderSignedTx {
2707                         txid,
2708                         revocation_key: tx_keys.revocation_key,
2709                         a_htlc_key: tx_keys.broadcaster_htlc_key,
2710                         b_htlc_key: tx_keys.countersignatory_htlc_key,
2711                         delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2712                         per_commitment_point: tx_keys.per_commitment_point,
2713                         htlc_outputs,
2714                         to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2715                         feerate_per_kw: trusted_tx.feerate_per_kw(),
2716                 };
2717                 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2718                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2719                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2720                 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2721                         #[cfg(debug_assertions)] {
2722                                 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
2723                                                 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2724                                 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
2725                                         if let Some(source) = source_opt {
2726                                                 SentHTLCId::from_source(source) == *claimed_htlc_id
2727                                         } else { false }
2728                                 }));
2729                         }
2730                         self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
2731                 }
2732                 if self.holder_tx_signed {
2733                         return Err("Latest holder commitment signed has already been signed, update is rejected");
2734                 }
2735                 Ok(())
2736         }
2737
2738         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2739         /// commitment_tx_infos which contain the payment hash have been revoked.
2740         fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2741                 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2742                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
2743         where B::Target: BroadcasterInterface,
2744                     F::Target: FeeEstimator,
2745                     L::Target: Logger,
2746         {
2747                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2748
2749                 let confirmed_spend_txid = self.funding_spend_confirmed.or_else(|| {
2750                         self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
2751                                 OnchainEvent::FundingSpendConfirmation { .. } => Some(event.txid),
2752                                 _ => None,
2753                         })
2754                 });
2755                 let confirmed_spend_txid = if let Some(txid) = confirmed_spend_txid {
2756                         txid
2757                 } else {
2758                         return;
2759                 };
2760
2761                 // If the channel is force closed, try to claim the output from this preimage.
2762                 // First check if a counterparty commitment transaction has been broadcasted:
2763                 macro_rules! claim_htlcs {
2764                         ($commitment_number: expr, $txid: expr) => {
2765                                 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2766                                 self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
2767                         }
2768                 }
2769                 if let Some(txid) = self.current_counterparty_commitment_txid {
2770                         if txid == confirmed_spend_txid {
2771                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2772                                         claim_htlcs!(*commitment_number, txid);
2773                                 } else {
2774                                         debug_assert!(false);
2775                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2776                                 }
2777                                 return;
2778                         }
2779                 }
2780                 if let Some(txid) = self.prev_counterparty_commitment_txid {
2781                         if txid == confirmed_spend_txid {
2782                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2783                                         claim_htlcs!(*commitment_number, txid);
2784                                 } else {
2785                                         debug_assert!(false);
2786                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2787                                 }
2788                                 return;
2789                         }
2790                 }
2791
2792                 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2793                 // claiming the HTLC output from each of the holder commitment transactions.
2794                 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2795                 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2796                 // holder commitment transactions.
2797                 if self.broadcasted_holder_revokable_script.is_some() {
2798                         let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
2799                                 Some(&self.current_holder_commitment_tx)
2800                         } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
2801                                 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
2802                                         Some(prev_holder_commitment_tx)
2803                                 } else {
2804                                         None
2805                                 }
2806                         } else {
2807                                 None
2808                         };
2809                         if let Some(holder_commitment_tx) = holder_commitment_tx {
2810                                 // Assume that the broadcasted commitment transaction confirmed in the current best
2811                                 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2812                                 // transactions.
2813                                 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
2814                                 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
2815                         }
2816                 }
2817         }
2818
2819         fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
2820                 let funding_outp = HolderFundingOutput::build(
2821                         self.funding_redeemscript.clone(),
2822                         self.channel_value_satoshis,
2823                         self.onchain_tx_handler.channel_type_features().clone()
2824                 );
2825                 let commitment_package = PackageTemplate::build_package(
2826                         self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
2827                         PackageSolvingData::HolderFundingOutput(funding_outp),
2828                         self.best_block.height, self.best_block.height
2829                 );
2830                 let mut claimable_outpoints = vec![commitment_package];
2831                 let event = MonitorEvent::HolderForceClosedWithInfo {
2832                         reason,
2833                         outpoint: self.funding_info.0,
2834                         channel_id: self.channel_id,
2835                 };
2836                 self.pending_monitor_events.push(event);
2837
2838                 // Although we aren't signing the transaction directly here, the transaction will be signed
2839                 // in the claim that is queued to OnchainTxHandler. We set holder_tx_signed here to reject
2840                 // new channel updates.
2841                 self.holder_tx_signed = true;
2842                 let mut watch_outputs = Vec::new();
2843                 // We can't broadcast our HTLC transactions while the commitment transaction is
2844                 // unconfirmed. We'll delay doing so until we detect the confirmed commitment in
2845                 // `transactions_confirmed`.
2846                 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
2847                         // Because we're broadcasting a commitment transaction, we should construct the package
2848                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2849                         // "not yet confirmed" things as discardable, so we cannot do that here.
2850                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
2851                                 &self.current_holder_commitment_tx, self.best_block.height
2852                         );
2853                         let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
2854                         let new_outputs = self.get_broadcasted_holder_watch_outputs(
2855                                 &self.current_holder_commitment_tx, &unsigned_commitment_tx
2856                         );
2857                         if !new_outputs.is_empty() {
2858                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2859                         }
2860                         claimable_outpoints.append(&mut new_outpoints);
2861                 }
2862                 (claimable_outpoints, watch_outputs)
2863         }
2864
2865         pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
2866                 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
2867         )
2868         where
2869                 B::Target: BroadcasterInterface,
2870                 F::Target: FeeEstimator,
2871                 L::Target: Logger,
2872         {
2873                 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed);
2874                 self.onchain_tx_handler.update_claims_view_from_requests(
2875                         claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
2876                         fee_estimator, logger
2877                 );
2878         }
2879
2880         fn update_monitor<B: Deref, F: Deref, L: Deref>(
2881                 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
2882         ) -> Result<(), ()>
2883         where B::Target: BroadcasterInterface,
2884                 F::Target: FeeEstimator,
2885                 L::Target: Logger,
2886         {
2887                 if self.latest_update_id == CLOSED_CHANNEL_UPDATE_ID && updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2888                         log_info!(logger, "Applying post-force-closed update to monitor {} with {} change(s).",
2889                                 log_funding_info!(self), updates.updates.len());
2890                 } else if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2891                         log_info!(logger, "Applying force close update to monitor {} with {} change(s).",
2892                                 log_funding_info!(self), updates.updates.len());
2893                 } else {
2894                         log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
2895                                 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2896                 }
2897
2898                 if updates.counterparty_node_id.is_some() {
2899                         if self.counterparty_node_id.is_none() {
2900                                 self.counterparty_node_id = updates.counterparty_node_id;
2901                         } else {
2902                                 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
2903                         }
2904                 }
2905
2906                 // ChannelMonitor updates may be applied after force close if we receive a preimage for a
2907                 // broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
2908                 // is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
2909                 // sentinel value instead.
2910                 //
2911                 // The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
2912                 // thinks the channel needs to have its commitment transaction broadcast, so we'll allow
2913                 // them as well.
2914                 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2915                         assert_eq!(updates.updates.len(), 1);
2916                         match updates.updates[0] {
2917                                 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
2918                                 // We should have already seen a `ChannelForceClosed` update if we're trying to
2919                                 // provide a preimage at this point.
2920                                 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
2921                                         debug_assert_eq!(self.latest_update_id, CLOSED_CHANNEL_UPDATE_ID),
2922                                 _ => {
2923                                         log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2924                                         panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2925                                 },
2926                         }
2927                 } else if self.latest_update_id + 1 != updates.update_id {
2928                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2929                 }
2930                 let mut ret = Ok(());
2931                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
2932                 for update in updates.updates.iter() {
2933                         match update {
2934                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
2935                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2936                                         if self.lockdown_from_offchain { panic!(); }
2937                                         if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone()) {
2938                                                 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2939                                                 log_error!(logger, "    {}", e);
2940                                                 ret = Err(());
2941                                         }
2942                                 }
2943                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
2944                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2945                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2946                                 },
2947                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2948                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2949                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2950                                 },
2951                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2952                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2953                                         if let Err(e) = self.provide_secret(*idx, *secret) {
2954                                                 debug_assert!(false, "Latest counterparty commitment secret was invalid");
2955                                                 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2956                                                 log_error!(logger, "    {}", e);
2957                                                 ret = Err(());
2958                                         }
2959                                 },
2960                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2961                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2962                                         self.lockdown_from_offchain = true;
2963                                         if *should_broadcast {
2964                                                 // There's no need to broadcast our commitment transaction if we've seen one
2965                                                 // confirmed (even with 1 confirmation) as it'll be rejected as
2966                                                 // duplicate/conflicting.
2967                                                 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
2968                                                         self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
2969                                                                 OnchainEvent::FundingSpendConfirmation { .. } => true,
2970                                                                 _ => false,
2971                                                         }).is_some();
2972                                                 if detected_funding_spend {
2973                                                         log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
2974                                                         continue;
2975                                                 }
2976                                                 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
2977                                         } else if !self.holder_tx_signed {
2978                                                 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
2979                                                 log_error!(logger, "    in channel monitor for channel {}!", &self.channel_id());
2980                                                 log_error!(logger, "    Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
2981                                         } else {
2982                                                 // If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
2983                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2984                                                 // shouldn't print the scary warning above.
2985                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2986                                         }
2987                                 },
2988                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2989                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2990                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2991                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2992                                         }
2993                                 },
2994                         }
2995                 }
2996
2997                 #[cfg(debug_assertions)] {
2998                         self.counterparty_commitment_txs_from_update(updates);
2999                 }
3000
3001                 // If the updates succeeded and we were in an already closed channel state, then there's no
3002                 // need to refuse any updates we expect to receive afer seeing a confirmed commitment.
3003                 if ret.is_ok() && updates.update_id == CLOSED_CHANNEL_UPDATE_ID && self.latest_update_id == updates.update_id {
3004                         return Ok(());
3005                 }
3006
3007                 self.latest_update_id = updates.update_id;
3008
3009                 // Refuse updates after we've detected a spend onchain, but only if we haven't processed a
3010                 // force closed monitor update yet.
3011                 if ret.is_ok() && self.funding_spend_seen && self.latest_update_id != CLOSED_CHANNEL_UPDATE_ID {
3012                         log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3013                         Err(())
3014                 } else { ret }
3015         }
3016
3017         fn get_latest_update_id(&self) -> u64 {
3018                 self.latest_update_id
3019         }
3020
3021         fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3022                 &self.funding_info
3023         }
3024
3025         pub fn channel_id(&self) -> ChannelId {
3026                 self.channel_id
3027         }
3028
3029         fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3030                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
3031                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
3032                 // its trivial to do, double-check that here.
3033                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
3034                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3035                 }
3036                 &self.outputs_to_watch
3037         }
3038
3039         fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3040                 let mut ret = Vec::new();
3041                 mem::swap(&mut ret, &mut self.pending_monitor_events);
3042                 ret
3043         }
3044
3045         /// Gets the set of events that are repeated regularly (e.g. those which RBF bump
3046         /// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
3047         /// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
3048         pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3049                 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3050                 let mut ret = Vec::with_capacity(pending_claim_events.len());
3051                 for (claim_id, claim_event) in pending_claim_events {
3052                         match claim_event {
3053                                 ClaimEvent::BumpCommitment {
3054                                         package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3055                                 } => {
3056                                         let channel_id = self.channel_id;
3057                                         // unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3058                                         // introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3059                                         // since v0.0.110.
3060                                         let counterparty_node_id = self.counterparty_node_id.unwrap();
3061                                         let commitment_txid = commitment_tx.txid();
3062                                         debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3063                                         let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3064                                         let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3065                                                 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value);
3066                                         ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3067                                                 channel_id,
3068                                                 counterparty_node_id,
3069                                                 claim_id,
3070                                                 package_target_feerate_sat_per_1000_weight,
3071                                                 commitment_tx,
3072                                                 commitment_tx_fee_satoshis,
3073                                                 anchor_descriptor: AnchorDescriptor {
3074                                                         channel_derivation_parameters: ChannelDerivationParameters {
3075                                                                 keys_id: self.channel_keys_id,
3076                                                                 value_satoshis: self.channel_value_satoshis,
3077                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3078                                                         },
3079                                                         outpoint: BitcoinOutPoint {
3080                                                                 txid: commitment_txid,
3081                                                                 vout: anchor_output_idx,
3082                                                         },
3083                                                 },
3084                                                 pending_htlcs,
3085                                         }));
3086                                 },
3087                                 ClaimEvent::BumpHTLC {
3088                                         target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3089                                 } => {
3090                                         let channel_id = self.channel_id;
3091                                         // unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3092                                         // introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3093                                         // since v0.0.110.
3094                                         let counterparty_node_id = self.counterparty_node_id.unwrap();
3095                                         let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3096                                         for htlc in htlcs {
3097                                                 htlc_descriptors.push(HTLCDescriptor {
3098                                                         channel_derivation_parameters: ChannelDerivationParameters {
3099                                                                 keys_id: self.channel_keys_id,
3100                                                                 value_satoshis: self.channel_value_satoshis,
3101                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3102                                                         },
3103                                                         commitment_txid: htlc.commitment_txid,
3104                                                         per_commitment_number: htlc.per_commitment_number,
3105                                                         per_commitment_point: self.onchain_tx_handler.signer.get_per_commitment_point(
3106                                                                 htlc.per_commitment_number, &self.onchain_tx_handler.secp_ctx,
3107                                                         ),
3108                                                         feerate_per_kw: 0,
3109                                                         htlc: htlc.htlc,
3110                                                         preimage: htlc.preimage,
3111                                                         counterparty_sig: htlc.counterparty_sig,
3112                                                 });
3113                                         }
3114                                         ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
3115                                                 channel_id,
3116                                                 counterparty_node_id,
3117                                                 claim_id,
3118                                                 target_feerate_sat_per_1000_weight,
3119                                                 htlc_descriptors,
3120                                                 tx_lock_time,
3121                                         }));
3122                                 }
3123                         }
3124                 }
3125                 ret
3126         }
3127
3128         fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
3129                 let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
3130                         to_countersignatory_value) = self.initial_counterparty_commitment_info?;
3131                 let htlc_outputs = vec![];
3132
3133                 let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
3134                         &their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
3135                         feerate_per_kw, htlc_outputs);
3136                 Some(commitment_tx)
3137         }
3138
3139         fn build_counterparty_commitment_tx(
3140                 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
3141                 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
3142                 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
3143         ) -> CommitmentTransaction {
3144                 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
3145                         .counterparty_parameters.as_ref().unwrap().pubkeys;
3146                 let countersignatory_keys =
3147                         &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
3148
3149                 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
3150                 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
3151                 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
3152                         &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
3153                 let channel_parameters =
3154                         &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
3155
3156                 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
3157                         to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
3158                         countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
3159                         channel_parameters)
3160         }
3161
3162         fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3163                 update.updates.iter().filter_map(|update| {
3164                         match update {
3165                                 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3166                                         ref htlc_outputs, commitment_number, their_per_commitment_point,
3167                                         feerate_per_kw: Some(feerate_per_kw),
3168                                         to_broadcaster_value_sat: Some(to_broadcaster_value),
3169                                         to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3170
3171                                         let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3172                                                 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3173                                         }).collect::<Vec<_>>();
3174
3175                                         let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3176                                                         &their_per_commitment_point, to_broadcaster_value,
3177                                                         to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3178
3179                                         debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3180
3181                                         Some(commitment_tx)
3182                                 },
3183                                 _ => None,
3184                         }
3185                 }).collect()
3186         }
3187
3188         fn sign_to_local_justice_tx(
3189                 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3190         ) -> Result<Transaction, ()> {
3191                 let secret = self.get_secret(commitment_number).ok_or(())?;
3192                 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3193                 let their_per_commitment_point = PublicKey::from_secret_key(
3194                         &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3195
3196                 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3197                         &self.holder_revocation_basepoint, &their_per_commitment_point);
3198                 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3199                         &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3200                 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3201                         self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3202
3203                 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3204                         &justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3205                 justice_tx.input[input_idx].witness.push_bitcoin_signature(&sig.serialize_der(), EcdsaSighashType::All);
3206                 justice_tx.input[input_idx].witness.push(&[1u8]);
3207                 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3208                 Ok(justice_tx)
3209         }
3210
3211         /// Can only fail if idx is < get_min_seen_secret
3212         fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3213                 self.commitment_secrets.get_secret(idx)
3214         }
3215
3216         fn get_min_seen_secret(&self) -> u64 {
3217                 self.commitment_secrets.get_min_seen_secret()
3218         }
3219
3220         fn get_cur_counterparty_commitment_number(&self) -> u64 {
3221                 self.current_counterparty_commitment_number
3222         }
3223
3224         fn get_cur_holder_commitment_number(&self) -> u64 {
3225                 self.current_holder_commitment_number
3226         }
3227
3228         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
3229         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
3230         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
3231         /// HTLC-Success/HTLC-Timeout transactions.
3232         ///
3233         /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
3234         /// general information about the output that is to the counterparty in the commitment
3235         /// transaction.
3236         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3237                 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
3238         where L::Target: Logger {
3239                 // Most secp and related errors trying to create keys means we have no hope of constructing
3240                 // a spend transaction...so we return no transactions to broadcast
3241                 let mut claimable_outpoints = Vec::new();
3242                 let mut watch_outputs = Vec::new();
3243                 let mut to_counterparty_output_info = None;
3244
3245                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
3246                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3247
3248                 macro_rules! ignore_error {
3249                         ( $thing : expr ) => {
3250                                 match $thing {
3251                                         Ok(a) => a,
3252                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
3253                                 }
3254                         };
3255                 }
3256
3257                 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);
3258                 if commitment_number >= self.get_min_seen_secret() {
3259                         let secret = self.get_secret(commitment_number).unwrap();
3260                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3261                         let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3262                         let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point,);
3263                         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));
3264
3265                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3266                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
3267
3268                         // First, process non-htlc outputs (to_holder & to_counterparty)
3269                         for (idx, outp) in tx.output.iter().enumerate() {
3270                                 if outp.script_pubkey == revokeable_p2wsh {
3271                                         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());
3272                                         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);
3273                                         claimable_outpoints.push(justice_package);
3274                                         to_counterparty_output_info =
3275                                                 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3276                                 }
3277                         }
3278
3279                         // Then, try to find revoked htlc outputs
3280                         if let Some(ref per_commitment_data) = per_commitment_option {
3281                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
3282                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3283                                                 if transaction_output_index as usize >= tx.output.len() ||
3284                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
3285                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
3286                                                         return (claimable_outpoints, (commitment_txid, watch_outputs),
3287                                                                 to_counterparty_output_info);
3288                                                 }
3289                                                 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);
3290                                                 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, height);
3291                                                 claimable_outpoints.push(justice_package);
3292                                         }
3293                                 }
3294                         }
3295
3296                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
3297                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
3298                                 // We're definitely a counterparty commitment transaction!
3299                                 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
3300                                 for (idx, outp) in tx.output.iter().enumerate() {
3301                                         watch_outputs.push((idx as u32, outp.clone()));
3302                                 }
3303                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3304
3305                                 if let Some(per_commitment_data) = per_commitment_option {
3306                                         fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3307                                                 block_hash, per_commitment_data.iter().map(|(htlc, htlc_source)|
3308                                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3309                                                 ), logger);
3310                                 } else {
3311                                         // Our fuzzers aren't constrained by pesky things like valid signatures, so can
3312                                         // spend our funding output with a transaction which doesn't match our past
3313                                         // commitment transactions. Thus, we can only debug-assert here when not
3314                                         // fuzzing.
3315                                         debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
3316                                         fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3317                                                 block_hash, [].iter().map(|reference| *reference), logger);
3318                                 }
3319                         }
3320                 } else if let Some(per_commitment_data) = per_commitment_option {
3321                         // While this isn't useful yet, there is a potential race where if a counterparty
3322                         // revokes a state at the same time as the commitment transaction for that state is
3323                         // confirmed, and the watchtower receives the block before the user, the user could
3324                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
3325                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
3326                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
3327                         // insert it here.
3328                         for (idx, outp) in tx.output.iter().enumerate() {
3329                                 watch_outputs.push((idx as u32, outp.clone()));
3330                         }
3331                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3332
3333                         log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3334                         fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3335                                 per_commitment_data.iter().map(|(htlc, htlc_source)|
3336                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3337                                 ), logger);
3338
3339                         let (htlc_claim_reqs, counterparty_output_info) =
3340                                 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
3341                         to_counterparty_output_info = counterparty_output_info;
3342                         for req in htlc_claim_reqs {
3343                                 claimable_outpoints.push(req);
3344                         }
3345
3346                 }
3347                 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
3348         }
3349
3350         /// Returns the HTLC claim package templates and the counterparty output info
3351         fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
3352         -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3353                 let mut claimable_outpoints = Vec::new();
3354                 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3355
3356                 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
3357                         Some(outputs) => outputs,
3358                         None => return (claimable_outpoints, to_counterparty_output_info),
3359                 };
3360                 let per_commitment_points = match self.their_cur_per_commitment_points {
3361                         Some(points) => points,
3362                         None => return (claimable_outpoints, to_counterparty_output_info),
3363                 };
3364
3365                 let per_commitment_point =
3366                         // If the counterparty commitment tx is the latest valid state, use their latest
3367                         // per-commitment point
3368                         if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
3369                         else if let Some(point) = per_commitment_points.2.as_ref() {
3370                                 // If counterparty commitment tx is the state previous to the latest valid state, use
3371                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
3372                                 // them to temporarily have two valid commitment txns from our viewpoint)
3373                                 if per_commitment_points.0 == commitment_number + 1 {
3374                                         point
3375                                 } else { return (claimable_outpoints, to_counterparty_output_info); }
3376                         } else { return (claimable_outpoints, to_counterparty_output_info); };
3377
3378                 if let Some(transaction) = tx {
3379                         let revocation_pubkey = RevocationKey::from_basepoint(
3380                                 &self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point);
3381
3382                         let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point);
3383
3384                         let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3385                                 self.counterparty_commitment_params.on_counterparty_tx_csv,
3386                                 &delayed_key).to_v0_p2wsh();
3387                         for (idx, outp) in transaction.output.iter().enumerate() {
3388                                 if outp.script_pubkey == revokeable_p2wsh {
3389                                         to_counterparty_output_info =
3390                                                 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3391                                 }
3392                         }
3393                 }
3394
3395                 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
3396                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3397                                 if let Some(transaction) = tx {
3398                                         if transaction_output_index as usize >= transaction.output.len() ||
3399                                                 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
3400                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
3401                                                         return (claimable_outpoints, to_counterparty_output_info);
3402                                                 }
3403                                 }
3404                                 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
3405                                 if preimage.is_some() || !htlc.offered {
3406                                         let counterparty_htlc_outp = if htlc.offered {
3407                                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(
3408                                                         CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
3409                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3410                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
3411                                                                 preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3412                                         } else {
3413                                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(
3414                                                         CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
3415                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3416                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
3417                                                                 htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3418                                         };
3419                                         let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry, 0);
3420                                         claimable_outpoints.push(counterparty_package);
3421                                 }
3422                         }
3423                 }
3424
3425                 (claimable_outpoints, to_counterparty_output_info)
3426         }
3427
3428         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
3429         fn check_spend_counterparty_htlc<L: Deref>(
3430                 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3431         ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3432                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3433                 let per_commitment_key = match SecretKey::from_slice(&secret) {
3434                         Ok(key) => key,
3435                         Err(_) => return (Vec::new(), None)
3436                 };
3437                 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3438
3439                 let htlc_txid = tx.txid();
3440                 let mut claimable_outpoints = vec![];
3441                 let mut outputs_to_watch = None;
3442                 // Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
3443                 // with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
3444                 // counterparty can now aggregate multiple HTLCs into a single transaction thanks to
3445                 // `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
3446                 // confirmed revoked HTLC transaction (for more details, see
3447                 // https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
3448                 //
3449                 // We make sure we're not vulnerable to this case by checking all inputs of the transaction,
3450                 // and claim those which spend the commitment transaction, have a witness of 5 elements, and
3451                 // have a corresponding output at the same index within the transaction.
3452                 for (idx, input) in tx.input.iter().enumerate() {
3453                         if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3454                                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3455                                 let revk_outp = RevokedOutput::build(
3456                                         per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3457                                         self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3458                                         tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3459                                         false
3460                                 );
3461                                 let justice_package = PackageTemplate::build_package(
3462                                         htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3463                                         height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, height
3464                                 );
3465                                 claimable_outpoints.push(justice_package);
3466                                 if outputs_to_watch.is_none() {
3467                                         outputs_to_watch = Some((htlc_txid, vec![]));
3468                                 }
3469                                 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3470                         }
3471                 }
3472                 (claimable_outpoints, outputs_to_watch)
3473         }
3474
3475         // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
3476         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
3477         // script so we can detect whether a holder transaction has been seen on-chain.
3478         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3479                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3480
3481                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3482                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3483
3484                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3485                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3486                                 let htlc_output = if htlc.offered {
3487                                         let htlc_output = HolderHTLCOutput::build_offered(
3488                                                 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone()
3489                                         );
3490                                         htlc_output
3491                                 } else {
3492                                         let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
3493                                                 preimage.clone()
3494                                         } else {
3495                                                 // We can't build an HTLC-Success transaction without the preimage
3496                                                 continue;
3497                                         };
3498                                         let htlc_output = HolderHTLCOutput::build_accepted(
3499                                                 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone()
3500                                         );
3501                                         htlc_output
3502                                 };
3503                                 let htlc_package = PackageTemplate::build_package(
3504                                         holder_tx.txid, transaction_output_index,
3505                                         PackageSolvingData::HolderHTLCOutput(htlc_output),
3506                                         htlc.cltv_expiry, conf_height
3507                                 );
3508                                 claim_requests.push(htlc_package);
3509                         }
3510                 }
3511
3512                 (claim_requests, broadcasted_holder_revokable_script)
3513         }
3514
3515         // Returns holder HTLC outputs to watch and react to in case of spending.
3516         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3517                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3518                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3519                         if let Some(transaction_output_index) = htlc.transaction_output_index {
3520                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3521                         }
3522                 }
3523                 watch_outputs
3524         }
3525
3526         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
3527         /// revoked using data in holder_claimable_outpoints.
3528         /// Should not be used if check_spend_revoked_transaction succeeds.
3529         /// Returns None unless the transaction is definitely one of our commitment transactions.
3530         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 {
3531                 let commitment_txid = tx.txid();
3532                 let mut claim_requests = Vec::new();
3533                 let mut watch_outputs = Vec::new();
3534
3535                 macro_rules! append_onchain_update {
3536                         ($updates: expr, $to_watch: expr) => {
3537                                 claim_requests = $updates.0;
3538                                 self.broadcasted_holder_revokable_script = $updates.1;
3539                                 watch_outputs.append(&mut $to_watch);
3540                         }
3541                 }
3542
3543                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
3544                 let mut is_holder_tx = false;
3545
3546                 if self.current_holder_commitment_tx.txid == commitment_txid {
3547                         is_holder_tx = true;
3548                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3549                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3550                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3551                         append_onchain_update!(res, to_watch);
3552                         fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3553                                 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3554                                 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3555                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3556                         if holder_tx.txid == commitment_txid {
3557                                 is_holder_tx = true;
3558                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3559                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
3560                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3561                                 append_onchain_update!(res, to_watch);
3562                                 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3563                                         holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3564                                         logger);
3565                         }
3566                 }
3567
3568                 if is_holder_tx {
3569                         Some((claim_requests, (commitment_txid, watch_outputs)))
3570                 } else {
3571                         None
3572                 }
3573         }
3574
3575         /// Cancels any existing pending claims for a commitment that previously confirmed and has now
3576         /// been replaced by another.
3577         pub fn cancel_prev_commitment_claims<L: Deref>(
3578                 &mut self, logger: &L, confirmed_commitment_txid: &Txid
3579         ) where L::Target: Logger {
3580                 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
3581                         // Cancel any pending claims for counterparty commitments we've seen confirm.
3582                         if counterparty_commitment_txid == confirmed_commitment_txid {
3583                                 continue;
3584                         }
3585                         for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
3586                                 log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
3587                                         counterparty_commitment_txid);
3588                                 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
3589                                 if let Some(vout) = htlc.transaction_output_index {
3590                                         outpoint.vout = vout;
3591                                         self.onchain_tx_handler.abandon_claim(&outpoint);
3592                                 }
3593                         }
3594                 }
3595                 if self.holder_tx_signed {
3596                         // If we've signed, we may have broadcast either commitment (prev or current), and
3597                         // attempted to claim from it immediately without waiting for a confirmation.
3598                         if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
3599                                 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3600                                         self.current_holder_commitment_tx.txid);
3601                                 let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
3602                                 for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
3603                                         if let Some(vout) = htlc.transaction_output_index {
3604                                                 outpoint.vout = vout;
3605                                                 self.onchain_tx_handler.abandon_claim(&outpoint);
3606                                         }
3607                                 }
3608                         }
3609                         if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3610                                 if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
3611                                         log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3612                                                 prev_holder_commitment_tx.txid);
3613                                         let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
3614                                         for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
3615                                                 if let Some(vout) = htlc.transaction_output_index {
3616                                                         outpoint.vout = vout;
3617                                                         self.onchain_tx_handler.abandon_claim(&outpoint);
3618                                                 }
3619                                         }
3620                                 }
3621                         }
3622                 } else {
3623                         // No previous claim.
3624                 }
3625         }
3626
3627         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3628         /// Note that this includes possibly-locktimed-in-the-future transactions!
3629         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
3630                 &mut self, logger: &WithChannelMonitor<L>
3631         ) -> Vec<Transaction> where L::Target: Logger {
3632                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3633                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3634                 let txid = commitment_tx.txid();
3635                 let mut holder_transactions = vec![commitment_tx];
3636                 // When anchor outputs are present, the HTLC transactions are only final once the commitment
3637                 // transaction confirms due to the CSV 1 encumberance.
3638                 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3639                         return holder_transactions;
3640                 }
3641                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3642                         if let Some(vout) = htlc.0.transaction_output_index {
3643                                 let preimage = if !htlc.0.offered {
3644                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3645                                                 // We can't build an HTLC-Success transaction without the preimage
3646                                                 continue;
3647                                         }
3648                                 } else { None };
3649                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_maybe_signed_htlc_tx(
3650                                         &::bitcoin::OutPoint { txid, vout }, &preimage
3651                                 ) {
3652                                         if htlc_tx.is_fully_signed() {
3653                                                 holder_transactions.push(htlc_tx.0);
3654                                         }
3655                                 }
3656                         }
3657                 }
3658                 holder_transactions
3659         }
3660
3661         fn block_connected<B: Deref, F: Deref, L: Deref>(
3662                 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
3663                 fee_estimator: F, logger: &WithChannelMonitor<L>,
3664         ) -> Vec<TransactionOutputs>
3665                 where B::Target: BroadcasterInterface,
3666                         F::Target: FeeEstimator,
3667                         L::Target: Logger,
3668         {
3669                 let block_hash = header.block_hash();
3670                 self.best_block = BestBlock::new(block_hash, height);
3671
3672                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3673                 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3674         }
3675
3676         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3677                 &mut self,
3678                 header: &Header,
3679                 height: u32,
3680                 broadcaster: B,
3681                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3682                 logger: &WithChannelMonitor<L>,
3683         ) -> Vec<TransactionOutputs>
3684         where
3685                 B::Target: BroadcasterInterface,
3686                 F::Target: FeeEstimator,
3687                 L::Target: Logger,
3688         {
3689                 let block_hash = header.block_hash();
3690
3691                 if height > self.best_block.height {
3692                         self.best_block = BestBlock::new(block_hash, height);
3693                         log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
3694                         self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
3695                 } else if block_hash != self.best_block.block_hash {
3696                         self.best_block = BestBlock::new(block_hash, height);
3697                         log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
3698                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3699                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
3700                         Vec::new()
3701                 } else { Vec::new() }
3702         }
3703
3704         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3705                 &mut self,
3706                 header: &Header,
3707                 txdata: &TransactionData,
3708                 height: u32,
3709                 broadcaster: B,
3710                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3711                 logger: &WithChannelMonitor<L>,
3712         ) -> Vec<TransactionOutputs>
3713         where
3714                 B::Target: BroadcasterInterface,
3715                 F::Target: FeeEstimator,
3716                 L::Target: Logger,
3717         {
3718                 let txn_matched = self.filter_block(txdata);
3719                 for tx in &txn_matched {
3720                         let mut output_val = 0;
3721                         for out in tx.output.iter() {
3722                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3723                                 output_val += out.value;
3724                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3725                         }
3726                 }
3727
3728                 let block_hash = header.block_hash();
3729
3730                 let mut watch_outputs = Vec::new();
3731                 let mut claimable_outpoints = Vec::new();
3732                 'tx_iter: for tx in &txn_matched {
3733                         let txid = tx.txid();
3734                         log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
3735                         // If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
3736                         if Some(txid) == self.funding_spend_confirmed {
3737                                 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
3738                                 continue 'tx_iter;
3739                         }
3740                         for ev in self.onchain_events_awaiting_threshold_conf.iter() {
3741                                 if ev.txid == txid {
3742                                         if let Some(conf_hash) = ev.block_hash {
3743                                                 assert_eq!(header.block_hash(), conf_hash,
3744                                                         "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
3745                                                         This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
3746                                         }
3747                                         log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
3748                                         continue 'tx_iter;
3749                                 }
3750                         }
3751                         for htlc in self.htlcs_resolved_on_chain.iter() {
3752                                 if Some(txid) == htlc.resolving_txid {
3753                                         log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
3754                                         continue 'tx_iter;
3755                                 }
3756                         }
3757                         for spendable_txid in self.spendable_txids_confirmed.iter() {
3758                                 if txid == *spendable_txid {
3759                                         log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
3760                                         continue 'tx_iter;
3761                                 }
3762                         }
3763
3764                         if tx.input.len() == 1 {
3765                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
3766                                 // commitment transactions and HTLC transactions will all only ever have one input
3767                                 // (except for HTLC transactions for channels with anchor outputs), which is an easy
3768                                 // way to filter out any potential non-matching txn for lazy filters.
3769                                 let prevout = &tx.input[0].previous_output;
3770                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
3771                                         let mut balance_spendable_csv = None;
3772                                         log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
3773                                                 &self.channel_id(), txid);
3774                                         self.funding_spend_seen = true;
3775                                         let mut commitment_tx_to_counterparty_output = None;
3776                                         if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
3777                                                 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
3778                                                         self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
3779                                                 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
3780                                                 if !new_outputs.1.is_empty() {
3781                                                         watch_outputs.push(new_outputs);
3782                                                 }
3783                                                 claimable_outpoints.append(&mut new_outpoints);
3784                                                 if new_outpoints.is_empty() {
3785                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
3786                                                                 #[cfg(not(fuzzing))]
3787                                                                 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
3788                                                                         "A commitment transaction matched as both a counterparty and local commitment tx?");
3789                                                                 if !new_outputs.1.is_empty() {
3790                                                                         watch_outputs.push(new_outputs);
3791                                                                 }
3792                                                                 claimable_outpoints.append(&mut new_outpoints);
3793                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
3794                                                         }
3795                                                 }
3796                                         }
3797                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3798                                                 txid,
3799                                                 transaction: Some((*tx).clone()),
3800                                                 height,
3801                                                 block_hash: Some(block_hash),
3802                                                 event: OnchainEvent::FundingSpendConfirmation {
3803                                                         on_local_output_csv: balance_spendable_csv,
3804                                                         commitment_tx_to_counterparty_output,
3805                                                 },
3806                                         });
3807                                         // Now that we've detected a confirmed commitment transaction, attempt to cancel
3808                                         // pending claims for any commitments that were previously confirmed such that
3809                                         // we don't continue claiming inputs that no longer exist.
3810                                         self.cancel_prev_commitment_claims(&logger, &txid);
3811                                 }
3812                         }
3813                         if tx.input.len() >= 1 {
3814                                 // While all commitment transactions have one input, HTLC transactions may have more
3815                                 // if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
3816                                 // other ways which can have more than one output.
3817                                 for tx_input in &tx.input {
3818                                         let commitment_txid = tx_input.previous_output.txid;
3819                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
3820                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
3821                                                         &tx, commitment_number, &commitment_txid, height, &logger
3822                                                 );
3823                                                 claimable_outpoints.append(&mut new_outpoints);
3824                                                 if let Some(new_outputs) = new_outputs_option {
3825                                                         watch_outputs.push(new_outputs);
3826                                                 }
3827                                                 // Since there may be multiple HTLCs for this channel (all spending the
3828                                                 // same commitment tx) being claimed by the counterparty within the same
3829                                                 // transaction, and `check_spend_counterparty_htlc` already checks all the
3830                                                 // ones relevant to this channel, we can safely break from our loop.
3831                                                 break;
3832                                         }
3833                                 }
3834                                 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
3835
3836                                 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
3837                         }
3838                 }
3839
3840                 if height > self.best_block.height {
3841                         self.best_block = BestBlock::new(block_hash, height);
3842                 }
3843
3844                 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
3845         }
3846
3847         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
3848         /// `self.best_block` before calling if a new best blockchain tip is available. More
3849         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
3850         /// complexity especially in
3851         /// `OnchainTx::update_claims_view_from_requests`/`OnchainTx::update_claims_view_from_matched_txn`.
3852         ///
3853         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
3854         /// confirmed at, even if it is not the current best height.
3855         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
3856                 &mut self,
3857                 conf_height: u32,
3858                 conf_hash: BlockHash,
3859                 txn_matched: Vec<&Transaction>,
3860                 mut watch_outputs: Vec<TransactionOutputs>,
3861                 mut claimable_outpoints: Vec<PackageTemplate>,
3862                 broadcaster: &B,
3863                 fee_estimator: &LowerBoundedFeeEstimator<F>,
3864                 logger: &WithChannelMonitor<L>,
3865         ) -> Vec<TransactionOutputs>
3866         where
3867                 B::Target: BroadcasterInterface,
3868                 F::Target: FeeEstimator,
3869                 L::Target: Logger,
3870         {
3871                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
3872                 debug_assert!(self.best_block.height >= conf_height);
3873
3874                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
3875                 if should_broadcast {
3876                         let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HTLCsTimedOut);
3877                         claimable_outpoints.append(&mut new_outpoints);
3878                         watch_outputs.append(&mut new_outputs);
3879                 }
3880
3881                 // Find which on-chain events have reached their confirmation threshold.
3882                 let onchain_events_awaiting_threshold_conf =
3883                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
3884                 let mut onchain_events_reaching_threshold_conf = Vec::new();
3885                 for entry in onchain_events_awaiting_threshold_conf {
3886                         if entry.has_reached_confirmation_threshold(&self.best_block) {
3887                                 onchain_events_reaching_threshold_conf.push(entry);
3888                         } else {
3889                                 self.onchain_events_awaiting_threshold_conf.push(entry);
3890                         }
3891                 }
3892
3893                 // Used to check for duplicate HTLC resolutions.
3894                 #[cfg(debug_assertions)]
3895                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
3896                         .iter()
3897                         .filter_map(|entry| match &entry.event {
3898                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
3899                                 _ => None,
3900                         })
3901                         .collect();
3902                 #[cfg(debug_assertions)]
3903                 let mut matured_htlcs = Vec::new();
3904
3905                 // Produce actionable events from on-chain events having reached their threshold.
3906                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
3907                         match entry.event {
3908                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
3909                                         // Check for duplicate HTLC resolutions.
3910                                         #[cfg(debug_assertions)]
3911                                         {
3912                                                 debug_assert!(
3913                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
3914                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
3915                                                          call either transaction_unconfirmed for the conflicting transaction \
3916                                                          or block_disconnected for a block containing it.");
3917                                                 debug_assert!(
3918                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
3919                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
3920                                                          call either transaction_unconfirmed for the conflicting transaction \
3921                                                          or block_disconnected for a block containing it.");
3922                                                 matured_htlcs.push(source.clone());
3923                                         }
3924
3925                                         log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
3926                                                 &payment_hash, entry.txid);
3927                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3928                                                 payment_hash,
3929                                                 payment_preimage: None,
3930                                                 source: source.clone(),
3931                                                 htlc_value_satoshis,
3932                                         }));
3933                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3934                                                 commitment_tx_output_idx,
3935                                                 resolving_txid: Some(entry.txid),
3936                                                 resolving_tx: entry.transaction,
3937                                                 payment_preimage: None,
3938                                         });
3939                                 },
3940                                 OnchainEvent::MaturingOutput { descriptor } => {
3941                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
3942                                         self.pending_events.push(Event::SpendableOutputs {
3943                                                 outputs: vec![descriptor],
3944                                                 channel_id: Some(self.channel_id()),
3945                                         });
3946                                         self.spendable_txids_confirmed.push(entry.txid);
3947                                 },
3948                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
3949                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3950                                                 commitment_tx_output_idx: Some(commitment_tx_output_idx),
3951                                                 resolving_txid: Some(entry.txid),
3952                                                 resolving_tx: entry.transaction,
3953                                                 payment_preimage: preimage,
3954                                         });
3955                                 },
3956                                 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
3957                                         self.funding_spend_confirmed = Some(entry.txid);
3958                                         self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
3959                                 },
3960                         }
3961                 }
3962
3963                 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, fee_estimator, logger);
3964                 self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, fee_estimator, logger);
3965
3966                 // Determine new outputs to watch by comparing against previously known outputs to watch,
3967                 // updating the latter in the process.
3968                 watch_outputs.retain(|&(ref txid, ref txouts)| {
3969                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
3970                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
3971                 });
3972                 #[cfg(test)]
3973                 {
3974                         // If we see a transaction for which we registered outputs previously,
3975                         // make sure the registered scriptpubkey at the expected index match
3976                         // the actual transaction output one. We failed this case before #653.
3977                         for tx in &txn_matched {
3978                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
3979                                         for idx_and_script in outputs.iter() {
3980                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
3981                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
3982                                         }
3983                                 }
3984                         }
3985                 }
3986                 watch_outputs
3987         }
3988
3989         fn block_disconnected<B: Deref, F: Deref, L: Deref>(
3990                 &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
3991         ) where B::Target: BroadcasterInterface,
3992                 F::Target: FeeEstimator,
3993                 L::Target: Logger,
3994         {
3995                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
3996
3997                 //We may discard:
3998                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
3999                 //- maturing spendable output has transaction paying us has been disconnected
4000                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
4001
4002                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4003                 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
4004
4005                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
4006         }
4007
4008         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
4009                 &mut self,
4010                 txid: &Txid,
4011                 broadcaster: B,
4012                 fee_estimator: &LowerBoundedFeeEstimator<F>,
4013                 logger: &WithChannelMonitor<L>,
4014         ) where
4015                 B::Target: BroadcasterInterface,
4016                 F::Target: FeeEstimator,
4017                 L::Target: Logger,
4018         {
4019                 let mut removed_height = None;
4020                 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
4021                         if entry.txid == *txid {
4022                                 removed_height = Some(entry.height);
4023                                 break;
4024                         }
4025                 }
4026
4027                 if let Some(removed_height) = removed_height {
4028                         log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
4029                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
4030                                 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
4031                                 false
4032                         } else { true });
4033                 }
4034
4035                 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
4036
4037                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
4038         }
4039
4040         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
4041         /// transactions thereof.
4042         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
4043                 let mut matched_txn = new_hash_set();
4044                 txdata.iter().filter(|&&(_, tx)| {
4045                         let mut matches = self.spends_watched_output(tx);
4046                         for input in tx.input.iter() {
4047                                 if matches { break; }
4048                                 if matched_txn.contains(&input.previous_output.txid) {
4049                                         matches = true;
4050                                 }
4051                         }
4052                         if matches {
4053                                 matched_txn.insert(tx.txid());
4054                         }
4055                         matches
4056                 }).map(|(_, tx)| *tx).collect()
4057         }
4058
4059         /// Checks if a given transaction spends any watched outputs.
4060         fn spends_watched_output(&self, tx: &Transaction) -> bool {
4061                 for input in tx.input.iter() {
4062                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
4063                                 for (idx, _script_pubkey) in outputs.iter() {
4064                                         if *idx == input.previous_output.vout {
4065                                                 #[cfg(test)]
4066                                                 {
4067                                                         // If the expected script is a known type, check that the witness
4068                                                         // appears to be spending the correct type (ie that the match would
4069                                                         // actually succeed in BIP 158/159-style filters).
4070                                                         if _script_pubkey.is_v0_p2wsh() {
4071                                                                 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
4072                                                                         // In at least one test we use a deliberately bogus witness
4073                                                                         // script which hit an old panic. Thus, we check for that here
4074                                                                         // and avoid the assert if its the expected bogus script.
4075                                                                         return true;
4076                                                                 }
4077
4078                                                                 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4079                                                         } else if _script_pubkey.is_v0_p2wpkh() {
4080                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
4081                                                         } else { panic!(); }
4082                                                 }
4083                                                 return true;
4084                                         }
4085                                 }
4086                         }
4087                 }
4088
4089                 false
4090         }
4091
4092         fn should_broadcast_holder_commitment_txn<L: Deref>(
4093                 &self, logger: &WithChannelMonitor<L>
4094         ) -> bool where L::Target: Logger {
4095                 // There's no need to broadcast our commitment transaction if we've seen one confirmed (even
4096                 // with 1 confirmation) as it'll be rejected as duplicate/conflicting.
4097                 if self.funding_spend_confirmed.is_some() ||
4098                         self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
4099                                 OnchainEvent::FundingSpendConfirmation { .. } => true,
4100                                 _ => false,
4101                         }).is_some()
4102                 {
4103                         return false;
4104                 }
4105                 // We need to consider all HTLCs which are:
4106                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
4107                 //    transactions and we'd end up in a race, or
4108                 //  * are in our latest holder commitment transaction, as this is the thing we will
4109                 //    broadcast if we go on-chain.
4110                 // Note that we consider HTLCs which were below dust threshold here - while they don't
4111                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
4112                 // to the source, and if we don't fail the channel we will have to ensure that the next
4113                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
4114                 // easier to just fail the channel as this case should be rare enough anyway.
4115                 let height = self.best_block.height;
4116                 macro_rules! scan_commitment {
4117                         ($htlcs: expr, $holder_tx: expr) => {
4118                                 for ref htlc in $htlcs {
4119                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
4120                                         // chain with enough room to claim the HTLC without our counterparty being able to
4121                                         // time out the HTLC first.
4122                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
4123                                         // concern is being able to claim the corresponding inbound HTLC (on another
4124                                         // channel) before it expires. In fact, we don't even really care if our
4125                                         // counterparty here claims such an outbound HTLC after it expired as long as we
4126                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
4127                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
4128                                         // we give ourselves a few blocks of headroom after expiration before going
4129                                         // on-chain for an expired HTLC.
4130                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
4131                                         // from us until we've reached the point where we go on-chain with the
4132                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
4133                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
4134                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
4135                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
4136                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
4137                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
4138                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
4139                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
4140                                         //  The final, above, condition is checked for statically in channelmanager
4141                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
4142                                         let htlc_outbound = $holder_tx == htlc.offered;
4143                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4144                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4145                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4146                                                 return true;
4147                                         }
4148                                 }
4149                         }
4150                 }
4151
4152                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4153
4154                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
4155                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4156                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4157                         }
4158                 }
4159                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4160                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4161                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4162                         }
4163                 }
4164
4165                 false
4166         }
4167
4168         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
4169         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
4170         fn is_resolving_htlc_output<L: Deref>(
4171                 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4172         ) where L::Target: Logger {
4173                 'outer_loop: for input in &tx.input {
4174                         let mut payment_data = None;
4175                         let htlc_claim = HTLCClaim::from_witness(&input.witness);
4176                         let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4177                         let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4178                         #[cfg(not(fuzzing))]
4179                         let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4180                         let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4181                         #[cfg(not(fuzzing))]
4182                         let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4183
4184                         let mut payment_preimage = PaymentPreimage([0; 32]);
4185                         if offered_preimage_claim || accepted_preimage_claim {
4186                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4187                         }
4188
4189                         macro_rules! log_claim {
4190                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4191                                         let outbound_htlc = $holder_tx == $htlc.offered;
4192                                         // HTLCs must either be claimed by a matching script type or through the
4193                                         // revocation path:
4194                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4195                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4196                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4197                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4198                                         // Further, only exactly one of the possible spend paths should have been
4199                                         // matched by any HTLC spend:
4200                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4201                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4202                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4203                                                          revocation_sig_claim as u8, 1);
4204                                         if ($holder_tx && revocation_sig_claim) ||
4205                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4206                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
4207                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
4208                                                         if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4209                                                         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" });
4210                                         } else {
4211                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4212                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
4213                                                         if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4214                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4215                                         }
4216                                 }
4217                         }
4218
4219                         macro_rules! check_htlc_valid_counterparty {
4220                                 ($counterparty_txid: expr, $htlc_output: expr) => {
4221                                         if let Some(txid) = $counterparty_txid {
4222                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
4223                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4224                                                                 if let &Some(ref source) = pending_source {
4225                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4226                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4227                                                                         break;
4228                                                                 }
4229                                                         }
4230                                                 }
4231                                         }
4232                                 }
4233                         }
4234
4235                         macro_rules! scan_commitment {
4236                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4237                                         for (ref htlc_output, source_option) in $htlcs {
4238                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4239                                                         if let Some(ref source) = source_option {
4240                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
4241                                                                 // We have a resolution of an HTLC either from one of our latest
4242                                                                 // holder commitment transactions or an unrevoked counterparty commitment
4243                                                                 // transaction. This implies we either learned a preimage, the HTLC
4244                                                                 // has timed out, or we screwed up. In any case, we should now
4245                                                                 // resolve the source HTLC with the original sender.
4246                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4247                                                         } else if !$holder_tx {
4248                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
4249                                                                 if payment_data.is_none() {
4250                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
4251                                                                 }
4252                                                         }
4253                                                         if payment_data.is_none() {
4254                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
4255                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
4256                                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4257                                                                         txid: tx.txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4258                                                                         event: OnchainEvent::HTLCSpendConfirmation {
4259                                                                                 commitment_tx_output_idx: input.previous_output.vout,
4260                                                                                 preimage: if accepted_preimage_claim || offered_preimage_claim {
4261                                                                                         Some(payment_preimage) } else { None },
4262                                                                                 // If this is a payment to us (ie !outbound_htlc), wait for
4263                                                                                 // the CSV delay before dropping the HTLC from claimable
4264                                                                                 // balance if the claim was an HTLC-Success transaction (ie
4265                                                                                 // accepted_preimage_claim).
4266                                                                                 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4267                                                                                         Some(self.on_holder_tx_csv) } else { None },
4268                                                                         },
4269                                                                 });
4270                                                                 continue 'outer_loop;
4271                                                         }
4272                                                 }
4273                                         }
4274                                 }
4275                         }
4276
4277                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4278                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4279                                         "our latest holder commitment tx", true);
4280                         }
4281                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4282                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4283                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4284                                                 "our previous holder commitment tx", true);
4285                                 }
4286                         }
4287                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4288                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
4289                                         "counterparty commitment tx", false);
4290                         }
4291
4292                         // Check that scan_commitment, above, decided there is some source worth relaying an
4293                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
4294                         if let Some((source, payment_hash, amount_msat)) = payment_data {
4295                                 if accepted_preimage_claim {
4296                                         if !self.pending_monitor_events.iter().any(
4297                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4298                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4299                                                         txid: tx.txid(),
4300                                                         height,
4301                                                         block_hash: Some(*block_hash),
4302                                                         transaction: Some(tx.clone()),
4303                                                         event: OnchainEvent::HTLCSpendConfirmation {
4304                                                                 commitment_tx_output_idx: input.previous_output.vout,
4305                                                                 preimage: Some(payment_preimage),
4306                                                                 on_to_local_output_csv: None,
4307                                                         },
4308                                                 });
4309                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4310                                                         source,
4311                                                         payment_preimage: Some(payment_preimage),
4312                                                         payment_hash,
4313                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4314                                                 }));
4315                                         }
4316                                 } else if offered_preimage_claim {
4317                                         if !self.pending_monitor_events.iter().any(
4318                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4319                                                         upd.source == source
4320                                                 } else { false }) {
4321                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4322                                                         txid: tx.txid(),
4323                                                         transaction: Some(tx.clone()),
4324                                                         height,
4325                                                         block_hash: Some(*block_hash),
4326                                                         event: OnchainEvent::HTLCSpendConfirmation {
4327                                                                 commitment_tx_output_idx: input.previous_output.vout,
4328                                                                 preimage: Some(payment_preimage),
4329                                                                 on_to_local_output_csv: None,
4330                                                         },
4331                                                 });
4332                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4333                                                         source,
4334                                                         payment_preimage: Some(payment_preimage),
4335                                                         payment_hash,
4336                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4337                                                 }));
4338                                         }
4339                                 } else {
4340                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4341                                                 if entry.height != height { return true; }
4342                                                 match entry.event {
4343                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4344                                                                 *htlc_source != source
4345                                                         },
4346                                                         _ => true,
4347                                                 }
4348                                         });
4349                                         let entry = OnchainEventEntry {
4350                                                 txid: tx.txid(),
4351                                                 transaction: Some(tx.clone()),
4352                                                 height,
4353                                                 block_hash: Some(*block_hash),
4354                                                 event: OnchainEvent::HTLCUpdate {
4355                                                         source, payment_hash,
4356                                                         htlc_value_satoshis: Some(amount_msat / 1000),
4357                                                         commitment_tx_output_idx: Some(input.previous_output.vout),
4358                                                 },
4359                                         };
4360                                         log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4361                                         self.onchain_events_awaiting_threshold_conf.push(entry);
4362                                 }
4363                         }
4364                 }
4365         }
4366
4367         fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4368                 let mut spendable_outputs = Vec::new();
4369                 for (i, outp) in tx.output.iter().enumerate() {
4370                         if outp.script_pubkey == self.destination_script {
4371                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4372                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4373                                         output: outp.clone(),
4374                                         channel_keys_id: Some(self.channel_keys_id),
4375                                 });
4376                         }
4377                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4378                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4379                                         spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4380                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4381                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
4382                                                 to_self_delay: self.on_holder_tx_csv,
4383                                                 output: outp.clone(),
4384                                                 revocation_pubkey: broadcasted_holder_revokable_script.2,
4385                                                 channel_keys_id: self.channel_keys_id,
4386                                                 channel_value_satoshis: self.channel_value_satoshis,
4387                                         }));
4388                                 }
4389                         }
4390                         if self.counterparty_payment_script == outp.script_pubkey {
4391                                 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4392                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4393                                         output: outp.clone(),
4394                                         channel_keys_id: self.channel_keys_id,
4395                                         channel_value_satoshis: self.channel_value_satoshis,
4396                                         channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4397                                 }));
4398                         }
4399                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4400                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4401                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4402                                         output: outp.clone(),
4403                                         channel_keys_id: Some(self.channel_keys_id),
4404                                 });
4405                         }
4406                 }
4407                 spendable_outputs
4408         }
4409
4410         /// Checks if the confirmed transaction is paying funds back to some address we can assume to
4411         /// own.
4412         fn check_tx_and_push_spendable_outputs<L: Deref>(
4413                 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4414         ) where L::Target: Logger {
4415                 for spendable_output in self.get_spendable_outputs(tx) {
4416                         let entry = OnchainEventEntry {
4417                                 txid: tx.txid(),
4418                                 transaction: Some(tx.clone()),
4419                                 height,
4420                                 block_hash: Some(*block_hash),
4421                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4422                         };
4423                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4424                         self.onchain_events_awaiting_threshold_conf.push(entry);
4425                 }
4426         }
4427 }
4428
4429 impl<Signer: WriteableEcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4430 where
4431         T::Target: BroadcasterInterface,
4432         F::Target: FeeEstimator,
4433         L::Target: Logger,
4434 {
4435         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4436                 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4437         }
4438
4439         fn block_disconnected(&self, header: &Header, height: u32) {
4440                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4441         }
4442 }
4443
4444 impl<Signer: WriteableEcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4445 where
4446         M: Deref<Target = ChannelMonitor<Signer>>,
4447         T::Target: BroadcasterInterface,
4448         F::Target: FeeEstimator,
4449         L::Target: Logger,
4450 {
4451         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4452                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4453         }
4454
4455         fn transaction_unconfirmed(&self, txid: &Txid) {
4456                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4457         }
4458
4459         fn best_block_updated(&self, header: &Header, height: u32) {
4460                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4461         }
4462
4463         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4464                 self.0.get_relevant_txids()
4465         }
4466 }
4467
4468 const MAX_ALLOC_SIZE: usize = 64*1024;
4469
4470 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4471                 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4472         fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4473                 macro_rules! unwrap_obj {
4474                         ($key: expr) => {
4475                                 match $key {
4476                                         Ok(res) => res,
4477                                         Err(_) => return Err(DecodeError::InvalidValue),
4478                                 }
4479                         }
4480                 }
4481
4482                 let (entropy_source, signer_provider) = args;
4483
4484                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4485
4486                 let latest_update_id: u64 = Readable::read(reader)?;
4487                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4488
4489                 let destination_script = Readable::read(reader)?;
4490                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4491                         0 => {
4492                                 let revokable_address = Readable::read(reader)?;
4493                                 let per_commitment_point = Readable::read(reader)?;
4494                                 let revokable_script = Readable::read(reader)?;
4495                                 Some((revokable_address, per_commitment_point, revokable_script))
4496                         },
4497                         1 => { None },
4498                         _ => return Err(DecodeError::InvalidValue),
4499                 };
4500                 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4501                 let shutdown_script = {
4502                         let script = <ScriptBuf as Readable>::read(reader)?;
4503                         if script.is_empty() { None } else { Some(script) }
4504                 };
4505
4506                 let channel_keys_id = Readable::read(reader)?;
4507                 let holder_revocation_basepoint = Readable::read(reader)?;
4508                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
4509                 // barely-init'd ChannelMonitors that we can't do anything with.
4510                 let outpoint = OutPoint {
4511                         txid: Readable::read(reader)?,
4512                         index: Readable::read(reader)?,
4513                 };
4514                 let funding_info = (outpoint, Readable::read(reader)?);
4515                 let current_counterparty_commitment_txid = Readable::read(reader)?;
4516                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4517
4518                 let counterparty_commitment_params = Readable::read(reader)?;
4519                 let funding_redeemscript = Readable::read(reader)?;
4520                 let channel_value_satoshis = Readable::read(reader)?;
4521
4522                 let their_cur_per_commitment_points = {
4523                         let first_idx = <U48 as Readable>::read(reader)?.0;
4524                         if first_idx == 0 {
4525                                 None
4526                         } else {
4527                                 let first_point = Readable::read(reader)?;
4528                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4529                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4530                                         Some((first_idx, first_point, None))
4531                                 } else {
4532                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4533                                 }
4534                         }
4535                 };
4536
4537                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4538
4539                 let commitment_secrets = Readable::read(reader)?;
4540
4541                 macro_rules! read_htlc_in_commitment {
4542                         () => {
4543                                 {
4544                                         let offered: bool = Readable::read(reader)?;
4545                                         let amount_msat: u64 = Readable::read(reader)?;
4546                                         let cltv_expiry: u32 = Readable::read(reader)?;
4547                                         let payment_hash: PaymentHash = Readable::read(reader)?;
4548                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
4549
4550                                         HTLCOutputInCommitment {
4551                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4552                                         }
4553                                 }
4554                         }
4555                 }
4556
4557                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4558                 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4559                 for _ in 0..counterparty_claimable_outpoints_len {
4560                         let txid: Txid = Readable::read(reader)?;
4561                         let htlcs_count: u64 = Readable::read(reader)?;
4562                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4563                         for _ in 0..htlcs_count {
4564                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4565                         }
4566                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
4567                                 return Err(DecodeError::InvalidValue);
4568                         }
4569                 }
4570
4571                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4572                 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));
4573                 for _ in 0..counterparty_commitment_txn_on_chain_len {
4574                         let txid: Txid = Readable::read(reader)?;
4575                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4576                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
4577                                 return Err(DecodeError::InvalidValue);
4578                         }
4579                 }
4580
4581                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4582                 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4583                 for _ in 0..counterparty_hash_commitment_number_len {
4584                         let payment_hash: PaymentHash = Readable::read(reader)?;
4585                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4586                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
4587                                 return Err(DecodeError::InvalidValue);
4588                         }
4589                 }
4590
4591                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4592                         match <u8 as Readable>::read(reader)? {
4593                                 0 => None,
4594                                 1 => {
4595                                         Some(Readable::read(reader)?)
4596                                 },
4597                                 _ => return Err(DecodeError::InvalidValue),
4598                         };
4599                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4600
4601                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4602                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4603
4604                 let payment_preimages_len: u64 = Readable::read(reader)?;
4605                 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4606                 for _ in 0..payment_preimages_len {
4607                         let preimage: PaymentPreimage = Readable::read(reader)?;
4608                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4609                         if let Some(_) = payment_preimages.insert(hash, preimage) {
4610                                 return Err(DecodeError::InvalidValue);
4611                         }
4612                 }
4613
4614                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4615                 let mut pending_monitor_events = Some(
4616                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4617                 for _ in 0..pending_monitor_events_len {
4618                         let ev = match <u8 as Readable>::read(reader)? {
4619                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4620                                 1 => MonitorEvent::HolderForceClosed(funding_info.0),
4621                                 _ => return Err(DecodeError::InvalidValue)
4622                         };
4623                         pending_monitor_events.as_mut().unwrap().push(ev);
4624                 }
4625
4626                 let pending_events_len: u64 = Readable::read(reader)?;
4627                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4628                 for _ in 0..pending_events_len {
4629                         if let Some(event) = MaybeReadable::read(reader)? {
4630                                 pending_events.push(event);
4631                         }
4632                 }
4633
4634                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4635
4636                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4637                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4638                 for _ in 0..waiting_threshold_conf_len {
4639                         if let Some(val) = MaybeReadable::read(reader)? {
4640                                 onchain_events_awaiting_threshold_conf.push(val);
4641                         }
4642                 }
4643
4644                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4645                 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>>())));
4646                 for _ in 0..outputs_to_watch_len {
4647                         let txid = Readable::read(reader)?;
4648                         let outputs_len: u64 = Readable::read(reader)?;
4649                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
4650                         for _ in 0..outputs_len {
4651                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
4652                         }
4653                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
4654                                 return Err(DecodeError::InvalidValue);
4655                         }
4656                 }
4657                 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
4658                         reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
4659                 )?;
4660
4661                 let lockdown_from_offchain = Readable::read(reader)?;
4662                 let holder_tx_signed = Readable::read(reader)?;
4663
4664                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
4665                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
4666                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
4667                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
4668                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
4669                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
4670                                 return Err(DecodeError::InvalidValue);
4671                         }
4672                 }
4673
4674                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
4675                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
4676                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
4677                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
4678                         return Err(DecodeError::InvalidValue);
4679                 }
4680
4681                 let mut funding_spend_confirmed = None;
4682                 let mut htlcs_resolved_on_chain = Some(Vec::new());
4683                 let mut funding_spend_seen = Some(false);
4684                 let mut counterparty_node_id = None;
4685                 let mut confirmed_commitment_tx_counterparty_output = None;
4686                 let mut spendable_txids_confirmed = Some(Vec::new());
4687                 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
4688                 let mut initial_counterparty_commitment_info = None;
4689                 let mut balances_empty_height = None;
4690                 let mut channel_id = None;
4691                 read_tlv_fields!(reader, {
4692                         (1, funding_spend_confirmed, option),
4693                         (3, htlcs_resolved_on_chain, optional_vec),
4694                         (5, pending_monitor_events, optional_vec),
4695                         (7, funding_spend_seen, option),
4696                         (9, counterparty_node_id, option),
4697                         (11, confirmed_commitment_tx_counterparty_output, option),
4698                         (13, spendable_txids_confirmed, optional_vec),
4699                         (15, counterparty_fulfilled_htlcs, option),
4700                         (17, initial_counterparty_commitment_info, option),
4701                         (19, channel_id, option),
4702                         (21, balances_empty_height, option),
4703                 });
4704
4705                 // `HolderForceClosedWithInfo` replaced `HolderForceClosed` in v0.0.122. If we have both
4706                 // events, we can remove the `HolderForceClosed` event and just keep the `HolderForceClosedWithInfo`.
4707                 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
4708                         if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
4709                                 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
4710                         {
4711                                 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
4712                         }
4713                 }
4714
4715                 // Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
4716                 // wrong `counterparty_payment_script` was being tracked. Fix it now on deserialization to
4717                 // give them a chance to recognize the spendable output.
4718                 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
4719                         counterparty_payment_script.is_v0_p2wpkh()
4720                 {
4721                         let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
4722                         counterparty_payment_script =
4723                                 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_v0_p2wsh();
4724                 }
4725
4726                 Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
4727                         latest_update_id,
4728                         commitment_transaction_number_obscure_factor,
4729
4730                         destination_script,
4731                         broadcasted_holder_revokable_script,
4732                         counterparty_payment_script,
4733                         shutdown_script,
4734
4735                         channel_keys_id,
4736                         holder_revocation_basepoint,
4737                         channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
4738                         funding_info,
4739                         current_counterparty_commitment_txid,
4740                         prev_counterparty_commitment_txid,
4741
4742                         counterparty_commitment_params,
4743                         funding_redeemscript,
4744                         channel_value_satoshis,
4745                         their_cur_per_commitment_points,
4746
4747                         on_holder_tx_csv,
4748
4749                         commitment_secrets,
4750                         counterparty_claimable_outpoints,
4751                         counterparty_commitment_txn_on_chain,
4752                         counterparty_hash_commitment_number,
4753                         counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
4754
4755                         prev_holder_signed_commitment_tx,
4756                         current_holder_commitment_tx,
4757                         current_counterparty_commitment_number,
4758                         current_holder_commitment_number,
4759
4760                         payment_preimages,
4761                         pending_monitor_events: pending_monitor_events.unwrap(),
4762                         pending_events,
4763                         is_processing_pending_events: false,
4764
4765                         onchain_events_awaiting_threshold_conf,
4766                         outputs_to_watch,
4767
4768                         onchain_tx_handler,
4769
4770                         lockdown_from_offchain,
4771                         holder_tx_signed,
4772                         funding_spend_seen: funding_spend_seen.unwrap(),
4773                         funding_spend_confirmed,
4774                         confirmed_commitment_tx_counterparty_output,
4775                         htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
4776                         spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
4777
4778                         best_block,
4779                         counterparty_node_id,
4780                         initial_counterparty_commitment_info,
4781                         balances_empty_height,
4782                 })))
4783         }
4784 }
4785
4786 #[cfg(test)]
4787 mod tests {
4788         use bitcoin::blockdata::locktime::absolute::LockTime;
4789         use bitcoin::blockdata::script::{ScriptBuf, Builder};
4790         use bitcoin::blockdata::opcodes;
4791         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut};
4792         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
4793         use bitcoin::sighash;
4794         use bitcoin::sighash::EcdsaSighashType;
4795         use bitcoin::hashes::Hash;
4796         use bitcoin::hashes::sha256::Hash as Sha256;
4797         use bitcoin::hashes::hex::FromHex;
4798         use bitcoin::hash_types::{BlockHash, Txid};
4799         use bitcoin::network::constants::Network;
4800         use bitcoin::secp256k1::{SecretKey,PublicKey};
4801         use bitcoin::secp256k1::Secp256k1;
4802         use bitcoin::{Sequence, Witness};
4803
4804         use crate::chain::chaininterface::LowerBoundedFeeEstimator;
4805
4806         use super::ChannelMonitorUpdateStep;
4807         use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
4808         use crate::chain::{BestBlock, Confirm};
4809         use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
4810         use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
4811         use crate::chain::transaction::OutPoint;
4812         use crate::sign::InMemorySigner;
4813         use crate::ln::{PaymentPreimage, PaymentHash, ChannelId};
4814         use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
4815         use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
4816         use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
4817         use crate::ln::functional_test_utils::*;
4818         use crate::ln::script::ShutdownScript;
4819         use crate::util::errors::APIError;
4820         use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
4821         use crate::util::ser::{ReadableArgs, Writeable};
4822         use crate::util::logger::Logger;
4823         use crate::sync::{Arc, Mutex};
4824         use crate::io;
4825         use crate::ln::features::ChannelTypeFeatures;
4826
4827         #[allow(unused_imports)]
4828         use crate::prelude::*;
4829
4830         use std::str::FromStr;
4831
4832         fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
4833                 // Previously, monitor updates were allowed freely even after a funding-spend transaction
4834                 // confirmed. This would allow a race condition where we could receive a payment (including
4835                 // the counterparty revoking their broadcasted state!) and accept it without recourse as
4836                 // long as the ChannelMonitor receives the block first, the full commitment update dance
4837                 // occurs after the block is connected, and before the ChannelManager receives the block.
4838                 // Obviously this is an incredibly contrived race given the counterparty would be risking
4839                 // their full channel balance for it, but its worth fixing nonetheless as it makes the
4840                 // potential ChannelMonitor states simpler to reason about.
4841                 //
4842                 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
4843                 // updates is handled correctly in such conditions.
4844                 let chanmon_cfgs = create_chanmon_cfgs(3);
4845                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4846                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4847                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4848                 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
4849                 create_announced_chan_between_nodes(&nodes, 1, 2);
4850
4851                 // Rebalance somewhat
4852                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
4853
4854                 // First route two payments for testing at the end
4855                 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4856                 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4857
4858                 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
4859                 assert_eq!(local_txn.len(), 1);
4860                 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
4861                 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
4862                 check_spends!(remote_txn[1], remote_txn[0]);
4863                 check_spends!(remote_txn[2], remote_txn[0]);
4864                 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
4865
4866                 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
4867                 // channel is now closed, but the ChannelManager doesn't know that yet.
4868                 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
4869                 let conf_height = nodes[0].best_block_info().1 + 1;
4870                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
4871                         &[(0, broadcast_tx)], conf_height);
4872
4873                 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
4874                                                 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
4875                                                 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
4876
4877                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
4878                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
4879                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
4880                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash,
4881                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4882                         ), false, APIError::MonitorUpdateInProgress, {});
4883                 check_added_monitors!(nodes[1], 1);
4884
4885                 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
4886                 // and provides the claim preimages for the two pending HTLCs. The first update generates
4887                 // an error, but the point of this test is to ensure the later updates are still applied.
4888                 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
4889                 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
4890                 assert_eq!(replay_update.updates.len(), 1);
4891                 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
4892                 } else { panic!(); }
4893                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
4894                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
4895
4896                 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
4897                 assert!(
4898                         pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
4899                         .is_err());
4900                 // Even though we error'd on the first update, we should still have generated an HTLC claim
4901                 // transaction
4902                 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4903                 assert!(txn_broadcasted.len() >= 2);
4904                 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
4905                         assert_eq!(tx.input.len(), 1);
4906                         tx.input[0].previous_output.txid == broadcast_tx.txid()
4907                 }).collect::<Vec<_>>();
4908                 assert_eq!(htlc_txn.len(), 2);
4909                 check_spends!(htlc_txn[0], broadcast_tx);
4910                 check_spends!(htlc_txn[1], broadcast_tx);
4911         }
4912         #[test]
4913         fn test_funding_spend_refuses_updates() {
4914                 do_test_funding_spend_refuses_updates(true);
4915                 do_test_funding_spend_refuses_updates(false);
4916         }
4917
4918         #[test]
4919         fn test_prune_preimages() {
4920                 let secp_ctx = Secp256k1::new();
4921                 let logger = Arc::new(TestLogger::new());
4922                 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
4923                 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4924
4925                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4926
4927                 let mut preimages = Vec::new();
4928                 {
4929                         for i in 0..20 {
4930                                 let preimage = PaymentPreimage([i; 32]);
4931                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4932                                 preimages.push((preimage, hash));
4933                         }
4934                 }
4935
4936                 macro_rules! preimages_slice_to_htlcs {
4937                         ($preimages_slice: expr) => {
4938                                 {
4939                                         let mut res = Vec::new();
4940                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
4941                                                 res.push((HTLCOutputInCommitment {
4942                                                         offered: true,
4943                                                         amount_msat: 0,
4944                                                         cltv_expiry: 0,
4945                                                         payment_hash: preimage.1.clone(),
4946                                                         transaction_output_index: Some(idx as u32),
4947                                                 }, ()));
4948                                         }
4949                                         res
4950                                 }
4951                         }
4952                 }
4953                 macro_rules! preimages_slice_to_htlc_outputs {
4954                         ($preimages_slice: expr) => {
4955                                 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
4956                         }
4957                 }
4958                 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
4959                         &bitcoin::secp256k1::Message::from_slice(&[42; 32]).unwrap(),
4960                         &SecretKey::from_slice(&[42; 32]).unwrap());
4961
4962                 macro_rules! test_preimages_exist {
4963                         ($preimages_slice: expr, $monitor: expr) => {
4964                                 for preimage in $preimages_slice {
4965                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
4966                                 }
4967                         }
4968                 }
4969
4970                 let keys = InMemorySigner::new(
4971                         &secp_ctx,
4972                         SecretKey::from_slice(&[41; 32]).unwrap(),
4973                         SecretKey::from_slice(&[41; 32]).unwrap(),
4974                         SecretKey::from_slice(&[41; 32]).unwrap(),
4975                         SecretKey::from_slice(&[41; 32]).unwrap(),
4976                         SecretKey::from_slice(&[41; 32]).unwrap(),
4977                         [41; 32],
4978                         0,
4979                         [0; 32],
4980                         [0; 32],
4981                 );
4982
4983                 let counterparty_pubkeys = ChannelPublicKeys {
4984                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
4985                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
4986                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
4987                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
4988                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
4989                 };
4990                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
4991                 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
4992                 let channel_parameters = ChannelTransactionParameters {
4993                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
4994                         holder_selected_contest_delay: 66,
4995                         is_outbound_from_holder: true,
4996                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
4997                                 pubkeys: counterparty_pubkeys,
4998                                 selected_contest_delay: 67,
4999                         }),
5000                         funding_outpoint: Some(funding_outpoint),
5001                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5002                 };
5003                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
5004                 // old state.
5005                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5006                 let best_block = BestBlock::from_network(Network::Testnet);
5007                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5008                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5009                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5010                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5011                         best_block, dummy_key, channel_id);
5012
5013                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5014                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5015
5016                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5017                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5018                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5019                         preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5020                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5021                         preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5022                 for &(ref preimage, ref hash) in preimages.iter() {
5023                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5024                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
5025                 }
5026
5027                 // Now provide a secret, pruning preimages 10-15
5028                 let mut secret = [0; 32];
5029                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5030                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5031                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5032                 test_preimages_exist!(&preimages[0..10], monitor);
5033                 test_preimages_exist!(&preimages[15..20], monitor);
5034
5035                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5036                         preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5037
5038                 // Now provide a further secret, pruning preimages 15-17
5039                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5040                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5041                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5042                 test_preimages_exist!(&preimages[0..10], monitor);
5043                 test_preimages_exist!(&preimages[17..20], monitor);
5044
5045                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5046                         preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5047
5048                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
5049                 // previous commitment tx's preimages too
5050                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5051                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5052                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5053                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5054                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5055                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5056                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5057                 test_preimages_exist!(&preimages[0..10], monitor);
5058                 test_preimages_exist!(&preimages[18..20], monitor);
5059
5060                 // But if we do it again, we'll prune 5-10
5061                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5062                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5063                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5064                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5065                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5066                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5067                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5068                 test_preimages_exist!(&preimages[0..5], monitor);
5069         }
5070
5071         #[test]
5072         fn test_claim_txn_weight_computation() {
5073                 // We test Claim txn weight, knowing that we want expected weigth and
5074                 // not actual case to avoid sigs and time-lock delays hell variances.
5075
5076                 let secp_ctx = Secp256k1::new();
5077                 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5078                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5079
5080                 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5081                 macro_rules! sign_input {
5082                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5083                                 let htlc = HTLCOutputInCommitment {
5084                                         offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5085                                         amount_msat: 0,
5086                                         cltv_expiry: 2 << 16,
5087                                         payment_hash: PaymentHash([1; 32]),
5088                                         transaction_output_index: Some($idx as u32),
5089                                 };
5090                                 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)) };
5091                                 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5092                                 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5093                                 let mut ser_sig = sig.serialize_der().to_vec();
5094                                 ser_sig.push(EcdsaSighashType::All as u8);
5095                                 $sum_actual_sigs += ser_sig.len() as u64;
5096                                 let witness = $sighash_parts.witness_mut($idx).unwrap();
5097                                 witness.push(ser_sig);
5098                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
5099                                         witness.push(vec!(1));
5100                                 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5101                                         witness.push(pubkey.clone().serialize().to_vec());
5102                                 } else if *$weight == weight_received_htlc($opt_anchors) {
5103                                         witness.push(vec![0]);
5104                                 } else {
5105                                         witness.push(PaymentPreimage([1; 32]).0.to_vec());
5106                                 }
5107                                 witness.push(redeem_script.into_bytes());
5108                                 let witness = witness.to_vec();
5109                                 println!("witness[0] {}", witness[0].len());
5110                                 println!("witness[1] {}", witness[1].len());
5111                                 println!("witness[2] {}", witness[2].len());
5112                         }
5113                 }
5114
5115                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5116                 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5117
5118                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
5119                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5120                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5121                         let mut sum_actual_sigs = 0;
5122                         for i in 0..4 {
5123                                 claim_tx.input.push(TxIn {
5124                                         previous_output: BitcoinOutPoint {
5125                                                 txid,
5126                                                 vout: i,
5127                                         },
5128                                         script_sig: ScriptBuf::new(),
5129                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5130                                         witness: Witness::new(),
5131                                 });
5132                         }
5133                         claim_tx.output.push(TxOut {
5134                                 script_pubkey: script_pubkey.clone(),
5135                                 value: 0,
5136                         });
5137                         let base_weight = claim_tx.weight().to_wu();
5138                         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)];
5139                         let mut inputs_total_weight = 2; // count segwit flags
5140                         {
5141                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5142                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5143                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5144                                         inputs_total_weight += inp;
5145                                 }
5146                         }
5147                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5148                 }
5149
5150                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
5151                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5152                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5153                         let mut sum_actual_sigs = 0;
5154                         for i in 0..4 {
5155                                 claim_tx.input.push(TxIn {
5156                                         previous_output: BitcoinOutPoint {
5157                                                 txid,
5158                                                 vout: i,
5159                                         },
5160                                         script_sig: ScriptBuf::new(),
5161                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5162                                         witness: Witness::new(),
5163                                 });
5164                         }
5165                         claim_tx.output.push(TxOut {
5166                                 script_pubkey: script_pubkey.clone(),
5167                                 value: 0,
5168                         });
5169                         let base_weight = claim_tx.weight().to_wu();
5170                         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)];
5171                         let mut inputs_total_weight = 2; // count segwit flags
5172                         {
5173                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5174                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5175                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5176                                         inputs_total_weight += inp;
5177                                 }
5178                         }
5179                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5180                 }
5181
5182                 // Justice tx with 1 revoked HTLC-Success tx output
5183                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5184                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5185                         let mut sum_actual_sigs = 0;
5186                         claim_tx.input.push(TxIn {
5187                                 previous_output: BitcoinOutPoint {
5188                                         txid,
5189                                         vout: 0,
5190                                 },
5191                                 script_sig: ScriptBuf::new(),
5192                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5193                                 witness: Witness::new(),
5194                         });
5195                         claim_tx.output.push(TxOut {
5196                                 script_pubkey: script_pubkey.clone(),
5197                                 value: 0,
5198                         });
5199                         let base_weight = claim_tx.weight().to_wu();
5200                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5201                         let mut inputs_total_weight = 2; // count segwit flags
5202                         {
5203                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5204                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5205                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5206                                         inputs_total_weight += inp;
5207                                 }
5208                         }
5209                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_isg */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5210                 }
5211         }
5212
5213         #[test]
5214         fn test_with_channel_monitor_impl_logger() {
5215                 let secp_ctx = Secp256k1::new();
5216                 let logger = Arc::new(TestLogger::new());
5217
5218                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5219
5220                 let keys = InMemorySigner::new(
5221                         &secp_ctx,
5222                         SecretKey::from_slice(&[41; 32]).unwrap(),
5223                         SecretKey::from_slice(&[41; 32]).unwrap(),
5224                         SecretKey::from_slice(&[41; 32]).unwrap(),
5225                         SecretKey::from_slice(&[41; 32]).unwrap(),
5226                         SecretKey::from_slice(&[41; 32]).unwrap(),
5227                         [41; 32],
5228                         0,
5229                         [0; 32],
5230                         [0; 32],
5231                 );
5232
5233                 let counterparty_pubkeys = ChannelPublicKeys {
5234                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5235                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5236                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5237                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5238                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5239                 };
5240                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
5241                 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5242                 let channel_parameters = ChannelTransactionParameters {
5243                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5244                         holder_selected_contest_delay: 66,
5245                         is_outbound_from_holder: true,
5246                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5247                                 pubkeys: counterparty_pubkeys,
5248                                 selected_contest_delay: 67,
5249                         }),
5250                         funding_outpoint: Some(funding_outpoint),
5251                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5252                 };
5253                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5254                 let best_block = BestBlock::from_network(Network::Testnet);
5255                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5256                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5257                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5258                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5259                         best_block, dummy_key, channel_id);
5260
5261                 let chan_id = monitor.inner.lock().unwrap().channel_id();
5262                 let context_logger = WithChannelMonitor::from(&logger, &monitor);
5263                 log_error!(context_logger, "This is an error");
5264                 log_warn!(context_logger, "This is an error");
5265                 log_debug!(context_logger, "This is an error");
5266                 log_trace!(context_logger, "This is an error");
5267                 log_gossip!(context_logger, "This is an error");
5268                 log_info!(context_logger, "This is an error");
5269                 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5270         }
5271         // Further testing is done in the ChannelManager integration tests.
5272 }