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