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