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