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