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