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