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