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