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