Add types for updating ChannelMonitors without copying them.
[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::{TxIn,TxOut,SigHashType,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 use bitcoin::util::bip143;
22
23 use bitcoin_hashes::Hash;
24 use bitcoin_hashes::sha256::Hash as Sha256;
25 use bitcoin_hashes::hash160::Hash as Hash160;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
27
28 use secp256k1::{Secp256k1,Signature};
29 use secp256k1::key::{SecretKey,PublicKey};
30 use secp256k1;
31
32 use ln::msgs::DecodeError;
33 use ln::chan_utils;
34 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType};
35 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
36 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
37 use chain::transaction::OutPoint;
38 use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
39 use util::logger::Logger;
40 use util::ser::{ReadableArgs, Readable, Writer, Writeable, U48};
41 use util::{byte_utils, events};
42
43 use std::collections::{HashMap, hash_map, HashSet};
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<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdate {
76         fn read(r: &mut R) -> Result<Self, DecodeError> {
77                 let update_id: u64 = Readable::read(r)?;
78                 let len: u64 = Readable::read(r)?;
79                 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
80                 for _ in 0..len {
81                         updates.push(Readable::read(r)?);
82                 }
83                 Ok(Self { update_id, updates })
84         }
85 }
86
87 /// An error enum representing a failure to persist a channel monitor update.
88 #[derive(Clone)]
89 pub enum ChannelMonitorUpdateErr {
90         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
91         /// our state failed, but is expected to succeed at some point in the future).
92         ///
93         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
94         /// submitting new commitment transactions to the remote party. Once the update(s) which failed
95         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
96         /// restore the channel to an operational state.
97         ///
98         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
99         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
100         /// writing out the latest ChannelManager state.
101         ///
102         /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
103         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
104         /// to claim it on this channel) and those updates must be applied wherever they can be. At
105         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
106         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
107         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
108         /// been "frozen".
109         ///
110         /// Note that even if updates made after TemporaryFailure succeed you must still call
111         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
112         /// operation.
113         ///
114         /// Note that the update being processed here will not be replayed for you when you call
115         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
116         /// with the persisted ChannelMonitor on your own local disk prior to returning a
117         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
118         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
119         /// reload-time.
120         ///
121         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
122         /// remote location (with local copies persisted immediately), it is anticipated that all
123         /// updates will return TemporaryFailure until the remote copies could be updated.
124         TemporaryFailure,
125         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
126         /// different watchtower and cannot update with all watchtowers that were previously informed
127         /// of this channel). This will force-close the channel in question.
128         ///
129         /// Should also be used to indicate a failure to update the local copy of the channel monitor.
130         PermanentFailure,
131 }
132
133 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
134 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
135 /// means you tried to merge two monitors for different channels or for a channel which was
136 /// restored from a backup and then generated new commitment updates.
137 /// Contains a human-readable error message.
138 #[derive(Debug)]
139 pub struct MonitorUpdateError(pub &'static str);
140
141 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
142 /// forward channel and from which info are needed to update HTLC in a backward channel.
143 #[derive(Clone, PartialEq)]
144 pub struct HTLCUpdate {
145         pub(super) payment_hash: PaymentHash,
146         pub(super) payment_preimage: Option<PaymentPreimage>,
147         pub(super) source: HTLCSource
148 }
149 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
150
151 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
152 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
153 /// events to it, while also taking any add_update_monitor events and passing them to some remote
154 /// server(s).
155 ///
156 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
157 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
158 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
159 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
160 ///
161 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
162 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
163 /// than calling these methods directly, the user should register implementors as listeners to the
164 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
165 /// all registered listeners in one go.
166 pub trait ManyChannelMonitor<ChanSigner: ChannelKeys>: Send + Sync {
167         /// Adds or updates a monitor for the given `funding_txo`.
168         ///
169         /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
170         /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
171         /// callbacks with the funding transaction, or any spends of it.
172         ///
173         /// Further, the implementer must also ensure that each output returned in
174         /// monitor.get_outputs_to_watch() is registered to ensure that the provided monitor learns about
175         /// any spends of any of the outputs.
176         ///
177         /// Any spends of outputs which should have been registered which aren't passed to
178         /// ChannelMonitors via block_connected may result in FUNDS LOSS.
179         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr>;
180
181         /// Updates a monitor for the given `funding_txo`.
182         ///
183         /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
184         /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
185         /// callbacks with the funding transaction, or any spends of it.
186         ///
187         /// Further, the implementer must also ensure that each output returned in
188         /// monitor.get_watch_outputs() is registered to ensure that the provided monitor learns about
189         /// any spends of any of the outputs.
190         ///
191         /// Any spends of outputs which should have been registered which aren't passed to
192         /// ChannelMonitors via block_connected may result in FUNDS LOSS.
193         fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
194
195         /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
196         /// with success or failure.
197         ///
198         /// You should probably just call through to
199         /// ChannelMonitor::get_and_clear_pending_htlcs_updated() for each ChannelMonitor and return
200         /// the full list.
201         fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate>;
202 }
203
204 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
205 /// watchtower or watch our own channels.
206 ///
207 /// Note that you must provide your own key by which to refer to channels.
208 ///
209 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
210 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
211 /// index by a PublicKey which is required to sign any updates.
212 ///
213 /// If you're using this for local monitoring of your own channels, you probably want to use
214 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
215 pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys, T: Deref> where T::Target: BroadcasterInterface {
216         #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
217         pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
218         #[cfg(not(test))]
219         monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
220         chain_monitor: Arc<ChainWatchInterface>,
221         broadcaster: T,
222         pending_events: Mutex<Vec<events::Event>>,
223         logger: Arc<Logger>,
224         fee_estimator: Arc<FeeEstimator>
225 }
226
227 impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send> ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T>
228         where T::Target: BroadcasterInterface
229 {
230         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
231                 let block_hash = header.bitcoin_hash();
232                 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
233                 {
234                         let mut monitors = self.monitors.lock().unwrap();
235                         for monitor in monitors.values_mut() {
236                                 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
237                                 if spendable_outputs.len() > 0 {
238                                         new_events.push(events::Event::SpendableOutputs {
239                                                 outputs: spendable_outputs,
240                                         });
241                                 }
242
243                                 for (ref txid, ref outputs) in txn_outputs {
244                                         for (idx, output) in outputs.iter().enumerate() {
245                                                 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
246                                         }
247                                 }
248                         }
249                 }
250                 let mut pending_events = self.pending_events.lock().unwrap();
251                 pending_events.append(&mut new_events);
252         }
253
254         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
255                 let block_hash = header.bitcoin_hash();
256                 let mut monitors = self.monitors.lock().unwrap();
257                 for monitor in monitors.values_mut() {
258                         monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
259                 }
260         }
261 }
262
263 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T>
264         where T::Target: BroadcasterInterface
265 {
266         /// Creates a new object which can be used to monitor several channels given the chain
267         /// interface with which to register to receive notifications.
268         pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: T, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> SimpleManyChannelMonitor<Key, ChanSigner, T> {
269                 let res = SimpleManyChannelMonitor {
270                         monitors: Mutex::new(HashMap::new()),
271                         chain_monitor,
272                         broadcaster,
273                         pending_events: Mutex::new(Vec::new()),
274                         logger,
275                         fee_estimator: feeest,
276                 };
277
278                 res
279         }
280
281         /// Adds or updates the monitor which monitors the channel referred to by the given key.
282         pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
283                 let mut monitors = self.monitors.lock().unwrap();
284                 match monitors.get_mut(&key) {
285                         Some(orig_monitor) => {
286                                 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
287                                 return orig_monitor.insert_combine(monitor);
288                         },
289                         None => {}
290                 };
291                 match monitor.key_storage {
292                         Storage::Local { ref funding_info, .. } => {
293                                 match 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                         },
304                         Storage::Watchtower { .. } => {
305                                 self.chain_monitor.watch_all_txn();
306                         }
307                 }
308                 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
309                         for (idx, script) in outputs.iter().enumerate() {
310                                 self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script);
311                         }
312                 }
313                 monitors.insert(key, monitor);
314                 Ok(())
315         }
316
317         /// Updates the monitor which monitors the channel referred to by the given key.
318         pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
319                 let mut monitors = self.monitors.lock().unwrap();
320                 match monitors.get_mut(&key) {
321                         Some(orig_monitor) => {
322                                 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage));
323                                 orig_monitor.update_monitor(update)
324                         },
325                         None => Err(MonitorUpdateError("No such monitor registered"))
326                 }
327         }
328 }
329
330 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner, T>
331         where T::Target: BroadcasterInterface
332 {
333         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
334                 match self.add_update_monitor_by_key(funding_txo, monitor) {
335                         Ok(_) => Ok(()),
336                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
337                 }
338         }
339
340         fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
341                 match self.update_monitor_by_key(funding_txo, update) {
342                         Ok(_) => Ok(()),
343                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
344                 }
345         }
346
347         fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
348                 let mut pending_htlcs_updated = Vec::new();
349                 for chan in self.monitors.lock().unwrap().values_mut() {
350                         pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated());
351                 }
352                 pending_htlcs_updated
353         }
354 }
355
356 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T>
357         where T::Target: BroadcasterInterface
358 {
359         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
360                 let mut pending_events = self.pending_events.lock().unwrap();
361                 let mut ret = Vec::new();
362                 mem::swap(&mut ret, &mut *pending_events);
363                 ret
364         }
365 }
366
367 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
368 /// instead claiming it in its own individual transaction.
369 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
370 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
371 /// HTLC-Success transaction.
372 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
373 /// transaction confirmed (and we use it in a few more, equivalent, places).
374 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
375 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
376 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
377 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
378 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
379 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
380 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
381 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
382 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
383 /// accurate block height.
384 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
385 /// with at worst this delay, so we are not only using this value as a mercy for them but also
386 /// us as a safeguard to delay with enough time.
387 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
388 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
389 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
390 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
391 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
392 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
393 /// keeping bumping another claim tx to solve the outpoint.
394 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
395
396 #[derive(Clone)]
397 enum Storage<ChanSigner: ChannelKeys> {
398         Local {
399                 keys: ChanSigner,
400                 funding_key: SecretKey,
401                 revocation_base_key: SecretKey,
402                 htlc_base_key: SecretKey,
403                 delayed_payment_base_key: SecretKey,
404                 payment_base_key: SecretKey,
405                 shutdown_pubkey: PublicKey,
406                 funding_info: Option<(OutPoint, Script)>,
407                 current_remote_commitment_txid: Option<Sha256dHash>,
408                 prev_remote_commitment_txid: Option<Sha256dHash>,
409         },
410         Watchtower {
411                 revocation_base_key: PublicKey,
412                 htlc_base_key: PublicKey,
413         }
414 }
415
416 #[cfg(any(test, feature = "fuzztarget"))]
417 impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
418         fn eq(&self, other: &Self) -> bool {
419                 match *self {
420                         Storage::Local { ref keys, .. } => {
421                                 let k = keys;
422                                 match *other {
423                                         Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
424                                         Storage::Watchtower { .. } => false,
425                                 }
426                         },
427                         Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
428                                 let (rbk, hbk) = (revocation_base_key, htlc_base_key);
429                                 match *other {
430                                         Storage::Local { .. } => false,
431                                         Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
432                                                 revocation_base_key == rbk && htlc_base_key == hbk,
433                                 }
434                         },
435                 }
436         }
437 }
438
439 #[derive(Clone, PartialEq)]
440 struct LocalSignedTx {
441         /// txid of the transaction in tx, just used to make comparison faster
442         txid: Sha256dHash,
443         tx: LocalCommitmentTransaction,
444         revocation_key: PublicKey,
445         a_htlc_key: PublicKey,
446         b_htlc_key: PublicKey,
447         delayed_payment_key: PublicKey,
448         per_commitment_point: PublicKey,
449         feerate_per_kw: u64,
450         htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
451 }
452
453 #[derive(PartialEq)]
454 enum InputDescriptors {
455         RevokedOfferedHTLC,
456         RevokedReceivedHTLC,
457         OfferedHTLC,
458         ReceivedHTLC,
459         RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
460 }
461
462 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
463 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
464 /// a new bumped one in case of lenghty confirmation delay
465 #[derive(Clone, PartialEq)]
466 enum InputMaterial {
467         Revoked {
468                 script: Script,
469                 pubkey: Option<PublicKey>,
470                 key: SecretKey,
471                 is_htlc: bool,
472                 amount: u64,
473         },
474         RemoteHTLC {
475                 script: Script,
476                 key: SecretKey,
477                 preimage: Option<PaymentPreimage>,
478                 amount: u64,
479                 locktime: u32,
480         },
481         LocalHTLC {
482                 script: Script,
483                 sigs: (Signature, Signature),
484                 preimage: Option<PaymentPreimage>,
485                 amount: u64,
486         }
487 }
488
489 impl Writeable for InputMaterial  {
490         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
491                 match self {
492                         &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
493                                 writer.write_all(&[0; 1])?;
494                                 script.write(writer)?;
495                                 pubkey.write(writer)?;
496                                 writer.write_all(&key[..])?;
497                                 if *is_htlc {
498                                         writer.write_all(&[0; 1])?;
499                                 } else {
500                                         writer.write_all(&[1; 1])?;
501                                 }
502                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
503                         },
504                         &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
505                                 writer.write_all(&[1; 1])?;
506                                 script.write(writer)?;
507                                 key.write(writer)?;
508                                 preimage.write(writer)?;
509                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
510                                 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
511                         },
512                         &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
513                                 writer.write_all(&[2; 1])?;
514                                 script.write(writer)?;
515                                 sigs.0.write(writer)?;
516                                 sigs.1.write(writer)?;
517                                 preimage.write(writer)?;
518                                 writer.write_all(&byte_utils::be64_to_array(*amount))?;
519                         }
520                 }
521                 Ok(())
522         }
523 }
524
525 impl<R: ::std::io::Read> Readable<R> for InputMaterial {
526         fn read(reader: &mut R) -> Result<Self, DecodeError> {
527                 let input_material = match <u8 as Readable<R>>::read(reader)? {
528                         0 => {
529                                 let script = Readable::read(reader)?;
530                                 let pubkey = Readable::read(reader)?;
531                                 let key = Readable::read(reader)?;
532                                 let is_htlc = match <u8 as Readable<R>>::read(reader)? {
533                                         0 => true,
534                                         1 => false,
535                                         _ => return Err(DecodeError::InvalidValue),
536                                 };
537                                 let amount = Readable::read(reader)?;
538                                 InputMaterial::Revoked {
539                                         script,
540                                         pubkey,
541                                         key,
542                                         is_htlc,
543                                         amount
544                                 }
545                         },
546                         1 => {
547                                 let script = Readable::read(reader)?;
548                                 let key = Readable::read(reader)?;
549                                 let preimage = Readable::read(reader)?;
550                                 let amount = Readable::read(reader)?;
551                                 let locktime = Readable::read(reader)?;
552                                 InputMaterial::RemoteHTLC {
553                                         script,
554                                         key,
555                                         preimage,
556                                         amount,
557                                         locktime
558                                 }
559                         },
560                         2 => {
561                                 let script = Readable::read(reader)?;
562                                 let their_sig = Readable::read(reader)?;
563                                 let our_sig = Readable::read(reader)?;
564                                 let preimage = Readable::read(reader)?;
565                                 let amount = Readable::read(reader)?;
566                                 InputMaterial::LocalHTLC {
567                                         script,
568                                         sigs: (their_sig, our_sig),
569                                         preimage,
570                                         amount
571                                 }
572                         }
573                         _ => return Err(DecodeError::InvalidValue),
574                 };
575                 Ok(input_material)
576         }
577 }
578
579 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
580 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
581 #[derive(Clone, PartialEq)]
582 enum OnchainEvent {
583         /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
584         /// bump-txn candidate buffer.
585         Claim {
586                 claim_request: Sha256dHash,
587         },
588         /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
589         /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
590         /// only win from it, so it's never an OnchainEvent
591         HTLCUpdate {
592                 htlc_update: (HTLCSource, PaymentHash),
593         },
594         /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
595         /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
596         /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
597         ContentiousOutpoint {
598                 outpoint: BitcoinOutPoint,
599                 input_material: InputMaterial,
600         }
601 }
602
603 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
604 #[derive(Clone, PartialEq)]
605 pub struct ClaimTxBumpMaterial {
606         // At every block tick, used to check if pending claiming tx is taking too
607         // much time for confirmation and we need to bump it.
608         height_timer: u32,
609         // Tracked in case of reorg to wipe out now-superflous bump material
610         feerate_previous: u64,
611         // Soonest timelocks among set of outpoints claimed, used to compute
612         // a priority of not feerate
613         soonest_timelock: u32,
614         // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
615         per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
616 }
617
618 impl Writeable for ClaimTxBumpMaterial  {
619         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
620                 writer.write_all(&byte_utils::be32_to_array(self.height_timer))?;
621                 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
622                 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
623                 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
624                 for (outp, tx_material) in self.per_input_material.iter() {
625                         outp.write(writer)?;
626                         tx_material.write(writer)?;
627                 }
628                 Ok(())
629         }
630 }
631
632 impl<R: ::std::io::Read> Readable<R> for ClaimTxBumpMaterial {
633         fn read(reader: &mut R) -> Result<Self, DecodeError> {
634                 let height_timer = Readable::read(reader)?;
635                 let feerate_previous = Readable::read(reader)?;
636                 let soonest_timelock = Readable::read(reader)?;
637                 let per_input_material_len: u64 = Readable::read(reader)?;
638                 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
639                 for _ in 0 ..per_input_material_len {
640                         let outpoint = Readable::read(reader)?;
641                         let input_material = Readable::read(reader)?;
642                         per_input_material.insert(outpoint, input_material);
643                 }
644                 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
645         }
646 }
647
648 const SERIALIZATION_VERSION: u8 = 1;
649 const MIN_SERIALIZATION_VERSION: u8 = 1;
650
651 #[cfg_attr(test, derive(PartialEq))]
652 #[derive(Clone)]
653 pub(super) enum ChannelMonitorUpdateStep {
654 }
655
656 impl Writeable for ChannelMonitorUpdateStep {
657         fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::std::io::Error> {
658                 Ok(())
659         }
660 }
661 impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
662         fn read(_r: &mut R) -> Result<Self, DecodeError> {
663                 unimplemented!() // We don't have any enum variants to read (and never provide Monitor Updates)
664         }
665 }
666
667 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
668 /// on-chain transactions to ensure no loss of funds occurs.
669 ///
670 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
671 /// information and are actively monitoring the chain.
672 #[derive(Clone)]
673 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
674         latest_update_id: u64,
675         commitment_transaction_number_obscure_factor: u64,
676
677         key_storage: Storage<ChanSigner>,
678         their_htlc_base_key: Option<PublicKey>,
679         their_delayed_payment_base_key: Option<PublicKey>,
680         funding_redeemscript: Option<Script>,
681         channel_value_satoshis: Option<u64>,
682         // first is the idx of the first of the two revocation points
683         their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
684
685         our_to_self_delay: u16,
686         their_to_self_delay: Option<u16>,
687
688         commitment_secrets: CounterpartyCommitmentSecrets,
689         remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
690         /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
691         /// Nor can we figure out their commitment numbers without the commitment transaction they are
692         /// spending. Thus, in order to claim them via revocation key, we track all the remote
693         /// commitment transactions which we find on-chain, mapping them to the commitment number which
694         /// can be used to derive the revocation key and claim the transactions.
695         remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
696         /// Cache used to make pruning of payment_preimages faster.
697         /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
698         /// remote transactions (ie should remain pretty small).
699         /// Serialized to disk but should generally not be sent to Watchtowers.
700         remote_hash_commitment_number: HashMap<PaymentHash, u64>,
701
702         // We store two local commitment transactions to avoid any race conditions where we may update
703         // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
704         // various monitors for one channel being out of sync, and us broadcasting a local
705         // transaction for which we have deleted claim information on some watchtowers.
706         prev_local_signed_commitment_tx: Option<LocalSignedTx>,
707         current_local_signed_commitment_tx: Option<LocalSignedTx>,
708
709         // Used just for ChannelManager to make sure it has the latest channel data during
710         // deserialization
711         current_remote_commitment_number: u64,
712
713         payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
714
715         pending_htlcs_updated: Vec<HTLCUpdate>,
716
717         destination_script: Script,
718         // Thanks to data loss protection, we may be able to claim our non-htlc funds
719         // back, this is the script we have to spend from but we need to
720         // scan every commitment transaction for that
721         to_remote_rescue: Option<(Script, SecretKey)>,
722
723         // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
724         // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
725         // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
726         // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
727         // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
728         // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
729         // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
730         // we need to regenerate new claim request we reduced set of stil-claimable outpoints.
731         // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
732         // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
733         // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
734         #[cfg(test)] // Used in functional_test to verify sanitization
735         pub pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
736         #[cfg(not(test))]
737         pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
738
739         // Used to link outpoints claimed in a connected block to a pending claim request.
740         // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
741         // Value is (pending claim request identifier, confirmation_block), identifier
742         // is txid of the initial claiming transaction and is immutable until outpoint is
743         // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
744         // block with output gets disconnected.
745         #[cfg(test)] // Used in functional_test to verify sanitization
746         pub claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
747         #[cfg(not(test))]
748         claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
749
750         // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
751         // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
752         // actions when we receive a block with given height. Actions depend on OnchainEvent type.
753         onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
754
755         // If we get serialized out and re-read, we need to make sure that the chain monitoring
756         // interface knows about the TXOs that we want to be notified of spends of. We could probably
757         // be smart and derive them from the above storage fields, but its much simpler and more
758         // Obviously Correct (tm) if we just keep track of them explicitly.
759         outputs_to_watch: HashMap<Sha256dHash, Vec<Script>>,
760
761         // We simply modify last_block_hash in Channel's block_connected so that serialization is
762         // consistent but hopefully the users' copy handles block_connected in a consistent way.
763         // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
764         // their last_block_hash from its state and not based on updated copies that didn't run through
765         // the full block_connected).
766         pub(crate) last_block_hash: Sha256dHash,
767         secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
768         logger: Arc<Logger>,
769 }
770 macro_rules! subtract_high_prio_fee {
771         ($self: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
772                 {
773                         $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority);
774                         let mut fee = $used_feerate * ($predicted_weight as u64) / 1000;
775                         if $value <= fee {
776                                 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
777                                 fee = $used_feerate * ($predicted_weight as u64) / 1000;
778                                 if $value <= fee {
779                                         $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
780                                         fee = $used_feerate * ($predicted_weight as u64) / 1000;
781                                         if $value <= fee {
782                                                 log_error!($self, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
783                                                         fee, $value);
784                                                 false
785                                         } else {
786                                                 log_warn!($self, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
787                                                         $value);
788                                                 $value -= fee;
789                                                 true
790                                         }
791                                 } else {
792                                         log_warn!($self, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
793                                                 $value);
794                                         $value -= fee;
795                                         true
796                                 }
797                         } else {
798                                 $value -= fee;
799                                 true
800                         }
801                 }
802         }
803 }
804
805 #[cfg(any(test, feature = "fuzztarget"))]
806 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
807 /// underlying object
808 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
809         fn eq(&self, other: &Self) -> bool {
810                 if self.latest_update_id != other.latest_update_id ||
811                         self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
812                         self.key_storage != other.key_storage ||
813                         self.their_htlc_base_key != other.their_htlc_base_key ||
814                         self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
815                         self.funding_redeemscript != other.funding_redeemscript ||
816                         self.channel_value_satoshis != other.channel_value_satoshis ||
817                         self.their_cur_revocation_points != other.their_cur_revocation_points ||
818                         self.our_to_self_delay != other.our_to_self_delay ||
819                         self.their_to_self_delay != other.their_to_self_delay ||
820                         self.commitment_secrets != other.commitment_secrets ||
821                         self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
822                         self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
823                         self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
824                         self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
825                         self.current_remote_commitment_number != other.current_remote_commitment_number ||
826                         self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
827                         self.payment_preimages != other.payment_preimages ||
828                         self.pending_htlcs_updated != other.pending_htlcs_updated ||
829                         self.destination_script != other.destination_script ||
830                         self.to_remote_rescue != other.to_remote_rescue ||
831                         self.pending_claim_requests != other.pending_claim_requests ||
832                         self.claimable_outpoints != other.claimable_outpoints ||
833                         self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
834                         self.outputs_to_watch != other.outputs_to_watch
835                 {
836                         false
837                 } else {
838                         true
839                 }
840         }
841 }
842
843 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
844         /// Serializes into a vec, with various modes for the exposed pub fns
845         fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
846                 //TODO: We still write out all the serialization here manually instead of using the fancy
847                 //serialization framework we have, we should migrate things over to it.
848                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
849                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
850
851                 self.latest_update_id.write(writer)?;
852
853                 // Set in initial Channel-object creation, so should always be set by now:
854                 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
855
856                 macro_rules! write_option {
857                         ($thing: expr) => {
858                                 match $thing {
859                                         &Some(ref t) => {
860                                                 1u8.write(writer)?;
861                                                 t.write(writer)?;
862                                         },
863                                         &None => 0u8.write(writer)?,
864                                 }
865                         }
866                 }
867
868                 match self.key_storage {
869                         Storage::Local { ref keys, ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
870                                 writer.write_all(&[0; 1])?;
871                                 keys.write(writer)?;
872                                 writer.write_all(&funding_key[..])?;
873                                 writer.write_all(&revocation_base_key[..])?;
874                                 writer.write_all(&htlc_base_key[..])?;
875                                 writer.write_all(&delayed_payment_base_key[..])?;
876                                 writer.write_all(&payment_base_key[..])?;
877                                 writer.write_all(&shutdown_pubkey.serialize())?;
878                                 match funding_info  {
879                                         &Some((ref outpoint, ref script)) => {
880                                                 writer.write_all(&outpoint.txid[..])?;
881                                                 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
882                                                 script.write(writer)?;
883                                         },
884                                         &None => {
885                                                 debug_assert!(false, "Try to serialize a useless Local monitor !");
886                                         },
887                                 }
888                                 current_remote_commitment_txid.write(writer)?;
889                                 prev_remote_commitment_txid.write(writer)?;
890                         },
891                         Storage::Watchtower { .. } => unimplemented!(),
892                 }
893
894                 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
895                 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
896                 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
897                 self.channel_value_satoshis.unwrap().write(writer)?;
898
899                 match self.their_cur_revocation_points {
900                         Some((idx, pubkey, second_option)) => {
901                                 writer.write_all(&byte_utils::be48_to_array(idx))?;
902                                 writer.write_all(&pubkey.serialize())?;
903                                 match second_option {
904                                         Some(second_pubkey) => {
905                                                 writer.write_all(&second_pubkey.serialize())?;
906                                         },
907                                         None => {
908                                                 writer.write_all(&[0; 33])?;
909                                         },
910                                 }
911                         },
912                         None => {
913                                 writer.write_all(&byte_utils::be48_to_array(0))?;
914                         },
915                 }
916
917                 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
918                 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
919
920                 self.commitment_secrets.write(writer)?;
921
922                 macro_rules! serialize_htlc_in_commitment {
923                         ($htlc_output: expr) => {
924                                 writer.write_all(&[$htlc_output.offered as u8; 1])?;
925                                 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
926                                 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
927                                 writer.write_all(&$htlc_output.payment_hash.0[..])?;
928                                 $htlc_output.transaction_output_index.write(writer)?;
929                         }
930                 }
931
932                 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
933                 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
934                         writer.write_all(&txid[..])?;
935                         writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
936                         for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
937                                 serialize_htlc_in_commitment!(htlc_output);
938                                 write_option!(htlc_source);
939                         }
940                 }
941
942                 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
943                 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
944                         writer.write_all(&txid[..])?;
945                         writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
946                         (txouts.len() as u64).write(writer)?;
947                         for script in txouts.iter() {
948                                 script.write(writer)?;
949                         }
950                 }
951
952                 if for_local_storage {
953                         writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
954                         for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
955                                 writer.write_all(&payment_hash.0[..])?;
956                                 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
957                         }
958                 } else {
959                         writer.write_all(&byte_utils::be64_to_array(0))?;
960                 }
961
962                 macro_rules! serialize_local_tx {
963                         ($local_tx: expr) => {
964                                 $local_tx.tx.write(writer)?;
965                                 writer.write_all(&$local_tx.revocation_key.serialize())?;
966                                 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
967                                 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
968                                 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
969                                 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
970
971                                 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
972                                 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
973                                 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
974                                         serialize_htlc_in_commitment!(htlc_output);
975                                         if let &Some(ref their_sig) = sig {
976                                                 1u8.write(writer)?;
977                                                 writer.write_all(&their_sig.serialize_compact())?;
978                                         } else {
979                                                 0u8.write(writer)?;
980                                         }
981                                         write_option!(htlc_source);
982                                 }
983                         }
984                 }
985
986                 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
987                         writer.write_all(&[1; 1])?;
988                         serialize_local_tx!(prev_local_tx);
989                 } else {
990                         writer.write_all(&[0; 1])?;
991                 }
992
993                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
994                         writer.write_all(&[1; 1])?;
995                         serialize_local_tx!(cur_local_tx);
996                 } else {
997                         writer.write_all(&[0; 1])?;
998                 }
999
1000                 if for_local_storage {
1001                         writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1002                 } else {
1003                         writer.write_all(&byte_utils::be48_to_array(0))?;
1004                 }
1005
1006                 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1007                 for payment_preimage in self.payment_preimages.values() {
1008                         writer.write_all(&payment_preimage.0[..])?;
1009                 }
1010
1011                 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
1012                 for data in self.pending_htlcs_updated.iter() {
1013                         data.write(writer)?;
1014                 }
1015
1016                 self.last_block_hash.write(writer)?;
1017                 self.destination_script.write(writer)?;
1018                 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1019                         writer.write_all(&[1; 1])?;
1020                         to_remote_script.write(writer)?;
1021                         local_key.write(writer)?;
1022                 } else {
1023                         writer.write_all(&[0; 1])?;
1024                 }
1025
1026                 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
1027                 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
1028                         ancestor_claim_txid.write(writer)?;
1029                         claim_tx_data.write(writer)?;
1030                 }
1031
1032                 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
1033                 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
1034                         outp.write(writer)?;
1035                         claim_and_height.0.write(writer)?;
1036                         claim_and_height.1.write(writer)?;
1037                 }
1038
1039                 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1040                 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1041                         writer.write_all(&byte_utils::be32_to_array(**target))?;
1042                         writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1043                         for ev in events.iter() {
1044                                 match *ev {
1045                                         OnchainEvent::Claim { ref claim_request } => {
1046                                                 writer.write_all(&[0; 1])?;
1047                                                 claim_request.write(writer)?;
1048                                         },
1049                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1050                                                 writer.write_all(&[1; 1])?;
1051                                                 htlc_update.0.write(writer)?;
1052                                                 htlc_update.1.write(writer)?;
1053                                         },
1054                                         OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
1055                                                 writer.write_all(&[2; 1])?;
1056                                                 outpoint.write(writer)?;
1057                                                 input_material.write(writer)?;
1058                                         }
1059                                 }
1060                         }
1061                 }
1062
1063                 (self.outputs_to_watch.len() as u64).write(writer)?;
1064                 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1065                         txid.write(writer)?;
1066                         (output_scripts.len() as u64).write(writer)?;
1067                         for script in output_scripts.iter() {
1068                                 script.write(writer)?;
1069                         }
1070                 }
1071
1072                 Ok(())
1073         }
1074
1075         /// Writes this monitor into the given writer, suitable for writing to disk.
1076         ///
1077         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1078         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1079         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1080         /// common block that appears on your best chain as well as on the chain which contains the
1081         /// last block hash returned) upon deserializing the object!
1082         pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1083                 self.write(writer, true)
1084         }
1085
1086         /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1087         ///
1088         /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1089         /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1090         /// the "reorg path" (ie not just starting at the same height but starting at the highest
1091         /// common block that appears on your best chain as well as on the chain which contains the
1092         /// last block hash returned) upon deserializing the object!
1093         pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1094                 self.write(writer, false)
1095         }
1096 }
1097
1098 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1099         pub(super) fn new(keys: ChanSigner, funding_key: &SecretKey, revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
1100                 ChannelMonitor {
1101                         latest_update_id: 0,
1102                         commitment_transaction_number_obscure_factor: 0,
1103
1104                         key_storage: Storage::Local {
1105                                 keys,
1106                                 funding_key: funding_key.clone(),
1107                                 revocation_base_key: revocation_base_key.clone(),
1108                                 htlc_base_key: htlc_base_key.clone(),
1109                                 delayed_payment_base_key: delayed_payment_base_key.clone(),
1110                                 payment_base_key: payment_base_key.clone(),
1111                                 shutdown_pubkey: shutdown_pubkey.clone(),
1112                                 funding_info: None,
1113                                 current_remote_commitment_txid: None,
1114                                 prev_remote_commitment_txid: None,
1115                         },
1116                         their_htlc_base_key: None,
1117                         their_delayed_payment_base_key: None,
1118                         funding_redeemscript: None,
1119                         channel_value_satoshis: None,
1120                         their_cur_revocation_points: None,
1121
1122                         our_to_self_delay: our_to_self_delay,
1123                         their_to_self_delay: None,
1124
1125                         commitment_secrets: CounterpartyCommitmentSecrets::new(),
1126                         remote_claimable_outpoints: HashMap::new(),
1127                         remote_commitment_txn_on_chain: HashMap::new(),
1128                         remote_hash_commitment_number: HashMap::new(),
1129
1130                         prev_local_signed_commitment_tx: None,
1131                         current_local_signed_commitment_tx: None,
1132                         current_remote_commitment_number: 1 << 48,
1133
1134                         payment_preimages: HashMap::new(),
1135                         pending_htlcs_updated: Vec::new(),
1136
1137                         destination_script: destination_script,
1138                         to_remote_rescue: None,
1139
1140                         pending_claim_requests: HashMap::new(),
1141
1142                         claimable_outpoints: HashMap::new(),
1143
1144                         onchain_events_waiting_threshold_conf: HashMap::new(),
1145                         outputs_to_watch: HashMap::new(),
1146
1147                         last_block_hash: Default::default(),
1148                         secp_ctx: Secp256k1::new(),
1149                         logger,
1150                 }
1151         }
1152
1153         fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
1154                 let mut tx_weight = 2; // count segwit flags
1155                 for inp in inputs {
1156                         // We use expected weight (and not actual) as signatures and time lock delays may vary
1157                         tx_weight +=  match inp {
1158                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1159                                 &InputDescriptors::RevokedOfferedHTLC => {
1160                                         1 + 1 + 73 + 1 + 33 + 1 + 133
1161                                 },
1162                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1163                                 &InputDescriptors::RevokedReceivedHTLC => {
1164                                         1 + 1 + 73 + 1 + 33 + 1 + 139
1165                                 },
1166                                 // number_of_witness_elements + sig_length + remotehtlc_sig  + preimage_length + preimage + witness_script_length + witness_script
1167                                 &InputDescriptors::OfferedHTLC => {
1168                                         1 + 1 + 73 + 1 + 32 + 1 + 133
1169                                 },
1170                                 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1171                                 &InputDescriptors::ReceivedHTLC => {
1172                                         1 + 1 + 73 + 1 + 1 + 1 + 139
1173                                 },
1174                                 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
1175                                 &InputDescriptors::RevokedOutput => {
1176                                         1 + 1 + 73 + 1 + 1 + 1 + 77
1177                                 },
1178                         };
1179                 }
1180                 tx_weight
1181         }
1182
1183         fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
1184                 if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
1185                         return current_height + 1
1186                 } else if timelock_expiration - current_height <= 15 {
1187                         return current_height + 3
1188                 }
1189                 current_height + 15
1190         }
1191
1192         /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1193         /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1194         /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1195         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1196                 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1197                         return Err(MonitorUpdateError("Previous secret did not match new one"));
1198                 }
1199
1200                 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1201                 // events for now-revoked/fulfilled HTLCs.
1202                 // TODO: We should probably consider whether we're really getting the next secret here.
1203                 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1204                         if let Some(txid) = prev_remote_commitment_txid.take() {
1205                                 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1206                                         *source = None;
1207                                 }
1208                         }
1209                 }
1210
1211                 if !self.payment_preimages.is_empty() {
1212                         let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1213                         let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1214                         let min_idx = self.get_min_seen_secret();
1215                         let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1216
1217                         self.payment_preimages.retain(|&k, _| {
1218                                 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1219                                         if k == htlc.payment_hash {
1220                                                 return true
1221                                         }
1222                                 }
1223                                 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1224                                         for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1225                                                 if k == htlc.payment_hash {
1226                                                         return true
1227                                                 }
1228                                         }
1229                                 }
1230                                 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1231                                         if *cn < min_idx {
1232                                                 return true
1233                                         }
1234                                         true
1235                                 } else { false };
1236                                 if contains {
1237                                         remote_hash_commitment_number.remove(&k);
1238                                 }
1239                                 false
1240                         });
1241                 }
1242
1243                 Ok(())
1244         }
1245
1246         /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1247         /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1248         /// possibly future revocation/preimage information) to claim outputs where possible.
1249         /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1250         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) {
1251                 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1252                 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1253                 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1254                 // timeouts)
1255                 for &(ref htlc, _) in &htlc_outputs {
1256                         self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1257                 }
1258
1259                 let new_txid = unsigned_commitment_tx.txid();
1260                 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1261                 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1262                 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1263                         *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1264                         *current_remote_commitment_txid = Some(new_txid);
1265                 }
1266                 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1267                 self.current_remote_commitment_number = commitment_number;
1268                 //TODO: Merge this into the other per-remote-transaction output storage stuff
1269                 match self.their_cur_revocation_points {
1270                         Some(old_points) => {
1271                                 if old_points.0 == commitment_number + 1 {
1272                                         self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1273                                 } else if old_points.0 == commitment_number + 2 {
1274                                         if let Some(old_second_point) = old_points.2 {
1275                                                 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1276                                         } else {
1277                                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1278                                         }
1279                                 } else {
1280                                         self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1281                                 }
1282                         },
1283                         None => {
1284                                 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1285                         }
1286                 }
1287         }
1288
1289         pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1290                 match self.key_storage {
1291                         Storage::Local { ref payment_base_key, ref keys, .. } => {
1292                                 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1293                                         let to_remote_script =  Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1294                                                 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1295                                                 .into_script();
1296                                         if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1297                                                 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1298                                         }
1299                                 }
1300                         },
1301                         Storage::Watchtower { .. } => {}
1302                 }
1303         }
1304
1305         /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1306         /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1307         /// is important that any clones of this channel monitor (including remote clones) by kept
1308         /// up-to-date as our local commitment transaction is updated.
1309         /// Panics if set_their_to_self_delay has never been called.
1310         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>)>) {
1311                 assert!(self.their_to_self_delay.is_some());
1312                 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1313                 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1314                         txid: commitment_tx.txid(),
1315                         tx: commitment_tx,
1316                         revocation_key: local_keys.revocation_key,
1317                         a_htlc_key: local_keys.a_htlc_key,
1318                         b_htlc_key: local_keys.b_htlc_key,
1319                         delayed_payment_key: local_keys.a_delayed_payment_key,
1320                         per_commitment_point: local_keys.per_commitment_point,
1321                         feerate_per_kw,
1322                         htlc_outputs,
1323                 });
1324         }
1325
1326         /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1327         /// commitment_tx_infos which contain the payment hash have been revoked.
1328         pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1329                 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1330         }
1331
1332         /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1333         /// itself.
1334         ///
1335         /// panics if the given update is not the next update by update_id.
1336         pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1337                 if self.latest_update_id + 1 != updates.update_id {
1338                         panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1339                 }
1340                 for update in updates.updates.drain(..) {
1341                         match update {
1342                         }
1343                 }
1344                 self.latest_update_id = updates.update_id;
1345                 Ok(())
1346         }
1347
1348         /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
1349         /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
1350         /// chain for new blocks/transactions.
1351         pub fn insert_combine(&mut self, mut other: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
1352                 match self.key_storage {
1353                         Storage::Local { ref funding_info, .. } => {
1354                                 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
1355                                 let our_funding_info = funding_info;
1356                                 if let Storage::Local { ref funding_info, .. } = other.key_storage {
1357                                         if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
1358                                         // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially
1359                                         // easy to collide the funding_txo hash and have a different scriptPubKey.
1360                                         if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
1361                                                 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
1362                                         }
1363                                 } else {
1364                                         return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
1365                                 }
1366                         },
1367                         Storage::Watchtower { .. } => {
1368                                 if let Storage::Watchtower { .. } = other.key_storage {
1369                                         unimplemented!();
1370                                 } else {
1371                                         return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
1372                                 }
1373                         },
1374                 }
1375                 let other_min_secret = other.get_min_seen_secret();
1376                 let our_min_secret = self.get_min_seen_secret();
1377                 if our_min_secret > other_min_secret {
1378                         self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
1379                 }
1380                 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
1381                         if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
1382                                 let our_commitment_number = 0xffffffffffff - ((((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);
1383                                 let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
1384                                 if our_commitment_number >= other_commitment_number {
1385                                         self.key_storage = other.key_storage;
1386                                 }
1387                         }
1388                 }
1389                 // TODO: We should use current_remote_commitment_number and the commitment number out of
1390                 // local transactions to decide how to merge
1391                 if our_min_secret >= other_min_secret {
1392                         self.their_cur_revocation_points = other.their_cur_revocation_points;
1393                         for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
1394                                 self.remote_claimable_outpoints.insert(txid, htlcs);
1395                         }
1396                         if let Some(local_tx) = other.prev_local_signed_commitment_tx {
1397                                 self.prev_local_signed_commitment_tx = Some(local_tx);
1398                         }
1399                         if let Some(local_tx) = other.current_local_signed_commitment_tx {
1400                                 self.current_local_signed_commitment_tx = Some(local_tx);
1401                         }
1402                         self.payment_preimages = other.payment_preimages;
1403                         self.to_remote_rescue = other.to_remote_rescue;
1404                 }
1405
1406                 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
1407                 Ok(())
1408         }
1409
1410         /// Allows this monitor to scan only for transactions which are applicable. Note that this is
1411         /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
1412         /// avoid this on a monitor you wish to send to a watchtower as it provides slightly better
1413         /// privacy.
1414         /// It's the responsibility of the caller to register outpoint and script with passing the former
1415         /// value as key to add_update_monitor.
1416         pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
1417                 match self.key_storage {
1418                         Storage::Local { ref mut funding_info, .. } => {
1419                                 *funding_info = Some(new_funding_info);
1420                         },
1421                         Storage::Watchtower { .. } => {
1422                                 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
1423                         }
1424                 }
1425         }
1426
1427         /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
1428         /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
1429         pub(super) fn set_basic_channel_info(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey, their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64, commitment_transaction_number_obscure_factor: u64) {
1430                 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
1431                 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
1432                 self.their_to_self_delay = Some(their_to_self_delay);
1433                 self.funding_redeemscript = Some(funding_redeemscript);
1434                 self.channel_value_satoshis = Some(channel_value_satoshis);
1435                 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
1436                 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
1437         }
1438
1439         /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1440         /// ChannelMonitor.
1441         pub fn get_latest_update_id(&self) -> u64 {
1442                 self.latest_update_id
1443         }
1444
1445         /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1446         pub fn get_funding_txo(&self) -> Option<OutPoint> {
1447                 match self.key_storage {
1448                         Storage::Local { ref funding_info, .. } => {
1449                                 match funding_info {
1450                                         &Some((outpoint, _)) => Some(outpoint),
1451                                         &None => None
1452                                 }
1453                         },
1454                         Storage::Watchtower { .. } => {
1455                                 return None;
1456                         }
1457                 }
1458         }
1459
1460         /// Gets a list of txids, with their output scripts (in the order they appear in the
1461         /// transaction), which we must learn about spends of via block_connected().
1462         pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1463                 &self.outputs_to_watch
1464         }
1465
1466         /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1467         /// Generally useful when deserializing as during normal operation the return values of
1468         /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1469         /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1470         pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1471                 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1472                 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1473                         for (idx, output) in outputs.iter().enumerate() {
1474                                 res.push(((*txid).clone(), idx as u32, output));
1475                         }
1476                 }
1477                 res
1478         }
1479
1480         /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1481         /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1482         pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1483                 let mut ret = Vec::new();
1484                 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1485                 ret
1486         }
1487
1488         /// Can only fail if idx is < get_min_seen_secret
1489         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1490                 self.commitment_secrets.get_secret(idx)
1491         }
1492
1493         pub(super) fn get_min_seen_secret(&self) -> u64 {
1494                 self.commitment_secrets.get_min_seen_secret()
1495         }
1496
1497         pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1498                 self.current_remote_commitment_number
1499         }
1500
1501         pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1502                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1503                         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)
1504                 } else { 0xffff_ffff_ffff }
1505         }
1506
1507         /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1508         /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1509         /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1510         /// HTLC-Success/HTLC-Timeout transactions.
1511         /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1512         /// revoked remote commitment tx
1513         fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32, fee_estimator: &FeeEstimator) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1514                 // Most secp and related errors trying to create keys means we have no hope of constructing
1515                 // a spend transaction...so we return no transactions to broadcast
1516                 let mut txn_to_broadcast = Vec::new();
1517                 let mut watch_outputs = Vec::new();
1518                 let mut spendable_outputs = Vec::new();
1519
1520                 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1521                 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1522
1523                 macro_rules! ignore_error {
1524                         ( $thing : expr ) => {
1525                                 match $thing {
1526                                         Ok(a) => a,
1527                                         Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1528                                 }
1529                         };
1530                 }
1531
1532                 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);
1533                 if commitment_number >= self.get_min_seen_secret() {
1534                         let secret = self.get_secret(commitment_number).unwrap();
1535                         let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1536                         let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1537                                 Storage::Local { ref keys, ref payment_base_key, .. } => {
1538                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1539                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1540                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1541                                         Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1542                                 },
1543                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1544                                         let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1545                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1546                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1547                                         None)
1548                                 },
1549                         };
1550                         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()));
1551                         let a_htlc_key = match self.their_htlc_base_key {
1552                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1553                                 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)),
1554                         };
1555
1556                         let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1557                         let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1558
1559                         let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1560                                 // Note that the Network here is ignored as we immediately drop the address for the
1561                                 // script_pubkey version.
1562                                 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1563                                 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1564                         } else { None };
1565
1566                         let mut total_value = 0;
1567                         let mut inputs = Vec::new();
1568                         let mut inputs_info = Vec::new();
1569                         let mut inputs_desc = Vec::new();
1570
1571                         for (idx, outp) in tx.output.iter().enumerate() {
1572                                 if outp.script_pubkey == revokeable_p2wsh {
1573                                         inputs.push(TxIn {
1574                                                 previous_output: BitcoinOutPoint {
1575                                                         txid: commitment_txid,
1576                                                         vout: idx as u32,
1577                                                 },
1578                                                 script_sig: Script::new(),
1579                                                 sequence: 0xfffffffd,
1580                                                 witness: Vec::new(),
1581                                         });
1582                                         inputs_desc.push(InputDescriptors::RevokedOutput);
1583                                         inputs_info.push((None, outp.value, self.our_to_self_delay as u32));
1584                                         total_value += outp.value;
1585                                 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1586                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1587                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1588                                                 key: local_payment_key.unwrap(),
1589                                                 output: outp.clone(),
1590                                         });
1591                                 }
1592                         }
1593
1594                         macro_rules! sign_input {
1595                                 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1596                                         {
1597                                                 let (sig, redeemscript, revocation_key) = match self.key_storage {
1598                                                         Storage::Local { ref revocation_base_key, .. } => {
1599                                                                 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1600                                                                         let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1601                                                                         chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1602                                                                 };
1603                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1604                                                                 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1605                                                                 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript, revocation_key)
1606                                                         },
1607                                                         Storage::Watchtower { .. } => {
1608                                                                 unimplemented!();
1609                                                         }
1610                                                 };
1611                                                 $input.witness.push(sig.serialize_der().to_vec());
1612                                                 $input.witness[0].push(SigHashType::All as u8);
1613                                                 if $htlc_idx.is_none() {
1614                                                         $input.witness.push(vec!(1));
1615                                                 } else {
1616                                                         $input.witness.push(revocation_pubkey.serialize().to_vec());
1617                                                 }
1618                                                 $input.witness.push(redeemscript.clone().into_bytes());
1619                                                 (redeemscript, revocation_key)
1620                                         }
1621                                 }
1622                         }
1623
1624                         if let Some(ref per_commitment_data) = per_commitment_option {
1625                                 inputs.reserve_exact(per_commitment_data.len());
1626
1627                                 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1628                                         if let Some(transaction_output_index) = htlc.transaction_output_index {
1629                                                 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1630                                                 if transaction_output_index as usize >= tx.output.len() ||
1631                                                                 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1632                                                                 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1633                                                         return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1634                                                 }
1635                                                 let input = TxIn {
1636                                                         previous_output: BitcoinOutPoint {
1637                                                                 txid: commitment_txid,
1638                                                                 vout: transaction_output_index,
1639                                                         },
1640                                                         script_sig: Script::new(),
1641                                                         sequence: 0xfffffffd,
1642                                                         witness: Vec::new(),
1643                                                 };
1644                                                 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1645                                                         inputs.push(input);
1646                                                         inputs_desc.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1647                                                         inputs_info.push((Some(idx), tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1648                                                         total_value += tx.output[transaction_output_index as usize].value;
1649                                                 } else {
1650                                                         let mut single_htlc_tx = Transaction {
1651                                                                 version: 2,
1652                                                                 lock_time: 0,
1653                                                                 input: vec![input],
1654                                                                 output: vec!(TxOut {
1655                                                                         script_pubkey: self.destination_script.clone(),
1656                                                                         value: htlc.amount_msat / 1000,
1657                                                                 }),
1658                                                         };
1659                                                         let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1660                                                         let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1661                                                         let mut used_feerate;
1662                                                         if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1663                                                                 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1664                                                                 let (redeemscript, revocation_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1665                                                                 assert!(predicted_weight >= single_htlc_tx.get_weight());
1666                                                                 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", single_htlc_tx.input[0].previous_output.txid, single_htlc_tx.input[0].previous_output.vout, height_timer);
1667                                                                 let mut per_input_material = HashMap::with_capacity(1);
1668                                                                 per_input_material.insert(single_htlc_tx.input[0].previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: htlc.amount_msat / 1000 });
1669                                                                 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1670                                                                         hash_map::Entry::Occupied(_) => {},
1671                                                                         hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1672                                                                 }
1673                                                                 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1674                                                                         hash_map::Entry::Occupied(_) => {},
1675                                                                         hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1676                                                                 }
1677                                                                 txn_to_broadcast.push(single_htlc_tx);
1678                                                         }
1679                                                 }
1680                                         }
1681                                 }
1682                         }
1683
1684                         if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1685                                 // We're definitely a remote commitment transaction!
1686                                 log_trace!(self, "Got broadcast of revoked remote commitment transaction, generating general spend tx with {} inputs and {} other txn to broadcast", inputs.len(), txn_to_broadcast.len());
1687                                 watch_outputs.append(&mut tx.output.clone());
1688                                 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1689
1690                                 macro_rules! check_htlc_fails {
1691                                         ($txid: expr, $commitment_tx: expr) => {
1692                                                 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1693                                                         for &(ref htlc, ref source_option) in outpoints.iter() {
1694                                                                 if let &Some(ref source) = source_option {
1695                                                                         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);
1696                                                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1697                                                                                 hash_map::Entry::Occupied(mut entry) => {
1698                                                                                         let e = entry.get_mut();
1699                                                                                         e.retain(|ref event| {
1700                                                                                                 match **event {
1701                                                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
1702                                                                                                                 return htlc_update.0 != **source
1703                                                                                                         },
1704                                                                                                         _ => return true
1705                                                                                                 }
1706                                                                                         });
1707                                                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1708                                                                                 }
1709                                                                                 hash_map::Entry::Vacant(entry) => {
1710                                                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1711                                                                                 }
1712                                                                         }
1713                                                                 }
1714                                                         }
1715                                                 }
1716                                         }
1717                                 }
1718                                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1719                                         if let &Some(ref txid) = current_remote_commitment_txid {
1720                                                 check_htlc_fails!(txid, "current");
1721                                         }
1722                                         if let &Some(ref txid) = prev_remote_commitment_txid {
1723                                                 check_htlc_fails!(txid, "remote");
1724                                         }
1725                                 }
1726                                 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1727                         }
1728                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1729
1730                         let outputs = vec!(TxOut {
1731                                 script_pubkey: self.destination_script.clone(),
1732                                 value: total_value,
1733                         });
1734                         let mut spend_tx = Transaction {
1735                                 version: 2,
1736                                 lock_time: 0,
1737                                 input: inputs,
1738                                 output: outputs,
1739                         };
1740
1741                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1742
1743                         let mut used_feerate;
1744                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1745                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1746                         }
1747
1748                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1749
1750                         let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1751                         let mut soonest_timelock = ::std::u32::MAX;
1752                         for info in inputs_info.iter() {
1753                                 if info.2 <= soonest_timelock {
1754                                         soonest_timelock = info.2;
1755                                 }
1756                         }
1757                         let height_timer = Self::get_height_timer(height, soonest_timelock);
1758                         let spend_txid = spend_tx.txid();
1759                         for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1760                                 let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1);
1761                                 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer);
1762                                 per_input_material.insert(input.previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: if info.0.is_some() { Some(revocation_pubkey) } else { None }, key: revocation_key, is_htlc: if info.0.is_some() { true } else { false }, amount: info.1 });
1763                                 match self.claimable_outpoints.entry(input.previous_output) {
1764                                         hash_map::Entry::Occupied(_) => {},
1765                                         hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1766                                 }
1767                         }
1768                         match self.pending_claim_requests.entry(spend_txid) {
1769                                 hash_map::Entry::Occupied(_) => {},
1770                                 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1771                         }
1772
1773                         assert!(predicted_weight >= spend_tx.get_weight());
1774
1775                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1776                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1777                                 output: spend_tx.output[0].clone(),
1778                         });
1779                         txn_to_broadcast.push(spend_tx);
1780                 } else if let Some(per_commitment_data) = per_commitment_option {
1781                         // While this isn't useful yet, there is a potential race where if a counterparty
1782                         // revokes a state at the same time as the commitment transaction for that state is
1783                         // confirmed, and the watchtower receives the block before the user, the user could
1784                         // upload a new ChannelMonitor with the revocation secret but the watchtower has
1785                         // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1786                         // not being generated by the above conditional. Thus, to be safe, we go ahead and
1787                         // insert it here.
1788                         watch_outputs.append(&mut tx.output.clone());
1789                         self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1790
1791                         log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1792
1793                         macro_rules! check_htlc_fails {
1794                                 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1795                                         if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1796                                                 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1797                                                         if let &Some(ref source) = source_option {
1798                                                                 // Check if the HTLC is present in the commitment transaction that was
1799                                                                 // broadcast, but not if it was below the dust limit, which we should
1800                                                                 // fail backwards immediately as there is no way for us to learn the
1801                                                                 // payment_preimage.
1802                                                                 // Note that if the dust limit were allowed to change between
1803                                                                 // commitment transactions we'd want to be check whether *any*
1804                                                                 // broadcastable commitment transaction has the HTLC in it, but it
1805                                                                 // cannot currently change after channel initialization, so we don't
1806                                                                 // need to here.
1807                                                                 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1808                                                                         if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1809                                                                                 continue $id;
1810                                                                         }
1811                                                                 }
1812                                                                 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);
1813                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1814                                                                         hash_map::Entry::Occupied(mut entry) => {
1815                                                                                 let e = entry.get_mut();
1816                                                                                 e.retain(|ref event| {
1817                                                                                         match **event {
1818                                                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1819                                                                                                         return htlc_update.0 != **source
1820                                                                                                 },
1821                                                                                                 _ => return true
1822                                                                                         }
1823                                                                                 });
1824                                                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1825                                                                         }
1826                                                                         hash_map::Entry::Vacant(entry) => {
1827                                                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1828                                                                         }
1829                                                                 }
1830                                                         }
1831                                                 }
1832                                         }
1833                                 }
1834                         }
1835                         if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1836                                 if let &Some(ref txid) = current_remote_commitment_txid {
1837                                         check_htlc_fails!(txid, "current", 'current_loop);
1838                                 }
1839                                 if let &Some(ref txid) = prev_remote_commitment_txid {
1840                                         check_htlc_fails!(txid, "previous", 'prev_loop);
1841                                 }
1842                         }
1843
1844                         if let Some(revocation_points) = self.their_cur_revocation_points {
1845                                 let revocation_point_option =
1846                                         if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1847                                         else if let Some(point) = revocation_points.2.as_ref() {
1848                                                 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1849                                         } else { None };
1850                                 if let Some(revocation_point) = revocation_point_option {
1851                                         let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1852                                                 Storage::Local { ref keys, .. } => {
1853                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1854                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)))
1855                                                 },
1856                                                 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1857                                                         (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1858                                                         ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1859                                                 },
1860                                         };
1861                                         let a_htlc_key = match self.their_htlc_base_key {
1862                                                 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1863                                                 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1864                                         };
1865
1866                                         for (idx, outp) in tx.output.iter().enumerate() {
1867                                                 if outp.script_pubkey.is_v0_p2wpkh() {
1868                                                         match self.key_storage {
1869                                                                 Storage::Local { ref payment_base_key, .. } => {
1870                                                                         if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1871                                                                                 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1872                                                                                         outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1873                                                                                         key: local_key,
1874                                                                                         output: outp.clone(),
1875                                                                                 });
1876                                                                         }
1877                                                                 },
1878                                                                 Storage::Watchtower { .. } => {}
1879                                                         }
1880                                                         break; // Only to_remote ouput is claimable
1881                                                 }
1882                                         }
1883
1884                                         let mut total_value = 0;
1885                                         let mut inputs = Vec::new();
1886                                         let mut inputs_desc = Vec::new();
1887                                         let mut inputs_info = Vec::new();
1888
1889                                         macro_rules! sign_input {
1890                                                 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr, $idx: expr) => {
1891                                                         {
1892                                                                 let (sig, redeemscript, htlc_key) = match self.key_storage {
1893                                                                         Storage::Local { ref htlc_base_key, .. } => {
1894                                                                                 let htlc = &per_commitment_option.unwrap()[$idx as usize].0;
1895                                                                                 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1896                                                                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1897                                                                                 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1898                                                                                 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript, htlc_key)
1899                                                                         },
1900                                                                         Storage::Watchtower { .. } => {
1901                                                                                 unimplemented!();
1902                                                                         }
1903                                                                 };
1904                                                                 $input.witness.push(sig.serialize_der().to_vec());
1905                                                                 $input.witness[0].push(SigHashType::All as u8);
1906                                                                 $input.witness.push($preimage);
1907                                                                 $input.witness.push(redeemscript.clone().into_bytes());
1908                                                                 (redeemscript, htlc_key)
1909                                                         }
1910                                                 }
1911                                         }
1912
1913                                         for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1914                                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
1915                                                         let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1916                                                         if transaction_output_index as usize >= tx.output.len() ||
1917                                                                         tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1918                                                                         tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1919                                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1920                                                         }
1921                                                         if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1922                                                                 if htlc.offered {
1923                                                                         let input = TxIn {
1924                                                                                 previous_output: BitcoinOutPoint {
1925                                                                                         txid: commitment_txid,
1926                                                                                         vout: transaction_output_index,
1927                                                                                 },
1928                                                                                 script_sig: Script::new(),
1929                                                                                 sequence: 0xff_ff_ff_fd,
1930                                                                                 witness: Vec::new(),
1931                                                                         };
1932                                                                         if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1933                                                                                 inputs.push(input);
1934                                                                                 inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
1935                                                                                 inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry, idx));
1936                                                                                 total_value += tx.output[transaction_output_index as usize].value;
1937                                                                         } else {
1938                                                                                 let mut single_htlc_tx = Transaction {
1939                                                                                         version: 2,
1940                                                                                         lock_time: 0,
1941                                                                                         input: vec![input],
1942                                                                                         output: vec!(TxOut {
1943                                                                                                 script_pubkey: self.destination_script.clone(),
1944                                                                                                 value: htlc.amount_msat / 1000,
1945                                                                                         }),
1946                                                                                 };
1947                                                                                 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
1948                                                                                 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1949                                                                                 let mut used_feerate;
1950                                                                                 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1951                                                                                         let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1952                                                                                         let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec(), idx);
1953                                                                                         assert!(predicted_weight >= single_htlc_tx.get_weight());
1954                                                                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1955                                                                                                 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1956                                                                                                 output: single_htlc_tx.output[0].clone(),
1957                                                                                         });
1958                                                                                         log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", single_htlc_tx.input[0].previous_output.txid, single_htlc_tx.input[0].previous_output.vout, height_timer);
1959                                                                                         let mut per_input_material = HashMap::with_capacity(1);
1960                                                                                         per_input_material.insert(single_htlc_tx.input[0].previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000, locktime: 0 });
1961                                                                                         match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1962                                                                                                 hash_map::Entry::Occupied(_) => {},
1963                                                                                                 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1964                                                                                         }
1965                                                                                         match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1966                                                                                                 hash_map::Entry::Occupied(_) => {},
1967                                                                                                 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material}); }
1968                                                                                         }
1969                                                                                         txn_to_broadcast.push(single_htlc_tx);
1970                                                                                 }
1971                                                                         }
1972                                                                 }
1973                                                         }
1974                                                         if !htlc.offered {
1975                                                                 // TODO: If the HTLC has already expired, potentially merge it with the
1976                                                                 // rest of the claim transaction, as above.
1977                                                                 let input = TxIn {
1978                                                                         previous_output: BitcoinOutPoint {
1979                                                                                 txid: commitment_txid,
1980                                                                                 vout: transaction_output_index,
1981                                                                         },
1982                                                                         script_sig: Script::new(),
1983                                                                         sequence: 0xff_ff_ff_fd,
1984                                                                         witness: Vec::new(),
1985                                                                 };
1986                                                                 let mut timeout_tx = Transaction {
1987                                                                         version: 2,
1988                                                                         lock_time: htlc.cltv_expiry,
1989                                                                         input: vec![input],
1990                                                                         output: vec!(TxOut {
1991                                                                                 script_pubkey: self.destination_script.clone(),
1992                                                                                 value: htlc.amount_msat / 1000,
1993                                                                         }),
1994                                                                 };
1995                                                                 let predicted_weight = timeout_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]);
1996                                                                 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1997                                                                 let mut used_feerate;
1998                                                                 if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
1999                                                                         let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
2000                                                                         let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0], idx);
2001                                                                         assert!(predicted_weight >= timeout_tx.get_weight());
2002                                                                         //TODO: track SpendableOutputDescriptor
2003                                                                         log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", timeout_tx.input[0].previous_output.txid, timeout_tx.input[0].previous_output.vout, height_timer);
2004                                                                         let mut per_input_material = HashMap::with_capacity(1);
2005                                                                         per_input_material.insert(timeout_tx.input[0].previous_output, InputMaterial::RemoteHTLC { script : redeemscript, key: htlc_key, preimage: None, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry });
2006                                                                         match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) {
2007                                                                                 hash_map::Entry::Occupied(_) => {},
2008                                                                                 hash_map::Entry::Vacant(entry) => { entry.insert((timeout_tx.txid(), height)); }
2009                                                                         }
2010                                                                         match self.pending_claim_requests.entry(timeout_tx.txid()) {
2011                                                                                 hash_map::Entry::Occupied(_) => {},
2012                                                                                 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
2013                                                                         }
2014                                                                 }
2015                                                                 txn_to_broadcast.push(timeout_tx);
2016                                                         }
2017                                                 }
2018                                         }
2019
2020                                         if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
2021
2022                                         let outputs = vec!(TxOut {
2023                                                 script_pubkey: self.destination_script.clone(),
2024                                                 value: total_value
2025                                         });
2026                                         let mut spend_tx = Transaction {
2027                                                 version: 2,
2028                                                 lock_time: 0,
2029                                                 input: inputs,
2030                                                 output: outputs,
2031                                         };
2032
2033                                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
2034
2035                                         let mut used_feerate;
2036                                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2037                                                 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
2038                                         }
2039
2040                                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2041
2042                                         let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
2043                                         let mut soonest_timelock = ::std::u32::MAX;
2044                                         for info in inputs_info.iter() {
2045                                                 if info.2 <= soonest_timelock {
2046                                                         soonest_timelock = info.2;
2047                                                 }
2048                                         }
2049                                         let height_timer = Self::get_height_timer(height, soonest_timelock);
2050                                         let spend_txid = spend_tx.txid();
2051                                         for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
2052                                                 let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec(), info.3);
2053                                                 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer);
2054                                                 per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
2055                                                 match self.claimable_outpoints.entry(input.previous_output) {
2056                                                         hash_map::Entry::Occupied(_) => {},
2057                                                         hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
2058                                                 }
2059                                         }
2060                                         match self.pending_claim_requests.entry(spend_txid) {
2061                                                 hash_map::Entry::Occupied(_) => {},
2062                                                 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
2063                                         }
2064                                         assert!(predicted_weight >= spend_tx.get_weight());
2065                                         spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2066                                                 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
2067                                                 output: spend_tx.output[0].clone(),
2068                                         });
2069                                         txn_to_broadcast.push(spend_tx);
2070                                 }
2071                         }
2072                 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
2073                         for (idx, outp) in tx.output.iter().enumerate() {
2074                                 if to_remote_rescue == &outp.script_pubkey {
2075                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
2076                                                 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
2077                                                 key: local_key.clone(),
2078                                                 output: outp.clone(),
2079                                         });
2080                                 }
2081                         }
2082                 }
2083
2084                 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
2085         }
2086
2087         /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
2088         fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32, fee_estimator: &FeeEstimator) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
2089                 //TODO: send back new outputs to guarantee pending_claim_request consistency
2090                 if tx.input.len() != 1 || tx.output.len() != 1 {
2091                         return (None, None)
2092                 }
2093
2094                 macro_rules! ignore_error {
2095                         ( $thing : expr ) => {
2096                                 match $thing {
2097                                         Ok(a) => a,
2098                                         Err(_) => return (None, None)
2099                                 }
2100                         };
2101                 }
2102
2103                 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
2104                 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2105                 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2106                 let revocation_pubkey = match self.key_storage {
2107                         Storage::Local { ref keys, .. } => {
2108                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint))
2109                         },
2110                         Storage::Watchtower { ref revocation_base_key, .. } => {
2111                                 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
2112                         },
2113                 };
2114                 let delayed_key = match self.their_delayed_payment_base_key {
2115                         None => return (None, None),
2116                         Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
2117                 };
2118                 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
2119                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2120                 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2121
2122                 let mut inputs = Vec::new();
2123                 let mut amount = 0;
2124
2125                 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
2126                         inputs.push(TxIn {
2127                                 previous_output: BitcoinOutPoint {
2128                                         txid: htlc_txid,
2129                                         vout: 0,
2130                                 },
2131                                 script_sig: Script::new(),
2132                                 sequence: 0xfffffffd,
2133                                 witness: Vec::new(),
2134                         });
2135                         amount = tx.output[0].value;
2136                 }
2137
2138                 if !inputs.is_empty() {
2139                         let outputs = vec!(TxOut {
2140                                 script_pubkey: self.destination_script.clone(),
2141                                 value: amount
2142                         });
2143
2144                         let mut spend_tx = Transaction {
2145                                 version: 2,
2146                                 lock_time: 0,
2147                                 input: inputs,
2148                                 output: outputs,
2149                         };
2150                         let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
2151                         let mut used_feerate;
2152                         if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2153                                 return (None, None);
2154                         }
2155
2156                         let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2157
2158                         let (sig, revocation_key) = match self.key_storage {
2159                                 Storage::Local { ref revocation_base_key, .. } => {
2160                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
2161                                         let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
2162                                         (self.secp_ctx.sign(&sighash, &revocation_key), revocation_key)
2163                                 }
2164                                 Storage::Watchtower { .. } => {
2165                                         unimplemented!();
2166                                 }
2167                         };
2168                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
2169                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
2170                         spend_tx.input[0].witness.push(vec!(1));
2171                         spend_tx.input[0].witness.push(redeemscript.clone().into_bytes());
2172
2173                         assert!(predicted_weight >= spend_tx.get_weight());
2174                         let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
2175                         let output = spend_tx.output[0].clone();
2176                         let height_timer = Self::get_height_timer(height, height + self.our_to_self_delay as u32);
2177                         log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", spend_tx.input[0].previous_output.txid, spend_tx.input[0].previous_output.vout, height_timer);
2178                         let mut per_input_material = HashMap::with_capacity(1);
2179                         per_input_material.insert(spend_tx.input[0].previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: None, key: revocation_key, is_htlc: false, amount: tx.output[0].value });
2180                         match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) {
2181                                 hash_map::Entry::Occupied(_) => {},
2182                                 hash_map::Entry::Vacant(entry) => { entry.insert((spend_tx.txid(), height)); }
2183                         }
2184                         match self.pending_claim_requests.entry(spend_tx.txid()) {
2185                                 hash_map::Entry::Occupied(_) => {},
2186                                 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: height + self.our_to_self_delay as u32, per_input_material }); }
2187                         }
2188                         (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
2189                 } else { (None, None) }
2190         }
2191
2192         fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>, Vec<(Sha256dHash, ClaimTxBumpMaterial)>) {
2193                 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
2194                 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2195                 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2196                 let mut pending_claims = Vec::with_capacity(local_tx.htlc_outputs.len());
2197
2198                 macro_rules! add_dynamic_output {
2199                         ($father_tx: expr, $vout: expr) => {
2200                                 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
2201                                         spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
2202                                                 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
2203                                                 key: local_delayedkey,
2204                                                 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
2205                                                 to_self_delay: self.our_to_self_delay,
2206                                                 output: $father_tx.output[$vout as usize].clone(),
2207                                         });
2208                                 }
2209                         }
2210                 }
2211
2212                 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
2213                 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2214                 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
2215                         if output.script_pubkey == revokeable_p2wsh {
2216                                 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
2217                                 break;
2218                         }
2219                 }
2220
2221                 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
2222                         for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
2223                                 if let Some(transaction_output_index) = htlc.transaction_output_index {
2224                                         if let &Some(ref their_sig) = sigs {
2225                                                 if htlc.offered {
2226                                                         log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
2227                                                         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);
2228                                                         let (our_sig, htlc_script) = match
2229                                                                         chan_utils::sign_htlc_transaction(&mut htlc_timeout_tx, their_sig, &None, htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
2230                                                                 Ok(res) => res,
2231                                                                 Err(_) => continue,
2232                                                         };
2233
2234                                                         add_dynamic_output!(htlc_timeout_tx, 0);
2235                                                         let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2236                                                         let mut per_input_material = HashMap::with_capacity(1);
2237                                                         per_input_material.insert(htlc_timeout_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: None, amount: htlc.amount_msat / 1000});
2238                                                         //TODO: with option_simplified_commitment track outpoint too
2239                                                         log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid, height_timer);
2240                                                         pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2241                                                         res.push(htlc_timeout_tx);
2242                                                 } else {
2243                                                         if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2244                                                                 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
2245                                                                 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);
2246                                                                 let (our_sig, htlc_script) = match
2247                                                                                 chan_utils::sign_htlc_transaction(&mut htlc_success_tx, their_sig, &Some(*payment_preimage), htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
2248                                                                         Ok(res) => res,
2249                                                                         Err(_) => continue,
2250                                                                 };
2251
2252                                                                 add_dynamic_output!(htlc_success_tx, 0);
2253                                                                 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2254                                                                 let mut per_input_material = HashMap::with_capacity(1);
2255                                                                 per_input_material.insert(htlc_success_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000});
2256                                                                 //TODO: with option_simplified_commitment track outpoint too
2257                                                                 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid, height_timer);
2258                                                                 pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2259                                                                 res.push(htlc_success_tx);
2260                                                         }
2261                                                 }
2262                                                 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
2263                                         } else { panic!("Should have sigs for non-dust local tx outputs!") }
2264                                 }
2265                         }
2266                 }
2267
2268                 (res, spendable_outputs, watch_outputs, pending_claims)
2269         }
2270
2271         /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2272         /// revoked using data in local_claimable_outpoints.
2273         /// Should not be used if check_spend_revoked_transaction succeeds.
2274         fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
2275                 let commitment_txid = tx.txid();
2276                 let mut local_txn = Vec::new();
2277                 let mut spendable_outputs = Vec::new();
2278                 let mut watch_outputs = Vec::new();
2279
2280                 macro_rules! wait_threshold_conf {
2281                         ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
2282                                 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);
2283                                 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
2284                                         hash_map::Entry::Occupied(mut entry) => {
2285                                                 let e = entry.get_mut();
2286                                                 e.retain(|ref event| {
2287                                                         match **event {
2288                                                                 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2289                                                                         return htlc_update.0 != $source
2290                                                                 },
2291                                                                 _ => return true
2292                                                         }
2293                                                 });
2294                                                 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
2295                                         }
2296                                         hash_map::Entry::Vacant(entry) => {
2297                                                 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
2298                                         }
2299                                 }
2300                         }
2301                 }
2302
2303                 macro_rules! append_onchain_update {
2304                         ($updates: expr) => {
2305                                 local_txn.append(&mut $updates.0);
2306                                 spendable_outputs.append(&mut $updates.1);
2307                                 watch_outputs.append(&mut $updates.2);
2308                                 for claim in $updates.3 {
2309                                         match self.pending_claim_requests.entry(claim.0) {
2310                                                 hash_map::Entry::Occupied(_) => {},
2311                                                 hash_map::Entry::Vacant(entry) => { entry.insert(claim.1); }
2312                                         }
2313                                 }
2314                         }
2315                 }
2316
2317                 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2318                 let mut is_local_tx = false;
2319
2320                 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2321                         if local_tx.txid == commitment_txid {
2322                                 match self.key_storage {
2323                                         Storage::Local { ref funding_key, .. } => {
2324                                                 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2325                                         },
2326                                         _ => {},
2327                                 }
2328                         }
2329                 }
2330                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2331                         if local_tx.txid == commitment_txid {
2332                                 is_local_tx = true;
2333                                 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
2334                                 assert!(local_tx.tx.has_local_sig());
2335                                 match self.key_storage {
2336                                         Storage::Local { ref delayed_payment_base_key, .. } => {
2337                                                 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2338                                                 append_onchain_update!(res);
2339                                         },
2340                                         Storage::Watchtower { .. } => { }
2341                                 }
2342                         }
2343                 }
2344                 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
2345                         if local_tx.txid == commitment_txid {
2346                                 match self.key_storage {
2347                                         Storage::Local { ref funding_key, .. } => {
2348                                                 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2349                                         },
2350                                         _ => {},
2351                                 }
2352                         }
2353                 }
2354                 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2355                         if local_tx.txid == commitment_txid {
2356                                 is_local_tx = true;
2357                                 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
2358                                 assert!(local_tx.tx.has_local_sig());
2359                                 match self.key_storage {
2360                                         Storage::Local { ref delayed_payment_base_key, .. } => {
2361                                                 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2362                                                 append_onchain_update!(res);
2363                                         },
2364                                         Storage::Watchtower { .. } => { }
2365                                 }
2366                         }
2367                 }
2368
2369                 macro_rules! fail_dust_htlcs_after_threshold_conf {
2370                         ($local_tx: expr) => {
2371                                 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
2372                                         if htlc.transaction_output_index.is_none() {
2373                                                 if let &Some(ref source) = source {
2374                                                         wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
2375                                                 }
2376                                         }
2377                                 }
2378                         }
2379                 }
2380
2381                 if is_local_tx {
2382                         if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2383                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
2384                         }
2385                         if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2386                                 fail_dust_htlcs_after_threshold_conf!(local_tx);
2387                         }
2388                 }
2389
2390                 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
2391         }
2392
2393         /// Generate a spendable output event when closing_transaction get registered onchain.
2394         fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
2395                 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
2396                         match self.key_storage {
2397                                 Storage::Local { ref shutdown_pubkey, .. } =>  {
2398                                         let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
2399                                         let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
2400                                         for (idx, output) in tx.output.iter().enumerate() {
2401                                                 if shutdown_script == output.script_pubkey {
2402                                                         return Some(SpendableOutputDescriptor::StaticOutput {
2403                                                                 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
2404                                                                 output: output.clone(),
2405                                                         });
2406                                                 }
2407                                         }
2408                                 }
2409                                 Storage::Watchtower { .. } => {
2410                                         //TODO: we need to ensure an offline client will generate the event when it
2411                                         // comes back online after only the watchtower saw the transaction
2412                                 }
2413                         }
2414                 }
2415                 None
2416         }
2417
2418         /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
2419         /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
2420         /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
2421         /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
2422         /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
2423         /// broadcast them if remote don't close channel with his higher commitment transaction after a
2424         /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
2425         /// out-of-band the other node operator to coordinate with him if option is available to you.
2426         /// In any-case, choice is up to the user.
2427         pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
2428                 log_trace!(self, "Getting signed latest local commitment transaction!");
2429                 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2430                         match self.key_storage {
2431                                 Storage::Local { ref funding_key, .. } => {
2432                                         local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2433                                 },
2434                                 _ => {},
2435                         }
2436                 }
2437                 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2438                         let mut res = vec![local_tx.tx.with_valid_witness().clone()];
2439                         match self.key_storage {
2440                                 Storage::Local { ref delayed_payment_base_key, .. } => {
2441                                         res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
2442                                         // 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.
2443                                         // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
2444                                 },
2445                                 _ => panic!("Can only broadcast by local channelmonitor"),
2446                         };
2447                         res
2448                 } else {
2449                         Vec::new()
2450                 }
2451         }
2452
2453         /// Called by SimpleManyChannelMonitor::block_connected, which implements
2454         /// ChainListener::block_connected.
2455         /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
2456         /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
2457         /// on-chain.
2458         fn block_connected<B: Deref>(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: &FeeEstimator)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>)
2459                 where B::Target: BroadcasterInterface
2460         {
2461                 for tx in txn_matched {
2462                         let mut output_val = 0;
2463                         for out in tx.output.iter() {
2464                                 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2465                                 output_val += out.value;
2466                                 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2467                         }
2468                 }
2469
2470                 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2471                 let mut watch_outputs = Vec::new();
2472                 let mut spendable_outputs = Vec::new();
2473                 let mut bump_candidates = HashSet::new();
2474                 for tx in txn_matched {
2475                         if tx.input.len() == 1 {
2476                                 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2477                                 // commitment transactions and HTLC transactions will all only ever have one input,
2478                                 // which is an easy way to filter out any potential non-matching txn for lazy
2479                                 // filters.
2480                                 let prevout = &tx.input[0].previous_output;
2481                                 let mut txn: Vec<Transaction> = Vec::new();
2482                                 let funding_txo = match self.key_storage {
2483                                         Storage::Local { ref funding_info, .. } => {
2484                                                 funding_info.clone()
2485                                         }
2486                                         Storage::Watchtower { .. } => {
2487                                                 unimplemented!();
2488                                         }
2489                                 };
2490                                 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) {
2491                                         if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2492                                                 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
2493                                                 txn = remote_txn;
2494                                                 spendable_outputs.append(&mut spendable_output);
2495                                                 if !new_outputs.1.is_empty() {
2496                                                         watch_outputs.push(new_outputs);
2497                                                 }
2498                                                 if txn.is_empty() {
2499                                                         let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2500                                                         spendable_outputs.append(&mut spendable_output);
2501                                                         txn = local_txn;
2502                                                         if !new_outputs.1.is_empty() {
2503                                                                 watch_outputs.push(new_outputs);
2504                                                         }
2505                                                 }
2506                                         }
2507                                         if !funding_txo.is_none() && txn.is_empty() {
2508                                                 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2509                                                         spendable_outputs.push(spendable_output);
2510                                                 }
2511                                         }
2512                                 } else {
2513                                         if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2514                                                 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
2515                                                 if let Some(tx) = tx {
2516                                                         txn.push(tx);
2517                                                 }
2518                                                 if let Some(spendable_output) = spendable_output {
2519                                                         spendable_outputs.push(spendable_output);
2520                                                 }
2521                                         }
2522                                 }
2523                                 for tx in txn.iter() {
2524                                         log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2525                                         broadcaster.broadcast_transaction(tx);
2526                                 }
2527                         }
2528                         // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2529                         // can also be resolved in a few other ways which can have more than one output. Thus,
2530                         // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2531                         self.is_resolving_htlc_output(&tx, height);
2532
2533                         // Scan all input to verify is one of the outpoint spent is of interest for us
2534                         let mut claimed_outputs_material = Vec::new();
2535                         for inp in &tx.input {
2536                                 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2537                                         // If outpoint has claim request pending on it...
2538                                         if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2539                                                 //... we need to verify equality between transaction outpoints and claim request
2540                                                 // outpoints to know if transaction is the original claim or a bumped one issued
2541                                                 // by us.
2542                                                 let mut set_equality = true;
2543                                                 if claim_material.per_input_material.len() != tx.input.len() {
2544                                                         set_equality = false;
2545                                                 } else {
2546                                                         for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2547                                                                 if *claim_inp != tx_inp.previous_output {
2548                                                                         set_equality = false;
2549                                                                 }
2550                                                         }
2551                                                 }
2552
2553                                                 macro_rules! clean_claim_request_after_safety_delay {
2554                                                         () => {
2555                                                                 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2556                                                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2557                                                                         hash_map::Entry::Occupied(mut entry) => {
2558                                                                                 if !entry.get().contains(&new_event) {
2559                                                                                         entry.get_mut().push(new_event);
2560                                                                                 }
2561                                                                         },
2562                                                                         hash_map::Entry::Vacant(entry) => {
2563                                                                                 entry.insert(vec![new_event]);
2564                                                                         }
2565                                                                 }
2566                                                         }
2567                                                 }
2568
2569                                                 // If this is our transaction (or our counterparty spent all the outputs
2570                                                 // before we could anyway with same inputs order than us), wait for
2571                                                 // ANTI_REORG_DELAY and clean the RBF tracking map.
2572                                                 if set_equality {
2573                                                         clean_claim_request_after_safety_delay!();
2574                                                 } else { // If false, generate new claim request with update outpoint set
2575                                                         for input in tx.input.iter() {
2576                                                                 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2577                                                                         claimed_outputs_material.push((input.previous_output, input_material));
2578                                                                 }
2579                                                                 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2580                                                                 if claim_material.per_input_material.is_empty() {
2581                                                                         clean_claim_request_after_safety_delay!();
2582                                                                 }
2583                                                         }
2584                                                         //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2585                                                         bump_candidates.insert(first_claim_txid_height.0.clone());
2586                                                 }
2587                                                 break; //No need to iterate further, either tx is our or their
2588                                         } else {
2589                                                 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2590                                         }
2591                                 }
2592                         }
2593                         for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2594                                 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2595                                 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2596                                         hash_map::Entry::Occupied(mut entry) => {
2597                                                 if !entry.get().contains(&new_event) {
2598                                                         entry.get_mut().push(new_event);
2599                                                 }
2600                                         },
2601                                         hash_map::Entry::Vacant(entry) => {
2602                                                 entry.insert(vec![new_event]);
2603                                         }
2604                                 }
2605                         }
2606                 }
2607                 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2608                         self.would_broadcast_at_height(height)
2609                 } else { false };
2610                 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2611                         if should_broadcast {
2612                                 match self.key_storage {
2613                                         Storage::Local { ref funding_key, .. } => {
2614                                                 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2615                                         },
2616                                         _ => {}
2617                                 }
2618                         }
2619                 }
2620                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2621                         if should_broadcast {
2622                                 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2623                                 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2624                                 match self.key_storage {
2625                                         Storage::Local { ref delayed_payment_base_key, .. } => {
2626                                                 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2627                                                 spendable_outputs.append(&mut spendable_output);
2628                                                 if !new_outputs.is_empty() {
2629                                                         watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2630                                                 }
2631                                                 for tx in txs {
2632                                                         log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2633                                                         broadcaster.broadcast_transaction(&tx);
2634                                                 }
2635                                         },
2636                                         Storage::Watchtower { .. } => { },
2637                                 }
2638                         }
2639                 }
2640                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2641                         for ev in events {
2642                                 match ev {
2643                                         OnchainEvent::Claim { claim_request } => {
2644                                                 // We may remove a whole set of claim outpoints here, as these one may have
2645                                                 // been aggregated in a single tx and claimed so atomically
2646                                                 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2647                                                         for outpoint in bump_material.per_input_material.keys() {
2648                                                                 self.claimable_outpoints.remove(&outpoint);
2649                                                         }
2650                                                 }
2651                                         },
2652                                         OnchainEvent::HTLCUpdate { htlc_update } => {
2653                                                 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2654                                                 self.pending_htlcs_updated.push(HTLCUpdate {
2655                                                         payment_hash: htlc_update.1,
2656                                                         payment_preimage: None,
2657                                                         source: htlc_update.0,
2658                                                 });
2659                                         },
2660                                         OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2661                                                 self.claimable_outpoints.remove(&outpoint);
2662                                         }
2663                                 }
2664                         }
2665                 }
2666                 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2667                         if cached_claim_datas.height_timer == height {
2668                                 bump_candidates.insert(first_claim_txid.clone());
2669                         }
2670                 }
2671                 for first_claim_txid in bump_candidates.iter() {
2672                         if let Some((new_timer, new_feerate)) = {
2673                                 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2674                                         if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2675                                                 broadcaster.broadcast_transaction(&bump_tx);
2676                                                 Some((new_timer, new_feerate))
2677                                         } else { None }
2678                                 } else { unreachable!(); }
2679                         } {
2680                                 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2681                                         claim_material.height_timer = new_timer;
2682                                         claim_material.feerate_previous = new_feerate;
2683                                 } else { unreachable!(); }
2684                         }
2685                 }
2686                 self.last_block_hash = block_hash.clone();
2687                 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2688                         self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2689                 }
2690                 (watch_outputs, spendable_outputs)
2691         }
2692
2693         fn block_disconnected<B: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: &FeeEstimator)
2694                 where B::Target: BroadcasterInterface
2695         {
2696                 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2697                 let mut bump_candidates = HashMap::new();
2698                 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2699                         //We may discard:
2700                         //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2701                         //- our claim tx on a commitment tx output
2702                         //- resurect outpoint back in its claimable set and regenerate tx
2703                         for ev in events {
2704                                 match ev {
2705                                         OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2706                                                 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2707                                                         if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2708                                                                 claim_material.per_input_material.insert(outpoint, input_material);
2709                                                                 // Using a HashMap guarantee us than if we have multiple outpoints getting
2710                                                                 // resurrected only one bump claim tx is going to be broadcast
2711                                                                 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2712                                                         }
2713                                                 }
2714                                         },
2715                                         _ => {},
2716                                 }
2717                         }
2718                 }
2719                 for (_, claim_material) in bump_candidates.iter_mut() {
2720                         if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2721                                 claim_material.height_timer = new_timer;
2722                                 claim_material.feerate_previous = new_feerate;
2723                                 broadcaster.broadcast_transaction(&bump_tx);
2724                         }
2725                 }
2726                 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2727                         self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2728                 }
2729                 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2730                 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2731                 let mut remove_request = Vec::new();
2732                 self.claimable_outpoints.retain(|_, ref v|
2733                         if v.1 == height {
2734                         remove_request.push(v.0.clone());
2735                         false
2736                         } else { true });
2737                 for req in remove_request {
2738                         self.pending_claim_requests.remove(&req);
2739                 }
2740                 self.last_block_hash = block_hash.clone();
2741         }
2742
2743         pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2744                 // We need to consider all HTLCs which are:
2745                 //  * in any unrevoked remote commitment transaction, as they could broadcast said
2746                 //    transactions and we'd end up in a race, or
2747                 //  * are in our latest local commitment transaction, as this is the thing we will
2748                 //    broadcast if we go on-chain.
2749                 // Note that we consider HTLCs which were below dust threshold here - while they don't
2750                 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2751                 // to the source, and if we don't fail the channel we will have to ensure that the next
2752                 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2753                 // easier to just fail the channel as this case should be rare enough anyway.
2754                 macro_rules! scan_commitment {
2755                         ($htlcs: expr, $local_tx: expr) => {
2756                                 for ref htlc in $htlcs {
2757                                         // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2758                                         // chain with enough room to claim the HTLC without our counterparty being able to
2759                                         // time out the HTLC first.
2760                                         // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2761                                         // concern is being able to claim the corresponding inbound HTLC (on another
2762                                         // channel) before it expires. In fact, we don't even really care if our
2763                                         // counterparty here claims such an outbound HTLC after it expired as long as we
2764                                         // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2765                                         // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2766                                         // we give ourselves a few blocks of headroom after expiration before going
2767                                         // on-chain for an expired HTLC.
2768                                         // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2769                                         // from us until we've reached the point where we go on-chain with the
2770                                         // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2771                                         // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2772                                         //  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2773                                         //      inbound_cltv == height + CLTV_CLAIM_BUFFER
2774                                         //      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2775                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2776                                         //      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2777                                         //      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2778                                         //  The final, above, condition is checked for statically in channelmanager
2779                                         //  with CHECK_CLTV_EXPIRY_SANITY_2.
2780                                         let htlc_outbound = $local_tx == htlc.offered;
2781                                         if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2782                                            (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2783                                                 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2784                                                 return true;
2785                                         }
2786                                 }
2787                         }
2788                 }
2789
2790                 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2791                         scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2792                 }
2793
2794                 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2795                         if let &Some(ref txid) = current_remote_commitment_txid {
2796                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2797                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2798                                 }
2799                         }
2800                         if let &Some(ref txid) = prev_remote_commitment_txid {
2801                                 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2802                                         scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2803                                 }
2804                         }
2805                 }
2806
2807                 false
2808         }
2809
2810         /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2811         /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2812         fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2813                 'outer_loop: for input in &tx.input {
2814                         let mut payment_data = None;
2815                         let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2816                                 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2817                         let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2818                         let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2819
2820                         macro_rules! log_claim {
2821                                 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2822                                         // We found the output in question, but aren't failing it backwards
2823                                         // as we have no corresponding source and no valid remote commitment txid
2824                                         // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2825                                         // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2826                                         let outbound_htlc = $local_tx == $htlc.offered;
2827                                         if ($local_tx && revocation_sig_claim) ||
2828                                                         (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2829                                                 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2830                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2831                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2832                                                         if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2833                                         } else {
2834                                                 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2835                                                         $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2836                                                         if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2837                                                         if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2838                                         }
2839                                 }
2840                         }
2841
2842                         macro_rules! check_htlc_valid_remote {
2843                                 ($remote_txid: expr, $htlc_output: expr) => {
2844                                         if let &Some(txid) = $remote_txid {
2845                                                 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2846                                                         if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2847                                                                 if let &Some(ref source) = pending_source {
2848                                                                         log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2849                                                                         payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2850                                                                         break;
2851                                                                 }
2852                                                         }
2853                                                 }
2854                                         }
2855                                 }
2856                         }
2857
2858                         macro_rules! scan_commitment {
2859                                 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2860                                         for (ref htlc_output, source_option) in $htlcs {
2861                                                 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2862                                                         if let Some(ref source) = source_option {
2863                                                                 log_claim!($tx_info, $local_tx, htlc_output, true);
2864                                                                 // We have a resolution of an HTLC either from one of our latest
2865                                                                 // local commitment transactions or an unrevoked remote commitment
2866                                                                 // transaction. This implies we either learned a preimage, the HTLC
2867                                                                 // has timed out, or we screwed up. In any case, we should now
2868                                                                 // resolve the source HTLC with the original sender.
2869                                                                 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2870                                                         } else if !$local_tx {
2871                                                                 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2872                                                                         check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2873                                                                 }
2874                                                                 if payment_data.is_none() {
2875                                                                         if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2876                                                                                 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2877                                                                         }
2878                                                                 }
2879                                                         }
2880                                                         if payment_data.is_none() {
2881                                                                 log_claim!($tx_info, $local_tx, htlc_output, false);
2882                                                                 continue 'outer_loop;
2883                                                         }
2884                                                 }
2885                                         }
2886                                 }
2887                         }
2888
2889                         if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2890                                 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2891                                         scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2892                                                 "our latest local commitment tx", true);
2893                                 }
2894                         }
2895                         if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2896                                 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2897                                         scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2898                                                 "our previous local commitment tx", true);
2899                                 }
2900                         }
2901                         if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2902                                 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2903                                         "remote commitment tx", false);
2904                         }
2905
2906                         // Check that scan_commitment, above, decided there is some source worth relaying an
2907                         // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2908                         if let Some((source, payment_hash)) = payment_data {
2909                                 let mut payment_preimage = PaymentPreimage([0; 32]);
2910                                 if accepted_preimage_claim {
2911                                         payment_preimage.0.copy_from_slice(&input.witness[3]);
2912                                         self.pending_htlcs_updated.push(HTLCUpdate {
2913                                                 source,
2914                                                 payment_preimage: Some(payment_preimage),
2915                                                 payment_hash
2916                                         });
2917                                 } else if offered_preimage_claim {
2918                                         payment_preimage.0.copy_from_slice(&input.witness[1]);
2919                                         self.pending_htlcs_updated.push(HTLCUpdate {
2920                                                 source,
2921                                                 payment_preimage: Some(payment_preimage),
2922                                                 payment_hash
2923                                         });
2924                                 } else {
2925                                         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);
2926                                         match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2927                                                 hash_map::Entry::Occupied(mut entry) => {
2928                                                         let e = entry.get_mut();
2929                                                         e.retain(|ref event| {
2930                                                                 match **event {
2931                                                                         OnchainEvent::HTLCUpdate { ref htlc_update } => {
2932                                                                                 return htlc_update.0 != source
2933                                                                         },
2934                                                                         _ => return true
2935                                                                 }
2936                                                         });
2937                                                         e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2938                                                 }
2939                                                 hash_map::Entry::Vacant(entry) => {
2940                                                         entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2941                                                 }
2942                                         }
2943                                 }
2944                         }
2945                 }
2946         }
2947
2948         /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
2949         /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
2950         fn bump_claim_tx(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: &FeeEstimator) -> Option<(u32, u64, Transaction)> {
2951                 if cached_claim_datas.per_input_material.len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
2952                 let mut inputs = Vec::new();
2953                 for outp in cached_claim_datas.per_input_material.keys() {
2954                         inputs.push(TxIn {
2955                                 previous_output: *outp,
2956                                 script_sig: Script::new(),
2957                                 sequence: 0xfffffffd,
2958                                 witness: Vec::new(),
2959                         });
2960                 }
2961                 let mut bumped_tx = Transaction {
2962                         version: 2,
2963                         lock_time: 0,
2964                         input: inputs,
2965                         output: vec![TxOut {
2966                                 script_pubkey: self.destination_script.clone(),
2967                                 value: 0
2968                         }],
2969                 };
2970
2971                 macro_rules! RBF_bump {
2972                         ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
2973                                 {
2974                                         let mut used_feerate;
2975                                         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
2976                                         let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
2977                                                 let mut value = $amount;
2978                                                 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
2979                                                         // Overflow check is done in subtract_high_prio_fee
2980                                                         $amount - value
2981                                                 } else {
2982                                                         log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
2983                                                         return None;
2984                                                 }
2985                                         // ...else just increase the previous feerate by 25% (because that's a nice number)
2986                                         } else {
2987                                                 let fee = $old_feerate * $predicted_weight / 750;
2988                                                 if $amount <= fee {
2989                                                         log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
2990                                                         return None;
2991                                                 }
2992                                                 fee
2993                                         };
2994
2995                                         let previous_fee = $old_feerate * $predicted_weight / 1000;
2996                                         let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
2997                                         // BIP 125 Opt-in Full Replace-by-Fee Signaling
2998                                         //      * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
2999                                         //      * 4. The replacement transaction must also pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting.
3000                                         let new_fee = if new_fee < previous_fee + min_relay_fee {
3001                                                 new_fee + previous_fee + min_relay_fee - new_fee
3002                                         } else {
3003                                                 new_fee
3004                                         };
3005                                         Some((new_fee, new_fee * 1000 / $predicted_weight))
3006                                 }
3007                         }
3008                 }
3009
3010                 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
3011                 let mut inputs_witnesses_weight = 0;
3012                 let mut amt = 0;
3013                 for per_outp_material in cached_claim_datas.per_input_material.values() {
3014                         match per_outp_material {
3015                                 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
3016                                         inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { &[InputDescriptors::RevokedOfferedHTLC] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { &[InputDescriptors::RevokedReceivedHTLC] } else { unreachable!() });
3017                                         amt += *amount;
3018                                 },
3019                                 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
3020                                         inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
3021                                         amt += *amount;
3022                                 },
3023                                 &InputMaterial::LocalHTLC { .. } => { return None; }
3024                         }
3025                 }
3026
3027                 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
3028                 let new_feerate;
3029                 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
3030                         // If new computed fee is superior at the whole claimable amount burn all in fees
3031                         if new_fee > amt {
3032                                 bumped_tx.output[0].value = 0;
3033                         } else {
3034                                 bumped_tx.output[0].value = amt - new_fee;
3035                         }
3036                         new_feerate = feerate;
3037                 } else {
3038                         return None;
3039                 }
3040                 assert!(new_feerate != 0);
3041
3042                 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
3043                         match per_outp_material {
3044                                 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
3045                                         let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3046                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3047                                         let sig = self.secp_ctx.sign(&sighash, &key);
3048                                         bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3049                                         bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3050                                         if *is_htlc {
3051                                                 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
3052                                         } else {
3053                                                 bumped_tx.input[i].witness.push(vec!(1));
3054                                         }
3055                                         bumped_tx.input[i].witness.push(script.clone().into_bytes());
3056                                         log_trace!(self, "Going to broadcast bumped Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}", bumped_tx.txid(), if !is_htlc { "to_local" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { "offered" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
3057                                 },
3058                                 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
3059                                         if !preimage.is_some() { bumped_tx.lock_time = *locktime };
3060                                         let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3061                                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3062                                         let sig = self.secp_ctx.sign(&sighash, &key);
3063                                         bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3064                                         bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3065                                         if let &Some(preimage) = preimage {
3066                                                 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
3067                                         } else {
3068                                                 bumped_tx.input[i].witness.push(vec![0]);
3069                                         }
3070                                         bumped_tx.input[i].witness.push(script.clone().into_bytes());
3071                                         log_trace!(self, "Going to broadcast bumped Claim Transaction {} claiming remote {} htlc output {} from {} with new feerate {}", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
3072                                 },
3073                                 &InputMaterial::LocalHTLC { .. } => {
3074                                         //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
3075                                         // RBF them. Need a Lightning specs change and package relay modification :
3076                                         // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
3077                                         return None;
3078                                 }
3079                         }
3080                 }
3081                 assert!(predicted_weight >= bumped_tx.get_weight());
3082                 Some((new_timer, new_feerate, bumped_tx))
3083         }
3084 }
3085
3086 const MAX_ALLOC_SIZE: usize = 64*1024;
3087
3088 impl<R: ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
3089         fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
3090                 let secp_ctx = Secp256k1::new();
3091                 macro_rules! unwrap_obj {
3092                         ($key: expr) => {
3093                                 match $key {
3094                                         Ok(res) => res,
3095                                         Err(_) => return Err(DecodeError::InvalidValue),
3096                                 }
3097                         }
3098                 }
3099
3100                 let _ver: u8 = Readable::read(reader)?;
3101                 let min_ver: u8 = Readable::read(reader)?;
3102                 if min_ver > SERIALIZATION_VERSION {
3103                         return Err(DecodeError::UnknownVersion);
3104                 }
3105
3106                 let latest_update_id: u64 = Readable::read(reader)?;
3107                 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
3108
3109                 let key_storage = match <u8 as Readable<R>>::read(reader)? {
3110                         0 => {
3111                                 let keys = Readable::read(reader)?;
3112                                 let funding_key = Readable::read(reader)?;
3113                                 let revocation_base_key = Readable::read(reader)?;
3114                                 let htlc_base_key = Readable::read(reader)?;
3115                                 let delayed_payment_base_key = Readable::read(reader)?;
3116                                 let payment_base_key = Readable::read(reader)?;
3117                                 let shutdown_pubkey = Readable::read(reader)?;
3118                                 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3119                                 // barely-init'd ChannelMonitors that we can't do anything with.
3120                                 let outpoint = OutPoint {
3121                                         txid: Readable::read(reader)?,
3122                                         index: Readable::read(reader)?,
3123                                 };
3124                                 let funding_info = Some((outpoint, Readable::read(reader)?));
3125                                 let current_remote_commitment_txid = Readable::read(reader)?;
3126                                 let prev_remote_commitment_txid = Readable::read(reader)?;
3127                                 Storage::Local {
3128                                         keys,
3129                                         funding_key,
3130                                         revocation_base_key,
3131                                         htlc_base_key,
3132                                         delayed_payment_base_key,
3133                                         payment_base_key,
3134                                         shutdown_pubkey,
3135                                         funding_info,
3136                                         current_remote_commitment_txid,
3137                                         prev_remote_commitment_txid,
3138                                 }
3139                         },
3140                         _ => return Err(DecodeError::InvalidValue),
3141                 };
3142
3143                 let their_htlc_base_key = Some(Readable::read(reader)?);
3144                 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3145                 let funding_redeemscript = Some(Readable::read(reader)?);
3146                 let channel_value_satoshis = Some(Readable::read(reader)?);
3147
3148                 let their_cur_revocation_points = {
3149                         let first_idx = <U48 as Readable<R>>::read(reader)?.0;
3150                         if first_idx == 0 {
3151                                 None
3152                         } else {
3153                                 let first_point = Readable::read(reader)?;
3154                                 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3155                                 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3156                                         Some((first_idx, first_point, None))
3157                                 } else {
3158                                         Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3159                                 }
3160                         }
3161                 };
3162
3163                 let our_to_self_delay: u16 = Readable::read(reader)?;
3164                 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3165
3166                 let commitment_secrets = Readable::read(reader)?;
3167
3168                 macro_rules! read_htlc_in_commitment {
3169                         () => {
3170                                 {
3171                                         let offered: bool = Readable::read(reader)?;
3172                                         let amount_msat: u64 = Readable::read(reader)?;
3173                                         let cltv_expiry: u32 = Readable::read(reader)?;
3174                                         let payment_hash: PaymentHash = Readable::read(reader)?;
3175                                         let transaction_output_index: Option<u32> = Readable::read(reader)?;
3176
3177                                         HTLCOutputInCommitment {
3178                                                 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3179                                         }
3180                                 }
3181                         }
3182                 }
3183
3184                 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3185                 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3186                 for _ in 0..remote_claimable_outpoints_len {
3187                         let txid: Sha256dHash = Readable::read(reader)?;
3188                         let htlcs_count: u64 = Readable::read(reader)?;
3189                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3190                         for _ in 0..htlcs_count {
3191                                 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3192                         }
3193                         if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3194                                 return Err(DecodeError::InvalidValue);
3195                         }
3196                 }
3197
3198                 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3199                 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3200                 for _ in 0..remote_commitment_txn_on_chain_len {
3201                         let txid: Sha256dHash = Readable::read(reader)?;
3202                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3203                         let outputs_count = <u64 as Readable<R>>::read(reader)?;
3204                         let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3205                         for _ in 0..outputs_count {
3206                                 outputs.push(Readable::read(reader)?);
3207                         }
3208                         if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3209                                 return Err(DecodeError::InvalidValue);
3210                         }
3211                 }
3212
3213                 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3214                 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3215                 for _ in 0..remote_hash_commitment_number_len {
3216                         let payment_hash: PaymentHash = Readable::read(reader)?;
3217                         let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3218                         if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3219                                 return Err(DecodeError::InvalidValue);
3220                         }
3221                 }
3222
3223                 macro_rules! read_local_tx {
3224                         () => {
3225                                 {
3226                                         let tx = <LocalCommitmentTransaction as Readable<R>>::read(reader)?;
3227                                         let revocation_key = Readable::read(reader)?;
3228                                         let a_htlc_key = Readable::read(reader)?;
3229                                         let b_htlc_key = Readable::read(reader)?;
3230                                         let delayed_payment_key = Readable::read(reader)?;
3231                                         let per_commitment_point = Readable::read(reader)?;
3232                                         let feerate_per_kw: u64 = Readable::read(reader)?;
3233
3234                                         let htlcs_len: u64 = Readable::read(reader)?;
3235                                         let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3236                                         for _ in 0..htlcs_len {
3237                                                 let htlc = read_htlc_in_commitment!();
3238                                                 let sigs = match <u8 as Readable<R>>::read(reader)? {
3239                                                         0 => None,
3240                                                         1 => Some(Readable::read(reader)?),
3241                                                         _ => return Err(DecodeError::InvalidValue),
3242                                                 };
3243                                                 htlcs.push((htlc, sigs, Readable::read(reader)?));
3244                                         }
3245
3246                                         LocalSignedTx {
3247                                                 txid: tx.txid(),
3248                                                 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3249                                                 htlc_outputs: htlcs
3250                                         }
3251                                 }
3252                         }
3253                 }
3254
3255                 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3256                         0 => None,
3257                         1 => {
3258                                 Some(read_local_tx!())
3259                         },
3260                         _ => return Err(DecodeError::InvalidValue),
3261                 };
3262
3263                 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3264                         0 => None,
3265                         1 => {
3266                                 Some(read_local_tx!())
3267                         },
3268                         _ => return Err(DecodeError::InvalidValue),
3269                 };
3270
3271                 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3272
3273                 let payment_preimages_len: u64 = Readable::read(reader)?;
3274                 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3275                 for _ in 0..payment_preimages_len {
3276                         let preimage: PaymentPreimage = Readable::read(reader)?;
3277                         let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3278                         if let Some(_) = payment_preimages.insert(hash, preimage) {
3279                                 return Err(DecodeError::InvalidValue);
3280                         }
3281                 }
3282
3283                 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
3284                 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
3285                 for _ in 0..pending_htlcs_updated_len {
3286                         pending_htlcs_updated.push(Readable::read(reader)?);
3287                 }
3288
3289                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3290                 let destination_script = Readable::read(reader)?;
3291                 let to_remote_rescue = match <u8 as Readable<R>>::read(reader)? {
3292                         0 => None,
3293                         1 => {
3294                                 let to_remote_script = Readable::read(reader)?;
3295                                 let local_key = Readable::read(reader)?;
3296                                 Some((to_remote_script, local_key))
3297                         }
3298                         _ => return Err(DecodeError::InvalidValue),
3299                 };
3300
3301                 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3302                 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3303                 for _ in 0..pending_claim_requests_len {
3304                         pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3305                 }
3306
3307                 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3308                 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3309                 for _ in 0..claimable_outpoints_len {
3310                         let outpoint = Readable::read(reader)?;
3311                         let ancestor_claim_txid = Readable::read(reader)?;
3312                         let height = Readable::read(reader)?;
3313                         claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3314                 }
3315
3316                 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3317                 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3318                 for _ in 0..waiting_threshold_conf_len {
3319                         let height_target = Readable::read(reader)?;
3320                         let events_len: u64 = Readable::read(reader)?;
3321                         let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3322                         for _ in 0..events_len {
3323                                 let ev = match <u8 as Readable<R>>::read(reader)? {
3324                                         0 => {
3325                                                 let claim_request = Readable::read(reader)?;
3326                                                 OnchainEvent::Claim {
3327                                                         claim_request
3328                                                 }
3329                                         },
3330                                         1 => {
3331                                                 let htlc_source = Readable::read(reader)?;
3332                                                 let hash = Readable::read(reader)?;
3333                                                 OnchainEvent::HTLCUpdate {
3334                                                         htlc_update: (htlc_source, hash)
3335                                                 }
3336                                         },
3337                                         2 => {
3338                                                 let outpoint = Readable::read(reader)?;
3339                                                 let input_material = Readable::read(reader)?;
3340                                                 OnchainEvent::ContentiousOutpoint {
3341                                                         outpoint,
3342                                                         input_material
3343                                                 }
3344                                         }
3345                                         _ => return Err(DecodeError::InvalidValue),
3346                                 };
3347                                 events.push(ev);
3348                         }
3349                         onchain_events_waiting_threshold_conf.insert(height_target, events);
3350                 }
3351
3352                 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3353                 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>>())));
3354                 for _ in 0..outputs_to_watch_len {
3355                         let txid = Readable::read(reader)?;
3356                         let outputs_len: u64 = Readable::read(reader)?;
3357                         let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
3358                         for _ in 0..outputs_len {
3359                                 outputs.push(Readable::read(reader)?);
3360                         }
3361                         if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3362                                 return Err(DecodeError::InvalidValue);
3363                         }
3364                 }
3365
3366                 Ok((last_block_hash.clone(), ChannelMonitor {
3367                         latest_update_id,
3368                         commitment_transaction_number_obscure_factor,
3369
3370                         key_storage,
3371                         their_htlc_base_key,
3372                         their_delayed_payment_base_key,
3373                         funding_redeemscript,
3374                         channel_value_satoshis,
3375                         their_cur_revocation_points,
3376
3377                         our_to_self_delay,
3378                         their_to_self_delay,
3379
3380                         commitment_secrets,
3381                         remote_claimable_outpoints,
3382                         remote_commitment_txn_on_chain,
3383                         remote_hash_commitment_number,
3384
3385                         prev_local_signed_commitment_tx,
3386                         current_local_signed_commitment_tx,
3387                         current_remote_commitment_number,
3388
3389                         payment_preimages,
3390                         pending_htlcs_updated,
3391
3392                         destination_script,
3393                         to_remote_rescue,
3394
3395                         pending_claim_requests,
3396
3397                         claimable_outpoints,
3398
3399                         onchain_events_waiting_threshold_conf,
3400                         outputs_to_watch,
3401
3402                         last_block_hash,
3403                         secp_ctx,
3404                         logger,
3405                 }))
3406         }
3407
3408 }
3409
3410 #[cfg(test)]
3411 mod tests {
3412         use bitcoin::blockdata::script::{Script, Builder};
3413         use bitcoin::blockdata::opcodes;
3414         use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3415         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3416         use bitcoin::util::bip143;
3417         use bitcoin_hashes::Hash;
3418         use bitcoin_hashes::sha256::Hash as Sha256;
3419         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3420         use bitcoin_hashes::hex::FromHex;
3421         use hex;
3422         use ln::channelmanager::{PaymentPreimage, PaymentHash};
3423         use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3424         use ln::chan_utils;
3425         use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3426         use util::test_utils::TestLogger;
3427         use secp256k1::key::{SecretKey,PublicKey};
3428         use secp256k1::Secp256k1;
3429         use rand::{thread_rng,Rng};
3430         use std::sync::Arc;
3431         use chain::keysinterface::InMemoryChannelKeys;
3432
3433         #[test]
3434         fn test_prune_preimages() {
3435                 let secp_ctx = Secp256k1::new();
3436                 let logger = Arc::new(TestLogger::new());
3437
3438                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3439                 macro_rules! dummy_keys {
3440                         () => {
3441                                 {
3442                                         TxCreationKeys {
3443                                                 per_commitment_point: dummy_key.clone(),
3444                                                 revocation_key: dummy_key.clone(),
3445                                                 a_htlc_key: dummy_key.clone(),
3446                                                 b_htlc_key: dummy_key.clone(),
3447                                                 a_delayed_payment_key: dummy_key.clone(),
3448                                                 b_payment_key: dummy_key.clone(),
3449                                         }
3450                                 }
3451                         }
3452                 }
3453                 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3454
3455                 let mut preimages = Vec::new();
3456                 {
3457                         let mut rng  = thread_rng();
3458                         for _ in 0..20 {
3459                                 let mut preimage = PaymentPreimage([0; 32]);
3460                                 rng.fill_bytes(&mut preimage.0[..]);
3461                                 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3462                                 preimages.push((preimage, hash));
3463                         }
3464                 }
3465
3466                 macro_rules! preimages_slice_to_htlc_outputs {
3467                         ($preimages_slice: expr) => {
3468                                 {
3469                                         let mut res = Vec::new();
3470                                         for (idx, preimage) in $preimages_slice.iter().enumerate() {
3471                                                 res.push((HTLCOutputInCommitment {
3472                                                         offered: true,
3473                                                         amount_msat: 0,
3474                                                         cltv_expiry: 0,
3475                                                         payment_hash: preimage.1.clone(),
3476                                                         transaction_output_index: Some(idx as u32),
3477                                                 }, None));
3478                                         }
3479                                         res
3480                                 }
3481                         }
3482                 }
3483                 macro_rules! preimages_to_local_htlcs {
3484                         ($preimages_slice: expr) => {
3485                                 {
3486                                         let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3487                                         let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3488                                         res
3489                                 }
3490                         }
3491                 }
3492
3493                 macro_rules! test_preimages_exist {
3494                         ($preimages_slice: expr, $monitor: expr) => {
3495                                 for preimage in $preimages_slice {
3496                                         assert!($monitor.payment_preimages.contains_key(&preimage.1));
3497                                 }
3498                         }
3499                 }
3500
3501                 let keys = InMemoryChannelKeys::new(
3502                         &secp_ctx,
3503                         SecretKey::from_slice(&[41; 32]).unwrap(),
3504                         SecretKey::from_slice(&[41; 32]).unwrap(),
3505                         SecretKey::from_slice(&[41; 32]).unwrap(),
3506                         SecretKey::from_slice(&[41; 32]).unwrap(),
3507                         SecretKey::from_slice(&[41; 32]).unwrap(),
3508                         [41; 32],
3509                         0,
3510                 );
3511
3512                 // Prune with one old state and a local commitment tx holding a few overlaps with the
3513                 // old state.
3514                 let mut monitor = ChannelMonitor::new(keys, &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3515                 monitor.their_to_self_delay = Some(10);
3516
3517                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3518                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3519                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3520                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3521                 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3522                 for &(ref preimage, ref hash) in preimages.iter() {
3523                         monitor.provide_payment_preimage(hash, preimage);
3524                 }
3525
3526                 // Now provide a secret, pruning preimages 10-15
3527                 let mut secret = [0; 32];
3528                 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3529                 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3530                 assert_eq!(monitor.payment_preimages.len(), 15);
3531                 test_preimages_exist!(&preimages[0..10], monitor);
3532                 test_preimages_exist!(&preimages[15..20], monitor);
3533
3534                 // Now provide a further secret, pruning preimages 15-17
3535                 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3536                 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3537                 assert_eq!(monitor.payment_preimages.len(), 13);
3538                 test_preimages_exist!(&preimages[0..10], monitor);
3539                 test_preimages_exist!(&preimages[17..20], monitor);
3540
3541                 // Now update local commitment tx info, pruning only element 18 as we still care about the
3542                 // previous commitment tx's preimages too
3543                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3544                 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3545                 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3546                 assert_eq!(monitor.payment_preimages.len(), 12);
3547                 test_preimages_exist!(&preimages[0..10], monitor);
3548                 test_preimages_exist!(&preimages[18..20], monitor);
3549
3550                 // But if we do it again, we'll prune 5-10
3551                 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
3552                 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3553                 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3554                 assert_eq!(monitor.payment_preimages.len(), 5);
3555                 test_preimages_exist!(&preimages[0..5], monitor);
3556         }
3557
3558         #[test]
3559         fn test_claim_txn_weight_computation() {
3560                 // We test Claim txn weight, knowing that we want expected weigth and
3561                 // not actual case to avoid sigs and time-lock delays hell variances.
3562
3563                 let secp_ctx = Secp256k1::new();
3564                 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3565                 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3566                 let mut sum_actual_sigs = 0;
3567
3568                 macro_rules! sign_input {
3569                         ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3570                                 let htlc = HTLCOutputInCommitment {
3571                                         offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3572                                         amount_msat: 0,
3573                                         cltv_expiry: 2 << 16,
3574                                         payment_hash: PaymentHash([1; 32]),
3575                                         transaction_output_index: Some($idx),
3576                                 };
3577                                 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) };
3578                                 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3579                                 let sig = secp_ctx.sign(&sighash, &privkey);
3580                                 $input.witness.push(sig.serialize_der().to_vec());
3581                                 $input.witness[0].push(SigHashType::All as u8);
3582                                 sum_actual_sigs += $input.witness[0].len();
3583                                 if *$input_type == InputDescriptors::RevokedOutput {
3584                                         $input.witness.push(vec!(1));
3585                                 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3586                                         $input.witness.push(pubkey.clone().serialize().to_vec());
3587                                 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3588                                         $input.witness.push(vec![0]);
3589                                 } else {
3590                                         $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3591                                 }
3592                                 $input.witness.push(redeem_script.into_bytes());
3593                                 println!("witness[0] {}", $input.witness[0].len());
3594                                 println!("witness[1] {}", $input.witness[1].len());
3595                                 println!("witness[2] {}", $input.witness[2].len());
3596                         }
3597                 }
3598
3599                 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3600                 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3601
3602                 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3603                 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3604                 for i in 0..4 {
3605                         claim_tx.input.push(TxIn {
3606                                 previous_output: BitcoinOutPoint {
3607                                         txid,
3608                                         vout: i,
3609                                 },
3610                                 script_sig: Script::new(),
3611                                 sequence: 0xfffffffd,
3612                                 witness: Vec::new(),
3613                         });
3614                 }
3615                 claim_tx.output.push(TxOut {
3616                         script_pubkey: script_pubkey.clone(),
3617                         value: 0,
3618                 });
3619                 let base_weight = claim_tx.get_weight();
3620                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3621                 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3622                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3623                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3624                 }
3625                 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3626
3627                 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3628                 claim_tx.input.clear();
3629                 sum_actual_sigs = 0;
3630                 for i in 0..4 {
3631                         claim_tx.input.push(TxIn {
3632                                 previous_output: BitcoinOutPoint {
3633                                         txid,
3634                                         vout: i,
3635                                 },
3636                                 script_sig: Script::new(),
3637                                 sequence: 0xfffffffd,
3638                                 witness: Vec::new(),
3639                         });
3640                 }
3641                 let base_weight = claim_tx.get_weight();
3642                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3643                 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3644                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3645                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3646                 }
3647                 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3648
3649                 // Justice tx with 1 revoked HTLC-Success tx output
3650                 claim_tx.input.clear();
3651                 sum_actual_sigs = 0;
3652                 claim_tx.input.push(TxIn {
3653                         previous_output: BitcoinOutPoint {
3654                                 txid,
3655                                 vout: 0,
3656                         },
3657                         script_sig: Script::new(),
3658                         sequence: 0xfffffffd,
3659                         witness: Vec::new(),
3660                 });
3661                 let base_weight = claim_tx.get_weight();
3662                 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3663                 let inputs_des = vec![InputDescriptors::RevokedOutput];
3664                 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3665                         sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3666                 }
3667                 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
3668         }
3669
3670         // Further testing is done in the ChannelManager integration tests.
3671 }