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