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