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