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