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