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