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