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