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