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