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