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