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