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