Continue after a single failure in `ChannelMonitor::update_monitor`
[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                 let mut ret = Ok(());
1890                 for update in updates.updates.iter() {
1891                         match update {
1892                                 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1893                                         log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1894                                         if self.lockdown_from_offchain { panic!(); }
1895                                         if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
1896                                                 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
1897                                                 log_error!(logger, "    {}", e.0);
1898                                                 ret = Err(e);
1899                                         }
1900                                 }
1901                                 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1902                                         log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1903                                         self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1904                                 },
1905                                 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1906                                         log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1907                                         self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1908                                 },
1909                                 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1910                                         log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1911                                         if let Err(e) = self.provide_secret(*idx, *secret) {
1912                                                 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
1913                                                 log_error!(logger, "    {}", e.0);
1914                                                 ret = Err(e);
1915                                         }
1916                                 },
1917                                 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1918                                         log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1919                                         self.lockdown_from_offchain = true;
1920                                         if *should_broadcast {
1921                                                 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1922                                         } else if !self.holder_tx_signed {
1923                                                 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");
1924                                         } else {
1925                                                 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
1926                                                 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1927                                                 // shouldn't print the scary warning above.
1928                                                 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1929                                         }
1930                                 },
1931                                 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
1932                                         log_trace!(logger, "Updating ChannelMonitor with shutdown script");
1933                                         if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
1934                                                 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
1935                                         }
1936                                 },
1937                         }
1938                 }
1939                 self.latest_update_id = updates.update_id;
1940                 ret
1941         }
1942
1943         pub fn get_latest_update_id(&self) -> u64 {
1944                 self.latest_update_id
1945         }
1946
1947         pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1948                 &self.funding_info
1949         }
1950
1951         pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1952                 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1953                 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1954                 // its trivial to do, double-check that here.
1955                 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1956                         self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1957                 }
1958                 &self.outputs_to_watch
1959         }
1960
1961         pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1962                 let mut ret = Vec::new();
1963                 mem::swap(&mut ret, &mut self.pending_monitor_events);
1964                 ret
1965         }
1966
1967         pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1968                 let mut ret = Vec::new();
1969                 mem::swap(&mut ret, &mut self.pending_events);
1970                 ret
1971         }
1972
1973         /// Can only fail if idx is < get_min_seen_secret
1974         fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1975                 self.commitment_secrets.get_secret(idx)
1976         }
1977
1978         pub(crate) fn get_min_seen_secret(&self) -> u64 {
1979                 self.commitment_secrets.get_min_seen_secret()
1980         }
1981
1982         pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1983                 self.current_counterparty_commitment_number
1984         }
1985
1986         pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1987                 self.current_holder_commitment_number
1988         }
1989
1990         /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1991         /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1992         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1993         /// HTLC-Success/HTLC-Timeout transactions.
1994         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1995         /// revoked counterparty commitment tx
1996         fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1997                 // Most secp and related errors trying to create keys means we have no hope of constructing
1998                 // a spend transaction...so we return no transactions to broadcast
1999                 let mut claimable_outpoints = Vec::new();
2000                 let mut watch_outputs = Vec::new();
2001
2002                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2003                 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2004
2005                 macro_rules! ignore_error {
2006                         ( $thing : expr ) => {
2007                                 match $thing {
2008                                         Ok(a) => a,
2009                                         Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
2010                                 }
2011                         };
2012                 }
2013
2014                 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);
2015                 if commitment_number >= self.get_min_seen_secret() {
2016                         let secret = self.get_secret(commitment_number).unwrap();
2017                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2018                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2019                         let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2020                         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));
2021
2022                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2023                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2024
2025                         // First, process non-htlc outputs (to_holder & to_counterparty)
2026                         for (idx, outp) in tx.output.iter().enumerate() {
2027                                 if outp.script_pubkey == revokeable_p2wsh {
2028                                         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);
2029                                         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);
2030                                         claimable_outpoints.push(justice_package);
2031                                 }
2032                         }
2033
2034                         // Then, try to find revoked htlc outputs
2035                         if let Some(ref per_commitment_data) = per_commitment_option {
2036                                 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2037                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2038                                                 if transaction_output_index as usize >= tx.output.len() ||
2039                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2040                                                         return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
2041                                                 }
2042                                                 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());
2043                                                 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2044                                                 claimable_outpoints.push(justice_package);
2045                                         }
2046                                 }
2047                         }
2048
2049                         // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2050                         if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2051                                 // We're definitely a counterparty commitment transaction!
2052                                 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2053                                 for (idx, outp) in tx.output.iter().enumerate() {
2054                                         watch_outputs.push((idx as u32, outp.clone()));
2055                                 }
2056                                 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2057
2058                                 fail_unbroadcast_htlcs!(self, "revoked counterparty", height, [].iter().map(|a| *a), logger);
2059                         }
2060                 } else if let Some(per_commitment_data) = per_commitment_option {
2061                         // While this isn't useful yet, there is a potential race where if a counterparty
2062                         // revokes a state at the same time as the commitment transaction for that state is
2063                         // confirmed, and the watchtower receives the block before the user, the user could
2064                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
2065                         // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2066                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
2067                         // insert it here.
2068                         for (idx, outp) in tx.output.iter().enumerate() {
2069                                 watch_outputs.push((idx as u32, outp.clone()));
2070                         }
2071                         self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2072
2073                         log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2074                         fail_unbroadcast_htlcs!(self, "counterparty", height, per_commitment_data.iter().map(|(a, b)| (a, b.as_ref().map(|b| b.as_ref()))), logger);
2075
2076                         let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
2077                         for req in htlc_claim_reqs {
2078                                 claimable_outpoints.push(req);
2079                         }
2080
2081                 }
2082                 (claimable_outpoints, (commitment_txid, watch_outputs))
2083         }
2084
2085         fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
2086                 let mut claimable_outpoints = Vec::new();
2087                 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
2088                         if let Some(revocation_points) = self.their_cur_revocation_points {
2089                                 let revocation_point_option =
2090                                         // If the counterparty commitment tx is the latest valid state, use their latest
2091                                         // per-commitment point
2092                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
2093                                         else if let Some(point) = revocation_points.2.as_ref() {
2094                                                 // If counterparty commitment tx is the state previous to the latest valid state, use
2095                                                 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2096                                                 // them to temporarily have two valid commitment txns from our viewpoint)
2097                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
2098                                         } else { None };
2099                                 if let Some(revocation_point) = revocation_point_option {
2100                                         for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2101                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
2102                                                         if let Some(transaction) = tx {
2103                                                                 if transaction_output_index as usize >= transaction.output.len() ||
2104                                                                         transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2105                                                                                 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
2106                                                                         }
2107                                                         }
2108                                                         let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2109                                                         if preimage.is_some() || !htlc.offered {
2110                                                                 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())) };
2111                                                                 let aggregation = if !htlc.offered { false } else { true };
2112                                                                 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2113                                                                 claimable_outpoints.push(counterparty_package);
2114                                                         }
2115                                                 }
2116                                         }
2117                                 }
2118                         }
2119                 }
2120                 claimable_outpoints
2121         }
2122
2123         /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2124         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 {
2125                 let htlc_txid = tx.txid();
2126                 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2127                         return (Vec::new(), None)
2128                 }
2129
2130                 macro_rules! ignore_error {
2131                         ( $thing : expr ) => {
2132                                 match $thing {
2133                                         Ok(a) => a,
2134                                         Err(_) => return (Vec::new(), None)
2135                                 }
2136                         };
2137                 }
2138
2139                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2140                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2141                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2142
2143                 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2144                 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);
2145                 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);
2146                 let claimable_outpoints = vec!(justice_package);
2147                 let outputs = vec![(0, tx.output[0].clone())];
2148                 (claimable_outpoints, Some((htlc_txid, outputs)))
2149         }
2150
2151         // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2152         // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2153         // script so we can detect whether a holder transaction has been seen on-chain.
2154         fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2155                 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2156
2157                 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2158                 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2159
2160                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2161                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2162                                 let htlc_output = if htlc.offered {
2163                                                 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2164                                         } else {
2165                                                 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2166                                                         preimage.clone()
2167                                                 } else {
2168                                                         // We can't build an HTLC-Success transaction without the preimage
2169                                                         continue;
2170                                                 };
2171                                                 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2172                                         };
2173                                 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2174                                 claim_requests.push(htlc_package);
2175                         }
2176                 }
2177
2178                 (claim_requests, broadcasted_holder_revokable_script)
2179         }
2180
2181         // Returns holder HTLC outputs to watch and react to in case of spending.
2182         fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2183                 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2184                 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2185                         if let Some(transaction_output_index) = htlc.transaction_output_index {
2186                                 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2187                         }
2188                 }
2189                 watch_outputs
2190         }
2191
2192         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2193         /// revoked using data in holder_claimable_outpoints.
2194         /// Should not be used if check_spend_revoked_transaction succeeds.
2195         /// Returns None unless the transaction is definitely one of our commitment transactions.
2196         fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2197                 let commitment_txid = tx.txid();
2198                 let mut claim_requests = Vec::new();
2199                 let mut watch_outputs = Vec::new();
2200
2201                 macro_rules! append_onchain_update {
2202                         ($updates: expr, $to_watch: expr) => {
2203                                 claim_requests = $updates.0;
2204                                 self.broadcasted_holder_revokable_script = $updates.1;
2205                                 watch_outputs.append(&mut $to_watch);
2206                         }
2207                 }
2208
2209                 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2210                 let mut is_holder_tx = false;
2211
2212                 if self.current_holder_commitment_tx.txid == commitment_txid {
2213                         is_holder_tx = true;
2214                         log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2215                         let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2216                         let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2217                         append_onchain_update!(res, to_watch);
2218                         fail_unbroadcast_htlcs!(self, "latest holder", height, self.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2219                 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2220                         if holder_tx.txid == commitment_txid {
2221                                 is_holder_tx = true;
2222                                 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2223                                 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2224                                 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2225                                 append_onchain_update!(res, to_watch);
2226                                 fail_unbroadcast_htlcs!(self, "previous holder", height, holder_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2227                         }
2228                 }
2229
2230                 if is_holder_tx {
2231                         Some((claim_requests, (commitment_txid, watch_outputs)))
2232                 } else {
2233                         None
2234                 }
2235         }
2236
2237         pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2238                 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2239                 self.holder_tx_signed = true;
2240                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2241                 let txid = commitment_tx.txid();
2242                 let mut holder_transactions = vec![commitment_tx];
2243                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2244                         if let Some(vout) = htlc.0.transaction_output_index {
2245                                 let preimage = if !htlc.0.offered {
2246                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2247                                                 // We can't build an HTLC-Success transaction without the preimage
2248                                                 continue;
2249                                         }
2250                                 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2251                                         // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2252                                         // current locktime requirements on-chain. We will broadcast them in
2253                                         // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2254                                         // Note that we add + 1 as transactions are broadcastable when they can be
2255                                         // confirmed in the next block.
2256                                         continue;
2257                                 } else { None };
2258                                 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2259                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2260                                         holder_transactions.push(htlc_tx);
2261                                 }
2262                         }
2263                 }
2264                 // 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.
2265                 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2266                 holder_transactions
2267         }
2268
2269         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2270         /// Note that this includes possibly-locktimed-in-the-future transactions!
2271         fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2272                 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2273                 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2274                 let txid = commitment_tx.txid();
2275                 let mut holder_transactions = vec![commitment_tx];
2276                 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2277                         if let Some(vout) = htlc.0.transaction_output_index {
2278                                 let preimage = if !htlc.0.offered {
2279                                         if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2280                                                 // We can't build an HTLC-Success transaction without the preimage
2281                                                 continue;
2282                                         }
2283                                 } else { None };
2284                                 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2285                                         &::bitcoin::OutPoint { txid, vout }, &preimage) {
2286                                         holder_transactions.push(htlc_tx);
2287                                 }
2288                         }
2289                 }
2290                 holder_transactions
2291         }
2292
2293         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>
2294                 where B::Target: BroadcasterInterface,
2295                       F::Target: FeeEstimator,
2296                                         L::Target: Logger,
2297         {
2298                 let block_hash = header.block_hash();
2299                 self.best_block = BestBlock::new(block_hash, height);
2300
2301                 self.transactions_confirmed(header, txdata, height, broadcaster, fee_estimator, logger)
2302         }
2303
2304         fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2305                 &mut self,
2306                 header: &BlockHeader,
2307                 height: u32,
2308                 broadcaster: B,
2309                 fee_estimator: F,
2310                 logger: L,
2311         ) -> Vec<TransactionOutputs>
2312         where
2313                 B::Target: BroadcasterInterface,
2314                 F::Target: FeeEstimator,
2315                 L::Target: Logger,
2316         {
2317                 let block_hash = header.block_hash();
2318
2319                 if height > self.best_block.height() {
2320                         self.best_block = BestBlock::new(block_hash, height);
2321                         self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2322                 } else if block_hash != self.best_block.block_hash() {
2323                         self.best_block = BestBlock::new(block_hash, height);
2324                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2325                         self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2326                         Vec::new()
2327                 } else { Vec::new() }
2328         }
2329
2330         fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2331                 &mut self,
2332                 header: &BlockHeader,
2333                 txdata: &TransactionData,
2334                 height: u32,
2335                 broadcaster: B,
2336                 fee_estimator: F,
2337                 logger: L,
2338         ) -> Vec<TransactionOutputs>
2339         where
2340                 B::Target: BroadcasterInterface,
2341                 F::Target: FeeEstimator,
2342                 L::Target: Logger,
2343         {
2344                 let txn_matched = self.filter_block(txdata);
2345                 for tx in &txn_matched {
2346                         let mut output_val = 0;
2347                         for out in tx.output.iter() {
2348                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2349                                 output_val += out.value;
2350                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2351                         }
2352                 }
2353
2354                 let block_hash = header.block_hash();
2355
2356                 let mut watch_outputs = Vec::new();
2357                 let mut claimable_outpoints = Vec::new();
2358                 for tx in &txn_matched {
2359                         if tx.input.len() == 1 {
2360                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2361                                 // commitment transactions and HTLC transactions will all only ever have one input,
2362                                 // which is an easy way to filter out any potential non-matching txn for lazy
2363                                 // filters.
2364                                 let prevout = &tx.input[0].previous_output;
2365                                 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2366                                         let mut balance_spendable_csv = None;
2367                                         log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2368                                                 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2369                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2370                                                 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2371                                                 if !new_outputs.1.is_empty() {
2372                                                         watch_outputs.push(new_outputs);
2373                                                 }
2374                                                 claimable_outpoints.append(&mut new_outpoints);
2375                                                 if new_outpoints.is_empty() {
2376                                                         if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2377                                                                 if !new_outputs.1.is_empty() {
2378                                                                         watch_outputs.push(new_outputs);
2379                                                                 }
2380                                                                 claimable_outpoints.append(&mut new_outpoints);
2381                                                                 balance_spendable_csv = Some(self.on_holder_tx_csv);
2382                                                         }
2383                                                 }
2384                                         }
2385                                         let txid = tx.txid();
2386                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2387                                                 txid,
2388                                                 height: height,
2389                                                 event: OnchainEvent::FundingSpendConfirmation {
2390                                                         on_local_output_csv: balance_spendable_csv,
2391                                                 },
2392                                         });
2393                                 } else {
2394                                         if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2395                                                 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2396                                                 claimable_outpoints.append(&mut new_outpoints);
2397                                                 if let Some(new_outputs) = new_outputs_option {
2398                                                         watch_outputs.push(new_outputs);
2399                                                 }
2400                                         }
2401                                 }
2402                         }
2403                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2404                         // can also be resolved in a few other ways which can have more than one output. Thus,
2405                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2406                         self.is_resolving_htlc_output(&tx, height, &logger);
2407
2408                         self.is_paying_spendable_output(&tx, height, &logger);
2409                 }
2410
2411                 if height > self.best_block.height() {
2412                         self.best_block = BestBlock::new(block_hash, height);
2413                 }
2414
2415                 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2416         }
2417
2418         /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2419         /// `self.best_block` before calling if a new best blockchain tip is available. More
2420         /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2421         /// complexity especially in `OnchainTx::update_claims_view`.
2422         ///
2423         /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2424         /// confirmed at, even if it is not the current best height.
2425         fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2426                 &mut self,
2427                 conf_height: u32,
2428                 txn_matched: Vec<&Transaction>,
2429                 mut watch_outputs: Vec<TransactionOutputs>,
2430                 mut claimable_outpoints: Vec<PackageTemplate>,
2431                 broadcaster: &B,
2432                 fee_estimator: &F,
2433                 logger: &L,
2434         ) -> Vec<TransactionOutputs>
2435         where
2436                 B::Target: BroadcasterInterface,
2437                 F::Target: FeeEstimator,
2438                 L::Target: Logger,
2439         {
2440                 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2441                 debug_assert!(self.best_block.height() >= conf_height);
2442
2443                 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2444                 if should_broadcast {
2445                         let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2446                         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());
2447                         claimable_outpoints.push(commitment_package);
2448                         self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2449                         let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2450                         self.holder_tx_signed = true;
2451                         // Because we're broadcasting a commitment transaction, we should construct the package
2452                         // assuming it gets confirmed in the next block. Sadly, we have code which considers
2453                         // "not yet confirmed" things as discardable, so we cannot do that here.
2454                         let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2455                         let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2456                         if !new_outputs.is_empty() {
2457                                 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2458                         }
2459                         claimable_outpoints.append(&mut new_outpoints);
2460                 }
2461
2462                 // Find which on-chain events have reached their confirmation threshold.
2463                 let onchain_events_awaiting_threshold_conf =
2464                         self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2465                 let mut onchain_events_reaching_threshold_conf = Vec::new();
2466                 for entry in onchain_events_awaiting_threshold_conf {
2467                         if entry.has_reached_confirmation_threshold(&self.best_block) {
2468                                 onchain_events_reaching_threshold_conf.push(entry);
2469                         } else {
2470                                 self.onchain_events_awaiting_threshold_conf.push(entry);
2471                         }
2472                 }
2473
2474                 // Used to check for duplicate HTLC resolutions.
2475                 #[cfg(debug_assertions)]
2476                 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2477                         .iter()
2478                         .filter_map(|entry| match &entry.event {
2479                                 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2480                                 _ => None,
2481                         })
2482                         .collect();
2483                 #[cfg(debug_assertions)]
2484                 let mut matured_htlcs = Vec::new();
2485
2486                 // Produce actionable events from on-chain events having reached their threshold.
2487                 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2488                         match entry.event {
2489                                 OnchainEvent::HTLCUpdate { ref source, payment_hash, onchain_value_satoshis, input_idx } => {
2490                                         // Check for duplicate HTLC resolutions.
2491                                         #[cfg(debug_assertions)]
2492                                         {
2493                                                 debug_assert!(
2494                                                         unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2495                                                         "An unmature HTLC transaction conflicts with a maturing one; failed to \
2496                                                          call either transaction_unconfirmed for the conflicting transaction \
2497                                                          or block_disconnected for a block containing it.");
2498                                                 debug_assert!(
2499                                                         matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2500                                                         "A matured HTLC transaction conflicts with a maturing one; failed to \
2501                                                          call either transaction_unconfirmed for the conflicting transaction \
2502                                                          or block_disconnected for a block containing it.");
2503                                                 matured_htlcs.push(source.clone());
2504                                         }
2505
2506                                         log_debug!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!(payment_hash.0));
2507                                         self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2508                                                 payment_hash,
2509                                                 payment_preimage: None,
2510                                                 source: source.clone(),
2511                                                 onchain_value_satoshis,
2512                                         }));
2513                                         if let Some(idx) = input_idx {
2514                                                 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx: idx, payment_preimage: None });
2515                                         }
2516                                 },
2517                                 OnchainEvent::MaturingOutput { descriptor } => {
2518                                         log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2519                                         self.pending_events.push(Event::SpendableOutputs {
2520                                                 outputs: vec![descriptor]
2521                                         });
2522                                 },
2523                                 OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } => {
2524                                         self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx, payment_preimage: preimage });
2525                                 },
2526                                 OnchainEvent::FundingSpendConfirmation { .. } => {
2527                                         self.funding_spend_confirmed = Some(entry.txid);
2528                                 },
2529                         }
2530                 }
2531
2532                 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2533
2534                 // Determine new outputs to watch by comparing against previously known outputs to watch,
2535                 // updating the latter in the process.
2536                 watch_outputs.retain(|&(ref txid, ref txouts)| {
2537                         let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2538                         self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2539                 });
2540                 #[cfg(test)]
2541                 {
2542                         // If we see a transaction for which we registered outputs previously,
2543                         // make sure the registered scriptpubkey at the expected index match
2544                         // the actual transaction output one. We failed this case before #653.
2545                         for tx in &txn_matched {
2546                                 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2547                                         for idx_and_script in outputs.iter() {
2548                                                 assert!((idx_and_script.0 as usize) < tx.output.len());
2549                                                 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2550                                         }
2551                                 }
2552                         }
2553                 }
2554                 watch_outputs
2555         }
2556
2557         pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2558                 where B::Target: BroadcasterInterface,
2559                       F::Target: FeeEstimator,
2560                       L::Target: Logger,
2561         {
2562                 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2563
2564                 //We may discard:
2565                 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2566                 //- maturing spendable output has transaction paying us has been disconnected
2567                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2568
2569                 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2570
2571                 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2572         }
2573
2574         fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2575                 &mut self,
2576                 txid: &Txid,
2577                 broadcaster: B,
2578                 fee_estimator: F,
2579                 logger: L,
2580         ) where
2581                 B::Target: BroadcasterInterface,
2582                 F::Target: FeeEstimator,
2583                 L::Target: Logger,
2584         {
2585                 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.txid != *txid);
2586                 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2587         }
2588
2589         /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2590         /// transactions thereof.
2591         fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2592                 let mut matched_txn = HashSet::new();
2593                 txdata.iter().filter(|&&(_, tx)| {
2594                         let mut matches = self.spends_watched_output(tx);
2595                         for input in tx.input.iter() {
2596                                 if matches { break; }
2597                                 if matched_txn.contains(&input.previous_output.txid) {
2598                                         matches = true;
2599                                 }
2600                         }
2601                         if matches {
2602                                 matched_txn.insert(tx.txid());
2603                         }
2604                         matches
2605                 }).map(|(_, tx)| *tx).collect()
2606         }
2607
2608         /// Checks if a given transaction spends any watched outputs.
2609         fn spends_watched_output(&self, tx: &Transaction) -> bool {
2610                 for input in tx.input.iter() {
2611                         if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2612                                 for (idx, _script_pubkey) in outputs.iter() {
2613                                         if *idx == input.previous_output.vout {
2614                                                 #[cfg(test)]
2615                                                 {
2616                                                         // If the expected script is a known type, check that the witness
2617                                                         // appears to be spending the correct type (ie that the match would
2618                                                         // actually succeed in BIP 158/159-style filters).
2619                                                         if _script_pubkey.is_v0_p2wsh() {
2620                                                                 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2621                                                         } else if _script_pubkey.is_v0_p2wpkh() {
2622                                                                 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2623                                                         } else { panic!(); }
2624                                                 }
2625                                                 return true;
2626                                         }
2627                                 }
2628                         }
2629                 }
2630
2631                 false
2632         }
2633
2634         fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2635                 // We need to consider all HTLCs which are:
2636                 //  * in any unrevoked counterparty commitment transaction, as they could broadcast said
2637                 //    transactions and we'd end up in a race, or
2638                 //  * are in our latest holder commitment transaction, as this is the thing we will
2639                 //    broadcast if we go on-chain.
2640                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2641                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2642                 // to the source, and if we don't fail the channel we will have to ensure that the next
2643                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2644                 // easier to just fail the channel as this case should be rare enough anyway.
2645                 let height = self.best_block.height();
2646                 macro_rules! scan_commitment {
2647                         ($htlcs: expr, $holder_tx: expr) => {
2648                                 for ref htlc in $htlcs {
2649                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2650                                         // chain with enough room to claim the HTLC without our counterparty being able to
2651                                         // time out the HTLC first.
2652                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2653                                         // concern is being able to claim the corresponding inbound HTLC (on another
2654                                         // channel) before it expires. In fact, we don't even really care if our
2655                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2656                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2657                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2658                                         // we give ourselves a few blocks of headroom after expiration before going
2659                                         // on-chain for an expired HTLC.
2660                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2661                                         // from us until we've reached the point where we go on-chain with the
2662                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2663                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2664                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2665                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2666                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2667                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2668                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2669                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2670                                         //  The final, above, condition is checked for statically in channelmanager
2671                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2672                                         let htlc_outbound = $holder_tx == htlc.offered;
2673                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2674                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2675                                                 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2676                                                 return true;
2677                                         }
2678                                 }
2679                         }
2680                 }
2681
2682                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2683
2684                 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2685                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2686                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2687                         }
2688                 }
2689                 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2690                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2691                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2692                         }
2693                 }
2694
2695                 false
2696         }
2697
2698         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2699         /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2700         fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2701                 'outer_loop: for input in &tx.input {
2702                         let mut payment_data = None;
2703                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2704                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2705                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2706                         #[cfg(not(fuzzing))]
2707                         let accepted_timeout_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2708                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && !revocation_sig_claim;
2709                         #[cfg(not(fuzzing))]
2710                         let offered_timeout_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::OfferedHTLC);
2711
2712                         let mut payment_preimage = PaymentPreimage([0; 32]);
2713                         if accepted_preimage_claim {
2714                                 payment_preimage.0.copy_from_slice(&input.witness[3]);
2715                         } else if offered_preimage_claim {
2716                                 payment_preimage.0.copy_from_slice(&input.witness[1]);
2717                         }
2718
2719                         macro_rules! log_claim {
2720                                 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2721                                         let outbound_htlc = $holder_tx == $htlc.offered;
2722                                         // HTLCs must either be claimed by a matching script type or through the
2723                                         // revocation path:
2724                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2725                                         debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2726                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2727                                         debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2728                                         // Further, only exactly one of the possible spend paths should have been
2729                                         // matched by any HTLC spend:
2730                                         #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2731                                         debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2732                                                          offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2733                                                          revocation_sig_claim as u8, 1);
2734                                         if ($holder_tx && revocation_sig_claim) ||
2735                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2736                                                 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2737                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2738                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2739                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2740                                         } else {
2741                                                 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2742                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2743                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2744                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2745                                         }
2746                                 }
2747                         }
2748
2749                         macro_rules! check_htlc_valid_counterparty {
2750                                 ($counterparty_txid: expr, $htlc_output: expr) => {
2751                                         if let Some(txid) = $counterparty_txid {
2752                                                 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2753                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2754                                                                 if let &Some(ref source) = pending_source {
2755                                                                         log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2756                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2757                                                                         break;
2758                                                                 }
2759                                                         }
2760                                                 }
2761                                         }
2762                                 }
2763                         }
2764
2765                         macro_rules! scan_commitment {
2766                                 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2767                                         for (ref htlc_output, source_option) in $htlcs {
2768                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2769                                                         if let Some(ref source) = source_option {
2770                                                                 log_claim!($tx_info, $holder_tx, htlc_output, true);
2771                                                                 // We have a resolution of an HTLC either from one of our latest
2772                                                                 // holder commitment transactions or an unrevoked counterparty commitment
2773                                                                 // transaction. This implies we either learned a preimage, the HTLC
2774                                                                 // has timed out, or we screwed up. In any case, we should now
2775                                                                 // resolve the source HTLC with the original sender.
2776                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2777                                                         } else if !$holder_tx {
2778                                                                 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2779                                                                 if payment_data.is_none() {
2780                                                                         check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2781                                                                 }
2782                                                         }
2783                                                         if payment_data.is_none() {
2784                                                                 log_claim!($tx_info, $holder_tx, htlc_output, false);
2785                                                                 let outbound_htlc = $holder_tx == htlc_output.offered;
2786                                                                 if !outbound_htlc || revocation_sig_claim {
2787                                                                         self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2788                                                                                 txid: tx.txid(), height,
2789                                                                                 event: OnchainEvent::HTLCSpendConfirmation {
2790                                                                                         input_idx: input.previous_output.vout,
2791                                                                                         preimage: if accepted_preimage_claim || offered_preimage_claim {
2792                                                                                                 Some(payment_preimage) } else { None },
2793                                                                                         // If this is a payment to us (!outbound_htlc, above),
2794                                                                                         // wait for the CSV delay before dropping the HTLC from
2795                                                                                         // claimable balance if the claim was an HTLC-Success
2796                                                                                         // transaction.
2797                                                                                         on_to_local_output_csv: if accepted_preimage_claim {
2798                                                                                                 Some(self.on_holder_tx_csv) } else { None },
2799                                                                                 },
2800                                                                         });
2801                                                                 } else {
2802                                                                         // Outbound claims should always have payment_data, unless
2803                                                                         // we've already failed the HTLC as the commitment transaction
2804                                                                         // which was broadcasted was revoked. In that case, we should
2805                                                                         // spend the HTLC output here immediately, and expose that fact
2806                                                                         // as a Balance, something which we do not yet do.
2807                                                                         // TODO: Track the above as claimable!
2808                                                                 }
2809                                                                 continue 'outer_loop;
2810                                                         }
2811                                                 }
2812                                         }
2813                                 }
2814                         }
2815
2816                         if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2817                                 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2818                                         "our latest holder commitment tx", true);
2819                         }
2820                         if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2821                                 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2822                                         scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2823                                                 "our previous holder commitment tx", true);
2824                                 }
2825                         }
2826                         if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2827                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2828                                         "counterparty commitment tx", false);
2829                         }
2830
2831                         // Check that scan_commitment, above, decided there is some source worth relaying an
2832                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2833                         if let Some((source, payment_hash, amount_msat)) = payment_data {
2834                                 if accepted_preimage_claim {
2835                                         if !self.pending_monitor_events.iter().any(
2836                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2837                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2838                                                         txid: tx.txid(),
2839                                                         height,
2840                                                         event: OnchainEvent::HTLCSpendConfirmation {
2841                                                                 input_idx: input.previous_output.vout,
2842                                                                 preimage: Some(payment_preimage),
2843                                                                 on_to_local_output_csv: None,
2844                                                         },
2845                                                 });
2846                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2847                                                         source,
2848                                                         payment_preimage: Some(payment_preimage),
2849                                                         payment_hash,
2850                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2851                                                 }));
2852                                         }
2853                                 } else if offered_preimage_claim {
2854                                         if !self.pending_monitor_events.iter().any(
2855                                                 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2856                                                         upd.source == source
2857                                                 } else { false }) {
2858                                                 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2859                                                         txid: tx.txid(),
2860                                                         height,
2861                                                         event: OnchainEvent::HTLCSpendConfirmation {
2862                                                                 input_idx: input.previous_output.vout,
2863                                                                 preimage: Some(payment_preimage),
2864                                                                 on_to_local_output_csv: None,
2865                                                         },
2866                                                 });
2867                                                 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2868                                                         source,
2869                                                         payment_preimage: Some(payment_preimage),
2870                                                         payment_hash,
2871                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2872                                                 }));
2873                                         }
2874                                 } else {
2875                                         self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2876                                                 if entry.height != height { return true; }
2877                                                 match entry.event {
2878                                                         OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
2879                                                                 *htlc_source != source
2880                                                         },
2881                                                         _ => true,
2882                                                 }
2883                                         });
2884                                         let entry = OnchainEventEntry {
2885                                                 txid: tx.txid(),
2886                                                 height,
2887                                                 event: OnchainEvent::HTLCUpdate {
2888                                                         source, payment_hash,
2889                                                         onchain_value_satoshis: Some(amount_msat / 1000),
2890                                                         input_idx: Some(input.previous_output.vout),
2891                                                 },
2892                                         };
2893                                         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());
2894                                         self.onchain_events_awaiting_threshold_conf.push(entry);
2895                                 }
2896                         }
2897                 }
2898         }
2899
2900         /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2901         fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2902                 let mut spendable_output = None;
2903                 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2904                         if i > ::core::u16::MAX as usize {
2905                                 // While it is possible that an output exists on chain which is greater than the
2906                                 // 2^16th output in a given transaction, this is only possible if the output is not
2907                                 // in a lightning transaction and was instead placed there by some third party who
2908                                 // wishes to give us money for no reason.
2909                                 // Namely, any lightning transactions which we pre-sign will never have anywhere
2910                                 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2911                                 // scripts are not longer than one byte in length and because they are inherently
2912                                 // non-standard due to their size.
2913                                 // Thus, it is completely safe to ignore such outputs, and while it may result in
2914                                 // us ignoring non-lightning fund to us, that is only possible if someone fills
2915                                 // nearly a full block with garbage just to hit this case.
2916                                 continue;
2917                         }
2918                         if outp.script_pubkey == self.destination_script {
2919                                 spendable_output =  Some(SpendableOutputDescriptor::StaticOutput {
2920                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2921                                         output: outp.clone(),
2922                                 });
2923                                 break;
2924                         }
2925                         if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2926                                 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2927                                         spendable_output =  Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2928                                                 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2929                                                 per_commitment_point: broadcasted_holder_revokable_script.1,
2930                                                 to_self_delay: self.on_holder_tx_csv,
2931                                                 output: outp.clone(),
2932                                                 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2933                                                 channel_keys_id: self.channel_keys_id,
2934                                                 channel_value_satoshis: self.channel_value_satoshis,
2935                                         }));
2936                                         break;
2937                                 }
2938                         }
2939                         if self.counterparty_payment_script == outp.script_pubkey {
2940                                 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2941                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2942                                         output: outp.clone(),
2943                                         channel_keys_id: self.channel_keys_id,
2944                                         channel_value_satoshis: self.channel_value_satoshis,
2945                                 }));
2946                                 break;
2947                         }
2948                         if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
2949                                 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2950                                         outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2951                                         output: outp.clone(),
2952                                 });
2953                                 break;
2954                         }
2955                 }
2956                 if let Some(spendable_output) = spendable_output {
2957                         let entry = OnchainEventEntry {
2958                                 txid: tx.txid(),
2959                                 height: height,
2960                                 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2961                         };
2962                         log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2963                         self.onchain_events_awaiting_threshold_conf.push(entry);
2964                 }
2965         }
2966 }
2967
2968 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2969 where
2970         T::Target: BroadcasterInterface,
2971         F::Target: FeeEstimator,
2972         L::Target: Logger,
2973 {
2974         fn block_connected(&self, block: &Block, height: u32) {
2975                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2976                 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2977         }
2978
2979         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2980                 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2981         }
2982 }
2983
2984 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
2985 where
2986         T::Target: BroadcasterInterface,
2987         F::Target: FeeEstimator,
2988         L::Target: Logger,
2989 {
2990         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
2991                 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
2992         }
2993
2994         fn transaction_unconfirmed(&self, txid: &Txid) {
2995                 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
2996         }
2997
2998         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
2999                 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3000         }
3001
3002         fn get_relevant_txids(&self) -> Vec<Txid> {
3003                 self.0.get_relevant_txids()
3004         }
3005 }
3006
3007 const MAX_ALLOC_SIZE: usize = 64*1024;
3008
3009 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3010                 for (BlockHash, ChannelMonitor<Signer>) {
3011         fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3012                 macro_rules! unwrap_obj {
3013                         ($key: expr) => {
3014                                 match $key {
3015                                         Ok(res) => res,
3016                                         Err(_) => return Err(DecodeError::InvalidValue),
3017                                 }
3018                         }
3019                 }
3020
3021                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3022
3023                 let latest_update_id: u64 = Readable::read(reader)?;
3024                 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3025
3026                 let destination_script = Readable::read(reader)?;
3027                 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3028                         0 => {
3029                                 let revokable_address = Readable::read(reader)?;
3030                                 let per_commitment_point = Readable::read(reader)?;
3031                                 let revokable_script = Readable::read(reader)?;
3032                                 Some((revokable_address, per_commitment_point, revokable_script))
3033                         },
3034                         1 => { None },
3035                         _ => return Err(DecodeError::InvalidValue),
3036                 };
3037                 let counterparty_payment_script = Readable::read(reader)?;
3038                 let shutdown_script = {
3039                         let script = <Script as Readable>::read(reader)?;
3040                         if script.is_empty() { None } else { Some(script) }
3041                 };
3042
3043                 let channel_keys_id = Readable::read(reader)?;
3044                 let holder_revocation_basepoint = Readable::read(reader)?;
3045                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3046                 // barely-init'd ChannelMonitors that we can't do anything with.
3047                 let outpoint = OutPoint {
3048                         txid: Readable::read(reader)?,
3049                         index: Readable::read(reader)?,
3050                 };
3051                 let funding_info = (outpoint, Readable::read(reader)?);
3052                 let current_counterparty_commitment_txid = Readable::read(reader)?;
3053                 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3054
3055                 let counterparty_commitment_params = Readable::read(reader)?;
3056                 let funding_redeemscript = Readable::read(reader)?;
3057                 let channel_value_satoshis = Readable::read(reader)?;
3058
3059                 let their_cur_revocation_points = {
3060                         let first_idx = <U48 as Readable>::read(reader)?.0;
3061                         if first_idx == 0 {
3062                                 None
3063                         } else {
3064                                 let first_point = Readable::read(reader)?;
3065                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3066                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3067                                         Some((first_idx, first_point, None))
3068                                 } else {
3069                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3070                                 }
3071                         }
3072                 };
3073
3074                 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3075
3076                 let commitment_secrets = Readable::read(reader)?;
3077
3078                 macro_rules! read_htlc_in_commitment {
3079                         () => {
3080                                 {
3081                                         let offered: bool = Readable::read(reader)?;
3082                                         let amount_msat: u64 = Readable::read(reader)?;
3083                                         let cltv_expiry: u32 = Readable::read(reader)?;
3084                                         let payment_hash: PaymentHash = Readable::read(reader)?;
3085                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
3086
3087                                         HTLCOutputInCommitment {
3088                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3089                                         }
3090                                 }
3091                         }
3092                 }
3093
3094                 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3095                 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3096                 for _ in 0..counterparty_claimable_outpoints_len {
3097                         let txid: Txid = Readable::read(reader)?;
3098                         let htlcs_count: u64 = Readable::read(reader)?;
3099                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3100                         for _ in 0..htlcs_count {
3101                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3102                         }
3103                         if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3104                                 return Err(DecodeError::InvalidValue);
3105                         }
3106                 }
3107
3108                 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3109                 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3110                 for _ in 0..counterparty_commitment_txn_on_chain_len {
3111                         let txid: Txid = Readable::read(reader)?;
3112                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3113                         if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3114                                 return Err(DecodeError::InvalidValue);
3115                         }
3116                 }
3117
3118                 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3119                 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3120                 for _ in 0..counterparty_hash_commitment_number_len {
3121                         let payment_hash: PaymentHash = Readable::read(reader)?;
3122                         let commitment_number = <U48 as Readable>::read(reader)?.0;
3123                         if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3124                                 return Err(DecodeError::InvalidValue);
3125                         }
3126                 }
3127
3128                 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3129                         match <u8 as Readable>::read(reader)? {
3130                                 0 => None,
3131                                 1 => {
3132                                         Some(Readable::read(reader)?)
3133                                 },
3134                                 _ => return Err(DecodeError::InvalidValue),
3135                         };
3136                 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3137
3138                 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3139                 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3140
3141                 let payment_preimages_len: u64 = Readable::read(reader)?;
3142                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3143                 for _ in 0..payment_preimages_len {
3144                         let preimage: PaymentPreimage = Readable::read(reader)?;
3145                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3146                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3147                                 return Err(DecodeError::InvalidValue);
3148                         }
3149                 }
3150
3151                 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3152                 let mut pending_monitor_events = Some(
3153                         Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3154                 for _ in 0..pending_monitor_events_len {
3155                         let ev = match <u8 as Readable>::read(reader)? {
3156                                 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3157                                 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3158                                 _ => return Err(DecodeError::InvalidValue)
3159                         };
3160                         pending_monitor_events.as_mut().unwrap().push(ev);
3161                 }
3162
3163                 let pending_events_len: u64 = Readable::read(reader)?;
3164                 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3165                 for _ in 0..pending_events_len {
3166                         if let Some(event) = MaybeReadable::read(reader)? {
3167                                 pending_events.push(event);
3168                         }
3169                 }
3170
3171                 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3172
3173                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3174                 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3175                 for _ in 0..waiting_threshold_conf_len {
3176                         if let Some(val) = MaybeReadable::read(reader)? {
3177                                 onchain_events_awaiting_threshold_conf.push(val);
3178                         }
3179                 }
3180
3181                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3182                 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>>())));
3183                 for _ in 0..outputs_to_watch_len {
3184                         let txid = Readable::read(reader)?;
3185                         let outputs_len: u64 = Readable::read(reader)?;
3186                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3187                         for _ in 0..outputs_len {
3188                                 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3189                         }
3190                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3191                                 return Err(DecodeError::InvalidValue);
3192                         }
3193                 }
3194                 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3195
3196                 let lockdown_from_offchain = Readable::read(reader)?;
3197                 let holder_tx_signed = Readable::read(reader)?;
3198
3199                 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3200                         let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3201                         if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3202                         if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3203                                 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3204                         } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3205                                 return Err(DecodeError::InvalidValue);
3206                         }
3207                 }
3208
3209                 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3210                 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3211                         current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3212                 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3213                         return Err(DecodeError::InvalidValue);
3214                 }
3215
3216                 let mut funding_spend_confirmed = None;
3217                 let mut htlcs_resolved_on_chain = Some(Vec::new());
3218                 read_tlv_fields!(reader, {
3219                         (1, funding_spend_confirmed, option),
3220                         (3, htlcs_resolved_on_chain, vec_type),
3221                         (5, pending_monitor_events, vec_type),
3222                 });
3223
3224                 let mut secp_ctx = Secp256k1::new();
3225                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3226
3227                 Ok((best_block.block_hash(), ChannelMonitor {
3228                         inner: Mutex::new(ChannelMonitorImpl {
3229                                 latest_update_id,
3230                                 commitment_transaction_number_obscure_factor,
3231
3232                                 destination_script,
3233                                 broadcasted_holder_revokable_script,
3234                                 counterparty_payment_script,
3235                                 shutdown_script,
3236
3237                                 channel_keys_id,
3238                                 holder_revocation_basepoint,
3239                                 funding_info,
3240                                 current_counterparty_commitment_txid,
3241                                 prev_counterparty_commitment_txid,
3242
3243                                 counterparty_commitment_params,
3244                                 funding_redeemscript,
3245                                 channel_value_satoshis,
3246                                 their_cur_revocation_points,
3247
3248                                 on_holder_tx_csv,
3249
3250                                 commitment_secrets,
3251                                 counterparty_claimable_outpoints,
3252                                 counterparty_commitment_txn_on_chain,
3253                                 counterparty_hash_commitment_number,
3254
3255                                 prev_holder_signed_commitment_tx,
3256                                 current_holder_commitment_tx,
3257                                 current_counterparty_commitment_number,
3258                                 current_holder_commitment_number,
3259
3260                                 payment_preimages,
3261                                 pending_monitor_events: pending_monitor_events.unwrap(),
3262                                 pending_events,
3263
3264                                 onchain_events_awaiting_threshold_conf,
3265                                 outputs_to_watch,
3266
3267                                 onchain_tx_handler,
3268
3269                                 lockdown_from_offchain,
3270                                 holder_tx_signed,
3271                                 funding_spend_confirmed,
3272                                 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3273
3274                                 best_block,
3275
3276                                 secp_ctx,
3277                         }),
3278                 }))
3279         }
3280 }
3281
3282 #[cfg(test)]
3283 mod tests {
3284         use bitcoin::blockdata::script::{Script, Builder};
3285         use bitcoin::blockdata::opcodes;
3286         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3287         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3288         use bitcoin::util::bip143;
3289         use bitcoin::hashes::Hash;
3290         use bitcoin::hashes::sha256::Hash as Sha256;
3291         use bitcoin::hashes::hex::FromHex;
3292         use bitcoin::hash_types::Txid;
3293         use bitcoin::network::constants::Network;
3294         use hex;
3295         use chain::BestBlock;
3296         use chain::channelmonitor::ChannelMonitor;
3297         use chain::package::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
3298         use chain::transaction::OutPoint;
3299         use ln::{PaymentPreimage, PaymentHash};
3300         use ln::chan_utils;
3301         use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3302         use ln::script::ShutdownScript;
3303         use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3304         use bitcoin::secp256k1::key::{SecretKey,PublicKey};
3305         use bitcoin::secp256k1::Secp256k1;
3306         use sync::{Arc, Mutex};
3307         use chain::keysinterface::InMemorySigner;
3308         use prelude::*;
3309
3310         #[test]
3311         fn test_prune_preimages() {
3312                 let secp_ctx = Secp256k1::new();
3313                 let logger = Arc::new(TestLogger::new());
3314                 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3315                 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: Mutex::new(253) });
3316
3317                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3318                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3319
3320                 let mut preimages = Vec::new();
3321                 {
3322                         for i in 0..20 {
3323                                 let preimage = PaymentPreimage([i; 32]);
3324                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3325                                 preimages.push((preimage, hash));
3326                         }
3327                 }
3328
3329                 macro_rules! preimages_slice_to_htlc_outputs {
3330                         ($preimages_slice: expr) => {
3331                                 {
3332                                         let mut res = Vec::new();
3333                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3334                                                 res.push((HTLCOutputInCommitment {
3335                                                         offered: true,
3336                                                         amount_msat: 0,
3337                                                         cltv_expiry: 0,
3338                                                         payment_hash: preimage.1.clone(),
3339                                                         transaction_output_index: Some(idx as u32),
3340                                                 }, None));
3341                                         }
3342                                         res
3343                                 }
3344                         }
3345                 }
3346                 macro_rules! preimages_to_holder_htlcs {
3347                         ($preimages_slice: expr) => {
3348                                 {
3349                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3350                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3351                                         res
3352                                 }
3353                         }
3354                 }
3355
3356                 macro_rules! test_preimages_exist {
3357                         ($preimages_slice: expr, $monitor: expr) => {
3358                                 for preimage in $preimages_slice {
3359                                         assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3360                                 }
3361                         }
3362                 }
3363
3364                 let keys = InMemorySigner::new(
3365                         &secp_ctx,
3366                         SecretKey::from_slice(&[41; 32]).unwrap(),
3367                         SecretKey::from_slice(&[41; 32]).unwrap(),
3368                         SecretKey::from_slice(&[41; 32]).unwrap(),
3369                         SecretKey::from_slice(&[41; 32]).unwrap(),
3370                         SecretKey::from_slice(&[41; 32]).unwrap(),
3371                         [41; 32],
3372                         0,
3373                         [0; 32]
3374                 );
3375
3376                 let counterparty_pubkeys = ChannelPublicKeys {
3377                         funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3378                         revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3379                         payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3380                         delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3381                         htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3382                 };
3383                 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
3384                 let channel_parameters = ChannelTransactionParameters {
3385                         holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3386                         holder_selected_contest_delay: 66,
3387                         is_outbound_from_holder: true,
3388                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3389                                 pubkeys: counterparty_pubkeys,
3390                                 selected_contest_delay: 67,
3391                         }),
3392                         funding_outpoint: Some(funding_outpoint),
3393                         opt_anchors: None,
3394                 };
3395                 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3396                 // old state.
3397                 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3398                 let best_block = BestBlock::from_genesis(Network::Testnet);
3399                 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3400                                                   Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3401                                                   (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3402                                                   &channel_parameters,
3403                                                   Script::new(), 46, 0,
3404                                                   HolderCommitmentTransaction::dummy(), best_block);
3405
3406                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3407                 let dummy_txid = dummy_tx.txid();
3408                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3409                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3410                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3411                 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3412                 for &(ref preimage, ref hash) in preimages.iter() {
3413                         monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
3414                 }
3415
3416                 // Now provide a secret, pruning preimages 10-15
3417                 let mut secret = [0; 32];
3418                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3419                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3420                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3421                 test_preimages_exist!(&preimages[0..10], monitor);
3422                 test_preimages_exist!(&preimages[15..20], monitor);
3423
3424                 // Now provide a further secret, pruning preimages 15-17
3425                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3426                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3427                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3428                 test_preimages_exist!(&preimages[0..10], monitor);
3429                 test_preimages_exist!(&preimages[17..20], monitor);
3430
3431                 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3432                 // previous commitment tx's preimages too
3433                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3434                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3435                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3436                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3437                 test_preimages_exist!(&preimages[0..10], monitor);
3438                 test_preimages_exist!(&preimages[18..20], monitor);
3439
3440                 // But if we do it again, we'll prune 5-10
3441                 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3442                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3443                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3444                 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3445                 test_preimages_exist!(&preimages[0..5], monitor);
3446         }
3447
3448         #[test]
3449         fn test_claim_txn_weight_computation() {
3450                 // We test Claim txn weight, knowing that we want expected weigth and
3451                 // not actual case to avoid sigs and time-lock delays hell variances.
3452
3453                 let secp_ctx = Secp256k1::new();
3454                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3455                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3456                 let mut sum_actual_sigs = 0;
3457
3458                 macro_rules! sign_input {
3459                         ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3460                                 let htlc = HTLCOutputInCommitment {
3461                                         offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
3462                                         amount_msat: 0,
3463                                         cltv_expiry: 2 << 16,
3464                                         payment_hash: PaymentHash([1; 32]),
3465                                         transaction_output_index: Some($idx as u32),
3466                                 };
3467                                 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &pubkey, &pubkey, &pubkey) };
3468                                 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3469                                 let sig = secp_ctx.sign(&sighash, &privkey);
3470                                 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3471                                 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3472                                 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3473                                 if *$weight == WEIGHT_REVOKED_OUTPUT {
3474                                         $sighash_parts.access_witness($idx).push(vec!(1));
3475                                 } else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
3476                                         $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3477                                 } else if *$weight == WEIGHT_RECEIVED_HTLC {
3478                                         $sighash_parts.access_witness($idx).push(vec![0]);
3479                                 } else {
3480                                         $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3481                                 }
3482                                 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3483                                 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3484                                 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3485                                 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3486                         }
3487                 }
3488
3489                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3490                 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3491
3492                 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3493                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3494                 for i in 0..4 {
3495                         claim_tx.input.push(TxIn {
3496                                 previous_output: BitcoinOutPoint {
3497                                         txid,
3498                                         vout: i,
3499                                 },
3500                                 script_sig: Script::new(),
3501                                 sequence: 0xfffffffd,
3502                                 witness: Vec::new(),
3503                         });
3504                 }
3505                 claim_tx.output.push(TxOut {
3506                         script_pubkey: script_pubkey.clone(),
3507                         value: 0,
3508                 });
3509                 let base_weight = claim_tx.get_weight();
3510                 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3511                 let mut inputs_total_weight = 2; // count segwit flags
3512                 {
3513                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3514                         for (idx, inp) in inputs_weight.iter().enumerate() {
3515                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3516                                 inputs_total_weight += inp;
3517                         }
3518                 }
3519                 assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3520
3521                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3522                 claim_tx.input.clear();
3523                 sum_actual_sigs = 0;
3524                 for i in 0..4 {
3525                         claim_tx.input.push(TxIn {
3526                                 previous_output: BitcoinOutPoint {
3527                                         txid,
3528                                         vout: i,
3529                                 },
3530                                 script_sig: Script::new(),
3531                                 sequence: 0xfffffffd,
3532                                 witness: Vec::new(),
3533                         });
3534                 }
3535                 let base_weight = claim_tx.get_weight();
3536                 let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3537                 let mut inputs_total_weight = 2; // count segwit flags
3538                 {
3539                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3540                         for (idx, inp) in inputs_weight.iter().enumerate() {
3541                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3542                                 inputs_total_weight += inp;
3543                         }
3544                 }
3545                 assert_eq!(base_weight + inputs_total_weight as usize,  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3546
3547                 // Justice tx with 1 revoked HTLC-Success tx output
3548                 claim_tx.input.clear();
3549                 sum_actual_sigs = 0;
3550                 claim_tx.input.push(TxIn {
3551                         previous_output: BitcoinOutPoint {
3552                                 txid,
3553                                 vout: 0,
3554                         },
3555                         script_sig: Script::new(),
3556                         sequence: 0xfffffffd,
3557                         witness: Vec::new(),
3558                 });
3559                 let base_weight = claim_tx.get_weight();
3560                 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3561                 let mut inputs_total_weight = 2; // count segwit flags
3562                 {
3563                         let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3564                         for (idx, inp) in inputs_weight.iter().enumerate() {
3565                                 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3566                                 inputs_total_weight += inp;
3567                         }
3568                 }
3569                 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3570         }
3571
3572         // Further testing is done in the ChannelManager integration tests.
3573 }