]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/chain/channelmonitor.rs
fa4ab601121475a2ea096eff29340df8a81a1ac4
[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                 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
2234                         if let Some(per_commitment_points) = self.their_cur_per_commitment_points {
2235                                 let per_commitment_point_option =
2236                                         // If the counterparty commitment tx is the latest valid state, use their latest
2237                                         // per-commitment point
2238                                         if per_commitment_points.0 == commitment_number { Some(&per_commitment_points.1) }
2239                                         else if let Some(point) = per_commitment_points.2.as_ref() {
2240                                                 // If counterparty commitment tx is the state previous to the latest valid state, use
2241                                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2242                                                 // them to temporarily have two valid commitment txns from our viewpoint)
2243                                                 if per_commitment_points.0 == commitment_number + 1 { Some(point) } else { None }
2244                                         } else { None };
2245                                 if let Some(per_commitment_point) = per_commitment_point_option {
2246                                         if let Some(transaction) = tx {
2247                                                 let revokeable_p2wsh_opt =
2248                                                         if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
2249                                                                 &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
2250                                                         {
2251                                                                 if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
2252                                                                         &per_commitment_point,
2253                                                                         &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
2254                                                                 {
2255                                                                         Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2256                                                                                 self.counterparty_commitment_params.on_counterparty_tx_csv,
2257                                                                                 &delayed_key).to_v0_p2wsh())
2258                                                                 } else {
2259                                                                         debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
2260                                                                         None
2261                                                                 }
2262                                                         } else {
2263                                                                 debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
2264                                                                 None
2265                                                         };
2266                                                 if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
2267                                                         for (idx, outp) in transaction.output.iter().enumerate() {
2268                                                                 if outp.script_pubkey == revokeable_p2wsh {
2269                                                                         to_counterparty_output_info =
2270                                                                                 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2271                                                                 }
2272                                                         }
2273                                                 }
2274                                         }
2275
2276                                         for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2277                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
2278                                                         if let Some(transaction) = tx {
2279                                                                 if transaction_output_index as usize >= transaction.output.len() ||
2280                                                                         transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2281                                                                                 // per_commitment_data is corrupt or our commitment signing key leaked!
2282                                                                                 return (claimable_outpoints, to_counterparty_output_info);
2283                                                                         }
2284                                                         }
2285                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2286                                                         if preimage.is_some() || !htlc.offered {
2287                                                                 let counterparty_htlc_outp = if htlc.offered {
2288                                                                         PackageSolvingData::CounterpartyOfferedHTLCOutput(
2289                                                                                 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2290                                                                                         self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2291                                                                                         self.counterparty_commitment_params.counterparty_htlc_base_key,
2292                                                                                         preimage.unwrap(), htlc.clone()))
2293                                                                 } else {
2294                                                                         PackageSolvingData::CounterpartyReceivedHTLCOutput(
2295                                                                                 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2296                                                                                         self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2297                                                                                         self.counterparty_commitment_params.counterparty_htlc_base_key,
2298                                                                                         htlc.clone()))
2299                                                                 };
2300                                                                 let aggregation = if !htlc.offered { false } else { true };
2301                                                                 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2302                                                                 claimable_outpoints.push(counterparty_package);
2303                                                         }
2304                                                 }
2305                                         }
2306                                 }
2307                         }
2308                 }
2309                 (claimable_outpoints, to_counterparty_output_info)
2310         }
2311
2312         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2313         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 {
2314                 let htlc_txid = tx.txid();
2315                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2316                         return (Vec::new(), None)
2317                 }
2318
2319                 macro_rules! ignore_error {
2320                         ( $thing : expr ) => {
2321                                 match $thing {
2322                                         Ok(a) => a,
2323                                         Err(_) => return (Vec::new(), None)
2324                                 }
2325                         };
2326                 }
2327
2328                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2329                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2330                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2331
2332                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2333                 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);
2334                 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);
2335                 let claimable_outpoints = vec!(justice_package);
2336                 let outputs = vec![(0, tx.output[0].clone())];
2337                 (claimable_outpoints, Some((htlc_txid, outputs)))
2338         }
2339
2340         // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2341         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2342         // script so we can detect whether a holder transaction has been seen on-chain.
2343         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2344                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2345
2346                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2347                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2348
2349                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2350                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2351                                 let htlc_output = if htlc.offered {
2352                                                 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2353                                         } else {
2354                                                 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2355                                                         preimage.clone()
2356                                                 } else {
2357                                                         // We can't build an HTLC-Success transaction without the preimage
2358                                                         continue;
2359                                                 };
2360                                                 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2361                                         };
2362                                 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2363                                 claim_requests.push(htlc_package);
2364                         }
2365                 }
2366
2367                 (claim_requests, broadcasted_holder_revokable_script)
2368         }
2369
2370         // Returns holder HTLC outputs to watch and react to in case of spending.
2371         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2372                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2373                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2374                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2375                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2376                         }
2377                 }
2378                 watch_outputs
2379         }
2380
2381         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2382         /// revoked using data in holder_claimable_outpoints.
2383         /// Should not be used if check_spend_revoked_transaction succeeds.
2384         /// Returns None unless the transaction is definitely one of our commitment transactions.
2385         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2386                 let commitment_txid = tx.txid();
2387                 let mut claim_requests = Vec::new();
2388                 let mut watch_outputs = Vec::new();
2389
2390                 macro_rules! append_onchain_update {
2391                         ($updates: expr, $to_watch: expr) => {
2392                                 claim_requests = $updates.0;
2393                                 self.broadcasted_holder_revokable_script = $updates.1;
2394                                 watch_outputs.append(&mut $to_watch);
2395                         }
2396                 }
2397
2398                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2399                 let mut is_holder_tx = false;
2400
2401                 if self.current_holder_commitment_tx.txid == commitment_txid {
2402                         is_holder_tx = true;
2403                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2404                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2405                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2406                         append_onchain_update!(res, to_watch);
2407                         fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
2408                                 self.current_holder_commitment_tx.htlc_outputs.iter()
2409                                 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2410                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2411                         if holder_tx.txid == commitment_txid {
2412                                 is_holder_tx = true;
2413                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2414                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2415                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2416                                 append_onchain_update!(res, to_watch);
2417                                 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height,
2418                                         holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2419                                         logger);
2420                         }
2421                 }
2422
2423                 if is_holder_tx {
2424                         Some((claim_requests, (commitment_txid, watch_outputs)))
2425                 } else {
2426                         None
2427                 }
2428         }
2429
2430         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2431                 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2432                 self.holder_tx_signed = true;
2433                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2434                 let txid = commitment_tx.txid();
2435                 let mut holder_transactions = vec![commitment_tx];
2436                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2437                         if let Some(vout) = htlc.0.transaction_output_index {
2438                                 let preimage = if !htlc.0.offered {
2439                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2440                                                 // We can't build an HTLC-Success transaction without the preimage
2441                                                 continue;
2442                                         }
2443                                 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2444                                         // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2445                                         // current locktime requirements on-chain. We will broadcast them in
2446                                         // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2447                                         // Note that we add + 1 as transactions are broadcastable when they can be
2448                                         // confirmed in the next block.
2449                                         continue;
2450                                 } else { None };
2451                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2452                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2453                                         holder_transactions.push(htlc_tx);
2454                                 }
2455                         }
2456                 }
2457                 // 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.
2458                 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2459                 holder_transactions
2460         }
2461
2462         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2463         /// Note that this includes possibly-locktimed-in-the-future transactions!
2464         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2465                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2466                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2467                 let txid = commitment_tx.txid();
2468                 let mut holder_transactions = vec![commitment_tx];
2469                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2470                         if let Some(vout) = htlc.0.transaction_output_index {
2471                                 let preimage = if !htlc.0.offered {
2472                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2473                                                 // We can't build an HTLC-Success transaction without the preimage
2474                                                 continue;
2475                                         }
2476                                 } else { None };
2477                                 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2478                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2479                                         holder_transactions.push(htlc_tx);
2480                                 }
2481                         }
2482                 }
2483                 holder_transactions
2484         }
2485
2486         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>
2487                 where B::Target: BroadcasterInterface,
2488                       F::Target: FeeEstimator,
2489                                         L::Target: Logger,
2490         {
2491                 let block_hash = header.block_hash();
2492                 self.best_block = BestBlock::new(block_hash, height);
2493
2494                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2495                 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2496         }
2497
2498         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2499                 &mut self,
2500                 header: &BlockHeader,
2501                 height: u32,
2502                 broadcaster: B,
2503                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2504                 logger: L,
2505         ) -> Vec<TransactionOutputs>
2506         where
2507                 B::Target: BroadcasterInterface,
2508                 F::Target: FeeEstimator,
2509                 L::Target: Logger,
2510         {
2511                 let block_hash = header.block_hash();
2512
2513                 if height > self.best_block.height() {
2514                         self.best_block = BestBlock::new(block_hash, height);
2515                         self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2516                 } else if block_hash != self.best_block.block_hash() {
2517                         self.best_block = BestBlock::new(block_hash, height);
2518                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2519                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2520                         Vec::new()
2521                 } else { Vec::new() }
2522         }
2523
2524         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2525                 &mut self,
2526                 header: &BlockHeader,
2527                 txdata: &TransactionData,
2528                 height: u32,
2529                 broadcaster: B,
2530                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2531                 logger: L,
2532         ) -> Vec<TransactionOutputs>
2533         where
2534                 B::Target: BroadcasterInterface,
2535                 F::Target: FeeEstimator,
2536                 L::Target: Logger,
2537         {
2538                 let txn_matched = self.filter_block(txdata);
2539                 for tx in &txn_matched {
2540                         let mut output_val = 0;
2541                         for out in tx.output.iter() {
2542                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2543                                 output_val += out.value;
2544                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2545                         }
2546                 }
2547
2548                 let block_hash = header.block_hash();
2549
2550                 let mut watch_outputs = Vec::new();
2551                 let mut claimable_outpoints = Vec::new();
2552                 for tx in &txn_matched {
2553                         if tx.input.len() == 1 {
2554                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2555                                 // commitment transactions and HTLC transactions will all only ever have one input,
2556                                 // which is an easy way to filter out any potential non-matching txn for lazy
2557                                 // filters.
2558                                 let prevout = &tx.input[0].previous_output;
2559                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2560                                         let mut balance_spendable_csv = None;
2561                                         log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2562                                                 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2563                                         self.funding_spend_seen = true;
2564                                         let mut commitment_tx_to_counterparty_output = None;
2565                                         if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
2566                                                 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
2567                                                         self.check_spend_counterparty_transaction(&tx, height, &logger);
2568                                                 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
2569                                                 if !new_outputs.1.is_empty() {
2570                                                         watch_outputs.push(new_outputs);
2571                                                 }
2572                                                 claimable_outpoints.append(&mut new_outpoints);
2573                                                 if new_outpoints.is_empty() {
2574                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2575                                                                 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
2576                                                                         "A commitment transaction matched as both a counterparty and local commitment tx?");
2577                                                                 if !new_outputs.1.is_empty() {
2578                                                                         watch_outputs.push(new_outputs);
2579                                                                 }
2580                                                                 claimable_outpoints.append(&mut new_outpoints);
2581                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
2582                                                         }
2583                                                 }
2584                                         }
2585                                         let txid = tx.txid();
2586                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2587                                                 txid,
2588                                                 transaction: Some((*tx).clone()),
2589                                                 height: height,
2590                                                 event: OnchainEvent::FundingSpendConfirmation {
2591                                                         on_local_output_csv: balance_spendable_csv,
2592                                                         commitment_tx_to_counterparty_output,
2593                                                 },
2594                                         });
2595                                 } else {
2596                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2597                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2598                                                 claimable_outpoints.append(&mut new_outpoints);
2599                                                 if let Some(new_outputs) = new_outputs_option {
2600                                                         watch_outputs.push(new_outputs);
2601                                                 }
2602                                         }
2603                                 }
2604                         }
2605                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2606                         // can also be resolved in a few other ways which can have more than one output. Thus,
2607                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2608                         self.is_resolving_htlc_output(&tx, height, &logger);
2609
2610                         self.is_paying_spendable_output(&tx, height, &logger);
2611                 }
2612
2613                 if height > self.best_block.height() {
2614                         self.best_block = BestBlock::new(block_hash, height);
2615                 }
2616
2617                 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2618         }
2619
2620         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2621         /// `self.best_block` before calling if a new best blockchain tip is available. More
2622         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2623         /// complexity especially in `OnchainTx::update_claims_view`.
2624         ///
2625         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2626         /// confirmed at, even if it is not the current best height.
2627         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2628                 &mut self,
2629                 conf_height: u32,
2630                 txn_matched: Vec<&Transaction>,
2631                 mut watch_outputs: Vec<TransactionOutputs>,
2632                 mut claimable_outpoints: Vec<PackageTemplate>,
2633                 broadcaster: &B,
2634                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2635                 logger: &L,
2636         ) -> Vec<TransactionOutputs>
2637         where
2638                 B::Target: BroadcasterInterface,
2639                 F::Target: FeeEstimator,
2640                 L::Target: Logger,
2641         {
2642                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2643                 debug_assert!(self.best_block.height() >= conf_height);
2644
2645                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2646                 if should_broadcast {
2647                         let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2648                         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());
2649                         claimable_outpoints.push(commitment_package);
2650                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2651                         let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2652                         self.holder_tx_signed = true;
2653                         // Because we're broadcasting a commitment transaction, we should construct the package
2654                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2655                         // "not yet confirmed" things as discardable, so we cannot do that here.
2656                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2657                         let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2658                         if !new_outputs.is_empty() {
2659                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2660                         }
2661                         claimable_outpoints.append(&mut new_outpoints);
2662                 }
2663
2664                 // Find which on-chain events have reached their confirmation threshold.
2665                 let onchain_events_awaiting_threshold_conf =
2666                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2667                 let mut onchain_events_reaching_threshold_conf = Vec::new();
2668                 for entry in onchain_events_awaiting_threshold_conf {
2669                         if entry.has_reached_confirmation_threshold(&self.best_block) {
2670                                 onchain_events_reaching_threshold_conf.push(entry);
2671                         } else {
2672                                 self.onchain_events_awaiting_threshold_conf.push(entry);
2673                         }
2674                 }
2675
2676                 // Used to check for duplicate HTLC resolutions.
2677                 #[cfg(debug_assertions)]
2678                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2679                         .iter()
2680                         .filter_map(|entry| match &entry.event {
2681                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2682                                 _ => None,
2683                         })
2684                         .collect();
2685                 #[cfg(debug_assertions)]
2686                 let mut matured_htlcs = Vec::new();
2687
2688                 // Produce actionable events from on-chain events having reached their threshold.
2689                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2690                         match entry.event {
2691                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2692                                         // Check for duplicate HTLC resolutions.
2693                                         #[cfg(debug_assertions)]
2694                                         {
2695                                                 debug_assert!(
2696                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2697                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
2698                                                          call either transaction_unconfirmed for the conflicting transaction \
2699                                                          or block_disconnected for a block containing it.");
2700                                                 debug_assert!(
2701                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2702                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
2703                                                          call either transaction_unconfirmed for the conflicting transaction \
2704                                                          or block_disconnected for a block containing it.");
2705                                                 matured_htlcs.push(source.clone());
2706                                         }
2707
2708                                         log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2709                                                 log_bytes!(payment_hash.0), entry.txid);
2710                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2711                                                 payment_hash,
2712                                                 payment_preimage: None,
2713                                                 source: source.clone(),
2714                                                 htlc_value_satoshis,
2715                                         }));
2716                                         if let Some(idx) = commitment_tx_output_idx {
2717                                                 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx: idx, payment_preimage: None });
2718                                         }
2719                                 },
2720                                 OnchainEvent::MaturingOutput { descriptor } => {
2721                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2722                                         self.pending_events.push(Event::SpendableOutputs {
2723                                                 outputs: vec![descriptor]
2724                                         });
2725                                 },
2726                                 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2727                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx, payment_preimage: preimage });
2728                                 },
2729                                 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
2730                                         self.funding_spend_confirmed = Some(entry.txid);
2731                                         self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
2732                                 },
2733                         }
2734                 }
2735
2736                 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2737
2738                 // Determine new outputs to watch by comparing against previously known outputs to watch,
2739                 // updating the latter in the process.
2740                 watch_outputs.retain(|&(ref txid, ref txouts)| {
2741                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2742                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2743                 });
2744                 #[cfg(test)]
2745                 {
2746                         // If we see a transaction for which we registered outputs previously,
2747                         // make sure the registered scriptpubkey at the expected index match
2748                         // the actual transaction output one. We failed this case before #653.
2749                         for tx in &txn_matched {
2750                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2751                                         for idx_and_script in outputs.iter() {
2752                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
2753                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2754                                         }
2755                                 }
2756                         }
2757                 }
2758                 watch_outputs
2759         }
2760
2761         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2762                 where B::Target: BroadcasterInterface,
2763                       F::Target: FeeEstimator,
2764                       L::Target: Logger,
2765         {
2766                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2767
2768                 //We may discard:
2769                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2770                 //- maturing spendable output has transaction paying us has been disconnected
2771                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2772
2773                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2774                 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2775
2776                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2777         }
2778
2779         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2780                 &mut self,
2781                 txid: &Txid,
2782                 broadcaster: B,
2783                 fee_estimator: &LowerBoundedFeeEstimator<F>,
2784                 logger: L,
2785         ) where
2786                 B::Target: BroadcasterInterface,
2787                 F::Target: FeeEstimator,
2788                 L::Target: Logger,
2789         {
2790                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2791                         log_info!(logger, "Removing onchain event with txid {}", txid);
2792                         false
2793                 } else { true });
2794                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2795         }
2796
2797         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2798         /// transactions thereof.
2799         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2800                 let mut matched_txn = HashSet::new();
2801                 txdata.iter().filter(|&&(_, tx)| {
2802                         let mut matches = self.spends_watched_output(tx);
2803                         for input in tx.input.iter() {
2804                                 if matches { break; }
2805                                 if matched_txn.contains(&input.previous_output.txid) {
2806                                         matches = true;
2807                                 }
2808                         }
2809                         if matches {
2810                                 matched_txn.insert(tx.txid());
2811                         }
2812                         matches
2813                 }).map(|(_, tx)| *tx).collect()
2814         }
2815
2816         /// Checks if a given transaction spends any watched outputs.
2817         fn spends_watched_output(&self, tx: &Transaction) -> bool {
2818                 for input in tx.input.iter() {
2819                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2820                                 for (idx, _script_pubkey) in outputs.iter() {
2821                                         if *idx == input.previous_output.vout {
2822                                                 #[cfg(test)]
2823                                                 {
2824                                                         // If the expected script is a known type, check that the witness
2825                                                         // appears to be spending the correct type (ie that the match would
2826                                                         // actually succeed in BIP 158/159-style filters).
2827                                                         if _script_pubkey.is_v0_p2wsh() {
2828                                                                 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
2829                                                                         // In at least one test we use a deliberately bogus witness
2830                                                                         // script which hit an old panic. Thus, we check for that here
2831                                                                         // and avoid the assert if its the expected bogus script.
2832                                                                         return true;
2833                                                                 }
2834
2835                                                                 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2836                                                         } else if _script_pubkey.is_v0_p2wpkh() {
2837                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2838                                                         } else { panic!(); }
2839                                                 }
2840                                                 return true;
2841                                         }
2842                                 }
2843                         }
2844                 }
2845
2846                 false
2847         }
2848
2849         fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2850                 // We need to consider all HTLCs which are:
2851                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
2852                 //    transactions and we'd end up in a race, or
2853                 //  * are in our latest holder commitment transaction, as this is the thing we will
2854                 //    broadcast if we go on-chain.
2855                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2856                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2857                 // to the source, and if we don't fail the channel we will have to ensure that the next
2858                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2859                 // easier to just fail the channel as this case should be rare enough anyway.
2860                 let height = self.best_block.height();
2861                 macro_rules! scan_commitment {
2862                         ($htlcs: expr, $holder_tx: expr) => {
2863                                 for ref htlc in $htlcs {
2864                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2865                                         // chain with enough room to claim the HTLC without our counterparty being able to
2866                                         // time out the HTLC first.
2867                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2868                                         // concern is being able to claim the corresponding inbound HTLC (on another
2869                                         // channel) before it expires. In fact, we don't even really care if our
2870                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2871                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2872                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2873                                         // we give ourselves a few blocks of headroom after expiration before going
2874                                         // on-chain for an expired HTLC.
2875                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2876                                         // from us until we've reached the point where we go on-chain with the
2877                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2878                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2879                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2880                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2881                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2882                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2883                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2884                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2885                                         //  The final, above, condition is checked for statically in channelmanager
2886                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2887                                         let htlc_outbound = $holder_tx == htlc.offered;
2888                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2889                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2890                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2891                                                 return true;
2892                                         }
2893                                 }
2894                         }
2895                 }
2896
2897                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2898
2899                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2900                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2901                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2902                         }
2903                 }
2904                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2905                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2906                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2907                         }
2908                 }
2909
2910                 false
2911         }
2912
2913         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2914         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2915         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2916                 'outer_loop: for input in &tx.input {
2917                         let mut payment_data = None;
2918                         let witness_items = input.witness.len();
2919                         let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
2920                         let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
2921                         let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
2922                                 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
2923                         let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
2924                                 && input.witness.second_to_last().unwrap().len() == 32;
2925                         #[cfg(not(fuzzing))]
2926                         let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2927                         let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
2928                                 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
2929
2930                         #[cfg(not(fuzzing))]
2931                         let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
2932
2933                         let mut payment_preimage = PaymentPreimage([0; 32]);
2934                         if accepted_preimage_claim {
2935                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2936                         } else if offered_preimage_claim {
2937                                 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2938                         }
2939
2940                         macro_rules! log_claim {
2941                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2942                                         let outbound_htlc = $holder_tx == $htlc.offered;
2943                                         // HTLCs must either be claimed by a matching script type or through the
2944                                         // revocation path:
2945                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2946                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2947                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2948                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2949                                         // Further, only exactly one of the possible spend paths should have been
2950                                         // matched by any HTLC spend:
2951                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2952                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2953                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2954                                                          revocation_sig_claim as u8, 1);
2955                                         if ($holder_tx && revocation_sig_claim) ||
2956                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2957                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2958                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2959                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2960                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2961                                         } else {
2962                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2963                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2964                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2965                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2966                                         }
2967                                 }
2968                         }
2969
2970                         macro_rules! check_htlc_valid_counterparty {
2971                                 ($counterparty_txid: expr, $htlc_output: expr) => {
2972                                         if let Some(txid) = $counterparty_txid {
2973                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2974                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2975                                                                 if let &Some(ref source) = pending_source {
2976                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2977                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2978                                                                         break;
2979                                                                 }
2980                                                         }
2981                                                 }
2982                                         }
2983                                 }
2984                         }
2985
2986                         macro_rules! scan_commitment {
2987                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2988                                         for (ref htlc_output, source_option) in $htlcs {
2989                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2990                                                         if let Some(ref source) = source_option {
2991                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
2992                                                                 // We have a resolution of an HTLC either from one of our latest
2993                                                                 // holder commitment transactions or an unrevoked counterparty commitment
2994                                                                 // transaction. This implies we either learned a preimage, the HTLC
2995                                                                 // has timed out, or we screwed up. In any case, we should now
2996                                                                 // resolve the source HTLC with the original sender.
2997                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2998                                                         } else if !$holder_tx {
2999                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3000                                                                 if payment_data.is_none() {
3001                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3002                                                                 }
3003                                                         }
3004                                                         if payment_data.is_none() {
3005                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
3006                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
3007                                                                 if !outbound_htlc || revocation_sig_claim {
3008                                                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3009                                                                                 txid: tx.txid(), height, transaction: Some(tx.clone()),
3010                                                                                 event: OnchainEvent::HTLCSpendConfirmation {
3011                                                                                         commitment_tx_output_idx: input.previous_output.vout,
3012                                                                                         preimage: if accepted_preimage_claim || offered_preimage_claim {
3013                                                                                                 Some(payment_preimage) } else { None },
3014                                                                                         // If this is a payment to us (!outbound_htlc, above),
3015                                                                                         // wait for the CSV delay before dropping the HTLC from
3016                                                                                         // claimable balance if the claim was an HTLC-Success
3017                                                                                         // transaction.
3018                                                                                         on_to_local_output_csv: if accepted_preimage_claim {
3019                                                                                                 Some(self.on_holder_tx_csv) } else { None },
3020                                                                                 },
3021                                                                         });
3022                                                                 } else {
3023                                                                         // Outbound claims should always have payment_data, unless
3024                                                                         // we've already failed the HTLC as the commitment transaction
3025                                                                         // which was broadcasted was revoked. In that case, we should
3026                                                                         // spend the HTLC output here immediately, and expose that fact
3027                                                                         // as a Balance, something which we do not yet do.
3028                                                                         // TODO: Track the above as claimable!
3029                                                                 }
3030                                                                 continue 'outer_loop;
3031                                                         }
3032                                                 }
3033                                         }
3034                                 }
3035                         }
3036
3037                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3038                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3039                                         "our latest holder commitment tx", true);
3040                         }
3041                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3042                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3043                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3044                                                 "our previous holder commitment tx", true);
3045                                 }
3046                         }
3047                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3048                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3049                                         "counterparty commitment tx", false);
3050                         }
3051
3052                         // Check that scan_commitment, above, decided there is some source worth relaying an
3053                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3054                         if let Some((source, payment_hash, amount_msat)) = payment_data {
3055                                 if accepted_preimage_claim {
3056                                         if !self.pending_monitor_events.iter().any(
3057                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3058                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3059                                                         txid: tx.txid(),
3060                                                         height,
3061                                                         transaction: Some(tx.clone()),
3062                                                         event: OnchainEvent::HTLCSpendConfirmation {
3063                                                                 commitment_tx_output_idx: input.previous_output.vout,
3064                                                                 preimage: Some(payment_preimage),
3065                                                                 on_to_local_output_csv: None,
3066                                                         },
3067                                                 });
3068                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3069                                                         source,
3070                                                         payment_preimage: Some(payment_preimage),
3071                                                         payment_hash,
3072                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3073                                                 }));
3074                                         }
3075                                 } else if offered_preimage_claim {
3076                                         if !self.pending_monitor_events.iter().any(
3077                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3078                                                         upd.source == source
3079                                                 } else { false }) {
3080                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3081                                                         txid: tx.txid(),
3082                                                         transaction: Some(tx.clone()),
3083                                                         height,
3084                                                         event: OnchainEvent::HTLCSpendConfirmation {
3085                                                                 commitment_tx_output_idx: input.previous_output.vout,
3086                                                                 preimage: Some(payment_preimage),
3087                                                                 on_to_local_output_csv: None,
3088                                                         },
3089                                                 });
3090                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3091                                                         source,
3092                                                         payment_preimage: Some(payment_preimage),
3093                                                         payment_hash,
3094                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3095                                                 }));
3096                                         }
3097                                 } else {
3098                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3099                                                 if entry.height != height { return true; }
3100                                                 match entry.event {
3101                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3102                                                                 *htlc_source != source
3103                                                         },
3104                                                         _ => true,
3105                                                 }
3106                                         });
3107                                         let entry = OnchainEventEntry {
3108                                                 txid: tx.txid(),
3109                                                 transaction: Some(tx.clone()),
3110                                                 height,
3111                                                 event: OnchainEvent::HTLCUpdate {
3112                                                         source, payment_hash,
3113                                                         htlc_value_satoshis: Some(amount_msat / 1000),
3114                                                         commitment_tx_output_idx: Some(input.previous_output.vout),
3115                                                 },
3116                                         };
3117                                         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());
3118                                         self.onchain_events_awaiting_threshold_conf.push(entry);
3119                                 }
3120                         }
3121                 }
3122         }
3123
3124         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3125         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3126                 let mut spendable_output = None;
3127                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3128                         if i > ::core::u16::MAX as usize {
3129                                 // While it is possible that an output exists on chain which is greater than the
3130                                 // 2^16th output in a given transaction, this is only possible if the output is not
3131                                 // in a lightning transaction and was instead placed there by some third party who
3132                                 // wishes to give us money for no reason.
3133                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
3134                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3135                                 // scripts are not longer than one byte in length and because they are inherently
3136                                 // non-standard due to their size.
3137                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
3138                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
3139                                 // nearly a full block with garbage just to hit this case.
3140                                 continue;
3141                         }
3142                         if outp.script_pubkey == self.destination_script {
3143                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
3144                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3145                                         output: outp.clone(),
3146                                 });
3147                                 break;
3148                         }
3149                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3150                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3151                                         spendable_output =  Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3152                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3153                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
3154                                                 to_self_delay: self.on_holder_tx_csv,
3155                                                 output: outp.clone(),
3156                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3157                                                 channel_keys_id: self.channel_keys_id,
3158                                                 channel_value_satoshis: self.channel_value_satoshis,
3159                                         }));
3160                                         break;
3161                                 }
3162                         }
3163                         if self.counterparty_payment_script == outp.script_pubkey {
3164                                 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3165                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3166                                         output: outp.clone(),
3167                                         channel_keys_id: self.channel_keys_id,
3168                                         channel_value_satoshis: self.channel_value_satoshis,
3169                                 }));
3170                                 break;
3171                         }
3172                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3173                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3174                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3175                                         output: outp.clone(),
3176                                 });
3177                                 break;
3178                         }
3179                 }
3180                 if let Some(spendable_output) = spendable_output {
3181                         let entry = OnchainEventEntry {
3182                                 txid: tx.txid(),
3183                                 transaction: Some(tx.clone()),
3184                                 height: height,
3185                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3186                         };
3187                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3188                         self.onchain_events_awaiting_threshold_conf.push(entry);
3189                 }
3190         }
3191 }
3192
3193 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3194 where
3195         T::Target: BroadcasterInterface,
3196         F::Target: FeeEstimator,
3197         L::Target: Logger,
3198 {
3199         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3200                 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3201         }
3202
3203         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3204                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3205         }
3206 }
3207
3208 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3209 where
3210         T::Target: BroadcasterInterface,
3211         F::Target: FeeEstimator,
3212         L::Target: Logger,
3213 {
3214         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3215                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3216         }
3217
3218         fn transaction_unconfirmed(&self, txid: &Txid) {
3219                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3220         }
3221
3222         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3223                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3224         }
3225
3226         fn get_relevant_txids(&self) -> Vec<Txid> {
3227                 self.0.get_relevant_txids()
3228         }
3229 }
3230
3231 const MAX_ALLOC_SIZE: usize = 64*1024;
3232
3233 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3234                 for (BlockHash, ChannelMonitor<Signer>) {
3235         fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3236                 macro_rules! unwrap_obj {
3237                         ($key: expr) => {
3238                                 match $key {
3239                                         Ok(res) => res,
3240                                         Err(_) => return Err(DecodeError::InvalidValue),
3241                                 }
3242                         }
3243                 }
3244
3245                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3246
3247                 let latest_update_id: u64 = Readable::read(reader)?;
3248                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3249
3250                 let destination_script = Readable::read(reader)?;
3251                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3252                         0 => {
3253                                 let revokable_address = Readable::read(reader)?;
3254                                 let per_commitment_point = Readable::read(reader)?;
3255                                 let revokable_script = Readable::read(reader)?;
3256                                 Some((revokable_address, per_commitment_point, revokable_script))
3257                         },
3258                         1 => { None },
3259                         _ => return Err(DecodeError::InvalidValue),
3260                 };
3261                 let counterparty_payment_script = Readable::read(reader)?;
3262                 let shutdown_script = {
3263                         let script = <Script as Readable>::read(reader)?;
3264                         if script.is_empty() { None } else { Some(script) }
3265                 };
3266
3267                 let channel_keys_id = Readable::read(reader)?;
3268                 let holder_revocation_basepoint = Readable::read(reader)?;
3269                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3270                 // barely-init'd ChannelMonitors that we can't do anything with.
3271                 let outpoint = OutPoint {
3272                         txid: Readable::read(reader)?,
3273                         index: Readable::read(reader)?,
3274                 };
3275                 let funding_info = (outpoint, Readable::read(reader)?);
3276                 let current_counterparty_commitment_txid = Readable::read(reader)?;
3277                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3278
3279                 let counterparty_commitment_params = Readable::read(reader)?;
3280                 let funding_redeemscript = Readable::read(reader)?;
3281                 let channel_value_satoshis = Readable::read(reader)?;
3282
3283                 let their_cur_per_commitment_points = {
3284                         let first_idx = <U48 as Readable>::read(reader)?.0;
3285                         if first_idx == 0 {
3286                                 None
3287                         } else {
3288                                 let first_point = Readable::read(reader)?;
3289                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3290                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3291                                         Some((first_idx, first_point, None))
3292                                 } else {
3293                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3294                                 }
3295                         }
3296                 };
3297
3298                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3299
3300                 let commitment_secrets = Readable::read(reader)?;
3301
3302                 macro_rules! read_htlc_in_commitment {
3303                         () => {
3304                                 {
3305                                         let offered: bool = Readable::read(reader)?;
3306                                         let amount_msat: u64 = Readable::read(reader)?;
3307                                         let cltv_expiry: u32 = Readable::read(reader)?;
3308                                         let payment_hash: PaymentHash = Readable::read(reader)?;
3309                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
3310
3311                                         HTLCOutputInCommitment {
3312                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3313                                         }
3314                                 }
3315                         }
3316                 }
3317
3318                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3319                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3320                 for _ in 0..counterparty_claimable_outpoints_len {
3321                         let txid: Txid = Readable::read(reader)?;
3322                         let htlcs_count: u64 = Readable::read(reader)?;
3323                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3324                         for _ in 0..htlcs_count {
3325                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3326                         }
3327                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3328                                 return Err(DecodeError::InvalidValue);
3329                         }
3330                 }
3331
3332                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3333                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3334                 for _ in 0..counterparty_commitment_txn_on_chain_len {
3335                         let txid: Txid = Readable::read(reader)?;
3336                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3337                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3338                                 return Err(DecodeError::InvalidValue);
3339                         }
3340                 }
3341
3342                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3343                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3344                 for _ in 0..counterparty_hash_commitment_number_len {
3345                         let payment_hash: PaymentHash = Readable::read(reader)?;
3346                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3347                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3348                                 return Err(DecodeError::InvalidValue);
3349                         }
3350                 }
3351
3352                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3353                         match <u8 as Readable>::read(reader)? {
3354                                 0 => None,
3355                                 1 => {
3356                                         Some(Readable::read(reader)?)
3357                                 },
3358                                 _ => return Err(DecodeError::InvalidValue),
3359                         };
3360                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3361
3362                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3363                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3364
3365                 let payment_preimages_len: u64 = Readable::read(reader)?;
3366                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3367                 for _ in 0..payment_preimages_len {
3368                         let preimage: PaymentPreimage = Readable::read(reader)?;
3369                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3370                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3371                                 return Err(DecodeError::InvalidValue);
3372                         }
3373                 }
3374
3375                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3376                 let mut pending_monitor_events = Some(
3377                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3378                 for _ in 0..pending_monitor_events_len {
3379                         let ev = match <u8 as Readable>::read(reader)? {
3380                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3381                                 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3382                                 _ => return Err(DecodeError::InvalidValue)
3383                         };
3384                         pending_monitor_events.as_mut().unwrap().push(ev);
3385                 }
3386
3387                 let pending_events_len: u64 = Readable::read(reader)?;
3388                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3389                 for _ in 0..pending_events_len {
3390                         if let Some(event) = MaybeReadable::read(reader)? {
3391                                 pending_events.push(event);
3392                         }
3393                 }
3394
3395                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3396
3397                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3398                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3399                 for _ in 0..waiting_threshold_conf_len {
3400                         if let Some(val) = MaybeReadable::read(reader)? {
3401                                 onchain_events_awaiting_threshold_conf.push(val);
3402                         }
3403                 }
3404
3405                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3406                 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>>())));
3407                 for _ in 0..outputs_to_watch_len {
3408                         let txid = Readable::read(reader)?;
3409                         let outputs_len: u64 = Readable::read(reader)?;
3410                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3411                         for _ in 0..outputs_len {
3412                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3413                         }
3414                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3415                                 return Err(DecodeError::InvalidValue);
3416                         }
3417                 }
3418                 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3419
3420                 let lockdown_from_offchain = Readable::read(reader)?;
3421                 let holder_tx_signed = Readable::read(reader)?;
3422
3423                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3424                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3425                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3426                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3427                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3428                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3429                                 return Err(DecodeError::InvalidValue);
3430                         }
3431                 }
3432
3433                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3434                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3435                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3436                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3437                         return Err(DecodeError::InvalidValue);
3438                 }
3439
3440                 let mut funding_spend_confirmed = None;
3441                 let mut htlcs_resolved_on_chain = Some(Vec::new());
3442                 let mut funding_spend_seen = Some(false);
3443                 let mut counterparty_node_id = None;
3444                 let mut confirmed_commitment_tx_counterparty_output = None;
3445                 read_tlv_fields!(reader, {
3446                         (1, funding_spend_confirmed, option),
3447                         (3, htlcs_resolved_on_chain, vec_type),
3448                         (5, pending_monitor_events, vec_type),
3449                         (7, funding_spend_seen, option),
3450                         (9, counterparty_node_id, option),
3451                         (11, confirmed_commitment_tx_counterparty_output, option),
3452                 });
3453
3454                 let mut secp_ctx = Secp256k1::new();
3455                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3456
3457                 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3458                         latest_update_id,
3459                         commitment_transaction_number_obscure_factor,
3460
3461                         destination_script,
3462                         broadcasted_holder_revokable_script,
3463                         counterparty_payment_script,
3464                         shutdown_script,
3465
3466                         channel_keys_id,
3467                         holder_revocation_basepoint,
3468                         funding_info,
3469                         current_counterparty_commitment_txid,
3470                         prev_counterparty_commitment_txid,
3471
3472                         counterparty_commitment_params,
3473                         funding_redeemscript,
3474                         channel_value_satoshis,
3475                         their_cur_per_commitment_points,
3476
3477                         on_holder_tx_csv,
3478
3479                         commitment_secrets,
3480                         counterparty_claimable_outpoints,
3481                         counterparty_commitment_txn_on_chain,
3482                         counterparty_hash_commitment_number,
3483
3484                         prev_holder_signed_commitment_tx,
3485                         current_holder_commitment_tx,
3486                         current_counterparty_commitment_number,
3487                         current_holder_commitment_number,
3488
3489                         payment_preimages,
3490                         pending_monitor_events: pending_monitor_events.unwrap(),
3491                         pending_events,
3492
3493                         onchain_events_awaiting_threshold_conf,
3494                         outputs_to_watch,
3495
3496                         onchain_tx_handler,
3497
3498                         lockdown_from_offchain,
3499                         holder_tx_signed,
3500                         funding_spend_seen: funding_spend_seen.unwrap(),
3501                         funding_spend_confirmed,
3502                         confirmed_commitment_tx_counterparty_output,
3503                         htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3504
3505                         best_block,
3506                         counterparty_node_id,
3507
3508                         secp_ctx,
3509                 })))
3510         }
3511 }
3512
3513 #[cfg(test)]
3514 mod tests {
3515         use bitcoin::blockdata::block::BlockHeader;
3516         use bitcoin::blockdata::script::{Script, Builder};
3517         use bitcoin::blockdata::opcodes;
3518         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3519         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3520         use bitcoin::util::sighash;
3521         use bitcoin::hashes::Hash;
3522         use bitcoin::hashes::sha256::Hash as Sha256;
3523         use bitcoin::hashes::hex::FromHex;
3524         use bitcoin::hash_types::{BlockHash, Txid};
3525         use bitcoin::network::constants::Network;
3526         use bitcoin::secp256k1::{SecretKey,PublicKey};
3527         use bitcoin::secp256k1::Secp256k1;
3528
3529         use hex;
3530
3531         use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3532
3533         use super::ChannelMonitorUpdateStep;
3534         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};
3535         use chain::{BestBlock, Confirm};
3536         use chain::channelmonitor::ChannelMonitor;
3537         use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3538         use chain::transaction::OutPoint;
3539         use chain::keysinterface::InMemorySigner;
3540         use ln::{PaymentPreimage, PaymentHash};
3541         use ln::chan_utils;
3542         use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3543         use ln::channelmanager::PaymentSendFailure;
3544         use ln::features::InitFeatures;
3545         use ln::functional_test_utils::*;
3546         use ln::script::ShutdownScript;
3547         use util::errors::APIError;
3548         use util::events::{ClosureReason, MessageSendEventsProvider};
3549         use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3550         use util::ser::{ReadableArgs, Writeable};
3551         use sync::{Arc, Mutex};
3552         use io;
3553         use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
3554         use prelude::*;
3555
3556         fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3557                 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3558                 // confirmed. This would allow a race condition where we could receive a payment (including
3559                 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3560                 // long as the ChannelMonitor receives the block first, the full commitment update dance
3561                 // occurs after the block is connected, and before the ChannelManager receives the block.
3562                 // Obviously this is an incredibly contrived race given the counterparty would be risking
3563                 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3564                 // potential ChannelMonitor states simpler to reason about.
3565                 //
3566                 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3567                 // updates is handled correctly in such conditions.
3568                 let chanmon_cfgs = create_chanmon_cfgs(3);
3569                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3570                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3571                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3572                 let channel = create_announced_chan_between_nodes(
3573                         &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3574                 create_announced_chan_between_nodes(
3575                         &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3576
3577                 // Rebalance somewhat
3578                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3579
3580                 // First route two payments for testing at the end
3581                 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3582                 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3583
3584                 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3585                 assert_eq!(local_txn.len(), 1);
3586                 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3587                 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3588                 check_spends!(remote_txn[1], remote_txn[0]);
3589                 check_spends!(remote_txn[2], remote_txn[0]);
3590                 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3591
3592                 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3593                 // channel is now closed, but the ChannelManager doesn't know that yet.
3594                 let new_header = BlockHeader {
3595                         version: 2, time: 0, bits: 0, nonce: 0,
3596                         prev_blockhash: nodes[0].best_block_info().0,
3597                         merkle_root: TxMerkleNode::all_zeros() };
3598                 let conf_height = nodes[0].best_block_info().1 + 1;
3599                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3600                         &[(0, broadcast_tx)], conf_height);
3601
3602                 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3603                                                 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3604                                                 &nodes[1].keys_manager.backing).unwrap();
3605
3606                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3607                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3608                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3609                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3610                         true, APIError::ChannelUnavailable { ref err },
3611                         assert!(err.contains("ChannelMonitor storage failure")));
3612                 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3613                 check_closed_broadcast!(nodes[1], true);
3614                 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3615
3616                 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3617                 // and provides the claim preimages for the two pending HTLCs. The first update generates
3618                 // an error, but the point of this test is to ensure the later updates are still applied.
3619                 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3620                 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3621                 assert_eq!(replay_update.updates.len(), 1);
3622                 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3623                 } else { panic!(); }
3624                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3625                 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3626
3627                 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3628                 assert!(
3629                         pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3630                         .is_err());
3631                 // Even though we error'd on the first update, we should still have generated an HTLC claim
3632                 // transaction
3633                 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3634                 assert!(txn_broadcasted.len() >= 2);
3635                 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3636                         assert_eq!(tx.input.len(), 1);
3637                         tx.input[0].previous_output.txid == broadcast_tx.txid()
3638                 }).collect::<Vec<_>>();
3639                 assert_eq!(htlc_txn.len(), 2);
3640                 check_spends!(htlc_txn[0], broadcast_tx);
3641                 check_spends!(htlc_txn[1], broadcast_tx);
3642         }
3643         #[test]
3644         fn test_funding_spend_refuses_updates() {
3645                 do_test_funding_spend_refuses_updates(true);
3646                 do_test_funding_spend_refuses_updates(false);
3647         }
3648
3649         #[test]
3650         fn test_prune_preimages() {
3651                 let secp_ctx = Secp256k1::new();
3652                 let logger = Arc::new(TestLogger::new());
3653                 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3654                 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3655
3656                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3657                 let dummy_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3658
3659                 let mut preimages = Vec::new();
3660                 {
3661                         for i in 0..20 {
3662                                 let preimage = PaymentPreimage([i; 32]);
3663                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3664                                 preimages.push((preimage, hash));
3665                         }
3666                 }
3667
3668                 macro_rules! preimages_slice_to_htlc_outputs {
3669                         ($preimages_slice: expr) => {
3670                                 {
3671                                         let mut res = Vec::new();
3672                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3673                                                 res.push((HTLCOutputInCommitment {
3674                                                         offered: true,
3675                                                         amount_msat: 0,
3676                                                         cltv_expiry: 0,
3677                                                         payment_hash: preimage.1.clone(),
3678                                                         transaction_output_index: Some(idx as u32),
3679                                                 }, None));
3680                                         }
3681                                         res
3682                                 }
3683                         }
3684                 }
3685                 macro_rules! preimages_to_holder_htlcs {
3686                         ($preimages_slice: expr) => {
3687                                 {
3688                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3689                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3690                                         res
3691                                 }
3692                         }
3693                 }
3694
3695                 macro_rules! test_preimages_exist {
3696                         ($preimages_slice: expr, $monitor: expr) => {
3697                                 for preimage in $preimages_slice {
3698                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3699                                 }
3700                         }
3701                 }
3702
3703                 let keys = InMemorySigner::new(
3704                         &secp_ctx,
3705                         SecretKey::from_slice(&[41; 32]).unwrap(),
3706                         SecretKey::from_slice(&[41; 32]).unwrap(),
3707                         SecretKey::from_slice(&[41; 32]).unwrap(),
3708                         SecretKey::from_slice(&[41; 32]).unwrap(),
3709                         SecretKey::from_slice(&[41; 32]).unwrap(),
3710                         SecretKey::from_slice(&[41; 32]).unwrap(),
3711                         [41; 32],
3712                         0,
3713                         [0; 32]
3714                 );
3715
3716                 let counterparty_pubkeys = ChannelPublicKeys {
3717                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3718                         revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3719                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3720                         delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3721                         htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3722                 };
3723                 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
3724                 let channel_parameters = ChannelTransactionParameters {
3725                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3726                         holder_selected_contest_delay: 66,
3727                         is_outbound_from_holder: true,
3728                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3729                                 pubkeys: counterparty_pubkeys,
3730                                 selected_contest_delay: 67,
3731                         }),
3732                         funding_outpoint: Some(funding_outpoint),
3733                         opt_anchors: None,
3734                 };
3735                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3736                 // old state.
3737                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3738                 let best_block = BestBlock::from_genesis(Network::Testnet);
3739                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3740                                                   Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3741                                                   (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3742                                                   &channel_parameters,
3743                                                   Script::new(), 46, 0,
3744                                                   HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3745
3746                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3747                 let dummy_txid = dummy_tx.txid();
3748                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3749                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3750                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3751                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3752                 for &(ref preimage, ref hash) in preimages.iter() {
3753                         let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3754                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3755                 }
3756
3757                 // Now provide a secret, pruning preimages 10-15
3758                 let mut secret = [0; 32];
3759                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3760                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3761                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3762                 test_preimages_exist!(&preimages[0..10], monitor);
3763                 test_preimages_exist!(&preimages[15..20], monitor);
3764
3765                 // Now provide a further secret, pruning preimages 15-17
3766                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3767                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3768                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3769                 test_preimages_exist!(&preimages[0..10], monitor);
3770                 test_preimages_exist!(&preimages[17..20], monitor);
3771
3772                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3773                 // previous commitment tx's preimages too
3774                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3775                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3776                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3777                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3778                 test_preimages_exist!(&preimages[0..10], monitor);
3779                 test_preimages_exist!(&preimages[18..20], monitor);
3780
3781                 // But if we do it again, we'll prune 5-10
3782                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3783                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3784                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3785                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3786                 test_preimages_exist!(&preimages[0..5], monitor);
3787         }
3788
3789         #[test]
3790         fn test_claim_txn_weight_computation() {
3791                 // We test Claim txn weight, knowing that we want expected weigth and
3792                 // not actual case to avoid sigs and time-lock delays hell variances.
3793
3794                 let secp_ctx = Secp256k1::new();
3795                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3796                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3797
3798                 macro_rules! sign_input {
3799                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3800                                 let htlc = HTLCOutputInCommitment {
3801                                         offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3802                                         amount_msat: 0,
3803                                         cltv_expiry: 2 << 16,
3804                                         payment_hash: PaymentHash([1; 32]),
3805                                         transaction_output_index: Some($idx as u32),
3806                                 };
3807                                 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) };
3808                                 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3809                                 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3810                                 let mut ser_sig = sig.serialize_der().to_vec();
3811                                 ser_sig.push(EcdsaSighashType::All as u8);
3812                                 $sum_actual_sigs += ser_sig.len();
3813                                 let witness = $sighash_parts.witness_mut($idx).unwrap();
3814                                 witness.push(ser_sig);
3815                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
3816                                         witness.push(vec!(1));
3817                                 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3818                                         witness.push(pubkey.clone().serialize().to_vec());
3819                                 } else if *$weight == weight_received_htlc($opt_anchors) {
3820                                         witness.push(vec![0]);
3821                                 } else {
3822                                         witness.push(PaymentPreimage([1; 32]).0.to_vec());
3823                                 }
3824                                 witness.push(redeem_script.into_bytes());
3825                                 let witness = witness.to_vec();
3826                                 println!("witness[0] {}", witness[0].len());
3827                                 println!("witness[1] {}", witness[1].len());
3828                                 println!("witness[2] {}", witness[2].len());
3829                         }
3830                 }
3831
3832                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3833                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3834
3835                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3836                 for &opt_anchors in [false, true].iter() {
3837                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3838                         let mut sum_actual_sigs = 0;
3839                         for i in 0..4 {
3840                                 claim_tx.input.push(TxIn {
3841                                         previous_output: BitcoinOutPoint {
3842                                                 txid,
3843                                                 vout: i,
3844                                         },
3845                                         script_sig: Script::new(),
3846                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3847                                         witness: Witness::new(),
3848                                 });
3849                         }
3850                         claim_tx.output.push(TxOut {
3851                                 script_pubkey: script_pubkey.clone(),
3852                                 value: 0,
3853                         });
3854                         let base_weight = claim_tx.weight();
3855                         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)];
3856                         let mut inputs_total_weight = 2; // count segwit flags
3857                         {
3858                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3859                                 for (idx, inp) in inputs_weight.iter().enumerate() {
3860                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3861                                         inputs_total_weight += inp;
3862                                 }
3863                         }
3864                         assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3865                 }
3866
3867                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3868                 for &opt_anchors in [false, true].iter() {
3869                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3870                         let mut sum_actual_sigs = 0;
3871                         for i in 0..4 {
3872                                 claim_tx.input.push(TxIn {
3873                                         previous_output: BitcoinOutPoint {
3874                                                 txid,
3875                                                 vout: i,
3876                                         },
3877                                         script_sig: Script::new(),
3878                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3879                                         witness: Witness::new(),
3880                                 });
3881                         }
3882                         claim_tx.output.push(TxOut {
3883                                 script_pubkey: script_pubkey.clone(),
3884                                 value: 0,
3885                         });
3886                         let base_weight = claim_tx.weight();
3887                         let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
3888                         let mut inputs_total_weight = 2; // count segwit flags
3889                         {
3890                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3891                                 for (idx, inp) in inputs_weight.iter().enumerate() {
3892                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3893                                         inputs_total_weight += inp;
3894                                 }
3895                         }
3896                         assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3897                 }
3898
3899                 // Justice tx with 1 revoked HTLC-Success tx output
3900                 for &opt_anchors in [false, true].iter() {
3901                         let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3902                         let mut sum_actual_sigs = 0;
3903                         claim_tx.input.push(TxIn {
3904                                 previous_output: BitcoinOutPoint {
3905                                         txid,
3906                                         vout: 0,
3907                                 },
3908                                 script_sig: Script::new(),
3909                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3910                                 witness: Witness::new(),
3911                         });
3912                         claim_tx.output.push(TxOut {
3913                                 script_pubkey: script_pubkey.clone(),
3914                                 value: 0,
3915                         });
3916                         let base_weight = claim_tx.weight();
3917                         let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3918                         let mut inputs_total_weight = 2; // count segwit flags
3919                         {
3920                                 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3921                                 for (idx, inp) in inputs_weight.iter().enumerate() {
3922                                         sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3923                                         inputs_total_weight += inp;
3924                                 }
3925                         }
3926                         assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3927                 }
3928         }
3929
3930         // Further testing is done in the ChannelManager integration tests.
3931 }