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