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