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