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