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