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