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