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