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