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