1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
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.
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.
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;
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;
28 use secp256k1::{Secp256k1,Signature};
29 use secp256k1::key::{SecretKey,PublicKey};
32 use ln::msgs::DecodeError;
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};
43 use std::collections::{HashMap, hash_map, HashSet};
44 use std::sync::{Arc,Mutex};
45 use std::{hash,cmp, mem};
48 /// An update generated by the underlying Channel itself which contains some new information the
49 /// ChannelMonitor should be made aware of.
50 #[cfg_attr(test, derive(PartialEq))]
53 pub struct ChannelMonitorUpdate {
54 pub(super) updates: Vec<ChannelMonitorUpdateStep>,
55 /// The sequence number of this update. Updates *must* be replayed in-order according to this
56 /// sequence number (and updates may panic if they are not). The update_id values are strictly
57 /// increasing and increase by one for each new update.
59 /// This sequence number is also used to track up to which points updates which returned
60 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
61 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
65 impl Writeable for ChannelMonitorUpdate {
66 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
67 self.update_id.write(w)?;
68 (self.updates.len() as u64).write(w)?;
69 for update_step in self.updates.iter() {
70 update_step.write(w)?;
75 impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdate {
76 fn read(r: &mut R) -> Result<Self, DecodeError> {
77 let update_id: u64 = Readable::read(r)?;
78 let len: u64 = Readable::read(r)?;
79 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
81 updates.push(Readable::read(r)?);
83 Ok(Self { update_id, updates })
87 /// An error enum representing a failure to persist a channel monitor update.
89 pub enum ChannelMonitorUpdateErr {
90 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
91 /// our state failed, but is expected to succeed at some point in the future).
93 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
94 /// submitting new commitment transactions to the remote party. Once the update(s) which failed
95 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
96 /// restore the channel to an operational state.
98 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
99 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
100 /// writing out the latest ChannelManager state.
102 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
103 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
104 /// to claim it on this channel) and those updates must be applied wherever they can be. At
105 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
106 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
107 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
110 /// Note that even if updates made after TemporaryFailure succeed you must still call
111 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
114 /// Note that the update being processed here will not be replayed for you when you call
115 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
116 /// with the persisted ChannelMonitor on your own local disk prior to returning a
117 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
118 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
121 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
122 /// remote location (with local copies persisted immediately), it is anticipated that all
123 /// updates will return TemporaryFailure until the remote copies could be updated.
125 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
126 /// different watchtower and cannot update with all watchtowers that were previously informed
127 /// of this channel). This will force-close the channel in question.
129 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
133 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
134 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
135 /// means you tried to merge two monitors for different channels or for a channel which was
136 /// restored from a backup and then generated new commitment updates.
137 /// Contains a human-readable error message.
139 pub struct MonitorUpdateError(pub &'static str);
141 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
142 /// forward channel and from which info are needed to update HTLC in a backward channel.
143 #[derive(Clone, PartialEq)]
144 pub struct HTLCUpdate {
145 pub(super) payment_hash: PaymentHash,
146 pub(super) payment_preimage: Option<PaymentPreimage>,
147 pub(super) source: HTLCSource
149 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
151 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
152 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
153 /// events to it, while also taking any add_update_monitor events and passing them to some remote
156 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
157 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
158 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
159 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
161 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
162 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
163 /// than calling these methods directly, the user should register implementors as listeners to the
164 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
165 /// all registered listeners in one go.
166 pub trait ManyChannelMonitor<ChanSigner: ChannelKeys>: Send + Sync {
167 /// Adds or updates a monitor for the given `funding_txo`.
169 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
170 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
171 /// callbacks with the funding transaction, or any spends of it.
173 /// Further, the implementer must also ensure that each output returned in
174 /// monitor.get_outputs_to_watch() is registered to ensure that the provided monitor learns about
175 /// any spends of any of the outputs.
177 /// Any spends of outputs which should have been registered which aren't passed to
178 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
179 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr>;
181 /// Updates a monitor for the given `funding_txo`.
183 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
184 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
185 /// callbacks with the funding transaction, or any spends of it.
187 /// Further, the implementer must also ensure that each output returned in
188 /// monitor.get_watch_outputs() is registered to ensure that the provided monitor learns about
189 /// any spends of any of the outputs.
191 /// Any spends of outputs which should have been registered which aren't passed to
192 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
193 fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
195 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
196 /// with success or failure.
198 /// You should probably just call through to
199 /// ChannelMonitor::get_and_clear_pending_htlcs_updated() for each ChannelMonitor and return
201 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate>;
204 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
205 /// watchtower or watch our own channels.
207 /// Note that you must provide your own key by which to refer to channels.
209 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
210 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
211 /// index by a PublicKey which is required to sign any updates.
213 /// If you're using this for local monitoring of your own channels, you probably want to use
214 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
215 pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys, T: Deref> where T::Target: BroadcasterInterface {
216 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
217 pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
219 monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
220 chain_monitor: Arc<ChainWatchInterface>,
222 pending_events: Mutex<Vec<events::Event>>,
224 fee_estimator: Arc<FeeEstimator>
227 impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send> ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T>
228 where T::Target: BroadcasterInterface
230 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
231 let block_hash = header.bitcoin_hash();
232 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
234 let mut monitors = self.monitors.lock().unwrap();
235 for monitor in monitors.values_mut() {
236 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
237 if spendable_outputs.len() > 0 {
238 new_events.push(events::Event::SpendableOutputs {
239 outputs: spendable_outputs,
243 for (ref txid, ref outputs) in txn_outputs {
244 for (idx, output) in outputs.iter().enumerate() {
245 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
250 let mut pending_events = self.pending_events.lock().unwrap();
251 pending_events.append(&mut new_events);
254 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
255 let block_hash = header.bitcoin_hash();
256 let mut monitors = self.monitors.lock().unwrap();
257 for monitor in monitors.values_mut() {
258 monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
263 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T>
264 where T::Target: BroadcasterInterface
266 /// Creates a new object which can be used to monitor several channels given the chain
267 /// interface with which to register to receive notifications.
268 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: T, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> SimpleManyChannelMonitor<Key, ChanSigner, T> {
269 let res = SimpleManyChannelMonitor {
270 monitors: Mutex::new(HashMap::new()),
273 pending_events: Mutex::new(Vec::new()),
275 fee_estimator: feeest,
281 /// Adds or updates the monitor which monitors the channel referred to by the given key.
282 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
283 let mut monitors = self.monitors.lock().unwrap();
284 match monitors.get_mut(&key) {
285 Some(orig_monitor) => {
286 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
287 return orig_monitor.insert_combine(monitor);
291 match monitor.key_storage {
292 Storage::Local { ref funding_info, .. } => {
295 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
297 &Some((ref outpoint, ref script)) => {
298 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
299 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
300 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
304 Storage::Watchtower { .. } => {
305 self.chain_monitor.watch_all_txn();
308 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
309 for (idx, script) in outputs.iter().enumerate() {
310 self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script);
313 monitors.insert(key, monitor);
317 /// Updates the monitor which monitors the channel referred to by the given key.
318 pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
319 let mut monitors = self.monitors.lock().unwrap();
320 match monitors.get_mut(&key) {
321 Some(orig_monitor) => {
322 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage));
323 orig_monitor.update_monitor(update)
325 None => Err(MonitorUpdateError("No such monitor registered"))
330 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner, T>
331 where T::Target: BroadcasterInterface
333 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
334 match self.add_update_monitor_by_key(funding_txo, monitor) {
336 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
340 fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
341 match self.update_monitor_by_key(funding_txo, update) {
343 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
347 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
348 let mut pending_htlcs_updated = Vec::new();
349 for chan in self.monitors.lock().unwrap().values_mut() {
350 pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated());
352 pending_htlcs_updated
356 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T>
357 where T::Target: BroadcasterInterface
359 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
360 let mut pending_events = self.pending_events.lock().unwrap();
361 let mut ret = Vec::new();
362 mem::swap(&mut ret, &mut *pending_events);
367 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
368 /// instead claiming it in its own individual transaction.
369 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
370 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
371 /// HTLC-Success transaction.
372 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
373 /// transaction confirmed (and we use it in a few more, equivalent, places).
374 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
375 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
376 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
377 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
378 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
379 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
380 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
381 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
382 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
383 /// accurate block height.
384 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
385 /// with at worst this delay, so we are not only using this value as a mercy for them but also
386 /// us as a safeguard to delay with enough time.
387 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
388 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
389 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
390 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
391 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
392 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
393 /// keeping bumping another claim tx to solve the outpoint.
394 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
397 enum Storage<ChanSigner: ChannelKeys> {
400 funding_key: SecretKey,
401 revocation_base_key: SecretKey,
402 htlc_base_key: SecretKey,
403 delayed_payment_base_key: SecretKey,
404 payment_base_key: SecretKey,
405 shutdown_pubkey: PublicKey,
406 funding_info: Option<(OutPoint, Script)>,
407 current_remote_commitment_txid: Option<Sha256dHash>,
408 prev_remote_commitment_txid: Option<Sha256dHash>,
411 revocation_base_key: PublicKey,
412 htlc_base_key: PublicKey,
416 #[cfg(any(test, feature = "fuzztarget"))]
417 impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
418 fn eq(&self, other: &Self) -> bool {
420 Storage::Local { ref keys, .. } => {
423 Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
424 Storage::Watchtower { .. } => false,
427 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
428 let (rbk, hbk) = (revocation_base_key, htlc_base_key);
430 Storage::Local { .. } => false,
431 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
432 revocation_base_key == rbk && htlc_base_key == hbk,
439 #[derive(Clone, PartialEq)]
440 struct LocalSignedTx {
441 /// txid of the transaction in tx, just used to make comparison faster
443 tx: LocalCommitmentTransaction,
444 revocation_key: PublicKey,
445 a_htlc_key: PublicKey,
446 b_htlc_key: PublicKey,
447 delayed_payment_key: PublicKey,
448 per_commitment_point: PublicKey,
450 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
454 enum InputDescriptors {
459 RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
462 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
463 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
464 /// a new bumped one in case of lenghty confirmation delay
465 #[derive(Clone, PartialEq)]
469 pubkey: Option<PublicKey>,
477 preimage: Option<PaymentPreimage>,
483 sigs: (Signature, Signature),
484 preimage: Option<PaymentPreimage>,
489 impl Writeable for InputMaterial {
490 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
492 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
493 writer.write_all(&[0; 1])?;
494 script.write(writer)?;
495 pubkey.write(writer)?;
496 writer.write_all(&key[..])?;
498 writer.write_all(&[0; 1])?;
500 writer.write_all(&[1; 1])?;
502 writer.write_all(&byte_utils::be64_to_array(*amount))?;
504 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
505 writer.write_all(&[1; 1])?;
506 script.write(writer)?;
508 preimage.write(writer)?;
509 writer.write_all(&byte_utils::be64_to_array(*amount))?;
510 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
512 &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
513 writer.write_all(&[2; 1])?;
514 script.write(writer)?;
515 sigs.0.write(writer)?;
516 sigs.1.write(writer)?;
517 preimage.write(writer)?;
518 writer.write_all(&byte_utils::be64_to_array(*amount))?;
525 impl<R: ::std::io::Read> Readable<R> for InputMaterial {
526 fn read(reader: &mut R) -> Result<Self, DecodeError> {
527 let input_material = match <u8 as Readable<R>>::read(reader)? {
529 let script = Readable::read(reader)?;
530 let pubkey = Readable::read(reader)?;
531 let key = Readable::read(reader)?;
532 let is_htlc = match <u8 as Readable<R>>::read(reader)? {
535 _ => return Err(DecodeError::InvalidValue),
537 let amount = Readable::read(reader)?;
538 InputMaterial::Revoked {
547 let script = Readable::read(reader)?;
548 let key = Readable::read(reader)?;
549 let preimage = Readable::read(reader)?;
550 let amount = Readable::read(reader)?;
551 let locktime = Readable::read(reader)?;
552 InputMaterial::RemoteHTLC {
561 let script = Readable::read(reader)?;
562 let their_sig = Readable::read(reader)?;
563 let our_sig = Readable::read(reader)?;
564 let preimage = Readable::read(reader)?;
565 let amount = Readable::read(reader)?;
566 InputMaterial::LocalHTLC {
568 sigs: (their_sig, our_sig),
573 _ => return Err(DecodeError::InvalidValue),
579 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
580 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
581 #[derive(Clone, PartialEq)]
583 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
584 /// bump-txn candidate buffer.
586 claim_request: Sha256dHash,
588 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
589 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
590 /// only win from it, so it's never an OnchainEvent
592 htlc_update: (HTLCSource, PaymentHash),
594 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
595 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
596 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
597 ContentiousOutpoint {
598 outpoint: BitcoinOutPoint,
599 input_material: InputMaterial,
603 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
604 #[derive(Clone, PartialEq)]
605 pub struct ClaimTxBumpMaterial {
606 // At every block tick, used to check if pending claiming tx is taking too
607 // much time for confirmation and we need to bump it.
609 // Tracked in case of reorg to wipe out now-superflous bump material
610 feerate_previous: u64,
611 // Soonest timelocks among set of outpoints claimed, used to compute
612 // a priority of not feerate
613 soonest_timelock: u32,
614 // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
615 per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
618 impl Writeable for ClaimTxBumpMaterial {
619 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
620 writer.write_all(&byte_utils::be32_to_array(self.height_timer))?;
621 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
622 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
623 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
624 for (outp, tx_material) in self.per_input_material.iter() {
626 tx_material.write(writer)?;
632 impl<R: ::std::io::Read> Readable<R> for ClaimTxBumpMaterial {
633 fn read(reader: &mut R) -> Result<Self, DecodeError> {
634 let height_timer = Readable::read(reader)?;
635 let feerate_previous = Readable::read(reader)?;
636 let soonest_timelock = Readable::read(reader)?;
637 let per_input_material_len: u64 = Readable::read(reader)?;
638 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
639 for _ in 0 ..per_input_material_len {
640 let outpoint = Readable::read(reader)?;
641 let input_material = Readable::read(reader)?;
642 per_input_material.insert(outpoint, input_material);
644 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
648 const SERIALIZATION_VERSION: u8 = 1;
649 const MIN_SERIALIZATION_VERSION: u8 = 1;
651 #[cfg_attr(test, derive(PartialEq))]
653 pub(super) enum ChannelMonitorUpdateStep {
654 LatestLocalCommitmentTXInfo {
655 // TODO: We really need to not be generating a fully-signed transaction in Channel and
656 // passing it here, we need to hold off so that the ChanSigner can enforce a
657 // only-sign-local-state-for-broadcast once invariant:
658 commitment_tx: LocalCommitmentTransaction,
659 local_keys: chan_utils::TxCreationKeys,
661 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
663 LatestRemoteCommitmentTXInfo {
664 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
665 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
666 commitment_number: u64,
667 their_revocation_point: PublicKey,
670 payment_preimage: PaymentPreimage,
678 impl Writeable for ChannelMonitorUpdateStep {
679 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
681 &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
683 commitment_tx.write(w)?;
684 local_keys.write(w)?;
685 feerate_per_kw.write(w)?;
686 (htlc_outputs.len() as u64).write(w)?;
687 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
693 &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
695 unsigned_commitment_tx.write(w)?;
696 commitment_number.write(w)?;
697 their_revocation_point.write(w)?;
698 (htlc_outputs.len() as u64).write(w)?;
699 for &(ref output, ref source) in htlc_outputs.iter() {
702 &None => 0u8.write(w)?,
710 &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
712 payment_preimage.write(w)?;
714 &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
723 impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
724 fn read(r: &mut R) -> Result<Self, DecodeError> {
725 match Readable::read(r)? {
727 Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
728 commitment_tx: Readable::read(r)?,
729 local_keys: Readable::read(r)?,
730 feerate_per_kw: Readable::read(r)?,
732 let len: u64 = Readable::read(r)?;
733 let mut res = Vec::new();
735 res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
742 Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
743 unsigned_commitment_tx: Readable::read(r)?,
744 commitment_number: Readable::read(r)?,
745 their_revocation_point: Readable::read(r)?,
747 let len: u64 = Readable::read(r)?;
748 let mut res = Vec::new();
750 res.push((Readable::read(r)?, <Option<HTLCSource> as Readable<R>>::read(r)?.map(|o| Box::new(o))));
757 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
758 payment_preimage: Readable::read(r)?,
762 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
763 idx: Readable::read(r)?,
764 secret: Readable::read(r)?,
767 _ => Err(DecodeError::InvalidValue),
772 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
773 /// on-chain transactions to ensure no loss of funds occurs.
775 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
776 /// information and are actively monitoring the chain.
778 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
779 latest_update_id: u64,
780 commitment_transaction_number_obscure_factor: u64,
782 key_storage: Storage<ChanSigner>,
783 their_htlc_base_key: Option<PublicKey>,
784 their_delayed_payment_base_key: Option<PublicKey>,
785 funding_redeemscript: Option<Script>,
786 channel_value_satoshis: Option<u64>,
787 // first is the idx of the first of the two revocation points
788 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
790 our_to_self_delay: u16,
791 their_to_self_delay: Option<u16>,
793 commitment_secrets: CounterpartyCommitmentSecrets,
794 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
795 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
796 /// Nor can we figure out their commitment numbers without the commitment transaction they are
797 /// spending. Thus, in order to claim them via revocation key, we track all the remote
798 /// commitment transactions which we find on-chain, mapping them to the commitment number which
799 /// can be used to derive the revocation key and claim the transactions.
800 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
801 /// Cache used to make pruning of payment_preimages faster.
802 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
803 /// remote transactions (ie should remain pretty small).
804 /// Serialized to disk but should generally not be sent to Watchtowers.
805 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
807 // We store two local commitment transactions to avoid any race conditions where we may update
808 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
809 // various monitors for one channel being out of sync, and us broadcasting a local
810 // transaction for which we have deleted claim information on some watchtowers.
811 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
812 current_local_signed_commitment_tx: Option<LocalSignedTx>,
814 // Used just for ChannelManager to make sure it has the latest channel data during
816 current_remote_commitment_number: u64,
818 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
820 pending_htlcs_updated: Vec<HTLCUpdate>,
822 destination_script: Script,
823 // Thanks to data loss protection, we may be able to claim our non-htlc funds
824 // back, this is the script we have to spend from but we need to
825 // scan every commitment transaction for that
826 to_remote_rescue: Option<(Script, SecretKey)>,
828 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
829 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
830 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
831 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
832 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
833 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
834 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
835 // we need to regenerate new claim request we reduced set of stil-claimable outpoints.
836 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
837 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
838 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
839 #[cfg(test)] // Used in functional_test to verify sanitization
840 pub pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
842 pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
844 // Used to link outpoints claimed in a connected block to a pending claim request.
845 // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
846 // Value is (pending claim request identifier, confirmation_block), identifier
847 // is txid of the initial claiming transaction and is immutable until outpoint is
848 // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
849 // block with output gets disconnected.
850 #[cfg(test)] // Used in functional_test to verify sanitization
851 pub claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
853 claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
855 // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
856 // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
857 // actions when we receive a block with given height. Actions depend on OnchainEvent type.
858 onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
860 // If we get serialized out and re-read, we need to make sure that the chain monitoring
861 // interface knows about the TXOs that we want to be notified of spends of. We could probably
862 // be smart and derive them from the above storage fields, but its much simpler and more
863 // Obviously Correct (tm) if we just keep track of them explicitly.
864 outputs_to_watch: HashMap<Sha256dHash, Vec<Script>>,
866 // We simply modify last_block_hash in Channel's block_connected so that serialization is
867 // consistent but hopefully the users' copy handles block_connected in a consistent way.
868 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
869 // their last_block_hash from its state and not based on updated copies that didn't run through
870 // the full block_connected).
871 pub(crate) last_block_hash: Sha256dHash,
872 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
875 macro_rules! subtract_high_prio_fee {
876 ($self: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
878 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority);
879 let mut fee = $used_feerate * ($predicted_weight as u64) / 1000;
881 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
882 fee = $used_feerate * ($predicted_weight as u64) / 1000;
884 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
885 fee = $used_feerate * ($predicted_weight as u64) / 1000;
887 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)",
891 log_warn!($self, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
897 log_warn!($self, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
910 #[cfg(any(test, feature = "fuzztarget"))]
911 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
912 /// underlying object
913 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
914 fn eq(&self, other: &Self) -> bool {
915 if self.latest_update_id != other.latest_update_id ||
916 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
917 self.key_storage != other.key_storage ||
918 self.their_htlc_base_key != other.their_htlc_base_key ||
919 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
920 self.funding_redeemscript != other.funding_redeemscript ||
921 self.channel_value_satoshis != other.channel_value_satoshis ||
922 self.their_cur_revocation_points != other.their_cur_revocation_points ||
923 self.our_to_self_delay != other.our_to_self_delay ||
924 self.their_to_self_delay != other.their_to_self_delay ||
925 self.commitment_secrets != other.commitment_secrets ||
926 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
927 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
928 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
929 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
930 self.current_remote_commitment_number != other.current_remote_commitment_number ||
931 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
932 self.payment_preimages != other.payment_preimages ||
933 self.pending_htlcs_updated != other.pending_htlcs_updated ||
934 self.destination_script != other.destination_script ||
935 self.to_remote_rescue != other.to_remote_rescue ||
936 self.pending_claim_requests != other.pending_claim_requests ||
937 self.claimable_outpoints != other.claimable_outpoints ||
938 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
939 self.outputs_to_watch != other.outputs_to_watch
948 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
949 /// Serializes into a vec, with various modes for the exposed pub fns
950 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
951 //TODO: We still write out all the serialization here manually instead of using the fancy
952 //serialization framework we have, we should migrate things over to it.
953 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
954 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
956 self.latest_update_id.write(writer)?;
958 // Set in initial Channel-object creation, so should always be set by now:
959 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
961 macro_rules! write_option {
968 &None => 0u8.write(writer)?,
973 match self.key_storage {
974 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 } => {
975 writer.write_all(&[0; 1])?;
977 writer.write_all(&funding_key[..])?;
978 writer.write_all(&revocation_base_key[..])?;
979 writer.write_all(&htlc_base_key[..])?;
980 writer.write_all(&delayed_payment_base_key[..])?;
981 writer.write_all(&payment_base_key[..])?;
982 writer.write_all(&shutdown_pubkey.serialize())?;
984 &Some((ref outpoint, ref script)) => {
985 writer.write_all(&outpoint.txid[..])?;
986 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
987 script.write(writer)?;
990 debug_assert!(false, "Try to serialize a useless Local monitor !");
993 current_remote_commitment_txid.write(writer)?;
994 prev_remote_commitment_txid.write(writer)?;
996 Storage::Watchtower { .. } => unimplemented!(),
999 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
1000 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
1001 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
1002 self.channel_value_satoshis.unwrap().write(writer)?;
1004 match self.their_cur_revocation_points {
1005 Some((idx, pubkey, second_option)) => {
1006 writer.write_all(&byte_utils::be48_to_array(idx))?;
1007 writer.write_all(&pubkey.serialize())?;
1008 match second_option {
1009 Some(second_pubkey) => {
1010 writer.write_all(&second_pubkey.serialize())?;
1013 writer.write_all(&[0; 33])?;
1018 writer.write_all(&byte_utils::be48_to_array(0))?;
1022 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
1023 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
1025 self.commitment_secrets.write(writer)?;
1027 macro_rules! serialize_htlc_in_commitment {
1028 ($htlc_output: expr) => {
1029 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1030 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1031 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1032 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1033 $htlc_output.transaction_output_index.write(writer)?;
1037 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
1038 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
1039 writer.write_all(&txid[..])?;
1040 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1041 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1042 serialize_htlc_in_commitment!(htlc_output);
1043 write_option!(htlc_source);
1047 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
1048 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
1049 writer.write_all(&txid[..])?;
1050 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1051 (txouts.len() as u64).write(writer)?;
1052 for script in txouts.iter() {
1053 script.write(writer)?;
1057 if for_local_storage {
1058 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
1059 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
1060 writer.write_all(&payment_hash.0[..])?;
1061 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1064 writer.write_all(&byte_utils::be64_to_array(0))?;
1067 macro_rules! serialize_local_tx {
1068 ($local_tx: expr) => {
1069 $local_tx.tx.write(writer)?;
1070 writer.write_all(&$local_tx.revocation_key.serialize())?;
1071 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
1072 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
1073 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
1074 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
1076 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
1077 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
1078 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
1079 serialize_htlc_in_commitment!(htlc_output);
1080 if let &Some(ref their_sig) = sig {
1082 writer.write_all(&their_sig.serialize_compact())?;
1086 write_option!(htlc_source);
1091 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
1092 writer.write_all(&[1; 1])?;
1093 serialize_local_tx!(prev_local_tx);
1095 writer.write_all(&[0; 1])?;
1098 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1099 writer.write_all(&[1; 1])?;
1100 serialize_local_tx!(cur_local_tx);
1102 writer.write_all(&[0; 1])?;
1105 if for_local_storage {
1106 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1108 writer.write_all(&byte_utils::be48_to_array(0))?;
1111 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1112 for payment_preimage in self.payment_preimages.values() {
1113 writer.write_all(&payment_preimage.0[..])?;
1116 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
1117 for data in self.pending_htlcs_updated.iter() {
1118 data.write(writer)?;
1121 self.last_block_hash.write(writer)?;
1122 self.destination_script.write(writer)?;
1123 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1124 writer.write_all(&[1; 1])?;
1125 to_remote_script.write(writer)?;
1126 local_key.write(writer)?;
1128 writer.write_all(&[0; 1])?;
1131 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
1132 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
1133 ancestor_claim_txid.write(writer)?;
1134 claim_tx_data.write(writer)?;
1137 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
1138 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
1139 outp.write(writer)?;
1140 claim_and_height.0.write(writer)?;
1141 claim_and_height.1.write(writer)?;
1144 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1145 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1146 writer.write_all(&byte_utils::be32_to_array(**target))?;
1147 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1148 for ev in events.iter() {
1150 OnchainEvent::Claim { ref claim_request } => {
1151 writer.write_all(&[0; 1])?;
1152 claim_request.write(writer)?;
1154 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1155 writer.write_all(&[1; 1])?;
1156 htlc_update.0.write(writer)?;
1157 htlc_update.1.write(writer)?;
1159 OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
1160 writer.write_all(&[2; 1])?;
1161 outpoint.write(writer)?;
1162 input_material.write(writer)?;
1168 (self.outputs_to_watch.len() as u64).write(writer)?;
1169 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1170 txid.write(writer)?;
1171 (output_scripts.len() as u64).write(writer)?;
1172 for script in output_scripts.iter() {
1173 script.write(writer)?;
1180 /// Writes this monitor into the given writer, suitable for writing to disk.
1182 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1183 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1184 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1185 /// common block that appears on your best chain as well as on the chain which contains the
1186 /// last block hash returned) upon deserializing the object!
1187 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1188 self.write(writer, true)
1191 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1193 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1194 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1195 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1196 /// common block that appears on your best chain as well as on the chain which contains the
1197 /// last block hash returned) upon deserializing the object!
1198 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1199 self.write(writer, false)
1203 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1204 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> {
1206 latest_update_id: 0,
1207 commitment_transaction_number_obscure_factor: 0,
1209 key_storage: Storage::Local {
1211 funding_key: funding_key.clone(),
1212 revocation_base_key: revocation_base_key.clone(),
1213 htlc_base_key: htlc_base_key.clone(),
1214 delayed_payment_base_key: delayed_payment_base_key.clone(),
1215 payment_base_key: payment_base_key.clone(),
1216 shutdown_pubkey: shutdown_pubkey.clone(),
1218 current_remote_commitment_txid: None,
1219 prev_remote_commitment_txid: None,
1221 their_htlc_base_key: None,
1222 their_delayed_payment_base_key: None,
1223 funding_redeemscript: None,
1224 channel_value_satoshis: None,
1225 their_cur_revocation_points: None,
1227 our_to_self_delay: our_to_self_delay,
1228 their_to_self_delay: None,
1230 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1231 remote_claimable_outpoints: HashMap::new(),
1232 remote_commitment_txn_on_chain: HashMap::new(),
1233 remote_hash_commitment_number: HashMap::new(),
1235 prev_local_signed_commitment_tx: None,
1236 current_local_signed_commitment_tx: None,
1237 current_remote_commitment_number: 1 << 48,
1239 payment_preimages: HashMap::new(),
1240 pending_htlcs_updated: Vec::new(),
1242 destination_script: destination_script,
1243 to_remote_rescue: None,
1245 pending_claim_requests: HashMap::new(),
1247 claimable_outpoints: HashMap::new(),
1249 onchain_events_waiting_threshold_conf: HashMap::new(),
1250 outputs_to_watch: HashMap::new(),
1252 last_block_hash: Default::default(),
1253 secp_ctx: Secp256k1::new(),
1258 fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
1259 let mut tx_weight = 2; // count segwit flags
1261 // We use expected weight (and not actual) as signatures and time lock delays may vary
1262 tx_weight += match inp {
1263 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1264 &InputDescriptors::RevokedOfferedHTLC => {
1265 1 + 1 + 73 + 1 + 33 + 1 + 133
1267 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1268 &InputDescriptors::RevokedReceivedHTLC => {
1269 1 + 1 + 73 + 1 + 33 + 1 + 139
1271 // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
1272 &InputDescriptors::OfferedHTLC => {
1273 1 + 1 + 73 + 1 + 32 + 1 + 133
1275 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1276 &InputDescriptors::ReceivedHTLC => {
1277 1 + 1 + 73 + 1 + 1 + 1 + 139
1279 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
1280 &InputDescriptors::RevokedOutput => {
1281 1 + 1 + 73 + 1 + 1 + 1 + 77
1288 fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
1289 if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
1290 return current_height + 1
1291 } else if timelock_expiration - current_height <= 15 {
1292 return current_height + 3
1297 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1298 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1299 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1300 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1301 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1302 return Err(MonitorUpdateError("Previous secret did not match new one"));
1305 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1306 // events for now-revoked/fulfilled HTLCs.
1307 // TODO: We should probably consider whether we're really getting the next secret here.
1308 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1309 if let Some(txid) = prev_remote_commitment_txid.take() {
1310 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1316 if !self.payment_preimages.is_empty() {
1317 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1318 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1319 let min_idx = self.get_min_seen_secret();
1320 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1322 self.payment_preimages.retain(|&k, _| {
1323 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1324 if k == htlc.payment_hash {
1328 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1329 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1330 if k == htlc.payment_hash {
1335 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1342 remote_hash_commitment_number.remove(&k);
1351 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1352 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1353 /// possibly future revocation/preimage information) to claim outputs where possible.
1354 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1355 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) {
1356 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1357 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1358 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1360 for &(ref htlc, _) in &htlc_outputs {
1361 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1364 let new_txid = unsigned_commitment_tx.txid();
1365 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1366 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1367 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1368 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1369 *current_remote_commitment_txid = Some(new_txid);
1371 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1372 self.current_remote_commitment_number = commitment_number;
1373 //TODO: Merge this into the other per-remote-transaction output storage stuff
1374 match self.their_cur_revocation_points {
1375 Some(old_points) => {
1376 if old_points.0 == commitment_number + 1 {
1377 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1378 } else if old_points.0 == commitment_number + 2 {
1379 if let Some(old_second_point) = old_points.2 {
1380 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1382 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1385 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1389 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1394 pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1395 match self.key_storage {
1396 Storage::Local { ref payment_base_key, ref keys, .. } => {
1397 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1398 let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1399 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1401 if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1402 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1406 Storage::Watchtower { .. } => {}
1410 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1411 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1412 /// is important that any clones of this channel monitor (including remote clones) by kept
1413 /// up-to-date as our local commitment transaction is updated.
1414 /// Panics if set_their_to_self_delay has never been called.
1415 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1416 if self.their_to_self_delay.is_none() {
1417 return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1419 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1420 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1421 txid: commitment_tx.txid(),
1423 revocation_key: local_keys.revocation_key,
1424 a_htlc_key: local_keys.a_htlc_key,
1425 b_htlc_key: local_keys.b_htlc_key,
1426 delayed_payment_key: local_keys.a_delayed_payment_key,
1427 per_commitment_point: local_keys.per_commitment_point,
1434 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1435 /// commitment_tx_infos which contain the payment hash have been revoked.
1436 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1437 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1440 /// Used in Channel to cheat wrt the update_ids since it plays games, will be removed soon!
1441 pub(super) fn update_monitor_ooo(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1442 for update in updates.updates.drain(..) {
1444 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1445 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1446 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1447 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1448 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1449 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1450 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1451 self.provide_secret(idx, secret)?
1454 self.latest_update_id = updates.update_id;
1458 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1461 /// panics if the given update is not the next update by update_id.
1462 pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1463 if self.latest_update_id + 1 != updates.update_id {
1464 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1466 for update in updates.updates.drain(..) {
1468 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1469 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1470 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1471 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1472 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1473 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1474 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1475 self.provide_secret(idx, secret)?
1478 self.latest_update_id = updates.update_id;
1482 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
1483 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
1484 /// chain for new blocks/transactions.
1485 pub fn insert_combine(&mut self, mut other: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
1486 match self.key_storage {
1487 Storage::Local { ref funding_info, .. } => {
1488 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
1489 let our_funding_info = funding_info;
1490 if let Storage::Local { ref funding_info, .. } = other.key_storage {
1491 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
1492 // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially
1493 // easy to collide the funding_txo hash and have a different scriptPubKey.
1494 if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
1495 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
1498 return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
1501 Storage::Watchtower { .. } => {
1502 if let Storage::Watchtower { .. } = other.key_storage {
1505 return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
1509 let other_min_secret = other.get_min_seen_secret();
1510 let our_min_secret = self.get_min_seen_secret();
1511 if our_min_secret > other_min_secret {
1512 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
1514 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
1515 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
1516 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);
1517 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);
1518 if our_commitment_number >= other_commitment_number {
1519 self.key_storage = other.key_storage;
1523 // TODO: We should use current_remote_commitment_number and the commitment number out of
1524 // local transactions to decide how to merge
1525 if our_min_secret >= other_min_secret {
1526 self.their_cur_revocation_points = other.their_cur_revocation_points;
1527 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
1528 self.remote_claimable_outpoints.insert(txid, htlcs);
1530 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
1531 self.prev_local_signed_commitment_tx = Some(local_tx);
1533 if let Some(local_tx) = other.current_local_signed_commitment_tx {
1534 self.current_local_signed_commitment_tx = Some(local_tx);
1536 self.payment_preimages = other.payment_preimages;
1537 self.to_remote_rescue = other.to_remote_rescue;
1540 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
1544 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
1545 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
1546 /// avoid this on a monitor you wish to send to a watchtower as it provides slightly better
1548 /// It's the responsibility of the caller to register outpoint and script with passing the former
1549 /// value as key to add_update_monitor.
1550 pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
1551 match self.key_storage {
1552 Storage::Local { ref mut funding_info, .. } => {
1553 *funding_info = Some(new_funding_info);
1555 Storage::Watchtower { .. } => {
1556 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
1561 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
1562 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
1563 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) {
1564 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
1565 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
1566 self.their_to_self_delay = Some(their_to_self_delay);
1567 self.funding_redeemscript = Some(funding_redeemscript);
1568 self.channel_value_satoshis = Some(channel_value_satoshis);
1569 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
1570 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
1573 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1575 pub fn get_latest_update_id(&self) -> u64 {
1576 self.latest_update_id
1579 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1580 pub fn get_funding_txo(&self) -> Option<OutPoint> {
1581 match self.key_storage {
1582 Storage::Local { ref funding_info, .. } => {
1583 match funding_info {
1584 &Some((outpoint, _)) => Some(outpoint),
1588 Storage::Watchtower { .. } => {
1594 /// Gets a list of txids, with their output scripts (in the order they appear in the
1595 /// transaction), which we must learn about spends of via block_connected().
1596 pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1597 &self.outputs_to_watch
1600 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1601 /// Generally useful when deserializing as during normal operation the return values of
1602 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1603 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1604 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1605 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1606 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1607 for (idx, output) in outputs.iter().enumerate() {
1608 res.push(((*txid).clone(), idx as u32, output));
1614 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1615 /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1616 pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1617 let mut ret = Vec::new();
1618 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1622 /// Can only fail if idx is < get_min_seen_secret
1623 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1624 self.commitment_secrets.get_secret(idx)
1627 pub(super) fn get_min_seen_secret(&self) -> u64 {
1628 self.commitment_secrets.get_min_seen_secret()
1631 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1632 self.current_remote_commitment_number
1635 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1636 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1637 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)
1638 } else { 0xffff_ffff_ffff }
1641 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1642 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1643 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1644 /// HTLC-Success/HTLC-Timeout transactions.
1645 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1646 /// revoked remote commitment tx
1647 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32, fee_estimator: &FeeEstimator) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1648 // Most secp and related errors trying to create keys means we have no hope of constructing
1649 // a spend transaction...so we return no transactions to broadcast
1650 let mut txn_to_broadcast = Vec::new();
1651 let mut watch_outputs = Vec::new();
1652 let mut spendable_outputs = Vec::new();
1654 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1655 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1657 macro_rules! ignore_error {
1658 ( $thing : expr ) => {
1661 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1666 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);
1667 if commitment_number >= self.get_min_seen_secret() {
1668 let secret = self.get_secret(commitment_number).unwrap();
1669 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1670 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1671 Storage::Local { ref keys, ref payment_base_key, .. } => {
1672 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1673 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1674 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1675 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1677 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1678 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1679 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1680 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1684 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()));
1685 let a_htlc_key = match self.their_htlc_base_key {
1686 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1687 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)),
1690 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1691 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1693 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1694 // Note that the Network here is ignored as we immediately drop the address for the
1695 // script_pubkey version.
1696 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1697 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1700 let mut total_value = 0;
1701 let mut inputs = Vec::new();
1702 let mut inputs_info = Vec::new();
1703 let mut inputs_desc = Vec::new();
1705 for (idx, outp) in tx.output.iter().enumerate() {
1706 if outp.script_pubkey == revokeable_p2wsh {
1708 previous_output: BitcoinOutPoint {
1709 txid: commitment_txid,
1712 script_sig: Script::new(),
1713 sequence: 0xfffffffd,
1714 witness: Vec::new(),
1716 inputs_desc.push(InputDescriptors::RevokedOutput);
1717 inputs_info.push((None, outp.value, self.our_to_self_delay as u32));
1718 total_value += outp.value;
1719 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1720 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1721 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1722 key: local_payment_key.unwrap(),
1723 output: outp.clone(),
1728 macro_rules! sign_input {
1729 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1731 let (sig, redeemscript, revocation_key) = match self.key_storage {
1732 Storage::Local { ref revocation_base_key, .. } => {
1733 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1734 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1735 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1737 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1738 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1739 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript, revocation_key)
1741 Storage::Watchtower { .. } => {
1745 $input.witness.push(sig.serialize_der().to_vec());
1746 $input.witness[0].push(SigHashType::All as u8);
1747 if $htlc_idx.is_none() {
1748 $input.witness.push(vec!(1));
1750 $input.witness.push(revocation_pubkey.serialize().to_vec());
1752 $input.witness.push(redeemscript.clone().into_bytes());
1753 (redeemscript, revocation_key)
1758 if let Some(ref per_commitment_data) = per_commitment_option {
1759 inputs.reserve_exact(per_commitment_data.len());
1761 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1762 if let Some(transaction_output_index) = htlc.transaction_output_index {
1763 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1764 if transaction_output_index as usize >= tx.output.len() ||
1765 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1766 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1767 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1770 previous_output: BitcoinOutPoint {
1771 txid: commitment_txid,
1772 vout: transaction_output_index,
1774 script_sig: Script::new(),
1775 sequence: 0xfffffffd,
1776 witness: Vec::new(),
1778 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1780 inputs_desc.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1781 inputs_info.push((Some(idx), tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1782 total_value += tx.output[transaction_output_index as usize].value;
1784 let mut single_htlc_tx = Transaction {
1788 output: vec!(TxOut {
1789 script_pubkey: self.destination_script.clone(),
1790 value: htlc.amount_msat / 1000,
1793 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1794 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1795 let mut used_feerate;
1796 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1797 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1798 let (redeemscript, revocation_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1799 assert!(predicted_weight >= single_htlc_tx.get_weight());
1800 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);
1801 let mut per_input_material = HashMap::with_capacity(1);
1802 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 });
1803 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1804 hash_map::Entry::Occupied(_) => {},
1805 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1807 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1808 hash_map::Entry::Occupied(_) => {},
1809 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1811 txn_to_broadcast.push(single_htlc_tx);
1818 if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1819 // We're definitely a remote commitment transaction!
1820 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());
1821 watch_outputs.append(&mut tx.output.clone());
1822 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1824 macro_rules! check_htlc_fails {
1825 ($txid: expr, $commitment_tx: expr) => {
1826 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1827 for &(ref htlc, ref source_option) in outpoints.iter() {
1828 if let &Some(ref source) = source_option {
1829 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);
1830 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1831 hash_map::Entry::Occupied(mut entry) => {
1832 let e = entry.get_mut();
1833 e.retain(|ref event| {
1835 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1836 return htlc_update.0 != **source
1841 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1843 hash_map::Entry::Vacant(entry) => {
1844 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1852 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1853 if let &Some(ref txid) = current_remote_commitment_txid {
1854 check_htlc_fails!(txid, "current");
1856 if let &Some(ref txid) = prev_remote_commitment_txid {
1857 check_htlc_fails!(txid, "remote");
1860 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1862 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1864 let outputs = vec!(TxOut {
1865 script_pubkey: self.destination_script.clone(),
1868 let mut spend_tx = Transaction {
1875 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1877 let mut used_feerate;
1878 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1879 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1882 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1884 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1885 let mut soonest_timelock = ::std::u32::MAX;
1886 for info in inputs_info.iter() {
1887 if info.2 <= soonest_timelock {
1888 soonest_timelock = info.2;
1891 let height_timer = Self::get_height_timer(height, soonest_timelock);
1892 let spend_txid = spend_tx.txid();
1893 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1894 let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1);
1895 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);
1896 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 });
1897 match self.claimable_outpoints.entry(input.previous_output) {
1898 hash_map::Entry::Occupied(_) => {},
1899 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1902 match self.pending_claim_requests.entry(spend_txid) {
1903 hash_map::Entry::Occupied(_) => {},
1904 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1907 assert!(predicted_weight >= spend_tx.get_weight());
1909 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1910 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1911 output: spend_tx.output[0].clone(),
1913 txn_to_broadcast.push(spend_tx);
1914 } else if let Some(per_commitment_data) = per_commitment_option {
1915 // While this isn't useful yet, there is a potential race where if a counterparty
1916 // revokes a state at the same time as the commitment transaction for that state is
1917 // confirmed, and the watchtower receives the block before the user, the user could
1918 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1919 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1920 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1922 watch_outputs.append(&mut tx.output.clone());
1923 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1925 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1927 macro_rules! check_htlc_fails {
1928 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1929 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1930 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1931 if let &Some(ref source) = source_option {
1932 // Check if the HTLC is present in the commitment transaction that was
1933 // broadcast, but not if it was below the dust limit, which we should
1934 // fail backwards immediately as there is no way for us to learn the
1935 // payment_preimage.
1936 // Note that if the dust limit were allowed to change between
1937 // commitment transactions we'd want to be check whether *any*
1938 // broadcastable commitment transaction has the HTLC in it, but it
1939 // cannot currently change after channel initialization, so we don't
1941 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1942 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1946 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);
1947 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1948 hash_map::Entry::Occupied(mut entry) => {
1949 let e = entry.get_mut();
1950 e.retain(|ref event| {
1952 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1953 return htlc_update.0 != **source
1958 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1960 hash_map::Entry::Vacant(entry) => {
1961 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1969 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1970 if let &Some(ref txid) = current_remote_commitment_txid {
1971 check_htlc_fails!(txid, "current", 'current_loop);
1973 if let &Some(ref txid) = prev_remote_commitment_txid {
1974 check_htlc_fails!(txid, "previous", 'prev_loop);
1978 if let Some(revocation_points) = self.their_cur_revocation_points {
1979 let revocation_point_option =
1980 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1981 else if let Some(point) = revocation_points.2.as_ref() {
1982 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1984 if let Some(revocation_point) = revocation_point_option {
1985 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1986 Storage::Local { ref keys, .. } => {
1987 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1988 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)))
1990 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1991 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1992 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1995 let a_htlc_key = match self.their_htlc_base_key {
1996 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1997 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
2000 for (idx, outp) in tx.output.iter().enumerate() {
2001 if outp.script_pubkey.is_v0_p2wpkh() {
2002 match self.key_storage {
2003 Storage::Local { ref payment_base_key, .. } => {
2004 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
2005 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
2006 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
2008 output: outp.clone(),
2012 Storage::Watchtower { .. } => {}
2014 break; // Only to_remote ouput is claimable
2018 let mut total_value = 0;
2019 let mut inputs = Vec::new();
2020 let mut inputs_desc = Vec::new();
2021 let mut inputs_info = Vec::new();
2023 macro_rules! sign_input {
2024 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr, $idx: expr) => {
2026 let (sig, redeemscript, htlc_key) = match self.key_storage {
2027 Storage::Local { ref htlc_base_key, .. } => {
2028 let htlc = &per_commitment_option.unwrap()[$idx as usize].0;
2029 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
2030 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
2031 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
2032 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript, htlc_key)
2034 Storage::Watchtower { .. } => {
2038 $input.witness.push(sig.serialize_der().to_vec());
2039 $input.witness[0].push(SigHashType::All as u8);
2040 $input.witness.push($preimage);
2041 $input.witness.push(redeemscript.clone().into_bytes());
2042 (redeemscript, htlc_key)
2047 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2048 if let Some(transaction_output_index) = htlc.transaction_output_index {
2049 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
2050 if transaction_output_index as usize >= tx.output.len() ||
2051 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
2052 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
2053 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
2055 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2058 previous_output: BitcoinOutPoint {
2059 txid: commitment_txid,
2060 vout: transaction_output_index,
2062 script_sig: Script::new(),
2063 sequence: 0xff_ff_ff_fd,
2064 witness: Vec::new(),
2066 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
2068 inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
2069 inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry, idx));
2070 total_value += tx.output[transaction_output_index as usize].value;
2072 let mut single_htlc_tx = Transaction {
2076 output: vec!(TxOut {
2077 script_pubkey: self.destination_script.clone(),
2078 value: htlc.amount_msat / 1000,
2081 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
2082 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2083 let mut used_feerate;
2084 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
2085 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
2086 let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec(), idx);
2087 assert!(predicted_weight >= single_htlc_tx.get_weight());
2088 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2089 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
2090 output: single_htlc_tx.output[0].clone(),
2092 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);
2093 let mut per_input_material = HashMap::with_capacity(1);
2094 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 });
2095 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
2096 hash_map::Entry::Occupied(_) => {},
2097 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
2099 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
2100 hash_map::Entry::Occupied(_) => {},
2101 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material}); }
2103 txn_to_broadcast.push(single_htlc_tx);
2109 // TODO: If the HTLC has already expired, potentially merge it with the
2110 // rest of the claim transaction, as above.
2112 previous_output: BitcoinOutPoint {
2113 txid: commitment_txid,
2114 vout: transaction_output_index,
2116 script_sig: Script::new(),
2117 sequence: 0xff_ff_ff_fd,
2118 witness: Vec::new(),
2120 let mut timeout_tx = Transaction {
2122 lock_time: htlc.cltv_expiry,
2124 output: vec!(TxOut {
2125 script_pubkey: self.destination_script.clone(),
2126 value: htlc.amount_msat / 1000,
2129 let predicted_weight = timeout_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]);
2130 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2131 let mut used_feerate;
2132 if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
2133 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
2134 let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0], idx);
2135 assert!(predicted_weight >= timeout_tx.get_weight());
2136 //TODO: track SpendableOutputDescriptor
2137 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);
2138 let mut per_input_material = HashMap::with_capacity(1);
2139 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 });
2140 match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) {
2141 hash_map::Entry::Occupied(_) => {},
2142 hash_map::Entry::Vacant(entry) => { entry.insert((timeout_tx.txid(), height)); }
2144 match self.pending_claim_requests.entry(timeout_tx.txid()) {
2145 hash_map::Entry::Occupied(_) => {},
2146 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
2149 txn_to_broadcast.push(timeout_tx);
2154 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
2156 let outputs = vec!(TxOut {
2157 script_pubkey: self.destination_script.clone(),
2160 let mut spend_tx = Transaction {
2167 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
2169 let mut used_feerate;
2170 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2171 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
2174 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2176 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
2177 let mut soonest_timelock = ::std::u32::MAX;
2178 for info in inputs_info.iter() {
2179 if info.2 <= soonest_timelock {
2180 soonest_timelock = info.2;
2183 let height_timer = Self::get_height_timer(height, soonest_timelock);
2184 let spend_txid = spend_tx.txid();
2185 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
2186 let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec(), info.3);
2187 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);
2188 per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
2189 match self.claimable_outpoints.entry(input.previous_output) {
2190 hash_map::Entry::Occupied(_) => {},
2191 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
2194 match self.pending_claim_requests.entry(spend_txid) {
2195 hash_map::Entry::Occupied(_) => {},
2196 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
2198 assert!(predicted_weight >= spend_tx.get_weight());
2199 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2200 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
2201 output: spend_tx.output[0].clone(),
2203 txn_to_broadcast.push(spend_tx);
2206 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
2207 for (idx, outp) in tx.output.iter().enumerate() {
2208 if to_remote_rescue == &outp.script_pubkey {
2209 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
2210 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
2211 key: local_key.clone(),
2212 output: outp.clone(),
2218 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
2221 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
2222 fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32, fee_estimator: &FeeEstimator) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
2223 //TODO: send back new outputs to guarantee pending_claim_request consistency
2224 if tx.input.len() != 1 || tx.output.len() != 1 {
2228 macro_rules! ignore_error {
2229 ( $thing : expr ) => {
2232 Err(_) => return (None, None)
2237 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
2238 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2239 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2240 let revocation_pubkey = match self.key_storage {
2241 Storage::Local { ref keys, .. } => {
2242 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint))
2244 Storage::Watchtower { ref revocation_base_key, .. } => {
2245 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
2248 let delayed_key = match self.their_delayed_payment_base_key {
2249 None => return (None, None),
2250 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
2252 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
2253 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2254 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2256 let mut inputs = Vec::new();
2259 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
2261 previous_output: BitcoinOutPoint {
2265 script_sig: Script::new(),
2266 sequence: 0xfffffffd,
2267 witness: Vec::new(),
2269 amount = tx.output[0].value;
2272 if !inputs.is_empty() {
2273 let outputs = vec!(TxOut {
2274 script_pubkey: self.destination_script.clone(),
2278 let mut spend_tx = Transaction {
2284 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
2285 let mut used_feerate;
2286 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2287 return (None, None);
2290 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2292 let (sig, revocation_key) = match self.key_storage {
2293 Storage::Local { ref revocation_base_key, .. } => {
2294 let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
2295 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
2296 (self.secp_ctx.sign(&sighash, &revocation_key), revocation_key)
2298 Storage::Watchtower { .. } => {
2302 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
2303 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
2304 spend_tx.input[0].witness.push(vec!(1));
2305 spend_tx.input[0].witness.push(redeemscript.clone().into_bytes());
2307 assert!(predicted_weight >= spend_tx.get_weight());
2308 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
2309 let output = spend_tx.output[0].clone();
2310 let height_timer = Self::get_height_timer(height, height + self.our_to_self_delay as u32);
2311 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);
2312 let mut per_input_material = HashMap::with_capacity(1);
2313 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 });
2314 match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) {
2315 hash_map::Entry::Occupied(_) => {},
2316 hash_map::Entry::Vacant(entry) => { entry.insert((spend_tx.txid(), height)); }
2318 match self.pending_claim_requests.entry(spend_tx.txid()) {
2319 hash_map::Entry::Occupied(_) => {},
2320 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 }); }
2322 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
2323 } else { (None, None) }
2326 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)>) {
2327 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
2328 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2329 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2330 let mut pending_claims = Vec::with_capacity(local_tx.htlc_outputs.len());
2332 macro_rules! add_dynamic_output {
2333 ($father_tx: expr, $vout: expr) => {
2334 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
2335 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
2336 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
2337 key: local_delayedkey,
2338 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
2339 to_self_delay: self.our_to_self_delay,
2340 output: $father_tx.output[$vout as usize].clone(),
2346 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
2347 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2348 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
2349 if output.script_pubkey == revokeable_p2wsh {
2350 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
2355 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
2356 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
2357 if let Some(transaction_output_index) = htlc.transaction_output_index {
2358 if let &Some(ref their_sig) = sigs {
2360 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
2361 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);
2362 let (our_sig, htlc_script) = match
2363 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) {
2368 add_dynamic_output!(htlc_timeout_tx, 0);
2369 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2370 let mut per_input_material = HashMap::with_capacity(1);
2371 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});
2372 //TODO: with option_simplified_commitment track outpoint too
2373 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);
2374 pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2375 res.push(htlc_timeout_tx);
2377 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2378 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
2379 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);
2380 let (our_sig, htlc_script) = match
2381 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) {
2386 add_dynamic_output!(htlc_success_tx, 0);
2387 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2388 let mut per_input_material = HashMap::with_capacity(1);
2389 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});
2390 //TODO: with option_simplified_commitment track outpoint too
2391 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);
2392 pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2393 res.push(htlc_success_tx);
2396 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
2397 } else { panic!("Should have sigs for non-dust local tx outputs!") }
2402 (res, spendable_outputs, watch_outputs, pending_claims)
2405 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2406 /// revoked using data in local_claimable_outpoints.
2407 /// Should not be used if check_spend_revoked_transaction succeeds.
2408 fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
2409 let commitment_txid = tx.txid();
2410 let mut local_txn = Vec::new();
2411 let mut spendable_outputs = Vec::new();
2412 let mut watch_outputs = Vec::new();
2414 macro_rules! wait_threshold_conf {
2415 ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
2416 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);
2417 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
2418 hash_map::Entry::Occupied(mut entry) => {
2419 let e = entry.get_mut();
2420 e.retain(|ref event| {
2422 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2423 return htlc_update.0 != $source
2428 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
2430 hash_map::Entry::Vacant(entry) => {
2431 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
2437 macro_rules! append_onchain_update {
2438 ($updates: expr) => {
2439 local_txn.append(&mut $updates.0);
2440 spendable_outputs.append(&mut $updates.1);
2441 watch_outputs.append(&mut $updates.2);
2442 for claim in $updates.3 {
2443 match self.pending_claim_requests.entry(claim.0) {
2444 hash_map::Entry::Occupied(_) => {},
2445 hash_map::Entry::Vacant(entry) => { entry.insert(claim.1); }
2451 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2452 let mut is_local_tx = false;
2454 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2455 if local_tx.txid == commitment_txid {
2456 match self.key_storage {
2457 Storage::Local { ref funding_key, .. } => {
2458 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2464 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2465 if local_tx.txid == commitment_txid {
2467 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
2468 assert!(local_tx.tx.has_local_sig());
2469 match self.key_storage {
2470 Storage::Local { ref delayed_payment_base_key, .. } => {
2471 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2472 append_onchain_update!(res);
2474 Storage::Watchtower { .. } => { }
2478 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
2479 if local_tx.txid == commitment_txid {
2480 match self.key_storage {
2481 Storage::Local { ref funding_key, .. } => {
2482 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2488 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2489 if local_tx.txid == commitment_txid {
2491 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
2492 assert!(local_tx.tx.has_local_sig());
2493 match self.key_storage {
2494 Storage::Local { ref delayed_payment_base_key, .. } => {
2495 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2496 append_onchain_update!(res);
2498 Storage::Watchtower { .. } => { }
2503 macro_rules! fail_dust_htlcs_after_threshold_conf {
2504 ($local_tx: expr) => {
2505 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
2506 if htlc.transaction_output_index.is_none() {
2507 if let &Some(ref source) = source {
2508 wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
2516 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2517 fail_dust_htlcs_after_threshold_conf!(local_tx);
2519 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2520 fail_dust_htlcs_after_threshold_conf!(local_tx);
2524 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
2527 /// Generate a spendable output event when closing_transaction get registered onchain.
2528 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
2529 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
2530 match self.key_storage {
2531 Storage::Local { ref shutdown_pubkey, .. } => {
2532 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
2533 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
2534 for (idx, output) in tx.output.iter().enumerate() {
2535 if shutdown_script == output.script_pubkey {
2536 return Some(SpendableOutputDescriptor::StaticOutput {
2537 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
2538 output: output.clone(),
2543 Storage::Watchtower { .. } => {
2544 //TODO: we need to ensure an offline client will generate the event when it
2545 // comes back online after only the watchtower saw the transaction
2552 /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
2553 /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
2554 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
2555 /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
2556 /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
2557 /// broadcast them if remote don't close channel with his higher commitment transaction after a
2558 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
2559 /// out-of-band the other node operator to coordinate with him if option is available to you.
2560 /// In any-case, choice is up to the user.
2561 pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
2562 log_trace!(self, "Getting signed latest local commitment transaction!");
2563 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2564 match self.key_storage {
2565 Storage::Local { ref funding_key, .. } => {
2566 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2571 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2572 let mut res = vec![local_tx.tx.with_valid_witness().clone()];
2573 match self.key_storage {
2574 Storage::Local { ref delayed_payment_base_key, .. } => {
2575 res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
2576 // 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.
2577 // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
2579 _ => panic!("Can only broadcast by local channelmonitor"),
2587 /// Called by SimpleManyChannelMonitor::block_connected, which implements
2588 /// ChainListener::block_connected.
2589 /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
2590 /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
2592 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>)
2593 where B::Target: BroadcasterInterface
2595 for tx in txn_matched {
2596 let mut output_val = 0;
2597 for out in tx.output.iter() {
2598 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2599 output_val += out.value;
2600 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2604 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2605 let mut watch_outputs = Vec::new();
2606 let mut spendable_outputs = Vec::new();
2607 let mut bump_candidates = HashSet::new();
2608 for tx in txn_matched {
2609 if tx.input.len() == 1 {
2610 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2611 // commitment transactions and HTLC transactions will all only ever have one input,
2612 // which is an easy way to filter out any potential non-matching txn for lazy
2614 let prevout = &tx.input[0].previous_output;
2615 let mut txn: Vec<Transaction> = Vec::new();
2616 let funding_txo = match self.key_storage {
2617 Storage::Local { ref funding_info, .. } => {
2618 funding_info.clone()
2620 Storage::Watchtower { .. } => {
2624 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) {
2625 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2626 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
2628 spendable_outputs.append(&mut spendable_output);
2629 if !new_outputs.1.is_empty() {
2630 watch_outputs.push(new_outputs);
2633 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2634 spendable_outputs.append(&mut spendable_output);
2636 if !new_outputs.1.is_empty() {
2637 watch_outputs.push(new_outputs);
2641 if !funding_txo.is_none() && txn.is_empty() {
2642 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2643 spendable_outputs.push(spendable_output);
2647 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2648 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
2649 if let Some(tx) = tx {
2652 if let Some(spendable_output) = spendable_output {
2653 spendable_outputs.push(spendable_output);
2657 for tx in txn.iter() {
2658 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2659 broadcaster.broadcast_transaction(tx);
2662 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2663 // can also be resolved in a few other ways which can have more than one output. Thus,
2664 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2665 self.is_resolving_htlc_output(&tx, height);
2667 // Scan all input to verify is one of the outpoint spent is of interest for us
2668 let mut claimed_outputs_material = Vec::new();
2669 for inp in &tx.input {
2670 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2671 // If outpoint has claim request pending on it...
2672 if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2673 //... we need to verify equality between transaction outpoints and claim request
2674 // outpoints to know if transaction is the original claim or a bumped one issued
2676 let mut set_equality = true;
2677 if claim_material.per_input_material.len() != tx.input.len() {
2678 set_equality = false;
2680 for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2681 if *claim_inp != tx_inp.previous_output {
2682 set_equality = false;
2687 macro_rules! clean_claim_request_after_safety_delay {
2689 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2690 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2691 hash_map::Entry::Occupied(mut entry) => {
2692 if !entry.get().contains(&new_event) {
2693 entry.get_mut().push(new_event);
2696 hash_map::Entry::Vacant(entry) => {
2697 entry.insert(vec![new_event]);
2703 // If this is our transaction (or our counterparty spent all the outputs
2704 // before we could anyway with same inputs order than us), wait for
2705 // ANTI_REORG_DELAY and clean the RBF tracking map.
2707 clean_claim_request_after_safety_delay!();
2708 } else { // If false, generate new claim request with update outpoint set
2709 for input in tx.input.iter() {
2710 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2711 claimed_outputs_material.push((input.previous_output, input_material));
2713 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2714 if claim_material.per_input_material.is_empty() {
2715 clean_claim_request_after_safety_delay!();
2718 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2719 bump_candidates.insert(first_claim_txid_height.0.clone());
2721 break; //No need to iterate further, either tx is our or their
2723 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2727 for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2728 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2729 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2730 hash_map::Entry::Occupied(mut entry) => {
2731 if !entry.get().contains(&new_event) {
2732 entry.get_mut().push(new_event);
2735 hash_map::Entry::Vacant(entry) => {
2736 entry.insert(vec![new_event]);
2741 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2742 self.would_broadcast_at_height(height)
2744 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2745 if should_broadcast {
2746 match self.key_storage {
2747 Storage::Local { ref funding_key, .. } => {
2748 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2754 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2755 if should_broadcast {
2756 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2757 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2758 match self.key_storage {
2759 Storage::Local { ref delayed_payment_base_key, .. } => {
2760 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2761 spendable_outputs.append(&mut spendable_output);
2762 if !new_outputs.is_empty() {
2763 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2766 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2767 broadcaster.broadcast_transaction(&tx);
2770 Storage::Watchtower { .. } => { },
2774 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2777 OnchainEvent::Claim { claim_request } => {
2778 // We may remove a whole set of claim outpoints here, as these one may have
2779 // been aggregated in a single tx and claimed so atomically
2780 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2781 for outpoint in bump_material.per_input_material.keys() {
2782 self.claimable_outpoints.remove(&outpoint);
2786 OnchainEvent::HTLCUpdate { htlc_update } => {
2787 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2788 self.pending_htlcs_updated.push(HTLCUpdate {
2789 payment_hash: htlc_update.1,
2790 payment_preimage: None,
2791 source: htlc_update.0,
2794 OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2795 self.claimable_outpoints.remove(&outpoint);
2800 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2801 if cached_claim_datas.height_timer == height {
2802 bump_candidates.insert(first_claim_txid.clone());
2805 for first_claim_txid in bump_candidates.iter() {
2806 if let Some((new_timer, new_feerate)) = {
2807 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2808 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2809 broadcaster.broadcast_transaction(&bump_tx);
2810 Some((new_timer, new_feerate))
2812 } else { unreachable!(); }
2814 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2815 claim_material.height_timer = new_timer;
2816 claim_material.feerate_previous = new_feerate;
2817 } else { unreachable!(); }
2820 self.last_block_hash = block_hash.clone();
2821 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2822 self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2824 (watch_outputs, spendable_outputs)
2827 fn block_disconnected<B: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: &FeeEstimator)
2828 where B::Target: BroadcasterInterface
2830 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2831 let mut bump_candidates = HashMap::new();
2832 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2834 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2835 //- our claim tx on a commitment tx output
2836 //- resurect outpoint back in its claimable set and regenerate tx
2839 OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2840 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2841 if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2842 claim_material.per_input_material.insert(outpoint, input_material);
2843 // Using a HashMap guarantee us than if we have multiple outpoints getting
2844 // resurrected only one bump claim tx is going to be broadcast
2845 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2853 for (_, claim_material) in bump_candidates.iter_mut() {
2854 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2855 claim_material.height_timer = new_timer;
2856 claim_material.feerate_previous = new_feerate;
2857 broadcaster.broadcast_transaction(&bump_tx);
2860 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2861 self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2863 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2864 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2865 let mut remove_request = Vec::new();
2866 self.claimable_outpoints.retain(|_, ref v|
2868 remove_request.push(v.0.clone());
2871 for req in remove_request {
2872 self.pending_claim_requests.remove(&req);
2874 self.last_block_hash = block_hash.clone();
2877 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2878 // We need to consider all HTLCs which are:
2879 // * in any unrevoked remote commitment transaction, as they could broadcast said
2880 // transactions and we'd end up in a race, or
2881 // * are in our latest local commitment transaction, as this is the thing we will
2882 // broadcast if we go on-chain.
2883 // Note that we consider HTLCs which were below dust threshold here - while they don't
2884 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2885 // to the source, and if we don't fail the channel we will have to ensure that the next
2886 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2887 // easier to just fail the channel as this case should be rare enough anyway.
2888 macro_rules! scan_commitment {
2889 ($htlcs: expr, $local_tx: expr) => {
2890 for ref htlc in $htlcs {
2891 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2892 // chain with enough room to claim the HTLC without our counterparty being able to
2893 // time out the HTLC first.
2894 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2895 // concern is being able to claim the corresponding inbound HTLC (on another
2896 // channel) before it expires. In fact, we don't even really care if our
2897 // counterparty here claims such an outbound HTLC after it expired as long as we
2898 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2899 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2900 // we give ourselves a few blocks of headroom after expiration before going
2901 // on-chain for an expired HTLC.
2902 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2903 // from us until we've reached the point where we go on-chain with the
2904 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2905 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2906 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2907 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2908 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2909 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2910 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2911 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2912 // The final, above, condition is checked for statically in channelmanager
2913 // with CHECK_CLTV_EXPIRY_SANITY_2.
2914 let htlc_outbound = $local_tx == htlc.offered;
2915 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2916 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2917 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2924 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2925 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2928 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2929 if let &Some(ref txid) = current_remote_commitment_txid {
2930 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2931 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2934 if let &Some(ref txid) = prev_remote_commitment_txid {
2935 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2936 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2944 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2945 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2946 fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2947 'outer_loop: for input in &tx.input {
2948 let mut payment_data = None;
2949 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2950 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2951 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2952 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2954 macro_rules! log_claim {
2955 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2956 // We found the output in question, but aren't failing it backwards
2957 // as we have no corresponding source and no valid remote commitment txid
2958 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2959 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2960 let outbound_htlc = $local_tx == $htlc.offered;
2961 if ($local_tx && revocation_sig_claim) ||
2962 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2963 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2964 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2965 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2966 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2968 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2969 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2970 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2971 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2976 macro_rules! check_htlc_valid_remote {
2977 ($remote_txid: expr, $htlc_output: expr) => {
2978 if let &Some(txid) = $remote_txid {
2979 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2980 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2981 if let &Some(ref source) = pending_source {
2982 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2983 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2992 macro_rules! scan_commitment {
2993 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2994 for (ref htlc_output, source_option) in $htlcs {
2995 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2996 if let Some(ref source) = source_option {
2997 log_claim!($tx_info, $local_tx, htlc_output, true);
2998 // We have a resolution of an HTLC either from one of our latest
2999 // local commitment transactions or an unrevoked remote commitment
3000 // transaction. This implies we either learned a preimage, the HTLC
3001 // has timed out, or we screwed up. In any case, we should now
3002 // resolve the source HTLC with the original sender.
3003 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
3004 } else if !$local_tx {
3005 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
3006 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
3008 if payment_data.is_none() {
3009 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
3010 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
3014 if payment_data.is_none() {
3015 log_claim!($tx_info, $local_tx, htlc_output, false);
3016 continue 'outer_loop;
3023 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
3024 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
3025 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3026 "our latest local commitment tx", true);
3029 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
3030 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
3031 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3032 "our previous local commitment tx", true);
3035 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
3036 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3037 "remote commitment tx", false);
3040 // Check that scan_commitment, above, decided there is some source worth relaying an
3041 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3042 if let Some((source, payment_hash)) = payment_data {
3043 let mut payment_preimage = PaymentPreimage([0; 32]);
3044 if accepted_preimage_claim {
3045 payment_preimage.0.copy_from_slice(&input.witness[3]);
3046 self.pending_htlcs_updated.push(HTLCUpdate {
3048 payment_preimage: Some(payment_preimage),
3051 } else if offered_preimage_claim {
3052 payment_preimage.0.copy_from_slice(&input.witness[1]);
3053 self.pending_htlcs_updated.push(HTLCUpdate {
3055 payment_preimage: Some(payment_preimage),
3059 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);
3060 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
3061 hash_map::Entry::Occupied(mut entry) => {
3062 let e = entry.get_mut();
3063 e.retain(|ref event| {
3065 OnchainEvent::HTLCUpdate { ref htlc_update } => {
3066 return htlc_update.0 != source
3071 e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
3073 hash_map::Entry::Vacant(entry) => {
3074 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
3082 /// 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
3083 /// (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.
3084 fn bump_claim_tx(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: &FeeEstimator) -> Option<(u32, u64, Transaction)> {
3085 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
3086 let mut inputs = Vec::new();
3087 for outp in cached_claim_datas.per_input_material.keys() {
3089 previous_output: *outp,
3090 script_sig: Script::new(),
3091 sequence: 0xfffffffd,
3092 witness: Vec::new(),
3095 let mut bumped_tx = Transaction {
3099 output: vec![TxOut {
3100 script_pubkey: self.destination_script.clone(),
3105 macro_rules! RBF_bump {
3106 ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
3108 let mut used_feerate;
3109 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
3110 let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
3111 let mut value = $amount;
3112 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
3113 // Overflow check is done in subtract_high_prio_fee
3116 log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
3119 // ...else just increase the previous feerate by 25% (because that's a nice number)
3121 let fee = $old_feerate * $predicted_weight / 750;
3123 log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
3129 let previous_fee = $old_feerate * $predicted_weight / 1000;
3130 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
3131 // BIP 125 Opt-in Full Replace-by-Fee Signaling
3132 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
3133 // * 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.
3134 let new_fee = if new_fee < previous_fee + min_relay_fee {
3135 new_fee + previous_fee + min_relay_fee - new_fee
3139 Some((new_fee, new_fee * 1000 / $predicted_weight))
3144 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
3145 let mut inputs_witnesses_weight = 0;
3147 for per_outp_material in cached_claim_datas.per_input_material.values() {
3148 match per_outp_material {
3149 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
3150 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!() });
3153 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
3154 inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
3157 &InputMaterial::LocalHTLC { .. } => { return None; }
3161 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
3163 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
3164 // If new computed fee is superior at the whole claimable amount burn all in fees
3166 bumped_tx.output[0].value = 0;
3168 bumped_tx.output[0].value = amt - new_fee;
3170 new_feerate = feerate;
3174 assert!(new_feerate != 0);
3176 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
3177 match per_outp_material {
3178 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
3179 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3180 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3181 let sig = self.secp_ctx.sign(&sighash, &key);
3182 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3183 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3185 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
3187 bumped_tx.input[i].witness.push(vec!(1));
3189 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3190 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);
3192 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
3193 if !preimage.is_some() { bumped_tx.lock_time = *locktime };
3194 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3195 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3196 let sig = self.secp_ctx.sign(&sighash, &key);
3197 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3198 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3199 if let &Some(preimage) = preimage {
3200 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
3202 bumped_tx.input[i].witness.push(vec![0]);
3204 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3205 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);
3207 &InputMaterial::LocalHTLC { .. } => {
3208 //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
3209 // RBF them. Need a Lightning specs change and package relay modification :
3210 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
3215 assert!(predicted_weight >= bumped_tx.get_weight());
3216 Some((new_timer, new_feerate, bumped_tx))
3220 const MAX_ALLOC_SIZE: usize = 64*1024;
3222 impl<R: ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
3223 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
3224 let secp_ctx = Secp256k1::new();
3225 macro_rules! unwrap_obj {
3229 Err(_) => return Err(DecodeError::InvalidValue),
3234 let _ver: u8 = Readable::read(reader)?;
3235 let min_ver: u8 = Readable::read(reader)?;
3236 if min_ver > SERIALIZATION_VERSION {
3237 return Err(DecodeError::UnknownVersion);
3240 let latest_update_id: u64 = Readable::read(reader)?;
3241 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
3243 let key_storage = match <u8 as Readable<R>>::read(reader)? {
3245 let keys = Readable::read(reader)?;
3246 let funding_key = Readable::read(reader)?;
3247 let revocation_base_key = Readable::read(reader)?;
3248 let htlc_base_key = Readable::read(reader)?;
3249 let delayed_payment_base_key = Readable::read(reader)?;
3250 let payment_base_key = Readable::read(reader)?;
3251 let shutdown_pubkey = Readable::read(reader)?;
3252 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3253 // barely-init'd ChannelMonitors that we can't do anything with.
3254 let outpoint = OutPoint {
3255 txid: Readable::read(reader)?,
3256 index: Readable::read(reader)?,
3258 let funding_info = Some((outpoint, Readable::read(reader)?));
3259 let current_remote_commitment_txid = Readable::read(reader)?;
3260 let prev_remote_commitment_txid = Readable::read(reader)?;
3264 revocation_base_key,
3266 delayed_payment_base_key,
3270 current_remote_commitment_txid,
3271 prev_remote_commitment_txid,
3274 _ => return Err(DecodeError::InvalidValue),
3277 let their_htlc_base_key = Some(Readable::read(reader)?);
3278 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3279 let funding_redeemscript = Some(Readable::read(reader)?);
3280 let channel_value_satoshis = Some(Readable::read(reader)?);
3282 let their_cur_revocation_points = {
3283 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
3287 let first_point = Readable::read(reader)?;
3288 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3289 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3290 Some((first_idx, first_point, None))
3292 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3297 let our_to_self_delay: u16 = Readable::read(reader)?;
3298 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3300 let commitment_secrets = Readable::read(reader)?;
3302 macro_rules! read_htlc_in_commitment {
3305 let offered: bool = Readable::read(reader)?;
3306 let amount_msat: u64 = Readable::read(reader)?;
3307 let cltv_expiry: u32 = Readable::read(reader)?;
3308 let payment_hash: PaymentHash = Readable::read(reader)?;
3309 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3311 HTLCOutputInCommitment {
3312 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3318 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3319 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3320 for _ in 0..remote_claimable_outpoints_len {
3321 let txid: Sha256dHash = Readable::read(reader)?;
3322 let htlcs_count: u64 = Readable::read(reader)?;
3323 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3324 for _ in 0..htlcs_count {
3325 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3327 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3328 return Err(DecodeError::InvalidValue);
3332 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3333 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3334 for _ in 0..remote_commitment_txn_on_chain_len {
3335 let txid: Sha256dHash = Readable::read(reader)?;
3336 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3337 let outputs_count = <u64 as Readable<R>>::read(reader)?;
3338 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3339 for _ in 0..outputs_count {
3340 outputs.push(Readable::read(reader)?);
3342 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3343 return Err(DecodeError::InvalidValue);
3347 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3348 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3349 for _ in 0..remote_hash_commitment_number_len {
3350 let payment_hash: PaymentHash = Readable::read(reader)?;
3351 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3352 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3353 return Err(DecodeError::InvalidValue);
3357 macro_rules! read_local_tx {
3360 let tx = <LocalCommitmentTransaction as Readable<R>>::read(reader)?;
3361 let revocation_key = Readable::read(reader)?;
3362 let a_htlc_key = Readable::read(reader)?;
3363 let b_htlc_key = Readable::read(reader)?;
3364 let delayed_payment_key = Readable::read(reader)?;
3365 let per_commitment_point = Readable::read(reader)?;
3366 let feerate_per_kw: u64 = Readable::read(reader)?;
3368 let htlcs_len: u64 = Readable::read(reader)?;
3369 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3370 for _ in 0..htlcs_len {
3371 let htlc = read_htlc_in_commitment!();
3372 let sigs = match <u8 as Readable<R>>::read(reader)? {
3374 1 => Some(Readable::read(reader)?),
3375 _ => return Err(DecodeError::InvalidValue),
3377 htlcs.push((htlc, sigs, Readable::read(reader)?));
3382 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3389 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3392 Some(read_local_tx!())
3394 _ => return Err(DecodeError::InvalidValue),
3397 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3400 Some(read_local_tx!())
3402 _ => return Err(DecodeError::InvalidValue),
3405 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3407 let payment_preimages_len: u64 = Readable::read(reader)?;
3408 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3409 for _ in 0..payment_preimages_len {
3410 let preimage: PaymentPreimage = Readable::read(reader)?;
3411 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3412 if let Some(_) = payment_preimages.insert(hash, preimage) {
3413 return Err(DecodeError::InvalidValue);
3417 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
3418 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
3419 for _ in 0..pending_htlcs_updated_len {
3420 pending_htlcs_updated.push(Readable::read(reader)?);
3423 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3424 let destination_script = Readable::read(reader)?;
3425 let to_remote_rescue = match <u8 as Readable<R>>::read(reader)? {
3428 let to_remote_script = Readable::read(reader)?;
3429 let local_key = Readable::read(reader)?;
3430 Some((to_remote_script, local_key))
3432 _ => return Err(DecodeError::InvalidValue),
3435 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3436 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3437 for _ in 0..pending_claim_requests_len {
3438 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3441 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3442 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3443 for _ in 0..claimable_outpoints_len {
3444 let outpoint = Readable::read(reader)?;
3445 let ancestor_claim_txid = Readable::read(reader)?;
3446 let height = Readable::read(reader)?;
3447 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3450 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3451 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3452 for _ in 0..waiting_threshold_conf_len {
3453 let height_target = Readable::read(reader)?;
3454 let events_len: u64 = Readable::read(reader)?;
3455 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3456 for _ in 0..events_len {
3457 let ev = match <u8 as Readable<R>>::read(reader)? {
3459 let claim_request = Readable::read(reader)?;
3460 OnchainEvent::Claim {
3465 let htlc_source = Readable::read(reader)?;
3466 let hash = Readable::read(reader)?;
3467 OnchainEvent::HTLCUpdate {
3468 htlc_update: (htlc_source, hash)
3472 let outpoint = Readable::read(reader)?;
3473 let input_material = Readable::read(reader)?;
3474 OnchainEvent::ContentiousOutpoint {
3479 _ => return Err(DecodeError::InvalidValue),
3483 onchain_events_waiting_threshold_conf.insert(height_target, events);
3486 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3487 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>>())));
3488 for _ in 0..outputs_to_watch_len {
3489 let txid = Readable::read(reader)?;
3490 let outputs_len: u64 = Readable::read(reader)?;
3491 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
3492 for _ in 0..outputs_len {
3493 outputs.push(Readable::read(reader)?);
3495 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3496 return Err(DecodeError::InvalidValue);
3500 Ok((last_block_hash.clone(), ChannelMonitor {
3502 commitment_transaction_number_obscure_factor,
3505 their_htlc_base_key,
3506 their_delayed_payment_base_key,
3507 funding_redeemscript,
3508 channel_value_satoshis,
3509 their_cur_revocation_points,
3512 their_to_self_delay,
3515 remote_claimable_outpoints,
3516 remote_commitment_txn_on_chain,
3517 remote_hash_commitment_number,
3519 prev_local_signed_commitment_tx,
3520 current_local_signed_commitment_tx,
3521 current_remote_commitment_number,
3524 pending_htlcs_updated,
3529 pending_claim_requests,
3531 claimable_outpoints,
3533 onchain_events_waiting_threshold_conf,
3546 use bitcoin::blockdata::script::{Script, Builder};
3547 use bitcoin::blockdata::opcodes;
3548 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3549 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3550 use bitcoin::util::bip143;
3551 use bitcoin_hashes::Hash;
3552 use bitcoin_hashes::sha256::Hash as Sha256;
3553 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3554 use bitcoin_hashes::hex::FromHex;
3556 use ln::channelmanager::{PaymentPreimage, PaymentHash};
3557 use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3559 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3560 use util::test_utils::TestLogger;
3561 use secp256k1::key::{SecretKey,PublicKey};
3562 use secp256k1::Secp256k1;
3563 use rand::{thread_rng,Rng};
3565 use chain::keysinterface::InMemoryChannelKeys;
3568 fn test_prune_preimages() {
3569 let secp_ctx = Secp256k1::new();
3570 let logger = Arc::new(TestLogger::new());
3572 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3573 macro_rules! dummy_keys {
3577 per_commitment_point: dummy_key.clone(),
3578 revocation_key: dummy_key.clone(),
3579 a_htlc_key: dummy_key.clone(),
3580 b_htlc_key: dummy_key.clone(),
3581 a_delayed_payment_key: dummy_key.clone(),
3582 b_payment_key: dummy_key.clone(),
3587 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3589 let mut preimages = Vec::new();
3591 let mut rng = thread_rng();
3593 let mut preimage = PaymentPreimage([0; 32]);
3594 rng.fill_bytes(&mut preimage.0[..]);
3595 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3596 preimages.push((preimage, hash));
3600 macro_rules! preimages_slice_to_htlc_outputs {
3601 ($preimages_slice: expr) => {
3603 let mut res = Vec::new();
3604 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3605 res.push((HTLCOutputInCommitment {
3609 payment_hash: preimage.1.clone(),
3610 transaction_output_index: Some(idx as u32),
3617 macro_rules! preimages_to_local_htlcs {
3618 ($preimages_slice: expr) => {
3620 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3621 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3627 macro_rules! test_preimages_exist {
3628 ($preimages_slice: expr, $monitor: expr) => {
3629 for preimage in $preimages_slice {
3630 assert!($monitor.payment_preimages.contains_key(&preimage.1));
3635 let keys = InMemoryChannelKeys::new(
3637 SecretKey::from_slice(&[41; 32]).unwrap(),
3638 SecretKey::from_slice(&[41; 32]).unwrap(),
3639 SecretKey::from_slice(&[41; 32]).unwrap(),
3640 SecretKey::from_slice(&[41; 32]).unwrap(),
3641 SecretKey::from_slice(&[41; 32]).unwrap(),
3646 // Prune with one old state and a local commitment tx holding a few overlaps with the
3648 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());
3649 monitor.their_to_self_delay = Some(10);
3651 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
3652 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3653 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3654 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3655 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3656 for &(ref preimage, ref hash) in preimages.iter() {
3657 monitor.provide_payment_preimage(hash, preimage);
3660 // Now provide a secret, pruning preimages 10-15
3661 let mut secret = [0; 32];
3662 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3663 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3664 assert_eq!(monitor.payment_preimages.len(), 15);
3665 test_preimages_exist!(&preimages[0..10], monitor);
3666 test_preimages_exist!(&preimages[15..20], monitor);
3668 // Now provide a further secret, pruning preimages 15-17
3669 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3670 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3671 assert_eq!(monitor.payment_preimages.len(), 13);
3672 test_preimages_exist!(&preimages[0..10], monitor);
3673 test_preimages_exist!(&preimages[17..20], monitor);
3675 // Now update local commitment tx info, pruning only element 18 as we still care about the
3676 // previous commitment tx's preimages too
3677 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
3678 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3679 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3680 assert_eq!(monitor.payment_preimages.len(), 12);
3681 test_preimages_exist!(&preimages[0..10], monitor);
3682 test_preimages_exist!(&preimages[18..20], monitor);
3684 // But if we do it again, we'll prune 5-10
3685 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
3686 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3687 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3688 assert_eq!(monitor.payment_preimages.len(), 5);
3689 test_preimages_exist!(&preimages[0..5], monitor);
3693 fn test_claim_txn_weight_computation() {
3694 // We test Claim txn weight, knowing that we want expected weigth and
3695 // not actual case to avoid sigs and time-lock delays hell variances.
3697 let secp_ctx = Secp256k1::new();
3698 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3699 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3700 let mut sum_actual_sigs = 0;
3702 macro_rules! sign_input {
3703 ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3704 let htlc = HTLCOutputInCommitment {
3705 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3707 cltv_expiry: 2 << 16,
3708 payment_hash: PaymentHash([1; 32]),
3709 transaction_output_index: Some($idx),
3711 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) };
3712 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3713 let sig = secp_ctx.sign(&sighash, &privkey);
3714 $input.witness.push(sig.serialize_der().to_vec());
3715 $input.witness[0].push(SigHashType::All as u8);
3716 sum_actual_sigs += $input.witness[0].len();
3717 if *$input_type == InputDescriptors::RevokedOutput {
3718 $input.witness.push(vec!(1));
3719 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3720 $input.witness.push(pubkey.clone().serialize().to_vec());
3721 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3722 $input.witness.push(vec![0]);
3724 $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3726 $input.witness.push(redeem_script.into_bytes());
3727 println!("witness[0] {}", $input.witness[0].len());
3728 println!("witness[1] {}", $input.witness[1].len());
3729 println!("witness[2] {}", $input.witness[2].len());
3733 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3734 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3736 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3737 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3739 claim_tx.input.push(TxIn {
3740 previous_output: BitcoinOutPoint {
3744 script_sig: Script::new(),
3745 sequence: 0xfffffffd,
3746 witness: Vec::new(),
3749 claim_tx.output.push(TxOut {
3750 script_pubkey: script_pubkey.clone(),
3753 let base_weight = claim_tx.get_weight();
3754 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3755 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3756 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3757 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3759 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));
3761 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3762 claim_tx.input.clear();
3763 sum_actual_sigs = 0;
3765 claim_tx.input.push(TxIn {
3766 previous_output: BitcoinOutPoint {
3770 script_sig: Script::new(),
3771 sequence: 0xfffffffd,
3772 witness: Vec::new(),
3775 let base_weight = claim_tx.get_weight();
3776 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3777 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3778 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3779 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3781 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));
3783 // Justice tx with 1 revoked HTLC-Success tx output
3784 claim_tx.input.clear();
3785 sum_actual_sigs = 0;
3786 claim_tx.input.push(TxIn {
3787 previous_output: BitcoinOutPoint {
3791 script_sig: Script::new(),
3792 sequence: 0xfffffffd,
3793 witness: Vec::new(),
3795 let base_weight = claim_tx.get_weight();
3796 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3797 let inputs_des = vec![InputDescriptors::RevokedOutput];
3798 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3799 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3801 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));
3804 // Further testing is done in the ChannelManager integration tests.