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