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