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