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