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