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