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