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