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