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