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