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