Cache commitment point on ExternalHTLCClaim to drop a signer call
[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::types::{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::EcdsaChannelSigner, 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: EcdsaChannelSigner> {
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: EcdsaChannelSigner> 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: EcdsaChannelSigner> {
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: EcdsaChannelSigner> 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: EcdsaChannelSigner> 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: EcdsaChannelSigner> 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         payment_hash: Option<PaymentHash>,
1199 }
1200
1201 impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger {
1202         fn log(&self, mut record: Record) {
1203                 record.peer_id = self.peer_id;
1204                 record.channel_id = self.channel_id;
1205                 record.payment_hash = self.payment_hash;
1206                 self.logger.log(record)
1207         }
1208 }
1209
1210 impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger {
1211         pub(crate) fn from<S: EcdsaChannelSigner>(logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>) -> Self {
1212                 Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1213         }
1214
1215         pub(crate) fn from_impl<S: EcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>) -> Self {
1216                 let peer_id = monitor_impl.counterparty_node_id;
1217                 let channel_id = Some(monitor_impl.channel_id());
1218                 WithChannelMonitor {
1219                         logger, peer_id, channel_id, payment_hash,
1220                 }
1221         }
1222 }
1223
1224 impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1225         /// For lockorder enforcement purposes, we need to have a single site which constructs the
1226         /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1227         /// PartialEq implementation) we may decide a lockorder violation has occurred.
1228         fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1229                 ChannelMonitor { inner: Mutex::new(imp) }
1230         }
1231
1232         pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1233                           on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, ScriptBuf),
1234                           channel_parameters: &ChannelTransactionParameters,
1235                           funding_redeemscript: ScriptBuf, channel_value_satoshis: u64,
1236                           commitment_transaction_number_obscure_factor: u64,
1237                           initial_holder_commitment_tx: HolderCommitmentTransaction,
1238                           best_block: BestBlock, counterparty_node_id: PublicKey, channel_id: ChannelId,
1239         ) -> ChannelMonitor<Signer> {
1240
1241                 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1242                 let counterparty_payment_script = chan_utils::get_counterparty_payment_script(
1243                         &channel_parameters.channel_type_features, &keys.pubkeys().payment_point
1244                 );
1245
1246                 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1247                 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1248                 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1249                 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1250
1251                 let channel_keys_id = keys.channel_keys_id();
1252                 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1253
1254                 // block for Rust 1.34 compat
1255                 let (holder_commitment_tx, current_holder_commitment_number) = {
1256                         let trusted_tx = initial_holder_commitment_tx.trust();
1257                         let txid = trusted_tx.txid();
1258
1259                         let tx_keys = trusted_tx.keys();
1260                         let holder_commitment_tx = HolderSignedTx {
1261                                 txid,
1262                                 revocation_key: tx_keys.revocation_key,
1263                                 a_htlc_key: tx_keys.broadcaster_htlc_key,
1264                                 b_htlc_key: tx_keys.countersignatory_htlc_key,
1265                                 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1266                                 per_commitment_point: tx_keys.per_commitment_point,
1267                                 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1268                                 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1269                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
1270                         };
1271                         (holder_commitment_tx, trusted_tx.commitment_number())
1272                 };
1273
1274                 let onchain_tx_handler = OnchainTxHandler::new(
1275                         channel_value_satoshis, channel_keys_id, destination_script.into(), keys,
1276                         channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx
1277                 );
1278
1279                 let mut outputs_to_watch = new_hash_map();
1280                 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1281
1282                 Self::from_impl(ChannelMonitorImpl {
1283                         latest_update_id: 0,
1284                         commitment_transaction_number_obscure_factor,
1285
1286                         destination_script: destination_script.into(),
1287                         broadcasted_holder_revokable_script: None,
1288                         counterparty_payment_script,
1289                         shutdown_script,
1290
1291                         channel_keys_id,
1292                         holder_revocation_basepoint,
1293                         channel_id,
1294                         funding_info,
1295                         current_counterparty_commitment_txid: None,
1296                         prev_counterparty_commitment_txid: None,
1297
1298                         counterparty_commitment_params,
1299                         funding_redeemscript,
1300                         channel_value_satoshis,
1301                         their_cur_per_commitment_points: None,
1302
1303                         on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1304
1305                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1306                         counterparty_claimable_outpoints: new_hash_map(),
1307                         counterparty_commitment_txn_on_chain: new_hash_map(),
1308                         counterparty_hash_commitment_number: new_hash_map(),
1309                         counterparty_fulfilled_htlcs: new_hash_map(),
1310
1311                         prev_holder_signed_commitment_tx: None,
1312                         current_holder_commitment_tx: holder_commitment_tx,
1313                         current_counterparty_commitment_number: 1 << 48,
1314                         current_holder_commitment_number,
1315
1316                         payment_preimages: new_hash_map(),
1317                         pending_monitor_events: Vec::new(),
1318                         pending_events: Vec::new(),
1319                         is_processing_pending_events: false,
1320
1321                         onchain_events_awaiting_threshold_conf: Vec::new(),
1322                         outputs_to_watch,
1323
1324                         onchain_tx_handler,
1325
1326                         lockdown_from_offchain: false,
1327                         holder_tx_signed: false,
1328                         funding_spend_seen: false,
1329                         funding_spend_confirmed: None,
1330                         confirmed_commitment_tx_counterparty_output: None,
1331                         htlcs_resolved_on_chain: Vec::new(),
1332                         spendable_txids_confirmed: Vec::new(),
1333
1334                         best_block,
1335                         counterparty_node_id: Some(counterparty_node_id),
1336                         initial_counterparty_commitment_info: None,
1337                         balances_empty_height: None,
1338                 })
1339         }
1340
1341         #[cfg(test)]
1342         fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1343                 self.inner.lock().unwrap().provide_secret(idx, secret)
1344         }
1345
1346         /// A variant of `Self::provide_latest_counterparty_commitment_tx` used to provide
1347         /// additional information to the monitor to store in order to recreate the initial
1348         /// counterparty commitment transaction during persistence (mainly for use in third-party
1349         /// watchtowers).
1350         ///
1351         /// This is used to provide the counterparty commitment information directly to the monitor
1352         /// before the initial persistence of a new channel.
1353         pub(crate) fn provide_initial_counterparty_commitment_tx<L: Deref>(
1354                 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1355                 commitment_number: u64, their_cur_per_commitment_point: PublicKey, feerate_per_kw: u32,
1356                 to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, logger: &L,
1357         )
1358         where L::Target: Logger
1359         {
1360                 let mut inner = self.inner.lock().unwrap();
1361                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1362                 inner.provide_initial_counterparty_commitment_tx(txid,
1363                         htlc_outputs, commitment_number, their_cur_per_commitment_point, feerate_per_kw,
1364                         to_broadcaster_value_sat, to_countersignatory_value_sat, &logger);
1365         }
1366
1367         /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1368         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1369         /// possibly future revocation/preimage information) to claim outputs where possible.
1370         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1371         #[cfg(test)]
1372         fn provide_latest_counterparty_commitment_tx<L: Deref>(
1373                 &self,
1374                 txid: Txid,
1375                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1376                 commitment_number: u64,
1377                 their_per_commitment_point: PublicKey,
1378                 logger: &L,
1379         ) where L::Target: Logger {
1380                 let mut inner = self.inner.lock().unwrap();
1381                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1382                 inner.provide_latest_counterparty_commitment_tx(
1383                         txid, htlc_outputs, commitment_number, their_per_commitment_point, &logger)
1384         }
1385
1386         #[cfg(test)]
1387         fn provide_latest_holder_commitment_tx(
1388                 &self, holder_commitment_tx: HolderCommitmentTransaction,
1389                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1390         ) -> Result<(), ()> {
1391                 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new()).map_err(|_| ())
1392         }
1393
1394         /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1395         /// off-chain state with a new commitment transaction.
1396         pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1397                 &self,
1398                 payment_hash: &PaymentHash,
1399                 payment_preimage: &PaymentPreimage,
1400                 broadcaster: &B,
1401                 fee_estimator: &LowerBoundedFeeEstimator<F>,
1402                 logger: &L,
1403         ) where
1404                 B::Target: BroadcasterInterface,
1405                 F::Target: FeeEstimator,
1406                 L::Target: Logger,
1407         {
1408                 let mut inner = self.inner.lock().unwrap();
1409                 let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
1410                 inner.provide_payment_preimage(
1411                         payment_hash, payment_preimage, broadcaster, fee_estimator, &logger)
1412         }
1413
1414         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1415         /// itself.
1416         ///
1417         /// panics if the given update is not the next update by update_id.
1418         pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1419                 &self,
1420                 updates: &ChannelMonitorUpdate,
1421                 broadcaster: &B,
1422                 fee_estimator: &F,
1423                 logger: &L,
1424         ) -> Result<(), ()>
1425         where
1426                 B::Target: BroadcasterInterface,
1427                 F::Target: FeeEstimator,
1428                 L::Target: Logger,
1429         {
1430                 let mut inner = self.inner.lock().unwrap();
1431                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1432                 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
1433         }
1434
1435         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1436         /// ChannelMonitor.
1437         pub fn get_latest_update_id(&self) -> u64 {
1438                 self.inner.lock().unwrap().get_latest_update_id()
1439         }
1440
1441         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1442         pub fn get_funding_txo(&self) -> (OutPoint, ScriptBuf) {
1443                 self.inner.lock().unwrap().get_funding_txo().clone()
1444         }
1445
1446         /// Gets the channel_id of the channel this ChannelMonitor is monitoring for.
1447         pub fn channel_id(&self) -> ChannelId {
1448                 self.inner.lock().unwrap().channel_id()
1449         }
1450
1451         /// Gets a list of txids, with their output scripts (in the order they appear in the
1452         /// transaction), which we must learn about spends of via block_connected().
1453         pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
1454                 self.inner.lock().unwrap().get_outputs_to_watch()
1455                         .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1456         }
1457
1458         /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1459         /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1460         /// have been registered.
1461         pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L)
1462         where
1463                 F::Target: chain::Filter, L::Target: Logger,
1464         {
1465                 let lock = self.inner.lock().unwrap();
1466                 let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
1467                 log_trace!(&logger, "Registering funding outpoint {}", &lock.get_funding_txo().0);
1468                 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1469                 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1470                         for (index, script_pubkey) in outputs.iter() {
1471                                 assert!(*index <= u16::max_value() as u32);
1472                                 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
1473                                 log_trace!(logger, "Registering outpoint {} with the filter for monitoring spends", outpoint);
1474                                 filter.register_output(WatchedOutput {
1475                                         block_hash: None,
1476                                         outpoint,
1477                                         script_pubkey: script_pubkey.clone(),
1478                                 });
1479                         }
1480                 }
1481         }
1482
1483         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1484         /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1485         pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1486                 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1487         }
1488
1489         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
1490         ///
1491         /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
1492         /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
1493         /// within each channel. As the confirmation of a commitment transaction may be critical to the
1494         /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
1495         /// environment with spotty connections, like on mobile.
1496         ///
1497         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
1498         /// order to handle these events.
1499         ///
1500         /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
1501         /// [`BumpTransaction`]: crate::events::Event::BumpTransaction
1502         pub fn process_pending_events<H: Deref>(&self, handler: &H) where H::Target: EventHandler {
1503                 let mut ev;
1504                 process_events_body!(Some(self), ev, handler.handle_event(ev));
1505         }
1506
1507         /// Processes any events asynchronously.
1508         ///
1509         /// See [`Self::process_pending_events`] for more information.
1510         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
1511                 &self, handler: &H
1512         ) {
1513                 let mut ev;
1514                 process_events_body!(Some(self), ev, { handler(ev).await });
1515         }
1516
1517         #[cfg(test)]
1518         pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1519                 let mut ret = Vec::new();
1520                 let mut lck = self.inner.lock().unwrap();
1521                 mem::swap(&mut ret, &mut lck.pending_events);
1522                 ret.append(&mut lck.get_repeated_events());
1523                 ret
1524         }
1525
1526         /// Gets the counterparty's initial commitment transaction. The returned commitment
1527         /// transaction is unsigned. This is intended to be called during the initial persistence of
1528         /// the monitor (inside an implementation of [`Persist::persist_new_channel`]), to allow for
1529         /// watchtowers in the persistence pipeline to have enough data to form justice transactions.
1530         ///
1531         /// This is similar to [`Self::counterparty_commitment_txs_from_update`], except
1532         /// that for the initial commitment transaction, we don't have a corresponding update.
1533         ///
1534         /// This will only return `Some` for channel monitors that have been created after upgrading
1535         /// to LDK 0.0.117+.
1536         ///
1537         /// [`Persist::persist_new_channel`]: crate::chain::chainmonitor::Persist::persist_new_channel
1538         pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
1539                 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
1540         }
1541
1542         /// Gets all of the counterparty commitment transactions provided by the given update. This
1543         /// may be empty if the update doesn't include any new counterparty commitments. Returned
1544         /// commitment transactions are unsigned.
1545         ///
1546         /// This is provided so that watchtower clients in the persistence pipeline are able to build
1547         /// justice transactions for each counterparty commitment upon each update. It's intended to be
1548         /// used within an implementation of [`Persist::update_persisted_channel`], which is provided
1549         /// with a monitor and an update. Once revoked, signing a justice transaction can be done using
1550         /// [`Self::sign_to_local_justice_tx`].
1551         ///
1552         /// It is expected that a watchtower client may use this method to retrieve the latest counterparty
1553         /// commitment transaction(s), and then hold the necessary data until a later update in which
1554         /// the monitor has been updated with the corresponding revocation data, at which point the
1555         /// monitor can sign the justice transaction.
1556         ///
1557         /// This will only return a non-empty list for monitor updates that have been created after
1558         /// upgrading to LDK 0.0.117+. Note that no restriction lies on the monitors themselves, which
1559         /// may have been created prior to upgrading.
1560         ///
1561         /// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel
1562         pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
1563                 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
1564         }
1565
1566         /// Wrapper around [`EcdsaChannelSigner::sign_justice_revoked_output`] to make
1567         /// signing the justice transaction easier for implementors of
1568         /// [`chain::chainmonitor::Persist`]. On success this method returns the provided transaction
1569         /// signing the input at `input_idx`. This method will only produce a valid signature for
1570         /// a transaction spending the `to_local` output of a commitment transaction, i.e. this cannot
1571         /// be used for revoked HTLC outputs.
1572         ///
1573         /// `Value` is the value of the output being spent by the input at `input_idx`, committed
1574         /// in the BIP 143 signature.
1575         ///
1576         /// This method will only succeed if this monitor has received the revocation secret for the
1577         /// provided `commitment_number`. If a commitment number is provided that does not correspond
1578         /// to the commitment transaction being revoked, this will return a signed transaction, but
1579         /// the signature will not be valid.
1580         ///
1581         /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_justice_revoked_output
1582         /// [`Persist`]: crate::chain::chainmonitor::Persist
1583         pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
1584                 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
1585         }
1586
1587         pub(crate) fn get_min_seen_secret(&self) -> u64 {
1588                 self.inner.lock().unwrap().get_min_seen_secret()
1589         }
1590
1591         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1592                 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1593         }
1594
1595         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1596                 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1597         }
1598
1599         /// Gets the `node_id` of the counterparty for this channel.
1600         ///
1601         /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1602         /// otherwise.
1603         pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1604                 self.inner.lock().unwrap().counterparty_node_id
1605         }
1606
1607         /// You may use this to broadcast the latest local commitment transaction, either because
1608         /// a monitor update failed or because we've fallen behind (i.e. we've received proof that our
1609         /// counterparty side knows a revocation secret we gave them that they shouldn't know).
1610         ///
1611         /// Broadcasting these transactions in this manner is UNSAFE, as they allow counterparty
1612         /// side to punish you. Nevertheless you may want to broadcast them if counterparty doesn't
1613         /// close channel with their commitment transaction after a substantial amount of time. Best
1614         /// may be to contact the other node operator out-of-band to coordinate other options available
1615         /// to you.
1616         pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
1617                 &self, broadcaster: &B, fee_estimator: &F, logger: &L
1618         )
1619         where
1620                 B::Target: BroadcasterInterface,
1621                 F::Target: FeeEstimator,
1622                 L::Target: Logger
1623         {
1624                 let mut inner = self.inner.lock().unwrap();
1625                 let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
1626                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1627                 inner.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &fee_estimator, &logger);
1628         }
1629
1630         /// Unsafe test-only version of `broadcast_latest_holder_commitment_txn` used by our test framework
1631         /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1632         /// revoked commitment transaction.
1633         #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1634         pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1635         where L::Target: Logger {
1636                 let mut inner = self.inner.lock().unwrap();
1637                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1638                 inner.unsafe_get_latest_holder_commitment_txn(&logger)
1639         }
1640
1641         /// Processes transactions in a newly connected block, which may result in any of the following:
1642         /// - update the monitor's state against resolved HTLCs
1643         /// - punish the counterparty in the case of seeing a revoked commitment transaction
1644         /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1645         /// - detect settled outputs for later spending
1646         /// - schedule and bump any in-flight claims
1647         ///
1648         /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1649         /// [`get_outputs_to_watch`].
1650         ///
1651         /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1652         pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1653                 &self,
1654                 header: &Header,
1655                 txdata: &TransactionData,
1656                 height: u32,
1657                 broadcaster: B,
1658                 fee_estimator: F,
1659                 logger: &L,
1660         ) -> Vec<TransactionOutputs>
1661         where
1662                 B::Target: BroadcasterInterface,
1663                 F::Target: FeeEstimator,
1664                 L::Target: Logger,
1665         {
1666                 let mut inner = self.inner.lock().unwrap();
1667                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1668                 inner.block_connected(
1669                         header, txdata, height, broadcaster, fee_estimator, &logger)
1670         }
1671
1672         /// Determines if the disconnected block contained any transactions of interest and updates
1673         /// appropriately.
1674         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1675                 &self,
1676                 header: &Header,
1677                 height: u32,
1678                 broadcaster: B,
1679                 fee_estimator: F,
1680                 logger: &L,
1681         ) where
1682                 B::Target: BroadcasterInterface,
1683                 F::Target: FeeEstimator,
1684                 L::Target: Logger,
1685         {
1686                 let mut inner = self.inner.lock().unwrap();
1687                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1688                 inner.block_disconnected(
1689                         header, height, broadcaster, fee_estimator, &logger)
1690         }
1691
1692         /// Processes transactions confirmed in a block with the given header and height, returning new
1693         /// outputs to watch. See [`block_connected`] for details.
1694         ///
1695         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1696         /// blocks. See [`chain::Confirm`] for calling expectations.
1697         ///
1698         /// [`block_connected`]: Self::block_connected
1699         pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1700                 &self,
1701                 header: &Header,
1702                 txdata: &TransactionData,
1703                 height: u32,
1704                 broadcaster: B,
1705                 fee_estimator: F,
1706                 logger: &L,
1707         ) -> Vec<TransactionOutputs>
1708         where
1709                 B::Target: BroadcasterInterface,
1710                 F::Target: FeeEstimator,
1711                 L::Target: Logger,
1712         {
1713                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1714                 let mut inner = self.inner.lock().unwrap();
1715                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1716                 inner.transactions_confirmed(
1717                         header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
1718         }
1719
1720         /// Processes a transaction that was reorganized out of the chain.
1721         ///
1722         /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1723         /// than blocks. See [`chain::Confirm`] for calling expectations.
1724         ///
1725         /// [`block_disconnected`]: Self::block_disconnected
1726         pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1727                 &self,
1728                 txid: &Txid,
1729                 broadcaster: B,
1730                 fee_estimator: F,
1731                 logger: &L,
1732         ) where
1733                 B::Target: BroadcasterInterface,
1734                 F::Target: FeeEstimator,
1735                 L::Target: Logger,
1736         {
1737                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1738                 let mut inner = self.inner.lock().unwrap();
1739                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1740                 inner.transaction_unconfirmed(
1741                         txid, broadcaster, &bounded_fee_estimator, &logger
1742                 );
1743         }
1744
1745         /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1746         /// [`block_connected`] for details.
1747         ///
1748         /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1749         /// blocks. See [`chain::Confirm`] for calling expectations.
1750         ///
1751         /// [`block_connected`]: Self::block_connected
1752         pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1753                 &self,
1754                 header: &Header,
1755                 height: u32,
1756                 broadcaster: B,
1757                 fee_estimator: F,
1758                 logger: &L,
1759         ) -> Vec<TransactionOutputs>
1760         where
1761                 B::Target: BroadcasterInterface,
1762                 F::Target: FeeEstimator,
1763                 L::Target: Logger,
1764         {
1765                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1766                 let mut inner = self.inner.lock().unwrap();
1767                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1768                 inner.best_block_updated(
1769                         header, height, broadcaster, &bounded_fee_estimator, &logger
1770                 )
1771         }
1772
1773         /// Returns the set of txids that should be monitored for re-organization out of the chain.
1774         pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
1775                 let inner = self.inner.lock().unwrap();
1776                 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
1777                         .iter()
1778                         .map(|entry| (entry.txid, entry.height, entry.block_hash))
1779                         .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1780                         .collect();
1781                 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
1782                 txids.dedup_by_key(|(txid, _, _)| *txid);
1783                 txids
1784         }
1785
1786         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1787         /// [`chain::Confirm`] interfaces.
1788         pub fn current_best_block(&self) -> BestBlock {
1789                 self.inner.lock().unwrap().best_block.clone()
1790         }
1791
1792         /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
1793         /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
1794         /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
1795         /// invoking this every 30 seconds, or lower if running in an environment with spotty
1796         /// connections, like on mobile.
1797         pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
1798                 &self, broadcaster: B, fee_estimator: F, logger: &L,
1799         )
1800         where
1801                 B::Target: BroadcasterInterface,
1802                 F::Target: FeeEstimator,
1803                 L::Target: Logger,
1804         {
1805                 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1806                 let mut inner = self.inner.lock().unwrap();
1807                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1808                 let current_height = inner.best_block.height;
1809                 inner.onchain_tx_handler.rebroadcast_pending_claims(
1810                         current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, &fee_estimator, &logger,
1811                 );
1812         }
1813
1814         /// Triggers rebroadcasts of pending claims from a force-closed channel after a transaction
1815         /// signature generation failure.
1816         pub fn signer_unblocked<B: Deref, F: Deref, L: Deref>(
1817                 &self, broadcaster: B, fee_estimator: F, logger: &L,
1818         )
1819         where
1820                 B::Target: BroadcasterInterface,
1821                 F::Target: FeeEstimator,
1822                 L::Target: Logger,
1823         {
1824                 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1825                 let mut inner = self.inner.lock().unwrap();
1826                 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1827                 let current_height = inner.best_block.height;
1828                 inner.onchain_tx_handler.rebroadcast_pending_claims(
1829                         current_height, FeerateStrategy::RetryPrevious, &broadcaster, &fee_estimator, &logger,
1830                 );
1831         }
1832
1833         /// Returns the descriptors for relevant outputs (i.e., those that we can spend) within the
1834         /// transaction if they exist and the transaction has at least [`ANTI_REORG_DELAY`]
1835         /// confirmations. For [`SpendableOutputDescriptor::DelayedPaymentOutput`] descriptors to be
1836         /// returned, the transaction must have at least `max(ANTI_REORG_DELAY, to_self_delay)`
1837         /// confirmations.
1838         ///
1839         /// Descriptors returned by this method are primarily exposed via [`Event::SpendableOutputs`]
1840         /// once they are no longer under reorg risk. This method serves as a way to retrieve these
1841         /// descriptors at a later time, either for historical purposes, or to replay any
1842         /// missed/unhandled descriptors. For the purpose of gathering historical records, if the
1843         /// channel close has fully resolved (i.e., [`ChannelMonitor::get_claimable_balances`] returns
1844         /// an empty set), you can retrieve all spendable outputs by providing all descendant spending
1845         /// transactions starting from the channel's funding transaction and going down three levels.
1846         ///
1847         /// `tx` is a transaction we'll scan the outputs of. Any transaction can be provided. If any
1848         /// outputs which can be spent by us are found, at least one descriptor is returned.
1849         ///
1850         /// `confirmation_height` must be the height of the block in which `tx` was included in.
1851         pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
1852                 let inner = self.inner.lock().unwrap();
1853                 let current_height = inner.best_block.height;
1854                 let mut spendable_outputs = inner.get_spendable_outputs(tx);
1855                 spendable_outputs.retain(|descriptor| {
1856                         let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
1857                         if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
1858                                 conf_threshold = cmp::min(conf_threshold,
1859                                         current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
1860                         }
1861                         conf_threshold >= confirmation_height
1862                 });
1863                 spendable_outputs
1864         }
1865
1866         /// Checks if the monitor is fully resolved. Resolved monitor is one that has claimed all of
1867         /// its outputs and balances (i.e. [`Self::get_claimable_balances`] returns an empty set).
1868         ///
1869         /// This function returns true only if [`Self::get_claimable_balances`] has been empty for at least
1870         /// 4032 blocks as an additional protection against any bugs resulting in spuriously empty balance sets.
1871         pub fn is_fully_resolved<L: Logger>(&self, logger: &L) -> bool {
1872                 let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
1873                 let current_height = self.current_best_block().height;
1874                 let mut inner = self.inner.lock().unwrap();
1875
1876                 if is_all_funds_claimed {
1877                         if !inner.funding_spend_seen {
1878                                 debug_assert!(false, "We should see funding spend by the time a monitor clears out");
1879                                 is_all_funds_claimed = false;
1880                         }
1881                 }
1882
1883                 const BLOCKS_THRESHOLD: u32 = 4032; // ~four weeks
1884                 match (inner.balances_empty_height, is_all_funds_claimed) {
1885                         (Some(balances_empty_height), true) => {
1886                                 // Claimed all funds, check if reached the blocks threshold.
1887                                 return current_height >= balances_empty_height + BLOCKS_THRESHOLD;
1888                         },
1889                         (Some(_), false) => {
1890                                 // previously assumed we claimed all funds, but we have new funds to claim.
1891                                 // Should not happen in practice.
1892                                 debug_assert!(false, "Thought we were done claiming funds, but claimable_balances now has entries");
1893                                 log_error!(logger,
1894                                         "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",
1895                                         inner.get_funding_txo().0);
1896                                 inner.balances_empty_height = None;
1897                                 false
1898                         },
1899                         (None, true) => {
1900                                 // Claimed all funds but `balances_empty_height` is None. It is set to the
1901                                 // current block height.
1902                                 log_debug!(logger,
1903                                         "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
1904                                         inner.get_funding_txo().0, BLOCKS_THRESHOLD);
1905                                 inner.balances_empty_height = Some(current_height);
1906                                 false
1907                         },
1908                         (None, false) => {
1909                                 // Have funds to claim.
1910                                 false
1911                         },
1912                 }
1913         }
1914
1915         #[cfg(test)]
1916         pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
1917                 self.inner.lock().unwrap().counterparty_payment_script.clone()
1918         }
1919
1920         #[cfg(test)]
1921         pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
1922                 self.inner.lock().unwrap().counterparty_payment_script = script;
1923         }
1924
1925         #[cfg(test)]
1926         pub fn do_signer_call<F: FnMut(&Signer) -> ()>(&self, mut f: F) {
1927                 let inner = self.inner.lock().unwrap();
1928                 f(&inner.onchain_tx_handler.signer);
1929         }
1930 }
1931
1932 impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
1933         /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1934         /// to one `Balance` for the HTLC.
1935         fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1936                 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1937         -> Option<Balance> {
1938                 let htlc_commitment_tx_output_idx =
1939                         if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1940
1941                 let mut htlc_spend_txid_opt = None;
1942                 let mut htlc_spend_tx_opt = None;
1943                 let mut holder_timeout_spend_pending = None;
1944                 let mut htlc_spend_pending = None;
1945                 let mut holder_delayed_output_pending = None;
1946                 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1947                         match event.event {
1948                                 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1949                                 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1950                                         debug_assert!(htlc_spend_txid_opt.is_none());
1951                                         htlc_spend_txid_opt = Some(&event.txid);
1952                                         debug_assert!(htlc_spend_tx_opt.is_none());
1953                                         htlc_spend_tx_opt = event.transaction.as_ref();
1954                                         debug_assert!(holder_timeout_spend_pending.is_none());
1955                                         debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1956                                         holder_timeout_spend_pending = Some(event.confirmation_threshold());
1957                                 },
1958                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1959                                 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1960                                         debug_assert!(htlc_spend_txid_opt.is_none());
1961                                         htlc_spend_txid_opt = Some(&event.txid);
1962                                         debug_assert!(htlc_spend_tx_opt.is_none());
1963                                         htlc_spend_tx_opt = event.transaction.as_ref();
1964                                         debug_assert!(htlc_spend_pending.is_none());
1965                                         htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1966                                 },
1967                                 OnchainEvent::MaturingOutput {
1968                                         descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1969                                 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
1970                                         .any(|(input_idx, inp)|
1971                                                  Some(inp.previous_output.txid) == confirmed_txid &&
1972                                                         inp.previous_output.vout == htlc_commitment_tx_output_idx &&
1973                                                                 // A maturing output for an HTLC claim will always be at the same
1974                                                                 // index as the HTLC input. This is true pre-anchors, as there's
1975                                                                 // only 1 input and 1 output. This is also true post-anchors,
1976                                                                 // because we have a SIGHASH_SINGLE|ANYONECANPAY signature from our
1977                                                                 // channel counterparty.
1978                                                                 descriptor.outpoint.index as usize == input_idx
1979                                         ))
1980                                         .unwrap_or(false)
1981                                 => {
1982                                         debug_assert!(holder_delayed_output_pending.is_none());
1983                                         holder_delayed_output_pending = Some(event.confirmation_threshold());
1984                                 },
1985                                 _ => {},
1986                         }
1987                 }
1988                 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1989                         .find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
1990                                 debug_assert!(htlc_spend_txid_opt.is_none());
1991                                 htlc_spend_txid_opt = v.resolving_txid.as_ref();
1992                                 debug_assert!(htlc_spend_tx_opt.is_none());
1993                                 htlc_spend_tx_opt = v.resolving_tx.as_ref();
1994                                 true
1995                         } else { false });
1996                 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1997
1998                 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
1999                 let htlc_output_to_spend =
2000                         if let Some(txid) = htlc_spend_txid_opt {
2001                                 // Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
2002                                 // are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
2003                                 // locate the correct output by ensuring its adjacent input spends the HTLC output
2004                                 // in the commitment.
2005                                 if let Some(ref tx) = htlc_spend_tx_opt {
2006                                         let htlc_input_idx_opt = tx.input.iter().enumerate()
2007                                                 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2008                                                 .map(|(idx, _)| idx as u32);
2009                                         debug_assert!(htlc_input_idx_opt.is_some());
2010                                         BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2011                                 } else {
2012                                         debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2013                                         BitcoinOutPoint::new(*txid, 0)
2014                                 }
2015                         } else {
2016                                 htlc_commitment_outpoint
2017                         };
2018                 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2019
2020                 if let Some(conf_thresh) = holder_delayed_output_pending {
2021                         debug_assert!(holder_commitment);
2022                         return Some(Balance::ClaimableAwaitingConfirmations {
2023                                 amount_satoshis: htlc.amount_msat / 1000,
2024                                 confirmation_height: conf_thresh,
2025                         });
2026                 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
2027                         // Funding transaction spends should be fully confirmed by the time any
2028                         // HTLC transactions are resolved, unless we're talking about a holder
2029                         // commitment tx, whose resolution is delayed until the CSV timeout is
2030                         // reached, even though HTLCs may be resolved after only
2031                         // ANTI_REORG_DELAY confirmations.
2032                         debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2033                 } else if counterparty_revoked_commitment {
2034                         let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2035                                 if let OnchainEvent::MaturingOutput {
2036                                         descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2037                                 } = &event.event {
2038                                         if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2039                                                 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2040                                                         tx.txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2041                                                 } else {
2042                                                         Some(inp.previous_output.txid) == confirmed_txid &&
2043                                                                 inp.previous_output.vout == htlc_commitment_tx_output_idx
2044                                                 }
2045                                         })).unwrap_or(false) {
2046                                                 Some(())
2047                                         } else { None }
2048                                 } else { None }
2049                         });
2050                         if htlc_output_claim_pending.is_some() {
2051                                 // We already push `Balance`s onto the `res` list for every
2052                                 // `StaticOutput` in a `MaturingOutput` in the revoked
2053                                 // counterparty commitment transaction case generally, so don't
2054                                 // need to do so again here.
2055                         } else {
2056                                 debug_assert!(holder_timeout_spend_pending.is_none(),
2057                                         "HTLCUpdate OnchainEvents should never appear for preimage claims");
2058                                 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2059                                         "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2060                                 return Some(Balance::CounterpartyRevokedOutputClaimable {
2061                                         amount_satoshis: htlc.amount_msat / 1000,
2062                                 });
2063                         }
2064                 } else if htlc.offered == holder_commitment {
2065                         // If the payment was outbound, check if there's an HTLCUpdate
2066                         // indicating we have spent this HTLC with a timeout, claiming it back
2067                         // and awaiting confirmations on it.
2068                         if let Some(conf_thresh) = holder_timeout_spend_pending {
2069                                 return Some(Balance::ClaimableAwaitingConfirmations {
2070                                         amount_satoshis: htlc.amount_msat / 1000,
2071                                         confirmation_height: conf_thresh,
2072                                 });
2073                         } else {
2074                                 return Some(Balance::MaybeTimeoutClaimableHTLC {
2075                                         amount_satoshis: htlc.amount_msat / 1000,
2076                                         claimable_height: htlc.cltv_expiry,
2077                                         payment_hash: htlc.payment_hash,
2078                                 });
2079                         }
2080                 } else if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2081                         // Otherwise (the payment was inbound), only expose it as claimable if
2082                         // we know the preimage.
2083                         // Note that if there is a pending claim, but it did not use the
2084                         // preimage, we lost funds to our counterparty! We will then continue
2085                         // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
2086                         debug_assert!(holder_timeout_spend_pending.is_none());
2087                         if let Some((conf_thresh, true)) = htlc_spend_pending {
2088                                 return Some(Balance::ClaimableAwaitingConfirmations {
2089                                         amount_satoshis: htlc.amount_msat / 1000,
2090                                         confirmation_height: conf_thresh,
2091                                 });
2092                         } else {
2093                                 return Some(Balance::ContentiousClaimable {
2094                                         amount_satoshis: htlc.amount_msat / 1000,
2095                                         timeout_height: htlc.cltv_expiry,
2096                                         payment_hash: htlc.payment_hash,
2097                                         payment_preimage: *payment_preimage,
2098                                 });
2099                         }
2100                 } else if htlc_resolved.is_none() {
2101                         return Some(Balance::MaybePreimageClaimableHTLC {
2102                                 amount_satoshis: htlc.amount_msat / 1000,
2103                                 expiry_height: htlc.cltv_expiry,
2104                                 payment_hash: htlc.payment_hash,
2105                         });
2106                 }
2107                 None
2108         }
2109 }
2110
2111 impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
2112         /// Gets the balances in this channel which are either claimable by us if we were to
2113         /// force-close the channel now or which are claimable on-chain (possibly awaiting
2114         /// confirmation).
2115         ///
2116         /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
2117         /// included here until an [`Event::SpendableOutputs`] event has been generated for the
2118         /// balance, or until our counterparty has claimed the balance and accrued several
2119         /// confirmations on the claim transaction.
2120         ///
2121         /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
2122         /// LDK prior to 0.0.111, not all or excess balances may be included.
2123         ///
2124         /// See [`Balance`] for additional details on the types of claimable balances which
2125         /// may be returned here and their meanings.
2126         pub fn get_claimable_balances(&self) -> Vec<Balance> {
2127                 let mut res = Vec::new();
2128                 let us = self.inner.lock().unwrap();
2129
2130                 let mut confirmed_txid = us.funding_spend_confirmed;
2131                 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2132                 let mut pending_commitment_tx_conf_thresh = None;
2133                 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2134                         if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2135                                 event.event
2136                         {
2137                                 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2138                                 Some((event.txid, event.confirmation_threshold()))
2139                         } else { None }
2140                 });
2141                 if let Some((txid, conf_thresh)) = funding_spend_pending {
2142                         debug_assert!(us.funding_spend_confirmed.is_none(),
2143                                 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2144                         confirmed_txid = Some(txid);
2145                         pending_commitment_tx_conf_thresh = Some(conf_thresh);
2146                 }
2147
2148                 macro_rules! walk_htlcs {
2149                         ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2150                                 for htlc in $htlc_iter {
2151                                         if htlc.transaction_output_index.is_some() {
2152
2153                                                 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
2154                                                         res.push(bal);
2155                                                 }
2156                                         }
2157                                 }
2158                         }
2159                 }
2160
2161                 if let Some(txid) = confirmed_txid {
2162                         let mut found_commitment_tx = false;
2163                         if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
2164                                 // First look for the to_remote output back to us.
2165                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2166                                         if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2167                                                 if let OnchainEvent::MaturingOutput {
2168                                                         descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2169                                                 } = &event.event {
2170                                                         Some(descriptor.output.value)
2171                                                 } else { None }
2172                                         }) {
2173                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2174                                                         amount_satoshis: value,
2175                                                         confirmation_height: conf_thresh,
2176                                                 });
2177                                         } else {
2178                                                 // If a counterparty commitment transaction is awaiting confirmation, we
2179                                                 // should either have a StaticPaymentOutput MaturingOutput event awaiting
2180                                                 // confirmation with the same height or have never met our dust amount.
2181                                         }
2182                                 }
2183                                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2184                                         walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2185                                 } else {
2186                                         walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
2187                                         // The counterparty broadcasted a revoked state!
2188                                         // Look for any StaticOutputs first, generating claimable balances for those.
2189                                         // If any match the confirmed counterparty revoked to_self output, skip
2190                                         // generating a CounterpartyRevokedOutputClaimable.
2191                                         let mut spent_counterparty_output = false;
2192                                         for event in us.onchain_events_awaiting_threshold_conf.iter() {
2193                                                 if let OnchainEvent::MaturingOutput {
2194                                                         descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
2195                                                 } = &event.event {
2196                                                         res.push(Balance::ClaimableAwaitingConfirmations {
2197                                                                 amount_satoshis: output.value,
2198                                                                 confirmation_height: event.confirmation_threshold(),
2199                                                         });
2200                                                         if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
2201                                                                 if event.transaction.as_ref().map(|tx|
2202                                                                         tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
2203                                                                 ).unwrap_or(false) {
2204                                                                         spent_counterparty_output = true;
2205                                                                 }
2206                                                         }
2207                                                 }
2208                                         }
2209
2210                                         if spent_counterparty_output {
2211                                         } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
2212                                                 let output_spendable = us.onchain_tx_handler
2213                                                         .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
2214                                                 if output_spendable {
2215                                                         res.push(Balance::CounterpartyRevokedOutputClaimable {
2216                                                                 amount_satoshis: amt,
2217                                                         });
2218                                                 }
2219                                         } else {
2220                                                 // Counterparty output is missing, either it was broadcasted on a
2221                                                 // previous version of LDK or the counterparty hadn't met dust.
2222                                         }
2223                                 }
2224                                 found_commitment_tx = true;
2225                         } else if txid == us.current_holder_commitment_tx.txid {
2226                                 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
2227                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2228                                         res.push(Balance::ClaimableAwaitingConfirmations {
2229                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2230                                                 confirmation_height: conf_thresh,
2231                                         });
2232                                 }
2233                                 found_commitment_tx = true;
2234                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2235                                 if txid == prev_commitment.txid {
2236                                         walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
2237                                         if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2238                                                 res.push(Balance::ClaimableAwaitingConfirmations {
2239                                                         amount_satoshis: prev_commitment.to_self_value_sat,
2240                                                         confirmation_height: conf_thresh,
2241                                                 });
2242                                         }
2243                                         found_commitment_tx = true;
2244                                 }
2245                         }
2246                         if !found_commitment_tx {
2247                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2248                                         // We blindly assume this is a cooperative close transaction here, and that
2249                                         // neither us nor our counterparty misbehaved. At worst we've under-estimated
2250                                         // the amount we can claim as we'll punish a misbehaving counterparty.
2251                                         res.push(Balance::ClaimableAwaitingConfirmations {
2252                                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2253                                                 confirmation_height: conf_thresh,
2254                                         });
2255                                 }
2256                         }
2257                 } else {
2258                         let mut claimable_inbound_htlc_value_sat = 0;
2259                         for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
2260                                 if htlc.transaction_output_index.is_none() { continue; }
2261                                 if htlc.offered {
2262                                         res.push(Balance::MaybeTimeoutClaimableHTLC {
2263                                                 amount_satoshis: htlc.amount_msat / 1000,
2264                                                 claimable_height: htlc.cltv_expiry,
2265                                                 payment_hash: htlc.payment_hash,
2266                                         });
2267                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
2268                                         claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
2269                                 } else {
2270                                         // As long as the HTLC is still in our latest commitment state, treat
2271                                         // it as potentially claimable, even if it has long-since expired.
2272                                         res.push(Balance::MaybePreimageClaimableHTLC {
2273                                                 amount_satoshis: htlc.amount_msat / 1000,
2274                                                 expiry_height: htlc.cltv_expiry,
2275                                                 payment_hash: htlc.payment_hash,
2276                                         });
2277                                 }
2278                         }
2279                         res.push(Balance::ClaimableOnChannelClose {
2280                                 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
2281                         });
2282                 }
2283
2284                 res
2285         }
2286
2287         /// Gets the set of outbound HTLCs which can be (or have been) resolved by this
2288         /// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
2289         /// to the `ChannelManager` having been persisted.
2290         ///
2291         /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes
2292         /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
2293         /// event from this `ChannelMonitor`).
2294         pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2295                 let mut res = new_hash_map();
2296                 // Just examine the available counterparty commitment transactions. See docs on
2297                 // `fail_unbroadcast_htlcs`, below, for justification.
2298                 let us = self.inner.lock().unwrap();
2299                 macro_rules! walk_counterparty_commitment {
2300                         ($txid: expr) => {
2301                                 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
2302                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2303                                                 if let &Some(ref source) = source_option {
2304                                                         res.insert((**source).clone(), (htlc.clone(),
2305                                                                 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned()));
2306                                                 }
2307                                         }
2308                                 }
2309                         }
2310                 }
2311                 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2312                         walk_counterparty_commitment!(txid);
2313                 }
2314                 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2315                         walk_counterparty_commitment!(txid);
2316                 }
2317                 res
2318         }
2319
2320         /// Gets the set of outbound HTLCs which are pending resolution in this channel or which were
2321         /// resolved with a preimage from our counterparty.
2322         ///
2323         /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
2324         ///
2325         /// Currently, the preimage is unused, however if it is present in the relevant internal state
2326         /// an HTLC is always included even if it has been resolved.
2327         pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2328                 let us = self.inner.lock().unwrap();
2329                 // We're only concerned with the confirmation count of HTLC transactions, and don't
2330                 // actually care how many confirmations a commitment transaction may or may not have. Thus,
2331                 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
2332                 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2333                         us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2334                                 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2335                                         Some(event.txid)
2336                                 } else { None }
2337                         })
2338                 });
2339
2340                 if confirmed_txid.is_none() {
2341                         // If we have not seen a commitment transaction on-chain (ie the channel is not yet
2342                         // closed), just get the full set.
2343                         mem::drop(us);
2344                         return self.get_all_current_outbound_htlcs();
2345                 }
2346
2347                 let mut res = new_hash_map();
2348                 macro_rules! walk_htlcs {
2349                         ($holder_commitment: expr, $htlc_iter: expr) => {
2350                                 for (htlc, source) in $htlc_iter {
2351                                         if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc.transaction_output_index) {
2352                                                 // We should assert that funding_spend_confirmed is_some() here, but we
2353                                                 // have some unit tests which violate HTLC transaction CSVs entirely and
2354                                                 // would fail.
2355                                                 // TODO: Once tests all connect transactions at consensus-valid times, we
2356                                                 // should assert here like we do in `get_claimable_balances`.
2357                                         } else if htlc.offered == $holder_commitment {
2358                                                 // If the payment was outbound, check if there's an HTLCUpdate
2359                                                 // indicating we have spent this HTLC with a timeout, claiming it back
2360                                                 // and awaiting confirmations on it.
2361                                                 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2362                                                         if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
2363                                                                 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
2364                                                                 // before considering it "no longer pending" - this matches when we
2365                                                                 // provide the ChannelManager an HTLC failure event.
2366                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
2367                                                                         us.best_block.height >= event.height + ANTI_REORG_DELAY - 1
2368                                                         } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
2369                                                                 // If the HTLC was fulfilled with a preimage, we consider the HTLC
2370                                                                 // immediately non-pending, matching when we provide ChannelManager
2371                                                                 // the preimage.
2372                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index
2373                                                         } else { false }
2374                                                 });
2375                                                 let counterparty_resolved_preimage_opt =
2376                                                         us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned();
2377                                                 if !htlc_update_confd || counterparty_resolved_preimage_opt.is_some() {
2378                                                         res.insert(source.clone(), (htlc.clone(), counterparty_resolved_preimage_opt));
2379                                                 }
2380                                         }
2381                                 }
2382                         }
2383                 }
2384
2385                 let txid = confirmed_txid.unwrap();
2386                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2387                         walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
2388                                 if let &Some(ref source) = b {
2389                                         Some((a, &**source))
2390                                 } else { None }
2391                         }));
2392                 } else if txid == us.current_holder_commitment_tx.txid {
2393                         walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
2394                                 if let Some(source) = c { Some((a, source)) } else { None }
2395                         }));
2396                 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2397                         if txid == prev_commitment.txid {
2398                                 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
2399                                         if let Some(source) = c { Some((a, source)) } else { None }
2400                                 }));
2401                         }
2402                 }
2403
2404                 res
2405         }
2406
2407         pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
2408                 self.inner.lock().unwrap().payment_preimages.clone()
2409         }
2410 }
2411
2412 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
2413 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
2414 /// after ANTI_REORG_DELAY blocks.
2415 ///
2416 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
2417 /// are the commitment transactions which are generated by us. The off-chain state machine in
2418 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
2419 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
2420 /// included in a remote commitment transaction are failed back if they are not present in the
2421 /// broadcasted commitment transaction.
2422 ///
2423 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
2424 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
2425 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
2426 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
2427 macro_rules! fail_unbroadcast_htlcs {
2428         ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2429          $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2430                 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
2431
2432                 macro_rules! check_htlc_fails {
2433                         ($txid: expr, $commitment_tx: expr) => {
2434                                 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
2435                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2436                                                 if let &Some(ref source) = source_option {
2437                                                         // Check if the HTLC is present in the commitment transaction that was
2438                                                         // broadcast, but not if it was below the dust limit, which we should
2439                                                         // fail backwards immediately as there is no way for us to learn the
2440                                                         // payment_preimage.
2441                                                         // Note that if the dust limit were allowed to change between
2442                                                         // commitment transactions we'd want to be check whether *any*
2443                                                         // broadcastable commitment transaction has the HTLC in it, but it
2444                                                         // cannot currently change after channel initialization, so we don't
2445                                                         // need to here.
2446                                                         let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2447
2448                                                         let mut matched_htlc = false;
2449                                                         for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2450                                                                 if broadcast_htlc.transaction_output_index.is_some() &&
2451                                                                         (Some(&**source) == *broadcast_source ||
2452                                                                          (broadcast_source.is_none() &&
2453                                                                           broadcast_htlc.payment_hash == htlc.payment_hash &&
2454                                                                           broadcast_htlc.amount_msat == htlc.amount_msat)) {
2455                                                                         matched_htlc = true;
2456                                                                         break;
2457                                                                 }
2458                                                         }
2459                                                         if matched_htlc { continue; }
2460                                                         if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2461                                                                 continue;
2462                                                         }
2463                                                         $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2464                                                                 if entry.height != $commitment_tx_conf_height { return true; }
2465                                                                 match entry.event {
2466                                                                         OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2467                                                                                 *update_source != **source
2468                                                                         },
2469                                                                         _ => true,
2470                                                                 }
2471                                                         });
2472                                                         let entry = OnchainEventEntry {
2473                                                                 txid: $commitment_txid_confirmed,
2474                                                                 transaction: Some($commitment_tx_confirmed.clone()),
2475                                                                 height: $commitment_tx_conf_height,
2476                                                                 block_hash: Some(*$commitment_tx_conf_hash),
2477                                                                 event: OnchainEvent::HTLCUpdate {
2478                                                                         source: (**source).clone(),
2479                                                                         payment_hash: htlc.payment_hash.clone(),
2480                                                                         htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2481                                                                         commitment_tx_output_idx: None,
2482                                                                 },
2483                                                         };
2484                                                         log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2485                                                                 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2486                                                                 $commitment_txid_confirmed, entry.confirmation_threshold());
2487                                                         $self.onchain_events_awaiting_threshold_conf.push(entry);
2488                                                 }
2489                                         }
2490                                 }
2491                         }
2492                 }
2493                 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2494                         check_htlc_fails!(txid, "current");
2495                 }
2496                 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2497                         check_htlc_fails!(txid, "previous");
2498                 }
2499         } }
2500 }
2501
2502 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
2503 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
2504 // in-line tests later.
2505
2506 #[cfg(test)]
2507 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2508         use bitcoin::blockdata::opcodes;
2509         let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2510         ret[131] = opcodes::all::OP_DROP.to_u8();
2511         ret[132] = opcodes::all::OP_DROP.to_u8();
2512         ret[133] = opcodes::all::OP_DROP.to_u8();
2513         ret[134] = opcodes::all::OP_DROP.to_u8();
2514         ret[135] = opcodes::OP_TRUE.to_u8();
2515         Vec::from(&ret[..])
2516 }
2517
2518 #[cfg(test)]
2519 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2520         vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2521 }
2522
2523 impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2524         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
2525         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
2526         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
2527         fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2528                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2529                         return Err("Previous secret did not match new one");
2530                 }
2531
2532                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
2533                 // events for now-revoked/fulfilled HTLCs.
2534                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2535                         if self.current_counterparty_commitment_txid.unwrap() != txid {
2536                                 let cur_claimables = self.counterparty_claimable_outpoints.get(
2537                                         &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2538                                 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2539                                         if let Some(source) = source_opt {
2540                                                 if !cur_claimables.iter()
2541                                                         .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2542                                                 {
2543                                                         self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2544                                                 }
2545                                         }
2546                                 }
2547                                 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2548                                         *source_opt = None;
2549                                 }
2550                         } else {
2551                                 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2552                         }
2553                 }
2554
2555                 if !self.payment_preimages.is_empty() {
2556                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2557                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2558                         let min_idx = self.get_min_seen_secret();
2559                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2560
2561                         self.payment_preimages.retain(|&k, _| {
2562                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2563                                         if k == htlc.payment_hash {
2564                                                 return true
2565                                         }
2566                                 }
2567                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2568                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2569                                                 if k == htlc.payment_hash {
2570                                                         return true
2571                                                 }
2572                                         }
2573                                 }
2574                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2575                                         if *cn < min_idx {
2576                                                 return true
2577                                         }
2578                                         true
2579                                 } else { false };
2580                                 if contains {
2581                                         counterparty_hash_commitment_number.remove(&k);
2582                                 }
2583                                 false
2584                         });
2585                 }
2586
2587                 Ok(())
2588         }
2589
2590         fn provide_initial_counterparty_commitment_tx<L: Deref>(
2591                 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2592                 commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32,
2593                 to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor<L>,
2594         ) where L::Target: Logger {
2595                 self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(),
2596                         feerate_per_kw, to_broadcaster_value, to_countersignatory_value));
2597
2598                 #[cfg(debug_assertions)] {
2599                         let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
2600                         debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), txid);
2601                 }
2602
2603                 self.provide_latest_counterparty_commitment_tx(txid, htlc_outputs, commitment_number,
2604                                 their_per_commitment_point, logger);
2605         }
2606
2607         fn provide_latest_counterparty_commitment_tx<L: Deref>(
2608                 &mut self, txid: Txid,
2609                 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2610                 commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor<L>,
2611         ) where L::Target: Logger {
2612                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2613                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2614                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2615                 // timeouts)
2616                 for &(ref htlc, _) in &htlc_outputs {
2617                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2618                 }
2619
2620                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2621                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2622                 self.current_counterparty_commitment_txid = Some(txid);
2623                 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2624                 self.current_counterparty_commitment_number = commitment_number;
2625                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2626                 match self.their_cur_per_commitment_points {
2627                         Some(old_points) => {
2628                                 if old_points.0 == commitment_number + 1 {
2629                                         self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2630                                 } else if old_points.0 == commitment_number + 2 {
2631                                         if let Some(old_second_point) = old_points.2 {
2632                                                 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2633                                         } else {
2634                                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2635                                         }
2636                                 } else {
2637                                         self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2638                                 }
2639                         },
2640                         None => {
2641                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2642                         }
2643                 }
2644                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2645                 for htlc in htlc_outputs {
2646                         if htlc.0.transaction_output_index.is_some() {
2647                                 htlcs.push(htlc.0);
2648                         }
2649                 }
2650         }
2651
2652         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2653         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2654         /// is important that any clones of this channel monitor (including remote clones) by kept
2655         /// up-to-date as our holder commitment transaction is updated.
2656         /// Panics if set_on_holder_tx_csv has never been called.
2657         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> {
2658                 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
2659                         // If we have non-dust HTLCs in htlc_outputs, ensure they match the HTLCs in the
2660                         // `holder_commitment_tx`. In the future, we'll no longer provide the redundant data
2661                         // and just pass in source data via `nondust_htlc_sources`.
2662                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
2663                         for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
2664                                 debug_assert_eq!(a, b);
2665                         }
2666                         debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
2667                         for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
2668                                 debug_assert_eq!(a, b);
2669                         }
2670                         debug_assert!(nondust_htlc_sources.is_empty());
2671                 } else {
2672                         // If we don't have any non-dust HTLCs in htlc_outputs, assume they were all passed via
2673                         // `nondust_htlc_sources`, building up the final htlc_outputs by combining
2674                         // `nondust_htlc_sources` and the `holder_commitment_tx`
2675                         #[cfg(debug_assertions)] {
2676                                 let mut prev = -1;
2677                                 for htlc in holder_commitment_tx.trust().htlcs().iter() {
2678                                         assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
2679                                         prev = htlc.transaction_output_index.unwrap() as i32;
2680                                 }
2681                         }
2682                         debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
2683                         debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
2684                         debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
2685
2686                         let mut sources_iter = nondust_htlc_sources.into_iter();
2687
2688                         for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
2689                                 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
2690                         {
2691                                 if htlc.offered {
2692                                         let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
2693                                         #[cfg(debug_assertions)] {
2694                                                 assert!(source.possibly_matches_output(htlc));
2695                                         }
2696                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
2697                                 } else {
2698                                         htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
2699                                 }
2700                         }
2701                         debug_assert!(sources_iter.next().is_none());
2702                 }
2703
2704                 let trusted_tx = holder_commitment_tx.trust();
2705                 let txid = trusted_tx.txid();
2706                 let tx_keys = trusted_tx.keys();
2707                 self.current_holder_commitment_number = trusted_tx.commitment_number();
2708                 let mut new_holder_commitment_tx = HolderSignedTx {
2709                         txid,
2710                         revocation_key: tx_keys.revocation_key,
2711                         a_htlc_key: tx_keys.broadcaster_htlc_key,
2712                         b_htlc_key: tx_keys.countersignatory_htlc_key,
2713                         delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2714                         per_commitment_point: tx_keys.per_commitment_point,
2715                         htlc_outputs,
2716                         to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2717                         feerate_per_kw: trusted_tx.feerate_per_kw(),
2718                 };
2719                 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2720                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2721                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2722                 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2723                         #[cfg(debug_assertions)] {
2724                                 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
2725                                                 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2726                                 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
2727                                         if let Some(source) = source_opt {
2728                                                 SentHTLCId::from_source(source) == *claimed_htlc_id
2729                                         } else { false }
2730                                 }));
2731                         }
2732                         self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
2733                 }
2734                 if self.holder_tx_signed {
2735                         return Err("Latest holder commitment signed has already been signed, update is rejected");
2736                 }
2737                 Ok(())
2738         }
2739
2740         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2741         /// commitment_tx_infos which contain the payment hash have been revoked.
2742         fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2743                 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2744                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
2745         where B::Target: BroadcasterInterface,
2746                     F::Target: FeeEstimator,
2747                     L::Target: Logger,
2748         {
2749                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2750
2751                 let confirmed_spend_txid = self.funding_spend_confirmed.or_else(|| {
2752                         self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
2753                                 OnchainEvent::FundingSpendConfirmation { .. } => Some(event.txid),
2754                                 _ => None,
2755                         })
2756                 });
2757                 let confirmed_spend_txid = if let Some(txid) = confirmed_spend_txid {
2758                         txid
2759                 } else {
2760                         return;
2761                 };
2762
2763                 // If the channel is force closed, try to claim the output from this preimage.
2764                 // First check if a counterparty commitment transaction has been broadcasted:
2765                 macro_rules! claim_htlcs {
2766                         ($commitment_number: expr, $txid: expr) => {
2767                                 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2768                                 self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
2769                         }
2770                 }
2771                 if let Some(txid) = self.current_counterparty_commitment_txid {
2772                         if txid == confirmed_spend_txid {
2773                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2774                                         claim_htlcs!(*commitment_number, txid);
2775                                 } else {
2776                                         debug_assert!(false);
2777                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2778                                 }
2779                                 return;
2780                         }
2781                 }
2782                 if let Some(txid) = self.prev_counterparty_commitment_txid {
2783                         if txid == confirmed_spend_txid {
2784                                 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2785                                         claim_htlcs!(*commitment_number, txid);
2786                                 } else {
2787                                         debug_assert!(false);
2788                                         log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
2789                                 }
2790                                 return;
2791                         }
2792                 }
2793
2794                 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2795                 // claiming the HTLC output from each of the holder commitment transactions.
2796                 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2797                 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2798                 // holder commitment transactions.
2799                 if self.broadcasted_holder_revokable_script.is_some() {
2800                         let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
2801                                 Some(&self.current_holder_commitment_tx)
2802                         } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
2803                                 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
2804                                         Some(prev_holder_commitment_tx)
2805                                 } else {
2806                                         None
2807                                 }
2808                         } else {
2809                                 None
2810                         };
2811                         if let Some(holder_commitment_tx) = holder_commitment_tx {
2812                                 // Assume that the broadcasted commitment transaction confirmed in the current best
2813                                 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2814                                 // transactions.
2815                                 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
2816                                 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
2817                         }
2818                 }
2819         }
2820
2821         fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
2822                 let funding_outp = HolderFundingOutput::build(
2823                         self.funding_redeemscript.clone(),
2824                         self.channel_value_satoshis,
2825                         self.onchain_tx_handler.channel_type_features().clone()
2826                 );
2827                 let commitment_package = PackageTemplate::build_package(
2828                         self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
2829                         PackageSolvingData::HolderFundingOutput(funding_outp),
2830                         self.best_block.height, self.best_block.height
2831                 );
2832                 let mut claimable_outpoints = vec![commitment_package];
2833                 let event = MonitorEvent::HolderForceClosedWithInfo {
2834                         reason,
2835                         outpoint: self.funding_info.0,
2836                         channel_id: self.channel_id,
2837                 };
2838                 self.pending_monitor_events.push(event);
2839
2840                 // Although we aren't signing the transaction directly here, the transaction will be signed
2841                 // in the claim that is queued to OnchainTxHandler. We set holder_tx_signed here to reject
2842                 // new channel updates.
2843                 self.holder_tx_signed = true;
2844                 let mut watch_outputs = Vec::new();
2845                 // We can't broadcast our HTLC transactions while the commitment transaction is
2846                 // unconfirmed. We'll delay doing so until we detect the confirmed commitment in
2847                 // `transactions_confirmed`.
2848                 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
2849                         // Because we're broadcasting a commitment transaction, we should construct the package
2850                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2851                         // "not yet confirmed" things as discardable, so we cannot do that here.
2852                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
2853                                 &self.current_holder_commitment_tx, self.best_block.height
2854                         );
2855                         let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
2856                         let new_outputs = self.get_broadcasted_holder_watch_outputs(
2857                                 &self.current_holder_commitment_tx, &unsigned_commitment_tx
2858                         );
2859                         if !new_outputs.is_empty() {
2860                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2861                         }
2862                         claimable_outpoints.append(&mut new_outpoints);
2863                 }
2864                 (claimable_outpoints, watch_outputs)
2865         }
2866
2867         pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
2868                 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
2869         )
2870         where
2871                 B::Target: BroadcasterInterface,
2872                 F::Target: FeeEstimator,
2873                 L::Target: Logger,
2874         {
2875                 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed);
2876                 self.onchain_tx_handler.update_claims_view_from_requests(
2877                         claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
2878                         fee_estimator, logger
2879                 );
2880         }
2881
2882         fn update_monitor<B: Deref, F: Deref, L: Deref>(
2883                 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
2884         ) -> Result<(), ()>
2885         where B::Target: BroadcasterInterface,
2886                 F::Target: FeeEstimator,
2887                 L::Target: Logger,
2888         {
2889                 if self.latest_update_id == CLOSED_CHANNEL_UPDATE_ID && updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2890                         log_info!(logger, "Applying post-force-closed update to monitor {} with {} change(s).",
2891                                 log_funding_info!(self), updates.updates.len());
2892                 } else if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2893                         log_info!(logger, "Applying force close update to monitor {} with {} change(s).",
2894                                 log_funding_info!(self), updates.updates.len());
2895                 } else {
2896                         log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
2897                                 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2898                 }
2899
2900                 if updates.counterparty_node_id.is_some() {
2901                         if self.counterparty_node_id.is_none() {
2902                                 self.counterparty_node_id = updates.counterparty_node_id;
2903                         } else {
2904                                 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
2905                         }
2906                 }
2907
2908                 // ChannelMonitor updates may be applied after force close if we receive a preimage for a
2909                 // broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
2910                 // is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
2911                 // sentinel value instead.
2912                 //
2913                 // The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
2914                 // thinks the channel needs to have its commitment transaction broadcast, so we'll allow
2915                 // them as well.
2916                 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2917                         assert_eq!(updates.updates.len(), 1);
2918                         match updates.updates[0] {
2919                                 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
2920                                 // We should have already seen a `ChannelForceClosed` update if we're trying to
2921                                 // provide a preimage at this point.
2922                                 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
2923                                         debug_assert_eq!(self.latest_update_id, CLOSED_CHANNEL_UPDATE_ID),
2924                                 _ => {
2925                                         log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2926                                         panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2927                                 },
2928                         }
2929                 } else if self.latest_update_id + 1 != updates.update_id {
2930                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2931                 }
2932                 let mut ret = Ok(());
2933                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
2934                 for update in updates.updates.iter() {
2935                         match update {
2936                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
2937                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2938                                         if self.lockdown_from_offchain { panic!(); }
2939                                         if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone()) {
2940                                                 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2941                                                 log_error!(logger, "    {}", e);
2942                                                 ret = Err(());
2943                                         }
2944                                 }
2945                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
2946                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2947                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2948                                 },
2949                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2950                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2951                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2952                                 },
2953                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2954                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2955                                         if let Err(e) = self.provide_secret(*idx, *secret) {
2956                                                 debug_assert!(false, "Latest counterparty commitment secret was invalid");
2957                                                 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2958                                                 log_error!(logger, "    {}", e);
2959                                                 ret = Err(());
2960                                         }
2961                                 },
2962                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2963                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2964                                         self.lockdown_from_offchain = true;
2965                                         if *should_broadcast {
2966                                                 // There's no need to broadcast our commitment transaction if we've seen one
2967                                                 // confirmed (even with 1 confirmation) as it'll be rejected as
2968                                                 // duplicate/conflicting.
2969                                                 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
2970                                                         self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
2971                                                                 OnchainEvent::FundingSpendConfirmation { .. } => true,
2972                                                                 _ => false,
2973                                                         }).is_some();
2974                                                 if detected_funding_spend {
2975                                                         log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
2976                                                         continue;
2977                                                 }
2978                                                 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
2979                                         } else if !self.holder_tx_signed {
2980                                                 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
2981                                                 log_error!(logger, "    in channel monitor for channel {}!", &self.channel_id());
2982                                                 log_error!(logger, "    Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
2983                                         } else {
2984                                                 // If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
2985                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2986                                                 // shouldn't print the scary warning above.
2987                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2988                                         }
2989                                 },
2990                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2991                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2992                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2993                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2994                                         }
2995                                 },
2996                         }
2997                 }
2998
2999                 #[cfg(debug_assertions)] {
3000                         self.counterparty_commitment_txs_from_update(updates);
3001                 }
3002
3003                 // If the updates succeeded and we were in an already closed channel state, then there's no
3004                 // need to refuse any updates we expect to receive afer seeing a confirmed commitment.
3005                 if ret.is_ok() && updates.update_id == CLOSED_CHANNEL_UPDATE_ID && self.latest_update_id == updates.update_id {
3006                         return Ok(());
3007                 }
3008
3009                 self.latest_update_id = updates.update_id;
3010
3011                 // Refuse updates after we've detected a spend onchain, but only if we haven't processed a
3012                 // force closed monitor update yet.
3013                 if ret.is_ok() && self.funding_spend_seen && self.latest_update_id != CLOSED_CHANNEL_UPDATE_ID {
3014                         log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3015                         Err(())
3016                 } else { ret }
3017         }
3018
3019         fn get_latest_update_id(&self) -> u64 {
3020                 self.latest_update_id
3021         }
3022
3023         fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3024                 &self.funding_info
3025         }
3026
3027         pub fn channel_id(&self) -> ChannelId {
3028                 self.channel_id
3029         }
3030
3031         fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3032                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
3033                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
3034                 // its trivial to do, double-check that here.
3035                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
3036                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3037                 }
3038                 &self.outputs_to_watch
3039         }
3040
3041         fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3042                 let mut ret = Vec::new();
3043                 mem::swap(&mut ret, &mut self.pending_monitor_events);
3044                 ret
3045         }
3046
3047         /// Gets the set of events that are repeated regularly (e.g. those which RBF bump
3048         /// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
3049         /// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
3050         pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3051                 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3052                 let mut ret = Vec::with_capacity(pending_claim_events.len());
3053                 for (claim_id, claim_event) in pending_claim_events {
3054                         match claim_event {
3055                                 ClaimEvent::BumpCommitment {
3056                                         package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3057                                 } => {
3058                                         let channel_id = self.channel_id;
3059                                         // unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3060                                         // introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3061                                         // since v0.0.110.
3062                                         let counterparty_node_id = self.counterparty_node_id.unwrap();
3063                                         let commitment_txid = commitment_tx.txid();
3064                                         debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3065                                         let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3066                                         let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3067                                                 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value);
3068                                         ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3069                                                 channel_id,
3070                                                 counterparty_node_id,
3071                                                 claim_id,
3072                                                 package_target_feerate_sat_per_1000_weight,
3073                                                 commitment_tx,
3074                                                 commitment_tx_fee_satoshis,
3075                                                 anchor_descriptor: AnchorDescriptor {
3076                                                         channel_derivation_parameters: ChannelDerivationParameters {
3077                                                                 keys_id: self.channel_keys_id,
3078                                                                 value_satoshis: self.channel_value_satoshis,
3079                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3080                                                         },
3081                                                         outpoint: BitcoinOutPoint {
3082                                                                 txid: commitment_txid,
3083                                                                 vout: anchor_output_idx,
3084                                                         },
3085                                                 },
3086                                                 pending_htlcs,
3087                                         }));
3088                                 },
3089                                 ClaimEvent::BumpHTLC {
3090                                         target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3091                                 } => {
3092                                         let channel_id = self.channel_id;
3093                                         // unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3094                                         // introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3095                                         // since v0.0.110.
3096                                         let counterparty_node_id = self.counterparty_node_id.unwrap();
3097                                         let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3098                                         for htlc in htlcs {
3099                                                 htlc_descriptors.push(HTLCDescriptor {
3100                                                         channel_derivation_parameters: ChannelDerivationParameters {
3101                                                                 keys_id: self.channel_keys_id,
3102                                                                 value_satoshis: self.channel_value_satoshis,
3103                                                                 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3104                                                         },
3105                                                         commitment_txid: htlc.commitment_txid,
3106                                                         per_commitment_number: htlc.per_commitment_number,
3107                                                         per_commitment_point: htlc.per_commitment_point,
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                                                 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4388                                         }));
4389                                 }
4390                         }
4391                         if self.counterparty_payment_script == outp.script_pubkey {
4392                                 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4393                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4394                                         output: outp.clone(),
4395                                         channel_keys_id: self.channel_keys_id,
4396                                         channel_value_satoshis: self.channel_value_satoshis,
4397                                         channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4398                                 }));
4399                         }
4400                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4401                                 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4402                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
4403                                         output: outp.clone(),
4404                                         channel_keys_id: Some(self.channel_keys_id),
4405                                 });
4406                         }
4407                 }
4408                 spendable_outputs
4409         }
4410
4411         /// Checks if the confirmed transaction is paying funds back to some address we can assume to
4412         /// own.
4413         fn check_tx_and_push_spendable_outputs<L: Deref>(
4414                 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4415         ) where L::Target: Logger {
4416                 for spendable_output in self.get_spendable_outputs(tx) {
4417                         let entry = OnchainEventEntry {
4418                                 txid: tx.txid(),
4419                                 transaction: Some(tx.clone()),
4420                                 height,
4421                                 block_hash: Some(*block_hash),
4422                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4423                         };
4424                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4425                         self.onchain_events_awaiting_threshold_conf.push(entry);
4426                 }
4427         }
4428 }
4429
4430 impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4431 where
4432         T::Target: BroadcasterInterface,
4433         F::Target: FeeEstimator,
4434         L::Target: Logger,
4435 {
4436         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4437                 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4438         }
4439
4440         fn block_disconnected(&self, header: &Header, height: u32) {
4441                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4442         }
4443 }
4444
4445 impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4446 where
4447         M: Deref<Target = ChannelMonitor<Signer>>,
4448         T::Target: BroadcasterInterface,
4449         F::Target: FeeEstimator,
4450         L::Target: Logger,
4451 {
4452         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4453                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4454         }
4455
4456         fn transaction_unconfirmed(&self, txid: &Txid) {
4457                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4458         }
4459
4460         fn best_block_updated(&self, header: &Header, height: u32) {
4461                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4462         }
4463
4464         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4465                 self.0.get_relevant_txids()
4466         }
4467 }
4468
4469 const MAX_ALLOC_SIZE: usize = 64*1024;
4470
4471 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4472                 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4473         fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4474                 macro_rules! unwrap_obj {
4475                         ($key: expr) => {
4476                                 match $key {
4477                                         Ok(res) => res,
4478                                         Err(_) => return Err(DecodeError::InvalidValue),
4479                                 }
4480                         }
4481                 }
4482
4483                 let (entropy_source, signer_provider) = args;
4484
4485                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4486
4487                 let latest_update_id: u64 = Readable::read(reader)?;
4488                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4489
4490                 let destination_script = Readable::read(reader)?;
4491                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4492                         0 => {
4493                                 let revokable_address = Readable::read(reader)?;
4494                                 let per_commitment_point = Readable::read(reader)?;
4495                                 let revokable_script = Readable::read(reader)?;
4496                                 Some((revokable_address, per_commitment_point, revokable_script))
4497                         },
4498                         1 => { None },
4499                         _ => return Err(DecodeError::InvalidValue),
4500                 };
4501                 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4502                 let shutdown_script = {
4503                         let script = <ScriptBuf as Readable>::read(reader)?;
4504                         if script.is_empty() { None } else { Some(script) }
4505                 };
4506
4507                 let channel_keys_id = Readable::read(reader)?;
4508                 let holder_revocation_basepoint = Readable::read(reader)?;
4509                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
4510                 // barely-init'd ChannelMonitors that we can't do anything with.
4511                 let outpoint = OutPoint {
4512                         txid: Readable::read(reader)?,
4513                         index: Readable::read(reader)?,
4514                 };
4515                 let funding_info = (outpoint, Readable::read(reader)?);
4516                 let current_counterparty_commitment_txid = Readable::read(reader)?;
4517                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4518
4519                 let counterparty_commitment_params = Readable::read(reader)?;
4520                 let funding_redeemscript = Readable::read(reader)?;
4521                 let channel_value_satoshis = Readable::read(reader)?;
4522
4523                 let their_cur_per_commitment_points = {
4524                         let first_idx = <U48 as Readable>::read(reader)?.0;
4525                         if first_idx == 0 {
4526                                 None
4527                         } else {
4528                                 let first_point = Readable::read(reader)?;
4529                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4530                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4531                                         Some((first_idx, first_point, None))
4532                                 } else {
4533                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4534                                 }
4535                         }
4536                 };
4537
4538                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4539
4540                 let commitment_secrets = Readable::read(reader)?;
4541
4542                 macro_rules! read_htlc_in_commitment {
4543                         () => {
4544                                 {
4545                                         let offered: bool = Readable::read(reader)?;
4546                                         let amount_msat: u64 = Readable::read(reader)?;
4547                                         let cltv_expiry: u32 = Readable::read(reader)?;
4548                                         let payment_hash: PaymentHash = Readable::read(reader)?;
4549                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
4550
4551                                         HTLCOutputInCommitment {
4552                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4553                                         }
4554                                 }
4555                         }
4556                 }
4557
4558                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4559                 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4560                 for _ in 0..counterparty_claimable_outpoints_len {
4561                         let txid: Txid = Readable::read(reader)?;
4562                         let htlcs_count: u64 = Readable::read(reader)?;
4563                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4564                         for _ in 0..htlcs_count {
4565                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4566                         }
4567                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
4568                                 return Err(DecodeError::InvalidValue);
4569                         }
4570                 }
4571
4572                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4573                 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));
4574                 for _ in 0..counterparty_commitment_txn_on_chain_len {
4575                         let txid: Txid = Readable::read(reader)?;
4576                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4577                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
4578                                 return Err(DecodeError::InvalidValue);
4579                         }
4580                 }
4581
4582                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4583                 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4584                 for _ in 0..counterparty_hash_commitment_number_len {
4585                         let payment_hash: PaymentHash = Readable::read(reader)?;
4586                         let commitment_number = <U48 as Readable>::read(reader)?.0;
4587                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
4588                                 return Err(DecodeError::InvalidValue);
4589                         }
4590                 }
4591
4592                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4593                         match <u8 as Readable>::read(reader)? {
4594                                 0 => None,
4595                                 1 => {
4596                                         Some(Readable::read(reader)?)
4597                                 },
4598                                 _ => return Err(DecodeError::InvalidValue),
4599                         };
4600                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4601
4602                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4603                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4604
4605                 let payment_preimages_len: u64 = Readable::read(reader)?;
4606                 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4607                 for _ in 0..payment_preimages_len {
4608                         let preimage: PaymentPreimage = Readable::read(reader)?;
4609                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4610                         if let Some(_) = payment_preimages.insert(hash, preimage) {
4611                                 return Err(DecodeError::InvalidValue);
4612                         }
4613                 }
4614
4615                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4616                 let mut pending_monitor_events = Some(
4617                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4618                 for _ in 0..pending_monitor_events_len {
4619                         let ev = match <u8 as Readable>::read(reader)? {
4620                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4621                                 1 => MonitorEvent::HolderForceClosed(funding_info.0),
4622                                 _ => return Err(DecodeError::InvalidValue)
4623                         };
4624                         pending_monitor_events.as_mut().unwrap().push(ev);
4625                 }
4626
4627                 let pending_events_len: u64 = Readable::read(reader)?;
4628                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4629                 for _ in 0..pending_events_len {
4630                         if let Some(event) = MaybeReadable::read(reader)? {
4631                                 pending_events.push(event);
4632                         }
4633                 }
4634
4635                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4636
4637                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4638                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4639                 for _ in 0..waiting_threshold_conf_len {
4640                         if let Some(val) = MaybeReadable::read(reader)? {
4641                                 onchain_events_awaiting_threshold_conf.push(val);
4642                         }
4643                 }
4644
4645                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4646                 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>>())));
4647                 for _ in 0..outputs_to_watch_len {
4648                         let txid = Readable::read(reader)?;
4649                         let outputs_len: u64 = Readable::read(reader)?;
4650                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
4651                         for _ in 0..outputs_len {
4652                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
4653                         }
4654                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
4655                                 return Err(DecodeError::InvalidValue);
4656                         }
4657                 }
4658                 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
4659                         reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
4660                 )?;
4661
4662                 let lockdown_from_offchain = Readable::read(reader)?;
4663                 let holder_tx_signed = Readable::read(reader)?;
4664
4665                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
4666                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
4667                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
4668                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
4669                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
4670                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
4671                                 return Err(DecodeError::InvalidValue);
4672                         }
4673                 }
4674
4675                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
4676                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
4677                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
4678                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
4679                         return Err(DecodeError::InvalidValue);
4680                 }
4681
4682                 let mut funding_spend_confirmed = None;
4683                 let mut htlcs_resolved_on_chain = Some(Vec::new());
4684                 let mut funding_spend_seen = Some(false);
4685                 let mut counterparty_node_id = None;
4686                 let mut confirmed_commitment_tx_counterparty_output = None;
4687                 let mut spendable_txids_confirmed = Some(Vec::new());
4688                 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
4689                 let mut initial_counterparty_commitment_info = None;
4690                 let mut balances_empty_height = None;
4691                 let mut channel_id = None;
4692                 read_tlv_fields!(reader, {
4693                         (1, funding_spend_confirmed, option),
4694                         (3, htlcs_resolved_on_chain, optional_vec),
4695                         (5, pending_monitor_events, optional_vec),
4696                         (7, funding_spend_seen, option),
4697                         (9, counterparty_node_id, option),
4698                         (11, confirmed_commitment_tx_counterparty_output, option),
4699                         (13, spendable_txids_confirmed, optional_vec),
4700                         (15, counterparty_fulfilled_htlcs, option),
4701                         (17, initial_counterparty_commitment_info, option),
4702                         (19, channel_id, option),
4703                         (21, balances_empty_height, option),
4704                 });
4705
4706                 // `HolderForceClosedWithInfo` replaced `HolderForceClosed` in v0.0.122. If we have both
4707                 // events, we can remove the `HolderForceClosed` event and just keep the `HolderForceClosedWithInfo`.
4708                 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
4709                         if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
4710                                 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
4711                         {
4712                                 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
4713                         }
4714                 }
4715
4716                 // Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
4717                 // wrong `counterparty_payment_script` was being tracked. Fix it now on deserialization to
4718                 // give them a chance to recognize the spendable output.
4719                 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
4720                         counterparty_payment_script.is_v0_p2wpkh()
4721                 {
4722                         let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
4723                         counterparty_payment_script =
4724                                 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_v0_p2wsh();
4725                 }
4726
4727                 Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
4728                         latest_update_id,
4729                         commitment_transaction_number_obscure_factor,
4730
4731                         destination_script,
4732                         broadcasted_holder_revokable_script,
4733                         counterparty_payment_script,
4734                         shutdown_script,
4735
4736                         channel_keys_id,
4737                         holder_revocation_basepoint,
4738                         channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
4739                         funding_info,
4740                         current_counterparty_commitment_txid,
4741                         prev_counterparty_commitment_txid,
4742
4743                         counterparty_commitment_params,
4744                         funding_redeemscript,
4745                         channel_value_satoshis,
4746                         their_cur_per_commitment_points,
4747
4748                         on_holder_tx_csv,
4749
4750                         commitment_secrets,
4751                         counterparty_claimable_outpoints,
4752                         counterparty_commitment_txn_on_chain,
4753                         counterparty_hash_commitment_number,
4754                         counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
4755
4756                         prev_holder_signed_commitment_tx,
4757                         current_holder_commitment_tx,
4758                         current_counterparty_commitment_number,
4759                         current_holder_commitment_number,
4760
4761                         payment_preimages,
4762                         pending_monitor_events: pending_monitor_events.unwrap(),
4763                         pending_events,
4764                         is_processing_pending_events: false,
4765
4766                         onchain_events_awaiting_threshold_conf,
4767                         outputs_to_watch,
4768
4769                         onchain_tx_handler,
4770
4771                         lockdown_from_offchain,
4772                         holder_tx_signed,
4773                         funding_spend_seen: funding_spend_seen.unwrap(),
4774                         funding_spend_confirmed,
4775                         confirmed_commitment_tx_counterparty_output,
4776                         htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
4777                         spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
4778
4779                         best_block,
4780                         counterparty_node_id,
4781                         initial_counterparty_commitment_info,
4782                         balances_empty_height,
4783                 })))
4784         }
4785 }
4786
4787 #[cfg(test)]
4788 mod tests {
4789         use bitcoin::blockdata::locktime::absolute::LockTime;
4790         use bitcoin::blockdata::script::{ScriptBuf, Builder};
4791         use bitcoin::blockdata::opcodes;
4792         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut};
4793         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
4794         use bitcoin::sighash;
4795         use bitcoin::sighash::EcdsaSighashType;
4796         use bitcoin::hashes::Hash;
4797         use bitcoin::hashes::sha256::Hash as Sha256;
4798         use bitcoin::hashes::hex::FromHex;
4799         use bitcoin::hash_types::{BlockHash, Txid};
4800         use bitcoin::network::constants::Network;
4801         use bitcoin::secp256k1::{SecretKey,PublicKey};
4802         use bitcoin::secp256k1::Secp256k1;
4803         use bitcoin::{Sequence, Witness};
4804
4805         use crate::chain::chaininterface::LowerBoundedFeeEstimator;
4806
4807         use super::ChannelMonitorUpdateStep;
4808         use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
4809         use crate::chain::{BestBlock, Confirm};
4810         use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
4811         use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
4812         use crate::chain::transaction::OutPoint;
4813         use crate::sign::InMemorySigner;
4814         use crate::ln::types::{PaymentPreimage, PaymentHash, ChannelId};
4815         use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
4816         use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
4817         use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
4818         use crate::ln::functional_test_utils::*;
4819         use crate::ln::script::ShutdownScript;
4820         use crate::util::errors::APIError;
4821         use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
4822         use crate::util::ser::{ReadableArgs, Writeable};
4823         use crate::util::logger::Logger;
4824         use crate::sync::{Arc, Mutex};
4825         use crate::io;
4826         use crate::ln::features::ChannelTypeFeatures;
4827
4828         #[allow(unused_imports)]
4829         use crate::prelude::*;
4830
4831         use std::str::FromStr;
4832
4833         fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
4834                 // Previously, monitor updates were allowed freely even after a funding-spend transaction
4835                 // confirmed. This would allow a race condition where we could receive a payment (including
4836                 // the counterparty revoking their broadcasted state!) and accept it without recourse as
4837                 // long as the ChannelMonitor receives the block first, the full commitment update dance
4838                 // occurs after the block is connected, and before the ChannelManager receives the block.
4839                 // Obviously this is an incredibly contrived race given the counterparty would be risking
4840                 // their full channel balance for it, but its worth fixing nonetheless as it makes the
4841                 // potential ChannelMonitor states simpler to reason about.
4842                 //
4843                 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
4844                 // updates is handled correctly in such conditions.
4845                 let chanmon_cfgs = create_chanmon_cfgs(3);
4846                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4847                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4848                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4849                 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
4850                 create_announced_chan_between_nodes(&nodes, 1, 2);
4851
4852                 // Rebalance somewhat
4853                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
4854
4855                 // First route two payments for testing at the end
4856                 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4857                 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4858
4859                 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
4860                 assert_eq!(local_txn.len(), 1);
4861                 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
4862                 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
4863                 check_spends!(remote_txn[1], remote_txn[0]);
4864                 check_spends!(remote_txn[2], remote_txn[0]);
4865                 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
4866
4867                 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
4868                 // channel is now closed, but the ChannelManager doesn't know that yet.
4869                 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
4870                 let conf_height = nodes[0].best_block_info().1 + 1;
4871                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
4872                         &[(0, broadcast_tx)], conf_height);
4873
4874                 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
4875                                                 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
4876                                                 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
4877
4878                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
4879                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
4880                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
4881                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash,
4882                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4883                         ), false, APIError::MonitorUpdateInProgress, {});
4884                 check_added_monitors!(nodes[1], 1);
4885
4886                 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
4887                 // and provides the claim preimages for the two pending HTLCs. The first update generates
4888                 // an error, but the point of this test is to ensure the later updates are still applied.
4889                 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
4890                 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
4891                 assert_eq!(replay_update.updates.len(), 1);
4892                 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
4893                 } else { panic!(); }
4894                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
4895                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
4896
4897                 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
4898                 assert!(
4899                         pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
4900                         .is_err());
4901                 // Even though we error'd on the first update, we should still have generated an HTLC claim
4902                 // transaction
4903                 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4904                 assert!(txn_broadcasted.len() >= 2);
4905                 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
4906                         assert_eq!(tx.input.len(), 1);
4907                         tx.input[0].previous_output.txid == broadcast_tx.txid()
4908                 }).collect::<Vec<_>>();
4909                 assert_eq!(htlc_txn.len(), 2);
4910                 check_spends!(htlc_txn[0], broadcast_tx);
4911                 check_spends!(htlc_txn[1], broadcast_tx);
4912         }
4913         #[test]
4914         fn test_funding_spend_refuses_updates() {
4915                 do_test_funding_spend_refuses_updates(true);
4916                 do_test_funding_spend_refuses_updates(false);
4917         }
4918
4919         #[test]
4920         fn test_prune_preimages() {
4921                 let secp_ctx = Secp256k1::new();
4922                 let logger = Arc::new(TestLogger::new());
4923                 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
4924                 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4925
4926                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4927
4928                 let mut preimages = Vec::new();
4929                 {
4930                         for i in 0..20 {
4931                                 let preimage = PaymentPreimage([i; 32]);
4932                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4933                                 preimages.push((preimage, hash));
4934                         }
4935                 }
4936
4937                 macro_rules! preimages_slice_to_htlcs {
4938                         ($preimages_slice: expr) => {
4939                                 {
4940                                         let mut res = Vec::new();
4941                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
4942                                                 res.push((HTLCOutputInCommitment {
4943                                                         offered: true,
4944                                                         amount_msat: 0,
4945                                                         cltv_expiry: 0,
4946                                                         payment_hash: preimage.1.clone(),
4947                                                         transaction_output_index: Some(idx as u32),
4948                                                 }, ()));
4949                                         }
4950                                         res
4951                                 }
4952                         }
4953                 }
4954                 macro_rules! preimages_slice_to_htlc_outputs {
4955                         ($preimages_slice: expr) => {
4956                                 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
4957                         }
4958                 }
4959                 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
4960                         &bitcoin::secp256k1::Message::from_slice(&[42; 32]).unwrap(),
4961                         &SecretKey::from_slice(&[42; 32]).unwrap());
4962
4963                 macro_rules! test_preimages_exist {
4964                         ($preimages_slice: expr, $monitor: expr) => {
4965                                 for preimage in $preimages_slice {
4966                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
4967                                 }
4968                         }
4969                 }
4970
4971                 let keys = InMemorySigner::new(
4972                         &secp_ctx,
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                         SecretKey::from_slice(&[41; 32]).unwrap(),
4978                         [41; 32],
4979                         0,
4980                         [0; 32],
4981                         [0; 32],
4982                 );
4983
4984                 let counterparty_pubkeys = ChannelPublicKeys {
4985                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
4986                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
4987                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
4988                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
4989                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
4990                 };
4991                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
4992                 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
4993                 let channel_parameters = ChannelTransactionParameters {
4994                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
4995                         holder_selected_contest_delay: 66,
4996                         is_outbound_from_holder: true,
4997                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
4998                                 pubkeys: counterparty_pubkeys,
4999                                 selected_contest_delay: 67,
5000                         }),
5001                         funding_outpoint: Some(funding_outpoint),
5002                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5003                 };
5004                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
5005                 // old state.
5006                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5007                 let best_block = BestBlock::from_network(Network::Testnet);
5008                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5009                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5010                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5011                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5012                         best_block, dummy_key, channel_id);
5013
5014                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5015                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5016
5017                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5018                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5019                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5020                         preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5021                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5022                         preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5023                 for &(ref preimage, ref hash) in preimages.iter() {
5024                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5025                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
5026                 }
5027
5028                 // Now provide a secret, pruning preimages 10-15
5029                 let mut secret = [0; 32];
5030                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5031                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5032                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5033                 test_preimages_exist!(&preimages[0..10], monitor);
5034                 test_preimages_exist!(&preimages[15..20], monitor);
5035
5036                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5037                         preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5038
5039                 // Now provide a further secret, pruning preimages 15-17
5040                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5041                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5042                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5043                 test_preimages_exist!(&preimages[0..10], monitor);
5044                 test_preimages_exist!(&preimages[17..20], monitor);
5045
5046                 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5047                         preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5048
5049                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
5050                 // previous commitment tx's preimages too
5051                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5052                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5053                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5054                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5055                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5056                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5057                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5058                 test_preimages_exist!(&preimages[0..10], monitor);
5059                 test_preimages_exist!(&preimages[18..20], monitor);
5060
5061                 // But if we do it again, we'll prune 5-10
5062                 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5063                 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5064                 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5065                         htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
5066                 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5067                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5068                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5069                 test_preimages_exist!(&preimages[0..5], monitor);
5070         }
5071
5072         #[test]
5073         fn test_claim_txn_weight_computation() {
5074                 // We test Claim txn weight, knowing that we want expected weigth and
5075                 // not actual case to avoid sigs and time-lock delays hell variances.
5076
5077                 let secp_ctx = Secp256k1::new();
5078                 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5079                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5080
5081                 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5082                 macro_rules! sign_input {
5083                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5084                                 let htlc = HTLCOutputInCommitment {
5085                                         offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5086                                         amount_msat: 0,
5087                                         cltv_expiry: 2 << 16,
5088                                         payment_hash: PaymentHash([1; 32]),
5089                                         transaction_output_index: Some($idx as u32),
5090                                 };
5091                                 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)) };
5092                                 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5093                                 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5094                                 let mut ser_sig = sig.serialize_der().to_vec();
5095                                 ser_sig.push(EcdsaSighashType::All as u8);
5096                                 $sum_actual_sigs += ser_sig.len() as u64;
5097                                 let witness = $sighash_parts.witness_mut($idx).unwrap();
5098                                 witness.push(ser_sig);
5099                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
5100                                         witness.push(vec!(1));
5101                                 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5102                                         witness.push(pubkey.clone().serialize().to_vec());
5103                                 } else if *$weight == weight_received_htlc($opt_anchors) {
5104                                         witness.push(vec![0]);
5105                                 } else {
5106                                         witness.push(PaymentPreimage([1; 32]).0.to_vec());
5107                                 }
5108                                 witness.push(redeem_script.into_bytes());
5109                                 let witness = witness.to_vec();
5110                                 println!("witness[0] {}", witness[0].len());
5111                                 println!("witness[1] {}", witness[1].len());
5112                                 println!("witness[2] {}", witness[2].len());
5113                         }
5114                 }
5115
5116                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5117                 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5118
5119                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
5120                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5121                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5122                         let mut sum_actual_sigs = 0;
5123                         for i in 0..4 {
5124                                 claim_tx.input.push(TxIn {
5125                                         previous_output: BitcoinOutPoint {
5126                                                 txid,
5127                                                 vout: i,
5128                                         },
5129                                         script_sig: ScriptBuf::new(),
5130                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5131                                         witness: Witness::new(),
5132                                 });
5133                         }
5134                         claim_tx.output.push(TxOut {
5135                                 script_pubkey: script_pubkey.clone(),
5136                                 value: 0,
5137                         });
5138                         let base_weight = claim_tx.weight().to_wu();
5139                         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)];
5140                         let mut inputs_total_weight = 2; // count segwit flags
5141                         {
5142                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5143                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5144                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5145                                         inputs_total_weight += inp;
5146                                 }
5147                         }
5148                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5149                 }
5150
5151                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
5152                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5153                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5154                         let mut sum_actual_sigs = 0;
5155                         for i in 0..4 {
5156                                 claim_tx.input.push(TxIn {
5157                                         previous_output: BitcoinOutPoint {
5158                                                 txid,
5159                                                 vout: i,
5160                                         },
5161                                         script_sig: ScriptBuf::new(),
5162                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5163                                         witness: Witness::new(),
5164                                 });
5165                         }
5166                         claim_tx.output.push(TxOut {
5167                                 script_pubkey: script_pubkey.clone(),
5168                                 value: 0,
5169                         });
5170                         let base_weight = claim_tx.weight().to_wu();
5171                         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)];
5172                         let mut inputs_total_weight = 2; // count segwit flags
5173                         {
5174                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5175                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5176                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5177                                         inputs_total_weight += inp;
5178                                 }
5179                         }
5180                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5181                 }
5182
5183                 // Justice tx with 1 revoked HTLC-Success tx output
5184                 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5185                         let mut claim_tx = Transaction { version: 0, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5186                         let mut sum_actual_sigs = 0;
5187                         claim_tx.input.push(TxIn {
5188                                 previous_output: BitcoinOutPoint {
5189                                         txid,
5190                                         vout: 0,
5191                                 },
5192                                 script_sig: ScriptBuf::new(),
5193                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5194                                 witness: Witness::new(),
5195                         });
5196                         claim_tx.output.push(TxOut {
5197                                 script_pubkey: script_pubkey.clone(),
5198                                 value: 0,
5199                         });
5200                         let base_weight = claim_tx.weight().to_wu();
5201                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5202                         let mut inputs_total_weight = 2; // count segwit flags
5203                         {
5204                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5205                                 for (idx, inp) in inputs_weight.iter().enumerate() {
5206                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
5207                                         inputs_total_weight += inp;
5208                                 }
5209                         }
5210                         assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_isg */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5211                 }
5212         }
5213
5214         #[test]
5215         fn test_with_channel_monitor_impl_logger() {
5216                 let secp_ctx = Secp256k1::new();
5217                 let logger = Arc::new(TestLogger::new());
5218
5219                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5220
5221                 let keys = InMemorySigner::new(
5222                         &secp_ctx,
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                         SecretKey::from_slice(&[41; 32]).unwrap(),
5228                         [41; 32],
5229                         0,
5230                         [0; 32],
5231                         [0; 32],
5232                 );
5233
5234                 let counterparty_pubkeys = ChannelPublicKeys {
5235                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5236                         revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5237                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5238                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5239                         htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5240                 };
5241                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
5242                 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5243                 let channel_parameters = ChannelTransactionParameters {
5244                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5245                         holder_selected_contest_delay: 66,
5246                         is_outbound_from_holder: true,
5247                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5248                                 pubkeys: counterparty_pubkeys,
5249                                 selected_contest_delay: 67,
5250                         }),
5251                         funding_outpoint: Some(funding_outpoint),
5252                         channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5253                 };
5254                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5255                 let best_block = BestBlock::from_network(Network::Testnet);
5256                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5257                         Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5258                         (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5259                         &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5260                         best_block, dummy_key, channel_id);
5261
5262                 let chan_id = monitor.inner.lock().unwrap().channel_id();
5263                 let payment_hash = PaymentHash([1; 32]);
5264                 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
5265                 log_error!(context_logger, "This is an error");
5266                 log_warn!(context_logger, "This is an error");
5267                 log_debug!(context_logger, "This is an error");
5268                 log_trace!(context_logger, "This is an error");
5269                 log_gossip!(context_logger, "This is an error");
5270                 log_info!(context_logger, "This is an error");
5271                 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5272         }
5273         // Further testing is done in the ChannelManager integration tests.
5274 }