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