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