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