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