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