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