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