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