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