Expose counterparty-revoked-outputs in `get_claimable_balance`
[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         /// Gets the balances in this channel which are either claimable by us if we were to
1432         /// force-close the channel now or which are claimable on-chain (possibly awaiting
1433         /// confirmation).
1434         ///
1435         /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1436         /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1437         /// balance, or until our counterparty has claimed the balance and accrued several
1438         /// confirmations on the claim transaction.
1439         ///
1440         /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1441         /// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1442         /// a revoked state.
1443         ///
1444         /// See [`Balance`] for additional details on the types of claimable balances which
1445         /// may be returned here and their meanings.
1446         pub fn get_claimable_balances(&self) -> Vec<Balance> {
1447                 let mut res = Vec::new();
1448                 let us = self.inner.lock().unwrap();
1449
1450                 let mut confirmed_txid = us.funding_spend_confirmed;
1451                 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
1452                 let mut pending_commitment_tx_conf_thresh = None;
1453                 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1454                         if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1455                                 event.event
1456                         {
1457                                 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
1458                                 Some((event.txid, event.confirmation_threshold()))
1459                         } else { None }
1460                 });
1461                 if let Some((txid, conf_thresh)) = funding_spend_pending {
1462                         debug_assert!(us.funding_spend_confirmed.is_none(),
1463                                 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1464                         confirmed_txid = Some(txid);
1465                         pending_commitment_tx_conf_thresh = Some(conf_thresh);
1466                 }
1467
1468                 macro_rules! walk_htlcs {
1469                         ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
1470                                 for htlc in $htlc_iter {
1471                                         if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1472                                                 let mut htlc_spend_txid_opt = None;
1473                                                 let mut htlc_update_pending = None;
1474                                                 let mut htlc_spend_pending = None;
1475                                                 let mut delayed_output_pending = None;
1476                                                 for event in us.onchain_events_awaiting_threshold_conf.iter() {
1477                                                         match event.event {
1478                                                                 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1479                                                                 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1480                                                                         debug_assert!(htlc_spend_txid_opt.is_none());
1481                                                                         htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1482                                                                         debug_assert!(htlc_update_pending.is_none());
1483                                                                         debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1484                                                                         htlc_update_pending = Some(event.confirmation_threshold());
1485                                                                 },
1486                                                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1487                                                                 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1488                                                                         debug_assert!(htlc_spend_txid_opt.is_none());
1489                                                                         htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1490                                                                         debug_assert!(htlc_spend_pending.is_none());
1491                                                                         htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1492                                                                 },
1493                                                                 OnchainEvent::MaturingOutput {
1494                                                                         descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1495                                                                 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx => {
1496                                                                         debug_assert!(delayed_output_pending.is_none());
1497                                                                         delayed_output_pending = Some(event.confirmation_threshold());
1498                                                                 },
1499                                                                 _ => {},
1500                                                         }
1501                                                 }
1502                                                 let htlc_resolved = us.htlcs_resolved_on_chain.iter()
1503                                                         .find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1504                                                                 debug_assert!(htlc_spend_txid_opt.is_none());
1505                                                                 htlc_spend_txid_opt = v.resolving_txid;
1506                                                                 true
1507                                                         } else { false });
1508                                                 debug_assert!(htlc_update_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1509
1510                                                 let htlc_output_to_spend =
1511                                                         if let Some(txid) = htlc_spend_txid_opt {
1512                                                                 debug_assert!(
1513                                                                         us.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1514                                                                         "This code needs updating for anchors");
1515                                                                 BitcoinOutPoint::new(txid, 0)
1516                                                         } else {
1517                                                                 BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1518                                                         };
1519                                                 let htlc_output_needs_spending = us.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1520
1521                                                 if let Some(conf_thresh) = delayed_output_pending {
1522                                                         debug_assert!($holder_commitment);
1523                                                         res.push(Balance::ClaimableAwaitingConfirmations {
1524                                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1525                                                                 confirmation_height: conf_thresh,
1526                                                         });
1527                                                 } else if htlc_resolved.is_some() && !htlc_output_needs_spending {
1528                                                         // Funding transaction spends should be fully confirmed by the time any
1529                                                         // HTLC transactions are resolved, unless we're talking about a holder
1530                                                         // commitment tx, whose resolution is delayed until the CSV timeout is
1531                                                         // reached, even though HTLCs may be resolved after only
1532                                                         // ANTI_REORG_DELAY confirmations.
1533                                                         debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1534                                                 } else if $counterparty_revoked_commitment {
1535                                                         let htlc_output_claim_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1536                                                                 if let OnchainEvent::MaturingOutput {
1537                                                                         descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1538                                                                 } = &event.event {
1539                                                                         if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1540                                                                                 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1541                                                                                         Some(tx.txid()) == htlc_spend_txid_opt ||
1542                                                                                                 inp.previous_output.txid == htlc_spend_txid
1543                                                                                 } else {
1544                                                                                         Some(inp.previous_output.txid) == confirmed_txid &&
1545                                                                                                 inp.previous_output.vout == htlc_commitment_tx_output_idx
1546                                                                                 }
1547                                                                         })).unwrap_or(false) {
1548                                                                                 Some(())
1549                                                                         } else { None }
1550                                                                 } else { None }
1551                                                         });
1552                                                         if htlc_output_claim_pending.is_some() {
1553                                                                 // We already push `Balance`s onto the `res` list for every
1554                                                                 // `StaticOutput` in a `MaturingOutput` in the revoked
1555                                                                 // counterparty commitment transaction case generally, so don't
1556                                                                 // need to do so again here.
1557                                                         } else {
1558                                                                 debug_assert!(htlc_update_pending.is_none(),
1559                                                                         "HTLCUpdate OnchainEvents should never appear for preimage claims");
1560                                                                 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1561                                                                         "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1562                                                                 res.push(Balance::CounterpartyRevokedOutputClaimable {
1563                                                                         claimable_amount_satoshis: htlc.amount_msat / 1000,
1564                                                                 });
1565                                                         }
1566                                                 } else {
1567                                                         if htlc.offered == $holder_commitment {
1568                                                                 // If the payment was outbound, check if there's an HTLCUpdate
1569                                                                 // indicating we have spent this HTLC with a timeout, claiming it back
1570                                                                 // and awaiting confirmations on it.
1571                                                                 if let Some(conf_thresh) = htlc_update_pending {
1572                                                                         res.push(Balance::ClaimableAwaitingConfirmations {
1573                                                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1574                                                                                 confirmation_height: conf_thresh,
1575                                                                         });
1576                                                                 } else {
1577                                                                         res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1578                                                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1579                                                                                 claimable_height: htlc.cltv_expiry,
1580                                                                         });
1581                                                                 }
1582                                                         } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1583                                                                 // Otherwise (the payment was inbound), only expose it as claimable if
1584                                                                 // we know the preimage.
1585                                                                 // Note that if there is a pending claim, but it did not use the
1586                                                                 // preimage, we lost funds to our counterparty! We will then continue
1587                                                                 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1588                                                                 debug_assert!(htlc_update_pending.is_none());
1589                                                                 if let Some((conf_thresh, true)) = htlc_spend_pending {
1590                                                                         res.push(Balance::ClaimableAwaitingConfirmations {
1591                                                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1592                                                                                 confirmation_height: conf_thresh,
1593                                                                         });
1594                                                                 } else {
1595                                                                         res.push(Balance::ContentiousClaimable {
1596                                                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1597                                                                                 timeout_height: htlc.cltv_expiry,
1598                                                                         });
1599                                                                 }
1600                                                         }
1601                                                 }
1602                                         }
1603                                 }
1604                         }
1605                 }
1606
1607                 if let Some(txid) = confirmed_txid {
1608                         let mut found_commitment_tx = false;
1609                         if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1610                                 // First look for the to_remote output back to us.
1611                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1612                                         if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1613                                                 if let OnchainEvent::MaturingOutput {
1614                                                         descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1615                                                 } = &event.event {
1616                                                         Some(descriptor.output.value)
1617                                                 } else { None }
1618                                         }) {
1619                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1620                                                         claimable_amount_satoshis: value,
1621                                                         confirmation_height: conf_thresh,
1622                                                 });
1623                                         } else {
1624                                                 // If a counterparty commitment transaction is awaiting confirmation, we
1625                                                 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1626                                                 // confirmation with the same height or have never met our dust amount.
1627                                         }
1628                                 }
1629                                 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1630                                         walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1631                                 } else {
1632                                         walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1633                                         // The counterparty broadcasted a revoked state!
1634                                         // Look for any StaticOutputs first, generating claimable balances for those.
1635                                         // If any match the confirmed counterparty revoked to_self output, skip
1636                                         // generating a CounterpartyRevokedOutputClaimable.
1637                                         let mut spent_counterparty_output = false;
1638                                         for event in us.onchain_events_awaiting_threshold_conf.iter() {
1639                                                 if let OnchainEvent::MaturingOutput {
1640                                                         descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1641                                                 } = &event.event {
1642                                                         res.push(Balance::ClaimableAwaitingConfirmations {
1643                                                                 claimable_amount_satoshis: output.value,
1644                                                                 confirmation_height: event.confirmation_threshold(),
1645                                                         });
1646                                                         if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1647                                                                 if event.transaction.as_ref().map(|tx|
1648                                                                         tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1649                                                                 ).unwrap_or(false) {
1650                                                                         spent_counterparty_output = true;
1651                                                                 }
1652                                                         }
1653                                                 }
1654                                         }
1655
1656                                         if spent_counterparty_output {
1657                                         } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1658                                                 let output_spendable = us.onchain_tx_handler
1659                                                         .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1660                                                 if output_spendable {
1661                                                         res.push(Balance::CounterpartyRevokedOutputClaimable {
1662                                                                 claimable_amount_satoshis: amt,
1663                                                         });
1664                                                 }
1665                                         } else {
1666                                                 // Counterparty output is missing, either it was broadcasted on a
1667                                                 // previous version of LDK or the counterparty hadn't met dust.
1668                                         }
1669                                 }
1670                                 found_commitment_tx = true;
1671                         } else if txid == us.current_holder_commitment_tx.txid {
1672                                 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1673                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1674                                         res.push(Balance::ClaimableAwaitingConfirmations {
1675                                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1676                                                 confirmation_height: conf_thresh,
1677                                         });
1678                                 }
1679                                 found_commitment_tx = true;
1680                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1681                                 if txid == prev_commitment.txid {
1682                                         walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1683                                         if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1684                                                 res.push(Balance::ClaimableAwaitingConfirmations {
1685                                                         claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1686                                                         confirmation_height: conf_thresh,
1687                                                 });
1688                                         }
1689                                         found_commitment_tx = true;
1690                                 }
1691                         }
1692                         if !found_commitment_tx {
1693                                 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1694                                         // We blindly assume this is a cooperative close transaction here, and that
1695                                         // neither us nor our counterparty misbehaved. At worst we've under-estimated
1696                                         // the amount we can claim as we'll punish a misbehaving counterparty.
1697                                         res.push(Balance::ClaimableAwaitingConfirmations {
1698                                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1699                                                 confirmation_height: conf_thresh,
1700                                         });
1701                                 }
1702                         }
1703                 } else {
1704                         let mut claimable_inbound_htlc_value_sat = 0;
1705                         for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1706                                 if htlc.transaction_output_index.is_none() { continue; }
1707                                 if htlc.offered {
1708                                         res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1709                                                 claimable_amount_satoshis: htlc.amount_msat / 1000,
1710                                                 claimable_height: htlc.cltv_expiry,
1711                                         });
1712                                 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1713                                         claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1714                                 }
1715                         }
1716                         res.push(Balance::ClaimableOnChannelClose {
1717                                 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1718                         });
1719                 }
1720
1721                 res
1722         }
1723
1724         /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1725         /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1726         pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1727                 let mut res = HashMap::new();
1728                 let us = self.inner.lock().unwrap();
1729
1730                 macro_rules! walk_htlcs {
1731                         ($holder_commitment: expr, $htlc_iter: expr) => {
1732                                 for (htlc, source) in $htlc_iter {
1733                                         if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.commitment_tx_output_idx) == htlc.transaction_output_index) {
1734                                                 // We should assert that funding_spend_confirmed is_some() here, but we
1735                                                 // have some unit tests which violate HTLC transaction CSVs entirely and
1736                                                 // would fail.
1737                                                 // TODO: Once tests all connect transactions at consensus-valid times, we
1738                                                 // should assert here like we do in `get_claimable_balances`.
1739                                         } else if htlc.offered == $holder_commitment {
1740                                                 // If the payment was outbound, check if there's an HTLCUpdate
1741                                                 // indicating we have spent this HTLC with a timeout, claiming it back
1742                                                 // and awaiting confirmations on it.
1743                                                 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1744                                                         if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1745                                                                 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1746                                                                 // before considering it "no longer pending" - this matches when we
1747                                                                 // provide the ChannelManager an HTLC failure event.
1748                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
1749                                                                         us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1750                                                         } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
1751                                                                 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1752                                                                 // immediately non-pending, matching when we provide ChannelManager
1753                                                                 // the preimage.
1754                                                                 Some(commitment_tx_output_idx) == htlc.transaction_output_index
1755                                                         } else { false }
1756                                                 });
1757                                                 if !htlc_update_confd {
1758                                                         res.insert(source.clone(), htlc.clone());
1759                                                 }
1760                                         }
1761                                 }
1762                         }
1763                 }
1764
1765                 // We're only concerned with the confirmation count of HTLC transactions, and don't
1766                 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1767                 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1768                 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1769                         us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1770                                 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1771                                         Some(event.txid)
1772                                 } else { None }
1773                         })
1774                 });
1775                 if let Some(txid) = confirmed_txid {
1776                         if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1777                                 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1778                                         if let &Some(ref source) = b {
1779                                                 Some((a, &**source))
1780                                         } else { None }
1781                                 }));
1782                         } else if txid == us.current_holder_commitment_tx.txid {
1783                                 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1784                                         if let Some(source) = c { Some((a, source)) } else { None }
1785                                 }));
1786                         } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1787                                 if txid == prev_commitment.txid {
1788                                         walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1789                                                 if let Some(source) = c { Some((a, source)) } else { None }
1790                                         }));
1791                                 }
1792                         }
1793                 } else {
1794                         // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1795                         // closed), just examine the available counterparty commitment transactions. See docs
1796                         // on `fail_unbroadcast_htlcs`, below, for justification.
1797                         macro_rules! walk_counterparty_commitment {
1798                                 ($txid: expr) => {
1799                                         if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1800                                                 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1801                                                         if let &Some(ref source) = source_option {
1802                                                                 res.insert((**source).clone(), htlc.clone());
1803                                                         }
1804                                                 }
1805                                         }
1806                                 }
1807                         }
1808                         if let Some(ref txid) = us.current_counterparty_commitment_txid {
1809                                 walk_counterparty_commitment!(txid);
1810                         }
1811                         if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1812                                 walk_counterparty_commitment!(txid);
1813                         }
1814                 }
1815
1816                 res
1817         }
1818
1819         pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
1820                 self.inner.lock().unwrap().payment_preimages.clone()
1821         }
1822 }
1823
1824 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1825 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1826 /// after ANTI_REORG_DELAY blocks.
1827 ///
1828 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1829 /// are the commitment transactions which are generated by us. The off-chain state machine in
1830 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1831 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1832 /// included in a remote commitment transaction are failed back if they are not present in the
1833 /// broadcasted commitment transaction.
1834 ///
1835 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1836 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1837 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1838 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1839 macro_rules! fail_unbroadcast_htlcs {
1840         ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
1841          $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1842                 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
1843
1844                 macro_rules! check_htlc_fails {
1845                         ($txid: expr, $commitment_tx: expr) => {
1846                                 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1847                                         for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1848                                                 if let &Some(ref source) = source_option {
1849                                                         // Check if the HTLC is present in the commitment transaction that was
1850                                                         // broadcast, but not if it was below the dust limit, which we should
1851                                                         // fail backwards immediately as there is no way for us to learn the
1852                                                         // payment_preimage.
1853                                                         // Note that if the dust limit were allowed to change between
1854                                                         // commitment transactions we'd want to be check whether *any*
1855                                                         // broadcastable commitment transaction has the HTLC in it, but it
1856                                                         // cannot currently change after channel initialization, so we don't
1857                                                         // need to here.
1858                                                         let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1859
1860                                                         let mut matched_htlc = false;
1861                                                         for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1862                                                                 if broadcast_htlc.transaction_output_index.is_some() &&
1863                                                                         (Some(&**source) == *broadcast_source ||
1864                                                                          (broadcast_source.is_none() &&
1865                                                                           broadcast_htlc.payment_hash == htlc.payment_hash &&
1866                                                                           broadcast_htlc.amount_msat == htlc.amount_msat)) {
1867                                                                         matched_htlc = true;
1868                                                                         break;
1869                                                                 }
1870                                                         }
1871                                                         if matched_htlc { continue; }
1872                                                         $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1873                                                                 if entry.height != $commitment_tx_conf_height { return true; }
1874                                                                 match entry.event {
1875                                                                         OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1876                                                                                 *update_source != **source
1877                                                                         },
1878                                                                         _ => true,
1879                                                                 }
1880                                                         });
1881                                                         let entry = OnchainEventEntry {
1882                                                                 txid: $commitment_txid_confirmed,
1883                                                                 transaction: Some($commitment_tx_confirmed.clone()),
1884                                                                 height: $commitment_tx_conf_height,
1885                                                                 event: OnchainEvent::HTLCUpdate {
1886                                                                         source: (**source).clone(),
1887                                                                         payment_hash: htlc.payment_hash.clone(),
1888                                                                         htlc_value_satoshis: Some(htlc.amount_msat / 1000),
1889                                                                         commitment_tx_output_idx: None,
1890                                                                 },
1891                                                         };
1892                                                         log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
1893                                                                 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type,
1894                                                                 $commitment_txid_confirmed, entry.confirmation_threshold());
1895                                                         $self.onchain_events_awaiting_threshold_conf.push(entry);
1896                                                 }
1897                                         }
1898                                 }
1899                         }
1900                 }
1901                 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1902                         check_htlc_fails!(txid, "current");
1903                 }
1904                 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1905                         check_htlc_fails!(txid, "previous");
1906                 }
1907         } }
1908 }
1909
1910 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
1911 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
1912 // in-line tests later.
1913
1914 #[cfg(test)]
1915 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
1916         let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
1917         ret[131] = opcodes::all::OP_DROP.to_u8();
1918         ret[132] = opcodes::all::OP_DROP.to_u8();
1919         ret[133] = opcodes::all::OP_DROP.to_u8();
1920         ret[134] = opcodes::all::OP_DROP.to_u8();
1921         ret[135] = opcodes::OP_TRUE.to_u8();
1922         Vec::from(&ret[..])
1923 }
1924
1925 #[cfg(test)]
1926 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
1927         vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
1928 }
1929
1930 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1931         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1932         /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1933         /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1934         fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1935                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1936                         return Err("Previous secret did not match new one");
1937                 }
1938
1939                 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1940                 // events for now-revoked/fulfilled HTLCs.
1941                 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1942                         for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1943                                 *source = None;
1944                         }
1945                 }
1946
1947                 if !self.payment_preimages.is_empty() {
1948                         let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1949                         let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1950                         let min_idx = self.get_min_seen_secret();
1951                         let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1952
1953                         self.payment_preimages.retain(|&k, _| {
1954                                 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1955                                         if k == htlc.payment_hash {
1956                                                 return true
1957                                         }
1958                                 }
1959                                 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1960                                         for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1961                                                 if k == htlc.payment_hash {
1962                                                         return true
1963                                                 }
1964                                         }
1965                                 }
1966                                 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1967                                         if *cn < min_idx {
1968                                                 return true
1969                                         }
1970                                         true
1971                                 } else { false };
1972                                 if contains {
1973                                         counterparty_hash_commitment_number.remove(&k);
1974                                 }
1975                                 false
1976                         });
1977                 }
1978
1979                 Ok(())
1980         }
1981
1982         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 {
1983                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1984                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1985                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1986                 // timeouts)
1987                 for &(ref htlc, _) in &htlc_outputs {
1988                         self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1989                 }
1990
1991                 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1992                 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1993                 self.current_counterparty_commitment_txid = Some(txid);
1994                 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1995                 self.current_counterparty_commitment_number = commitment_number;
1996                 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1997                 match self.their_cur_per_commitment_points {
1998                         Some(old_points) => {
1999                                 if old_points.0 == commitment_number + 1 {
2000                                         self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2001                                 } else if old_points.0 == commitment_number + 2 {
2002                                         if let Some(old_second_point) = old_points.2 {
2003                                                 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2004                                         } else {
2005                                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2006                                         }
2007                                 } else {
2008                                         self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2009                                 }
2010                         },
2011                         None => {
2012                                 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2013                         }
2014                 }
2015                 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2016                 for htlc in htlc_outputs {
2017                         if htlc.0.transaction_output_index.is_some() {
2018                                 htlcs.push(htlc.0);
2019                         }
2020                 }
2021         }
2022
2023         /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2024         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2025         /// is important that any clones of this channel monitor (including remote clones) by kept
2026         /// up-to-date as our holder commitment transaction is updated.
2027         /// Panics if set_on_holder_tx_csv has never been called.
2028         fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), &'static str> {
2029                 // block for Rust 1.34 compat
2030                 let mut new_holder_commitment_tx = {
2031                         let trusted_tx = holder_commitment_tx.trust();
2032                         let txid = trusted_tx.txid();
2033                         let tx_keys = trusted_tx.keys();
2034                         self.current_holder_commitment_number = trusted_tx.commitment_number();
2035                         HolderSignedTx {
2036                                 txid,
2037                                 revocation_key: tx_keys.revocation_key,
2038                                 a_htlc_key: tx_keys.broadcaster_htlc_key,
2039                                 b_htlc_key: tx_keys.countersignatory_htlc_key,
2040                                 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2041                                 per_commitment_point: tx_keys.per_commitment_point,
2042                                 htlc_outputs,
2043                                 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2044                                 feerate_per_kw: trusted_tx.feerate_per_kw(),
2045                         }
2046                 };
2047                 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2048                 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2049                 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2050                 if self.holder_tx_signed {
2051                         return Err("Latest holder commitment signed has already been signed, update is rejected");
2052                 }
2053                 Ok(())
2054         }
2055
2056         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2057         /// commitment_tx_infos which contain the payment hash have been revoked.
2058         fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2059                 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2060                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
2061         where B::Target: BroadcasterInterface,
2062                     F::Target: FeeEstimator,
2063                     L::Target: Logger,
2064         {
2065                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2066
2067                 // If the channel is force closed, try to claim the output from this preimage.
2068                 // First check if a counterparty commitment transaction has been broadcasted:
2069                 macro_rules! claim_htlcs {
2070                         ($commitment_number: expr, $txid: expr) => {
2071                                 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2072                                 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2073                         }
2074                 }
2075                 if let Some(txid) = self.current_counterparty_commitment_txid {
2076                         if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2077                                 claim_htlcs!(*commitment_number, txid);
2078                                 return;
2079                         }
2080                 }
2081                 if let Some(txid) = self.prev_counterparty_commitment_txid {
2082                         if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2083                                 claim_htlcs!(*commitment_number, txid);
2084                                 return;
2085                         }
2086                 }
2087
2088                 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2089                 // claiming the HTLC output from each of the holder commitment transactions.
2090                 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2091                 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2092                 // holder commitment transactions.
2093                 if self.broadcasted_holder_revokable_script.is_some() {
2094                         // Assume that the broadcasted commitment transaction confirmed in the current best
2095                         // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2096                         // transactions.
2097                         let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2098                         self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2099                         if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
2100                                 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
2101                                 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2102                         }
2103                 }
2104         }
2105
2106         pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
2107                 where B::Target: BroadcasterInterface,
2108                                         L::Target: Logger,
2109         {
2110                 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
2111                         log_info!(logger, "Broadcasting local {}", log_tx!(tx));
2112                         broadcaster.broadcast_transaction(tx);
2113                 }
2114                 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2115         }
2116
2117         pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
2118         where B::Target: BroadcasterInterface,
2119                 F::Target: FeeEstimator,
2120                 L::Target: Logger,
2121         {
2122                 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} changes.",
2123                         log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2124                 // ChannelMonitor updates may be applied after force close if we receive a
2125                 // preimage for a broadcasted commitment transaction HTLC output that we'd
2126                 // like to claim on-chain. If this is the case, we no longer have guaranteed
2127                 // access to the monitor's update ID, so we use a sentinel value instead.
2128                 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2129                         assert_eq!(updates.updates.len(), 1);
2130                         match updates.updates[0] {
2131                                 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
2132                                 _ => {
2133                                         log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2134                                         panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2135                                 },
2136                         }
2137                 } else if self.latest_update_id + 1 != updates.update_id {
2138                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2139                 }
2140                 let mut ret = Ok(());
2141                 for update in updates.updates.iter() {
2142                         match update {
2143                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
2144                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2145                                         if self.lockdown_from_offchain { panic!(); }
2146                                         if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
2147                                                 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2148                                                 log_error!(logger, "    {}", e);
2149                                                 ret = Err(());
2150                                         }
2151                                 }
2152                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point } => {
2153                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2154                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2155                                 },
2156                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2157                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2158                                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2159                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2160                                 },
2161                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2162                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2163                                         if let Err(e) = self.provide_secret(*idx, *secret) {
2164                                                 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2165                                                 log_error!(logger, "    {}", e);
2166                                                 ret = Err(());
2167                                         }
2168                                 },
2169                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2170                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2171                                         self.lockdown_from_offchain = true;
2172                                         if *should_broadcast {
2173                                                 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2174                                         } else if !self.holder_tx_signed {
2175                                                 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");
2176                                         } else {
2177                                                 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2178                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2179                                                 // shouldn't print the scary warning above.
2180                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2181                                         }
2182                                 },
2183                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2184                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2185                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2186                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2187                                         }
2188                                 },
2189                         }
2190                 }
2191                 self.latest_update_id = updates.update_id;
2192
2193                 if ret.is_ok() && self.funding_spend_seen {
2194                         log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2195                         Err(())
2196                 } else { ret }
2197         }
2198
2199         pub fn get_latest_update_id(&self) -> u64 {
2200                 self.latest_update_id
2201         }
2202
2203         pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2204                 &self.funding_info
2205         }
2206
2207         pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2208                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2209                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2210                 // its trivial to do, double-check that here.
2211                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2212                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2213                 }
2214                 &self.outputs_to_watch
2215         }
2216
2217         pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2218                 let mut ret = Vec::new();
2219                 mem::swap(&mut ret, &mut self.pending_monitor_events);
2220                 ret
2221         }
2222
2223         pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
2224                 let mut ret = Vec::new();
2225                 mem::swap(&mut ret, &mut self.pending_events);
2226                 ret
2227         }
2228
2229         /// Can only fail if idx is < get_min_seen_secret
2230         fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2231                 self.commitment_secrets.get_secret(idx)
2232         }
2233
2234         pub(crate) fn get_min_seen_secret(&self) -> u64 {
2235                 self.commitment_secrets.get_min_seen_secret()
2236         }
2237
2238         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2239                 self.current_counterparty_commitment_number
2240         }
2241
2242         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2243                 self.current_holder_commitment_number
2244         }
2245
2246         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2247         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2248         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2249         /// HTLC-Success/HTLC-Timeout transactions.
2250         ///
2251         /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
2252         /// general information about the output that is to the counterparty in the commitment
2253         /// transaction.
2254         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L)
2255                 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
2256         where L::Target: Logger {
2257                 // Most secp and related errors trying to create keys means we have no hope of constructing
2258                 // a spend transaction...so we return no transactions to broadcast
2259                 let mut claimable_outpoints = Vec::new();
2260                 let mut watch_outputs = Vec::new();
2261                 let mut to_counterparty_output_info = None;
2262
2263                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2264                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2265
2266                 macro_rules! ignore_error {
2267                         ( $thing : expr ) => {
2268                                 match $thing {
2269                                         Ok(a) => a,
2270                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2271                                 }
2272                         };
2273                 }
2274
2275                 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);
2276                 if commitment_number >= self.get_min_seen_secret() {
2277                         let secret = self.get_secret(commitment_number).unwrap();
2278                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2279                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2280                         let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2281                         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));
2282
2283                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2284                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2285
2286                         // First, process non-htlc outputs (to_holder & to_counterparty)
2287                         for (idx, outp) in tx.output.iter().enumerate() {
2288                                 if outp.script_pubkey == revokeable_p2wsh {
2289                                         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);
2290                                         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);
2291                                         claimable_outpoints.push(justice_package);
2292                                         to_counterparty_output_info =
2293                                                 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
2294                                 }
2295                         }
2296
2297                         // Then, try to find revoked htlc outputs
2298                         if let Some(ref per_commitment_data) = per_commitment_option {
2299                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2300                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2301                                                 if transaction_output_index as usize >= tx.output.len() ||
2302                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2303                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
2304                                                         return (claimable_outpoints, (commitment_txid, watch_outputs),
2305                                                                 to_counterparty_output_info);
2306                                                 }
2307                                                 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());
2308                                                 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2309                                                 claimable_outpoints.push(justice_package);
2310                                         }
2311                                 }
2312                         }
2313
2314                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2315                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2316                                 // We're definitely a counterparty commitment transaction!
2317                                 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2318                                 for (idx, outp) in tx.output.iter().enumerate() {
2319                                         watch_outputs.push((idx as u32, outp.clone()));
2320                                 }
2321                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2322
2323                                 if let Some(per_commitment_data) = per_commitment_option {
2324                                         fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
2325                                                 per_commitment_data.iter().map(|(htlc, htlc_source)|
2326                                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2327                                                 ), logger);
2328                                 } else {
2329                                         debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2330                                         fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
2331                                                 [].iter().map(|reference| *reference), logger);
2332                                 }
2333                         }
2334                 } else if let Some(per_commitment_data) = per_commitment_option {
2335                         // While this isn't useful yet, there is a potential race where if a counterparty
2336                         // revokes a state at the same time as the commitment transaction for that state is
2337                         // confirmed, and the watchtower receives the block before the user, the user could
2338                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
2339                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2340                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
2341                         // insert it here.
2342                         for (idx, outp) in tx.output.iter().enumerate() {
2343                                 watch_outputs.push((idx as u32, outp.clone()));
2344                         }
2345                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2346
2347                         log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2348                         fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height,
2349                                 per_commitment_data.iter().map(|(htlc, htlc_source)|
2350                                         (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2351                                 ), logger);
2352
2353                         let (htlc_claim_reqs, counterparty_output_info) =
2354                                 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
2355                         to_counterparty_output_info = counterparty_output_info;
2356                         for req in htlc_claim_reqs {
2357                                 claimable_outpoints.push(req);
2358                         }
2359
2360                 }
2361                 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2362         }
2363
2364         /// Returns the HTLC claim package templates and the counterparty output info
2365         fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
2366         -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
2367                 let mut claimable_outpoints = Vec::new();
2368                 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
2369
2370                 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
2371                         Some(outputs) => outputs,
2372                         None => return (claimable_outpoints, to_counterparty_output_info),
2373                 };
2374                 let per_commitment_points = match self.their_cur_per_commitment_points {
2375                         Some(points) => points,
2376                         None => return (claimable_outpoints, to_counterparty_output_info),
2377                 };
2378
2379                 let per_commitment_point =
2380                         // If the counterparty commitment tx is the latest valid state, use their latest
2381                         // per-commitment point
2382                         if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
2383                         else if let Some(point) = per_commitment_points.2.as_ref() {
2384                                 // If counterparty commitment tx is the state previous to the latest valid state, use
2385                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2386                                 // them to temporarily have two valid commitment txns from our viewpoint)
2387                                 if per_commitment_points.0 == commitment_number + 1 {
2388                                         point
2389                                 } else { return (claimable_outpoints, to_counterparty_output_info); }
2390                         } else { return (claimable_outpoints, to_counterparty_output_info); };
2391
2392                 if let Some(transaction) = tx {
2393                         let revokeable_p2wsh_opt =
2394                                 if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
2395                                         &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
2396                                 {
2397                                         if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
2398                                                 &per_commitment_point,
2399                                                 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
2400                                         {
2401                                                 Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2402                                                         self.counterparty_commitment_params.on_counterparty_tx_csv,
2403                                                         &delayed_key).to_v0_p2wsh())
2404                                         } else {
2405                                                 debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
2406                                                 None
2407                                         }
2408                                 } else {
2409                                         debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
2410                                         None
2411                                 };
2412                         if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
2413                                 for (idx, outp) in transaction.output.iter().enumerate() {
2414                                         if outp.script_pubkey == revokeable_p2wsh {
2415                                                 to_counterparty_output_info =
2416                                                         Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2417                                         }
2418                                 }
2419                         }
2420                 }
2421
2422                 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2423                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2424                                 if let Some(transaction) = tx {
2425                                         if transaction_output_index as usize >= transaction.output.len() ||
2426                                                 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2427                                                         // per_commitment_data is corrupt or our commitment signing key leaked!
2428                                                         return (claimable_outpoints, to_counterparty_output_info);
2429                                                 }
2430                                 }
2431                                 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2432                                 if preimage.is_some() || !htlc.offered {
2433                                         let counterparty_htlc_outp = if htlc.offered {
2434                                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2435                                                         CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2436                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2437                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
2438                                                                 preimage.unwrap(), htlc.clone()))
2439                                         } else {
2440                                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2441                                                         CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2442                                                                 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2443                                                                 self.counterparty_commitment_params.counterparty_htlc_base_key,
2444                                                                 htlc.clone()))
2445                                         };
2446                                         let aggregation = if !htlc.offered { false } else { true };
2447                                         let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2448                                         claimable_outpoints.push(counterparty_package);
2449                                 }
2450                         }
2451                 }
2452
2453                 (claimable_outpoints, to_counterparty_output_info)
2454         }
2455
2456         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2457         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 {
2458                 let htlc_txid = tx.txid();
2459                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2460                         return (Vec::new(), None)
2461                 }
2462
2463                 macro_rules! ignore_error {
2464                         ( $thing : expr ) => {
2465                                 match $thing {
2466                                         Ok(a) => a,
2467                                         Err(_) => return (Vec::new(), None)
2468                                 }
2469                         };
2470                 }
2471
2472                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2473                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2474                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2475
2476                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2477                 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);
2478                 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);
2479                 let claimable_outpoints = vec!(justice_package);
2480                 let outputs = vec![(0, tx.output[0].clone())];
2481                 (claimable_outpoints, Some((htlc_txid, outputs)))
2482         }
2483
2484         // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2485         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2486         // script so we can detect whether a holder transaction has been seen on-chain.
2487         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2488                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2489
2490                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2491                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2492
2493                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2494                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2495                                 let htlc_output = if htlc.offered {
2496                                                 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2497                                         } else {
2498                                                 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2499                                                         preimage.clone()
2500                                                 } else {
2501                                                         // We can't build an HTLC-Success transaction without the preimage
2502                                                         continue;
2503                                                 };
2504                                                 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2505                                         };
2506                                 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2507                                 claim_requests.push(htlc_package);
2508                         }
2509                 }
2510
2511                 (claim_requests, broadcasted_holder_revokable_script)
2512         }
2513
2514         // Returns holder HTLC outputs to watch and react to in case of spending.
2515         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2516                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2517                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2518                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2519                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2520                         }
2521                 }
2522                 watch_outputs
2523         }
2524
2525         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2526         /// revoked using data in holder_claimable_outpoints.
2527         /// Should not be used if check_spend_revoked_transaction succeeds.
2528         /// Returns None unless the transaction is definitely one of our commitment transactions.
2529         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2530                 let commitment_txid = tx.txid();
2531                 let mut claim_requests = Vec::new();
2532                 let mut watch_outputs = Vec::new();
2533
2534                 macro_rules! append_onchain_update {
2535                         ($updates: expr, $to_watch: expr) => {
2536                                 claim_requests = $updates.0;
2537                                 self.broadcasted_holder_revokable_script = $updates.1;
2538                                 watch_outputs.append(&mut $to_watch);
2539                         }
2540                 }
2541
2542                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2543                 let mut is_holder_tx = false;
2544
2545                 if self.current_holder_commitment_tx.txid == commitment_txid {
2546                         is_holder_tx = true;
2547                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2548                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2549                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2550                         append_onchain_update!(res, to_watch);
2551                         fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
2552                                 self.current_holder_commitment_tx.htlc_outputs.iter()
2553                                 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2554                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2555                         if holder_tx.txid == commitment_txid {
2556                                 is_holder_tx = true;
2557                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2558                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2559                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2560                                 append_onchain_update!(res, to_watch);
2561                                 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height,
2562                                         holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2563                                         logger);
2564                         }
2565                 }
2566
2567                 if is_holder_tx {
2568                         Some((claim_requests, (commitment_txid, watch_outputs)))
2569                 } else {
2570                         None
2571                 }
2572         }
2573
2574         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2575                 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2576                 self.holder_tx_signed = true;
2577                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2578                 let txid = commitment_tx.txid();
2579                 let mut holder_transactions = vec![commitment_tx];
2580                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2581                         if let Some(vout) = htlc.0.transaction_output_index {
2582                                 let preimage = if !htlc.0.offered {
2583                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2584                                                 // We can't build an HTLC-Success transaction without the preimage
2585                                                 continue;
2586                                         }
2587                                 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2588                                         // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2589                                         // current locktime requirements on-chain. We will broadcast them in
2590                                         // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2591                                         // Note that we add + 1 as transactions are broadcastable when they can be
2592                                         // confirmed in the next block.
2593                                         continue;
2594                                 } else { None };
2595                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2596                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2597                                         holder_transactions.push(htlc_tx);
2598                                 }
2599                         }
2600                 }
2601                 // 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.
2602                 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2603                 holder_transactions
2604         }
2605
2606         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2607         /// Note that this includes possibly-locktimed-in-the-future transactions!
2608         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2609                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2610                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2611                 let txid = commitment_tx.txid();
2612                 let mut holder_transactions = vec![commitment_tx];
2613                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2614                         if let Some(vout) = htlc.0.transaction_output_index {
2615                                 let preimage = if !htlc.0.offered {
2616                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2617                                                 // We can't build an HTLC-Success transaction without the preimage
2618                                                 continue;
2619                                         }
2620                                 } else { None };
2621                                 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2622                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2623                                         holder_transactions.push(htlc_tx);
2624                                 }
2625                         }
2626                 }
2627                 holder_transactions
2628         }
2629
2630         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>
2631                 where B::Target: BroadcasterInterface,
2632                       F::Target: FeeEstimator,
2633                                         L::Target: Logger,
2634         {
2635                 let block_hash = header.block_hash();
2636                 self.best_block = BestBlock::new(block_hash, height);
2637
2638                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2639                 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2640         }
2641
2642         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2643                 &mut self,
2644                 header: &BlockHeader,
2645                 height: u32,
2646                 broadcaster: B,
2647                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2648                 logger: L,
2649         ) -> Vec<TransactionOutputs>
2650         where
2651                 B::Target: BroadcasterInterface,
2652                 F::Target: FeeEstimator,
2653                 L::Target: Logger,
2654         {
2655                 let block_hash = header.block_hash();
2656
2657                 if height > self.best_block.height() {
2658                         self.best_block = BestBlock::new(block_hash, height);
2659                         self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2660                 } else if block_hash != self.best_block.block_hash() {
2661                         self.best_block = BestBlock::new(block_hash, height);
2662                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2663                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2664                         Vec::new()
2665                 } else { Vec::new() }
2666         }
2667
2668         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2669                 &mut self,
2670                 header: &BlockHeader,
2671                 txdata: &TransactionData,
2672                 height: u32,
2673                 broadcaster: B,
2674                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2675                 logger: L,
2676         ) -> Vec<TransactionOutputs>
2677         where
2678                 B::Target: BroadcasterInterface,
2679                 F::Target: FeeEstimator,
2680                 L::Target: Logger,
2681         {
2682                 let txn_matched = self.filter_block(txdata);
2683                 for tx in &txn_matched {
2684                         let mut output_val = 0;
2685                         for out in tx.output.iter() {
2686                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2687                                 output_val += out.value;
2688                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2689                         }
2690                 }
2691
2692                 let block_hash = header.block_hash();
2693
2694                 let mut watch_outputs = Vec::new();
2695                 let mut claimable_outpoints = Vec::new();
2696                 for tx in &txn_matched {
2697                         if tx.input.len() == 1 {
2698                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2699                                 // commitment transactions and HTLC transactions will all only ever have one input,
2700                                 // which is an easy way to filter out any potential non-matching txn for lazy
2701                                 // filters.
2702                                 let prevout = &tx.input[0].previous_output;
2703                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2704                                         let mut balance_spendable_csv = None;
2705                                         log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2706                                                 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2707                                         self.funding_spend_seen = true;
2708                                         let mut commitment_tx_to_counterparty_output = None;
2709                                         if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
2710                                                 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
2711                                                         self.check_spend_counterparty_transaction(&tx, height, &logger);
2712                                                 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
2713                                                 if !new_outputs.1.is_empty() {
2714                                                         watch_outputs.push(new_outputs);
2715                                                 }
2716                                                 claimable_outpoints.append(&mut new_outpoints);
2717                                                 if new_outpoints.is_empty() {
2718                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2719                                                                 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
2720                                                                         "A commitment transaction matched as both a counterparty and local commitment tx?");
2721                                                                 if !new_outputs.1.is_empty() {
2722                                                                         watch_outputs.push(new_outputs);
2723                                                                 }
2724                                                                 claimable_outpoints.append(&mut new_outpoints);
2725                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
2726                                                         }
2727                                                 }
2728                                         }
2729                                         let txid = tx.txid();
2730                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2731                                                 txid,
2732                                                 transaction: Some((*tx).clone()),
2733                                                 height: height,
2734                                                 event: OnchainEvent::FundingSpendConfirmation {
2735                                                         on_local_output_csv: balance_spendable_csv,
2736                                                         commitment_tx_to_counterparty_output,
2737                                                 },
2738                                         });
2739                                 } else {
2740                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2741                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2742                                                 claimable_outpoints.append(&mut new_outpoints);
2743                                                 if let Some(new_outputs) = new_outputs_option {
2744                                                         watch_outputs.push(new_outputs);
2745                                                 }
2746                                         }
2747                                 }
2748                         }
2749                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2750                         // can also be resolved in a few other ways which can have more than one output. Thus,
2751                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2752                         self.is_resolving_htlc_output(&tx, height, &logger);
2753
2754                         self.is_paying_spendable_output(&tx, height, &logger);
2755                 }
2756
2757                 if height > self.best_block.height() {
2758                         self.best_block = BestBlock::new(block_hash, height);
2759                 }
2760
2761                 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2762         }
2763
2764         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2765         /// `self.best_block` before calling if a new best blockchain tip is available. More
2766         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2767         /// complexity especially in `OnchainTx::update_claims_view`.
2768         ///
2769         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2770         /// confirmed at, even if it is not the current best height.
2771         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2772                 &mut self,
2773                 conf_height: u32,
2774                 txn_matched: Vec<&Transaction>,
2775                 mut watch_outputs: Vec<TransactionOutputs>,
2776                 mut claimable_outpoints: Vec<PackageTemplate>,
2777                 broadcaster: &B,
2778                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2779                 logger: &L,
2780         ) -> Vec<TransactionOutputs>
2781         where
2782                 B::Target: BroadcasterInterface,
2783                 F::Target: FeeEstimator,
2784                 L::Target: Logger,
2785         {
2786                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2787                 debug_assert!(self.best_block.height() >= conf_height);
2788
2789                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2790                 if should_broadcast {
2791                         let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2792                         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());
2793                         claimable_outpoints.push(commitment_package);
2794                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2795                         let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2796                         self.holder_tx_signed = true;
2797                         // Because we're broadcasting a commitment transaction, we should construct the package
2798                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2799                         // "not yet confirmed" things as discardable, so we cannot do that here.
2800                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2801                         let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2802                         if !new_outputs.is_empty() {
2803                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2804                         }
2805                         claimable_outpoints.append(&mut new_outpoints);
2806                 }
2807
2808                 // Find which on-chain events have reached their confirmation threshold.
2809                 let onchain_events_awaiting_threshold_conf =
2810                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2811                 let mut onchain_events_reaching_threshold_conf = Vec::new();
2812                 for entry in onchain_events_awaiting_threshold_conf {
2813                         if entry.has_reached_confirmation_threshold(&self.best_block) {
2814                                 onchain_events_reaching_threshold_conf.push(entry);
2815                         } else {
2816                                 self.onchain_events_awaiting_threshold_conf.push(entry);
2817                         }
2818                 }
2819
2820                 // Used to check for duplicate HTLC resolutions.
2821                 #[cfg(debug_assertions)]
2822                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2823                         .iter()
2824                         .filter_map(|entry| match &entry.event {
2825                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2826                                 _ => None,
2827                         })
2828                         .collect();
2829                 #[cfg(debug_assertions)]
2830                 let mut matured_htlcs = Vec::new();
2831
2832                 // Produce actionable events from on-chain events having reached their threshold.
2833                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2834                         match entry.event {
2835                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2836                                         // Check for duplicate HTLC resolutions.
2837                                         #[cfg(debug_assertions)]
2838                                         {
2839                                                 debug_assert!(
2840                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2841                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
2842                                                          call either transaction_unconfirmed for the conflicting transaction \
2843                                                          or block_disconnected for a block containing it.");
2844                                                 debug_assert!(
2845                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2846                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
2847                                                          call either transaction_unconfirmed for the conflicting transaction \
2848                                                          or block_disconnected for a block containing it.");
2849                                                 matured_htlcs.push(source.clone());
2850                                         }
2851
2852                                         log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2853                                                 log_bytes!(payment_hash.0), entry.txid);
2854                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2855                                                 payment_hash,
2856                                                 payment_preimage: None,
2857                                                 source: source.clone(),
2858                                                 htlc_value_satoshis,
2859                                         }));
2860                                         if let Some(idx) = commitment_tx_output_idx {
2861                                                 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2862                                                         commitment_tx_output_idx: idx, resolving_txid: Some(entry.txid),
2863                                                         payment_preimage: None,
2864                                                 });
2865                                         }
2866                                 },
2867                                 OnchainEvent::MaturingOutput { descriptor } => {
2868                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2869                                         self.pending_events.push(Event::SpendableOutputs {
2870                                                 outputs: vec![descriptor]
2871                                         });
2872                                 },
2873                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2874                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2875                                                 commitment_tx_output_idx, resolving_txid: Some(entry.txid),
2876                                                 payment_preimage: preimage,
2877                                         });
2878                                 },
2879                                 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
2880                                         self.funding_spend_confirmed = Some(entry.txid);
2881                                         self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
2882                                 },
2883                         }
2884                 }
2885
2886                 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2887
2888                 // Determine new outputs to watch by comparing against previously known outputs to watch,
2889                 // updating the latter in the process.
2890                 watch_outputs.retain(|&(ref txid, ref txouts)| {
2891                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2892                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2893                 });
2894                 #[cfg(test)]
2895                 {
2896                         // If we see a transaction for which we registered outputs previously,
2897                         // make sure the registered scriptpubkey at the expected index match
2898                         // the actual transaction output one. We failed this case before #653.
2899                         for tx in &txn_matched {
2900                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2901                                         for idx_and_script in outputs.iter() {
2902                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
2903                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2904                                         }
2905                                 }
2906                         }
2907                 }
2908                 watch_outputs
2909         }
2910
2911         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2912                 where B::Target: BroadcasterInterface,
2913                       F::Target: FeeEstimator,
2914                       L::Target: Logger,
2915         {
2916                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2917
2918                 //We may discard:
2919                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2920                 //- maturing spendable output has transaction paying us has been disconnected
2921                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2922
2923                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2924                 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2925
2926                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2927         }
2928
2929         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2930                 &mut self,
2931                 txid: &Txid,
2932                 broadcaster: B,
2933                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2934                 logger: L,
2935         ) where
2936                 B::Target: BroadcasterInterface,
2937                 F::Target: FeeEstimator,
2938                 L::Target: Logger,
2939         {
2940                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2941                         log_info!(logger, "Removing onchain event with txid {}", txid);
2942                         false
2943                 } else { true });
2944                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2945         }
2946
2947         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2948         /// transactions thereof.
2949         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2950                 let mut matched_txn = HashSet::new();
2951                 txdata.iter().filter(|&&(_, tx)| {
2952                         let mut matches = self.spends_watched_output(tx);
2953                         for input in tx.input.iter() {
2954                                 if matches { break; }
2955                                 if matched_txn.contains(&input.previous_output.txid) {
2956                                         matches = true;
2957                                 }
2958                         }
2959                         if matches {
2960                                 matched_txn.insert(tx.txid());
2961                         }
2962                         matches
2963                 }).map(|(_, tx)| *tx).collect()
2964         }
2965
2966         /// Checks if a given transaction spends any watched outputs.
2967         fn spends_watched_output(&self, tx: &Transaction) -> bool {
2968                 for input in tx.input.iter() {
2969                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2970                                 for (idx, _script_pubkey) in outputs.iter() {
2971                                         if *idx == input.previous_output.vout {
2972                                                 #[cfg(test)]
2973                                                 {
2974                                                         // If the expected script is a known type, check that the witness
2975                                                         // appears to be spending the correct type (ie that the match would
2976                                                         // actually succeed in BIP 158/159-style filters).
2977                                                         if _script_pubkey.is_v0_p2wsh() {
2978                                                                 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
2979                                                                         // In at least one test we use a deliberately bogus witness
2980                                                                         // script which hit an old panic. Thus, we check for that here
2981                                                                         // and avoid the assert if its the expected bogus script.
2982                                                                         return true;
2983                                                                 }
2984
2985                                                                 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2986                                                         } else if _script_pubkey.is_v0_p2wpkh() {
2987                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2988                                                         } else { panic!(); }
2989                                                 }
2990                                                 return true;
2991                                         }
2992                                 }
2993                         }
2994                 }
2995
2996                 false
2997         }
2998
2999         fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
3000                 // We need to consider all HTLCs which are:
3001                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
3002                 //    transactions and we'd end up in a race, or
3003                 //  * are in our latest holder commitment transaction, as this is the thing we will
3004                 //    broadcast if we go on-chain.
3005                 // Note that we consider HTLCs which were below dust threshold here - while they don't
3006                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
3007                 // to the source, and if we don't fail the channel we will have to ensure that the next
3008                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
3009                 // easier to just fail the channel as this case should be rare enough anyway.
3010                 let height = self.best_block.height();
3011                 macro_rules! scan_commitment {
3012                         ($htlcs: expr, $holder_tx: expr) => {
3013                                 for ref htlc in $htlcs {
3014                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
3015                                         // chain with enough room to claim the HTLC without our counterparty being able to
3016                                         // time out the HTLC first.
3017                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
3018                                         // concern is being able to claim the corresponding inbound HTLC (on another
3019                                         // channel) before it expires. In fact, we don't even really care if our
3020                                         // counterparty here claims such an outbound HTLC after it expired as long as we
3021                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
3022                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
3023                                         // we give ourselves a few blocks of headroom after expiration before going
3024                                         // on-chain for an expired HTLC.
3025                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
3026                                         // from us until we've reached the point where we go on-chain with the
3027                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
3028                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
3029                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
3030                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
3031                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
3032                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
3033                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
3034                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
3035                                         //  The final, above, condition is checked for statically in channelmanager
3036                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
3037                                         let htlc_outbound = $holder_tx == htlc.offered;
3038                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
3039                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
3040                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
3041                                                 return true;
3042                                         }
3043                                 }
3044                         }
3045                 }
3046
3047                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
3048
3049                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
3050                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3051                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3052                         }
3053                 }
3054                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
3055                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3056                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3057                         }
3058                 }
3059
3060                 false
3061         }
3062
3063         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
3064         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
3065         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3066                 'outer_loop: for input in &tx.input {
3067                         let mut payment_data = None;
3068                         let witness_items = input.witness.len();
3069                         let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
3070                         let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
3071                         let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
3072                                 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
3073                         let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
3074                                 && input.witness.second_to_last().unwrap().len() == 32;
3075                         #[cfg(not(fuzzing))]
3076                         let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
3077                         let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
3078                                 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
3079
3080                         #[cfg(not(fuzzing))]
3081                         let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
3082
3083                         let mut payment_preimage = PaymentPreimage([0; 32]);
3084                         if accepted_preimage_claim {
3085                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3086                         } else if offered_preimage_claim {
3087                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3088                         }
3089
3090                         macro_rules! log_claim {
3091                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
3092                                         let outbound_htlc = $holder_tx == $htlc.offered;
3093                                         // HTLCs must either be claimed by a matching script type or through the
3094                                         // revocation path:
3095                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3096                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
3097                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3098                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
3099                                         // Further, only exactly one of the possible spend paths should have been
3100                                         // matched by any HTLC spend:
3101                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3102                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
3103                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
3104                                                          revocation_sig_claim as u8, 1);
3105                                         if ($holder_tx && revocation_sig_claim) ||
3106                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
3107                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
3108                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3109                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3110                                                         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" });
3111                                         } else {
3112                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
3113                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3114                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3115                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
3116                                         }
3117                                 }
3118                         }
3119
3120                         macro_rules! check_htlc_valid_counterparty {
3121                                 ($counterparty_txid: expr, $htlc_output: expr) => {
3122                                         if let Some(txid) = $counterparty_txid {
3123                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
3124                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
3125                                                                 if let &Some(ref source) = pending_source {
3126                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
3127                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
3128                                                                         break;
3129                                                                 }
3130                                                         }
3131                                                 }
3132                                         }
3133                                 }
3134                         }
3135
3136                         macro_rules! scan_commitment {
3137                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
3138                                         for (ref htlc_output, source_option) in $htlcs {
3139                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
3140                                                         if let Some(ref source) = source_option {
3141                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
3142                                                                 // We have a resolution of an HTLC either from one of our latest
3143                                                                 // holder commitment transactions or an unrevoked counterparty commitment
3144                                                                 // transaction. This implies we either learned a preimage, the HTLC
3145                                                                 // has timed out, or we screwed up. In any case, we should now
3146                                                                 // resolve the source HTLC with the original sender.
3147                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
3148                                                         } else if !$holder_tx {
3149                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3150                                                                 if payment_data.is_none() {
3151                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3152                                                                 }
3153                                                         }
3154                                                         if payment_data.is_none() {
3155                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
3156                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
3157                                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3158                                                                         txid: tx.txid(), height, transaction: Some(tx.clone()),
3159                                                                         event: OnchainEvent::HTLCSpendConfirmation {
3160                                                                                 commitment_tx_output_idx: input.previous_output.vout,
3161                                                                                 preimage: if accepted_preimage_claim || offered_preimage_claim {
3162                                                                                         Some(payment_preimage) } else { None },
3163                                                                                 // If this is a payment to us (ie !outbound_htlc), wait for
3164                                                                                 // the CSV delay before dropping the HTLC from claimable
3165                                                                                 // balance if the claim was an HTLC-Success transaction (ie
3166                                                                                 // accepted_preimage_claim).
3167                                                                                 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
3168                                                                                         Some(self.on_holder_tx_csv) } else { None },
3169                                                                         },
3170                                                                 });
3171                                                                 continue 'outer_loop;
3172                                                         }
3173                                                 }
3174                                         }
3175                                 }
3176                         }
3177
3178                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3179                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3180                                         "our latest holder commitment tx", true);
3181                         }
3182                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3183                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3184                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3185                                                 "our previous holder commitment tx", true);
3186                                 }
3187                         }
3188                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3189                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3190                                         "counterparty commitment tx", false);
3191                         }
3192
3193                         // Check that scan_commitment, above, decided there is some source worth relaying an
3194                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3195                         if let Some((source, payment_hash, amount_msat)) = payment_data {
3196                                 if accepted_preimage_claim {
3197                                         if !self.pending_monitor_events.iter().any(
3198                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3199                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3200                                                         txid: tx.txid(),
3201                                                         height,
3202                                                         transaction: Some(tx.clone()),
3203                                                         event: OnchainEvent::HTLCSpendConfirmation {
3204                                                                 commitment_tx_output_idx: input.previous_output.vout,
3205                                                                 preimage: Some(payment_preimage),
3206                                                                 on_to_local_output_csv: None,
3207                                                         },
3208                                                 });
3209                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3210                                                         source,
3211                                                         payment_preimage: Some(payment_preimage),
3212                                                         payment_hash,
3213                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3214                                                 }));
3215                                         }
3216                                 } else if offered_preimage_claim {
3217                                         if !self.pending_monitor_events.iter().any(
3218                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3219                                                         upd.source == source
3220                                                 } else { false }) {
3221                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3222                                                         txid: tx.txid(),
3223                                                         transaction: Some(tx.clone()),
3224                                                         height,
3225                                                         event: OnchainEvent::HTLCSpendConfirmation {
3226                                                                 commitment_tx_output_idx: input.previous_output.vout,
3227                                                                 preimage: Some(payment_preimage),
3228                                                                 on_to_local_output_csv: None,
3229                                                         },
3230                                                 });
3231                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3232                                                         source,
3233                                                         payment_preimage: Some(payment_preimage),
3234                                                         payment_hash,
3235                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3236                                                 }));
3237                                         }
3238                                 } else {
3239                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3240                                                 if entry.height != height { return true; }
3241                                                 match entry.event {
3242                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3243                                                                 *htlc_source != source
3244                                                         },
3245                                                         _ => true,
3246                                                 }
3247                                         });
3248                                         let entry = OnchainEventEntry {
3249                                                 txid: tx.txid(),
3250                                                 transaction: Some(tx.clone()),
3251                                                 height,
3252                                                 event: OnchainEvent::HTLCUpdate {
3253                                                         source, payment_hash,
3254                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3255                                                         commitment_tx_output_idx: Some(input.previous_output.vout),
3256                                                 },
3257                                         };
3258                                         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());
3259                                         self.onchain_events_awaiting_threshold_conf.push(entry);
3260                                 }
3261                         }
3262                 }
3263         }
3264
3265         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3266         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3267                 let mut spendable_output = None;
3268                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3269                         if i > ::core::u16::MAX as usize {
3270                                 // While it is possible that an output exists on chain which is greater than the
3271                                 // 2^16th output in a given transaction, this is only possible if the output is not
3272                                 // in a lightning transaction and was instead placed there by some third party who
3273                                 // wishes to give us money for no reason.
3274                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
3275                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3276                                 // scripts are not longer than one byte in length and because they are inherently
3277                                 // non-standard due to their size.
3278                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
3279                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
3280                                 // nearly a full block with garbage just to hit this case.
3281                                 continue;
3282                         }
3283                         if outp.script_pubkey == self.destination_script {
3284                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
3285                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3286                                         output: outp.clone(),
3287                                 });
3288                                 break;
3289                         }
3290                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3291                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3292                                         spendable_output =  Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3293                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3294                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
3295                                                 to_self_delay: self.on_holder_tx_csv,
3296                                                 output: outp.clone(),
3297                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3298                                                 channel_keys_id: self.channel_keys_id,
3299                                                 channel_value_satoshis: self.channel_value_satoshis,
3300                                         }));
3301                                         break;
3302                                 }
3303                         }
3304                         if self.counterparty_payment_script == outp.script_pubkey {
3305                                 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3306                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3307                                         output: outp.clone(),
3308                                         channel_keys_id: self.channel_keys_id,
3309                                         channel_value_satoshis: self.channel_value_satoshis,
3310                                 }));
3311                                 break;
3312                         }
3313                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3314                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3315                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3316                                         output: outp.clone(),
3317                                 });
3318                                 break;
3319                         }
3320                 }
3321                 if let Some(spendable_output) = spendable_output {
3322                         let entry = OnchainEventEntry {
3323                                 txid: tx.txid(),
3324                                 transaction: Some(tx.clone()),
3325                                 height: height,
3326                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3327                         };
3328                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3329                         self.onchain_events_awaiting_threshold_conf.push(entry);
3330                 }
3331         }
3332 }
3333
3334 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3335 where
3336         T::Target: BroadcasterInterface,
3337         F::Target: FeeEstimator,
3338         L::Target: Logger,
3339 {
3340         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3341                 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3342         }
3343
3344         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3345                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3346         }
3347 }
3348
3349 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3350 where
3351         T::Target: BroadcasterInterface,
3352         F::Target: FeeEstimator,
3353         L::Target: Logger,
3354 {
3355         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3356                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3357         }
3358
3359         fn transaction_unconfirmed(&self, txid: &Txid) {
3360                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3361         }
3362
3363         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3364                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3365         }
3366
3367         fn get_relevant_txids(&self) -> Vec<Txid> {
3368                 self.0.get_relevant_txids()
3369         }
3370 }
3371
3372 const MAX_ALLOC_SIZE: usize = 64*1024;
3373
3374 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3375                 for (BlockHash, ChannelMonitor<Signer>) {
3376         fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3377                 macro_rules! unwrap_obj {
3378                         ($key: expr) => {
3379                                 match $key {
3380                                         Ok(res) => res,
3381                                         Err(_) => return Err(DecodeError::InvalidValue),
3382                                 }
3383                         }
3384                 }
3385
3386                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3387
3388                 let latest_update_id: u64 = Readable::read(reader)?;
3389                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3390
3391                 let destination_script = Readable::read(reader)?;
3392                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3393                         0 => {
3394                                 let revokable_address = Readable::read(reader)?;
3395                                 let per_commitment_point = Readable::read(reader)?;
3396                                 let revokable_script = Readable::read(reader)?;
3397                                 Some((revokable_address, per_commitment_point, revokable_script))
3398                         },
3399                         1 => { None },
3400                         _ => return Err(DecodeError::InvalidValue),
3401                 };
3402                 let counterparty_payment_script = Readable::read(reader)?;
3403                 let shutdown_script = {
3404                         let script = <Script as Readable>::read(reader)?;
3405                         if script.is_empty() { None } else { Some(script) }
3406                 };
3407
3408                 let channel_keys_id = Readable::read(reader)?;
3409                 let holder_revocation_basepoint = Readable::read(reader)?;
3410                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3411                 // barely-init'd ChannelMonitors that we can't do anything with.
3412                 let outpoint = OutPoint {
3413                         txid: Readable::read(reader)?,
3414                         index: Readable::read(reader)?,
3415                 };
3416                 let funding_info = (outpoint, Readable::read(reader)?);
3417                 let current_counterparty_commitment_txid = Readable::read(reader)?;
3418                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3419
3420                 let counterparty_commitment_params = Readable::read(reader)?;
3421                 let funding_redeemscript = Readable::read(reader)?;
3422                 let channel_value_satoshis = Readable::read(reader)?;
3423
3424                 let their_cur_per_commitment_points = {
3425                         let first_idx = <U48 as Readable>::read(reader)?.0;
3426                         if first_idx == 0 {
3427                                 None
3428                         } else {
3429                                 let first_point = Readable::read(reader)?;
3430                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3431                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3432                                         Some((first_idx, first_point, None))
3433                                 } else {
3434                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3435                                 }
3436                         }
3437                 };
3438
3439                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3440
3441                 let commitment_secrets = Readable::read(reader)?;
3442
3443                 macro_rules! read_htlc_in_commitment {
3444                         () => {
3445                                 {
3446                                         let offered: bool = Readable::read(reader)?;
3447                                         let amount_msat: u64 = Readable::read(reader)?;
3448                                         let cltv_expiry: u32 = Readable::read(reader)?;
3449                                         let payment_hash: PaymentHash = Readable::read(reader)?;
3450                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
3451
3452                                         HTLCOutputInCommitment {
3453                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3454                                         }
3455                                 }
3456                         }
3457                 }
3458
3459                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3460                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3461                 for _ in 0..counterparty_claimable_outpoints_len {
3462                         let txid: Txid = Readable::read(reader)?;
3463                         let htlcs_count: u64 = Readable::read(reader)?;
3464                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3465                         for _ in 0..htlcs_count {
3466                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3467                         }
3468                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3469                                 return Err(DecodeError::InvalidValue);
3470                         }
3471                 }
3472
3473                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3474                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3475                 for _ in 0..counterparty_commitment_txn_on_chain_len {
3476                         let txid: Txid = Readable::read(reader)?;
3477                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3478                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3479                                 return Err(DecodeError::InvalidValue);
3480                         }
3481                 }
3482
3483                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3484                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3485                 for _ in 0..counterparty_hash_commitment_number_len {
3486                         let payment_hash: PaymentHash = Readable::read(reader)?;
3487                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3488                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3489                                 return Err(DecodeError::InvalidValue);
3490                         }
3491                 }
3492
3493                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3494                         match <u8 as Readable>::read(reader)? {
3495                                 0 => None,
3496                                 1 => {
3497                                         Some(Readable::read(reader)?)
3498                                 },
3499                                 _ => return Err(DecodeError::InvalidValue),
3500                         };
3501                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3502
3503                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3504                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3505
3506                 let payment_preimages_len: u64 = Readable::read(reader)?;
3507                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3508                 for _ in 0..payment_preimages_len {
3509                         let preimage: PaymentPreimage = Readable::read(reader)?;
3510                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3511                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3512                                 return Err(DecodeError::InvalidValue);
3513                         }
3514                 }
3515
3516                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3517                 let mut pending_monitor_events = Some(
3518                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3519                 for _ in 0..pending_monitor_events_len {
3520                         let ev = match <u8 as Readable>::read(reader)? {
3521                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3522                                 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3523                                 _ => return Err(DecodeError::InvalidValue)
3524                         };
3525                         pending_monitor_events.as_mut().unwrap().push(ev);
3526                 }
3527
3528                 let pending_events_len: u64 = Readable::read(reader)?;
3529                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3530                 for _ in 0..pending_events_len {
3531                         if let Some(event) = MaybeReadable::read(reader)? {
3532                                 pending_events.push(event);
3533                         }
3534                 }
3535
3536                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3537
3538                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3539                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3540                 for _ in 0..waiting_threshold_conf_len {
3541                         if let Some(val) = MaybeReadable::read(reader)? {
3542                                 onchain_events_awaiting_threshold_conf.push(val);
3543                         }
3544                 }
3545
3546                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3547                 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>>())));
3548                 for _ in 0..outputs_to_watch_len {
3549                         let txid = Readable::read(reader)?;
3550                         let outputs_len: u64 = Readable::read(reader)?;
3551                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3552                         for _ in 0..outputs_len {
3553                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3554                         }
3555                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3556                                 return Err(DecodeError::InvalidValue);
3557                         }
3558                 }
3559                 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3560
3561                 let lockdown_from_offchain = Readable::read(reader)?;
3562                 let holder_tx_signed = Readable::read(reader)?;
3563
3564                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3565                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3566                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3567                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3568                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3569                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3570                                 return Err(DecodeError::InvalidValue);
3571                         }
3572                 }
3573
3574                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3575                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3576                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3577                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3578                         return Err(DecodeError::InvalidValue);
3579                 }
3580
3581                 let mut funding_spend_confirmed = None;
3582                 let mut htlcs_resolved_on_chain = Some(Vec::new());
3583                 let mut funding_spend_seen = Some(false);
3584                 let mut counterparty_node_id = None;
3585                 let mut confirmed_commitment_tx_counterparty_output = None;
3586                 read_tlv_fields!(reader, {
3587                         (1, funding_spend_confirmed, option),
3588                         (3, htlcs_resolved_on_chain, vec_type),
3589                         (5, pending_monitor_events, vec_type),
3590                         (7, funding_spend_seen, option),
3591                         (9, counterparty_node_id, option),
3592                         (11, confirmed_commitment_tx_counterparty_output, option),
3593                 });
3594
3595                 let mut secp_ctx = Secp256k1::new();
3596                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3597
3598                 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3599                         latest_update_id,
3600                         commitment_transaction_number_obscure_factor,
3601
3602                         destination_script,
3603                         broadcasted_holder_revokable_script,
3604                         counterparty_payment_script,
3605                         shutdown_script,
3606
3607                         channel_keys_id,
3608                         holder_revocation_basepoint,
3609                         funding_info,
3610                         current_counterparty_commitment_txid,
3611                         prev_counterparty_commitment_txid,
3612
3613                         counterparty_commitment_params,
3614                         funding_redeemscript,
3615                         channel_value_satoshis,
3616                         their_cur_per_commitment_points,
3617
3618                         on_holder_tx_csv,
3619
3620                         commitment_secrets,
3621                         counterparty_claimable_outpoints,
3622                         counterparty_commitment_txn_on_chain,
3623                         counterparty_hash_commitment_number,
3624
3625                         prev_holder_signed_commitment_tx,
3626                         current_holder_commitment_tx,
3627                         current_counterparty_commitment_number,
3628                         current_holder_commitment_number,
3629
3630                         payment_preimages,
3631                         pending_monitor_events: pending_monitor_events.unwrap(),
3632                         pending_events,
3633
3634                         onchain_events_awaiting_threshold_conf,
3635                         outputs_to_watch,
3636
3637                         onchain_tx_handler,
3638
3639                         lockdown_from_offchain,
3640                         holder_tx_signed,
3641                         funding_spend_seen: funding_spend_seen.unwrap(),
3642                         funding_spend_confirmed,
3643                         confirmed_commitment_tx_counterparty_output,
3644                         htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3645
3646                         best_block,
3647                         counterparty_node_id,
3648
3649                         secp_ctx,
3650                 })))
3651         }
3652 }
3653
3654 #[cfg(test)]
3655 mod tests {
3656         use bitcoin::blockdata::block::BlockHeader;
3657         use bitcoin::blockdata::script::{Script, Builder};
3658         use bitcoin::blockdata::opcodes;
3659         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3660         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3661         use bitcoin::util::sighash;
3662         use bitcoin::hashes::Hash;
3663         use bitcoin::hashes::sha256::Hash as Sha256;
3664         use bitcoin::hashes::hex::FromHex;
3665         use bitcoin::hash_types::{BlockHash, Txid};
3666         use bitcoin::network::constants::Network;
3667         use bitcoin::secp256k1::{SecretKey,PublicKey};
3668         use bitcoin::secp256k1::Secp256k1;
3669
3670         use hex;
3671
3672         use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3673
3674         use super::ChannelMonitorUpdateStep;
3675         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};
3676         use chain::{BestBlock, Confirm};
3677         use chain::channelmonitor::ChannelMonitor;
3678         use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3679         use chain::transaction::OutPoint;
3680         use chain::keysinterface::InMemorySigner;
3681         use ln::{PaymentPreimage, PaymentHash};
3682         use ln::chan_utils;
3683         use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3684         use ln::channelmanager::PaymentSendFailure;
3685         use ln::features::InitFeatures;
3686         use ln::functional_test_utils::*;
3687         use ln::script::ShutdownScript;
3688         use util::errors::APIError;
3689         use util::events::{ClosureReason, MessageSendEventsProvider};
3690         use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3691         use util::ser::{ReadableArgs, Writeable};
3692         use sync::{Arc, Mutex};
3693         use io;
3694         use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
3695         use prelude::*;
3696
3697         fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3698                 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3699                 // confirmed. This would allow a race condition where we could receive a payment (including
3700                 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3701                 // long as the ChannelMonitor receives the block first, the full commitment update dance
3702                 // occurs after the block is connected, and before the ChannelManager receives the block.
3703                 // Obviously this is an incredibly contrived race given the counterparty would be risking
3704                 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3705                 // potential ChannelMonitor states simpler to reason about.
3706                 //
3707                 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3708                 // updates is handled correctly in such conditions.
3709                 let chanmon_cfgs = create_chanmon_cfgs(3);
3710                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3711                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3712                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3713                 let channel = create_announced_chan_between_nodes(
3714                         &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3715                 create_announced_chan_between_nodes(
3716                         &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3717
3718                 // Rebalance somewhat
3719                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3720
3721                 // First route two payments for testing at the end
3722                 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3723                 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3724
3725                 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3726                 assert_eq!(local_txn.len(), 1);
3727                 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3728                 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3729                 check_spends!(remote_txn[1], remote_txn[0]);
3730                 check_spends!(remote_txn[2], remote_txn[0]);
3731                 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3732
3733                 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3734                 // channel is now closed, but the ChannelManager doesn't know that yet.
3735                 let new_header = BlockHeader {
3736                         version: 2, time: 0, bits: 0, nonce: 0,
3737                         prev_blockhash: nodes[0].best_block_info().0,
3738                         merkle_root: TxMerkleNode::all_zeros() };
3739                 let conf_height = nodes[0].best_block_info().1 + 1;
3740                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3741                         &[(0, broadcast_tx)], conf_height);
3742
3743                 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3744                                                 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3745                                                 &nodes[1].keys_manager.backing).unwrap();
3746
3747                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3748                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3749                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3750                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3751                         true, APIError::ChannelUnavailable { ref err },
3752                         assert!(err.contains("ChannelMonitor storage failure")));
3753                 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3754                 check_closed_broadcast!(nodes[1], true);
3755                 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3756
3757                 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3758                 // and provides the claim preimages for the two pending HTLCs. The first update generates
3759                 // an error, but the point of this test is to ensure the later updates are still applied.
3760                 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3761                 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3762                 assert_eq!(replay_update.updates.len(), 1);
3763                 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3764                 } else { panic!(); }
3765                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3766                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3767
3768                 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3769                 assert!(
3770                         pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3771                         .is_err());
3772                 // Even though we error'd on the first update, we should still have generated an HTLC claim
3773                 // transaction
3774                 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3775                 assert!(txn_broadcasted.len() >= 2);
3776                 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3777                         assert_eq!(tx.input.len(), 1);
3778                         tx.input[0].previous_output.txid == broadcast_tx.txid()
3779                 }).collect::<Vec<_>>();
3780                 assert_eq!(htlc_txn.len(), 2);
3781                 check_spends!(htlc_txn[0], broadcast_tx);
3782                 check_spends!(htlc_txn[1], broadcast_tx);
3783         }
3784         #[test]
3785         fn test_funding_spend_refuses_updates() {
3786                 do_test_funding_spend_refuses_updates(true);
3787                 do_test_funding_spend_refuses_updates(false);
3788         }
3789
3790         #[test]
3791         fn test_prune_preimages() {
3792                 let secp_ctx = Secp256k1::new();
3793                 let logger = Arc::new(TestLogger::new());
3794                 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3795                 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3796
3797                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3798                 let dummy_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3799
3800                 let mut preimages = Vec::new();
3801                 {
3802                         for i in 0..20 {
3803                                 let preimage = PaymentPreimage([i; 32]);
3804                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3805                                 preimages.push((preimage, hash));
3806                         }
3807                 }
3808
3809                 macro_rules! preimages_slice_to_htlc_outputs {
3810                         ($preimages_slice: expr) => {
3811                                 {
3812                                         let mut res = Vec::new();
3813                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3814                                                 res.push((HTLCOutputInCommitment {
3815                                                         offered: true,
3816                                                         amount_msat: 0,
3817                                                         cltv_expiry: 0,
3818                                                         payment_hash: preimage.1.clone(),
3819                                                         transaction_output_index: Some(idx as u32),
3820                                                 }, None));
3821                                         }
3822                                         res
3823                                 }
3824                         }
3825                 }
3826                 macro_rules! preimages_to_holder_htlcs {
3827                         ($preimages_slice: expr) => {
3828                                 {
3829                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3830                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3831                                         res
3832                                 }
3833                         }
3834                 }
3835
3836                 macro_rules! test_preimages_exist {
3837                         ($preimages_slice: expr, $monitor: expr) => {
3838                                 for preimage in $preimages_slice {
3839                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3840                                 }
3841                         }
3842                 }
3843
3844                 let keys = InMemorySigner::new(
3845                         &secp_ctx,
3846                         SecretKey::from_slice(&[41; 32]).unwrap(),
3847                         SecretKey::from_slice(&[41; 32]).unwrap(),
3848                         SecretKey::from_slice(&[41; 32]).unwrap(),
3849                         SecretKey::from_slice(&[41; 32]).unwrap(),
3850                         SecretKey::from_slice(&[41; 32]).unwrap(),
3851                         SecretKey::from_slice(&[41; 32]).unwrap(),
3852                         [41; 32],
3853                         0,
3854                         [0; 32]
3855                 );
3856
3857                 let counterparty_pubkeys = ChannelPublicKeys {
3858                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3859                         revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3860                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3861                         delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3862                         htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3863                 };
3864                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
3865                 let channel_parameters = ChannelTransactionParameters {
3866                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3867                         holder_selected_contest_delay: 66,
3868                         is_outbound_from_holder: true,
3869                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3870                                 pubkeys: counterparty_pubkeys,
3871                                 selected_contest_delay: 67,
3872                         }),
3873                         funding_outpoint: Some(funding_outpoint),
3874                         opt_anchors: None,
3875                 };
3876                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3877                 // old state.
3878                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3879                 let best_block = BestBlock::from_genesis(Network::Testnet);
3880                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3881                                                   Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3882                                                   (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3883                                                   &channel_parameters,
3884                                                   Script::new(), 46, 0,
3885                                                   HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3886
3887                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3888                 let dummy_txid = dummy_tx.txid();
3889                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3890                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3891                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3892                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3893                 for &(ref preimage, ref hash) in preimages.iter() {
3894                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3895                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3896                 }
3897
3898                 // Now provide a secret, pruning preimages 10-15
3899                 let mut secret = [0; 32];
3900                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3901                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3902                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3903                 test_preimages_exist!(&preimages[0..10], monitor);
3904                 test_preimages_exist!(&preimages[15..20], monitor);
3905
3906                 // Now provide a further secret, pruning preimages 15-17
3907                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3908                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3909                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3910                 test_preimages_exist!(&preimages[0..10], monitor);
3911                 test_preimages_exist!(&preimages[17..20], monitor);
3912
3913                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3914                 // previous commitment tx's preimages too
3915                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3916                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3917                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3918                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3919                 test_preimages_exist!(&preimages[0..10], monitor);
3920                 test_preimages_exist!(&preimages[18..20], monitor);
3921
3922                 // But if we do it again, we'll prune 5-10
3923                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3924                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3925                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3926                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3927                 test_preimages_exist!(&preimages[0..5], monitor);
3928         }
3929
3930         #[test]
3931         fn test_claim_txn_weight_computation() {
3932                 // We test Claim txn weight, knowing that we want expected weigth and
3933                 // not actual case to avoid sigs and time-lock delays hell variances.
3934
3935                 let secp_ctx = Secp256k1::new();
3936                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3937                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3938
3939                 macro_rules! sign_input {
3940                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3941                                 let htlc = HTLCOutputInCommitment {
3942                                         offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3943                                         amount_msat: 0,
3944                                         cltv_expiry: 2 << 16,
3945                                         payment_hash: PaymentHash([1; 32]),
3946                                         transaction_output_index: Some($idx as u32),
3947                                 };
3948                                 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) };
3949                                 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3950                                 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3951                                 let mut ser_sig = sig.serialize_der().to_vec();
3952                                 ser_sig.push(EcdsaSighashType::All as u8);
3953                                 $sum_actual_sigs += ser_sig.len();
3954                                 let witness = $sighash_parts.witness_mut($idx).unwrap();
3955                                 witness.push(ser_sig);
3956                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
3957                                         witness.push(vec!(1));
3958                                 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3959                                         witness.push(pubkey.clone().serialize().to_vec());
3960                                 } else if *$weight == weight_received_htlc($opt_anchors) {
3961                                         witness.push(vec![0]);
3962                                 } else {
3963                                         witness.push(PaymentPreimage([1; 32]).0.to_vec());
3964                                 }
3965                                 witness.push(redeem_script.into_bytes());
3966                                 let witness = witness.to_vec();
3967                                 println!("witness[0] {}", witness[0].len());
3968                                 println!("witness[1] {}", witness[1].len());
3969                                 println!("witness[2] {}", witness[2].len());
3970                         }
3971                 }
3972
3973                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3974                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3975
3976                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3977                 for &opt_anchors in [false, true].iter() {
3978                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3979                         let mut sum_actual_sigs = 0;
3980                         for i in 0..4 {
3981                                 claim_tx.input.push(TxIn {
3982                                         previous_output: BitcoinOutPoint {
3983                                                 txid,
3984                                                 vout: i,
3985                                         },
3986                                         script_sig: Script::new(),
3987                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3988                                         witness: Witness::new(),
3989                                 });
3990                         }
3991                         claim_tx.output.push(TxOut {
3992                                 script_pubkey: script_pubkey.clone(),
3993                                 value: 0,
3994                         });
3995                         let base_weight = claim_tx.weight();
3996                         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)];
3997                         let mut inputs_total_weight = 2; // count segwit flags
3998                         {
3999                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4000                                 for (idx, inp) in inputs_weight.iter().enumerate() {
4001                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4002                                         inputs_total_weight += inp;
4003                                 }
4004                         }
4005                         assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4006                 }
4007
4008                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
4009                 for &opt_anchors in [false, true].iter() {
4010                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4011                         let mut sum_actual_sigs = 0;
4012                         for i in 0..4 {
4013                                 claim_tx.input.push(TxIn {
4014                                         previous_output: BitcoinOutPoint {
4015                                                 txid,
4016                                                 vout: i,
4017                                         },
4018                                         script_sig: Script::new(),
4019                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4020                                         witness: Witness::new(),
4021                                 });
4022                         }
4023                         claim_tx.output.push(TxOut {
4024                                 script_pubkey: script_pubkey.clone(),
4025                                 value: 0,
4026                         });
4027                         let base_weight = claim_tx.weight();
4028                         let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
4029                         let mut inputs_total_weight = 2; // count segwit flags
4030                         {
4031                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4032                                 for (idx, inp) in inputs_weight.iter().enumerate() {
4033                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4034                                         inputs_total_weight += inp;
4035                                 }
4036                         }
4037                         assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4038                 }
4039
4040                 // Justice tx with 1 revoked HTLC-Success tx output
4041                 for &opt_anchors in [false, true].iter() {
4042                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4043                         let mut sum_actual_sigs = 0;
4044                         claim_tx.input.push(TxIn {
4045                                 previous_output: BitcoinOutPoint {
4046                                         txid,
4047                                         vout: 0,
4048                                 },
4049                                 script_sig: Script::new(),
4050                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4051                                 witness: Witness::new(),
4052                         });
4053                         claim_tx.output.push(TxOut {
4054                                 script_pubkey: script_pubkey.clone(),
4055                                 value: 0,
4056                         });
4057                         let base_weight = claim_tx.weight();
4058                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
4059                         let mut inputs_total_weight = 2; // count segwit flags
4060                         {
4061                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4062                                 for (idx, inp) in inputs_weight.iter().enumerate() {
4063                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4064                                         inputs_total_weight += inp;
4065                                 }
4066                         }
4067                         assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
4068                 }
4069         }
4070
4071         // Further testing is done in the ChannelManager integration tests.
4072 }