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