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