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