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