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