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, MaybeReadable, 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 Readable for ChannelMonitorUpdate {
76 fn read<R: ::std::io::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::update_monitor this
135 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
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 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_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, F: Deref>
216 where T::Target: BroadcasterInterface,
217 F::Target: FeeEstimator
219 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
220 pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
222 monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
223 chain_monitor: Arc<ChainWatchInterface>,
229 impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send>
230 ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
231 where T::Target: BroadcasterInterface,
232 F::Target: FeeEstimator
234 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
235 let block_hash = header.bitcoin_hash();
237 let mut monitors = self.monitors.lock().unwrap();
238 for monitor in monitors.values_mut() {
239 let txn_outputs = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
241 for (ref txid, ref outputs) in txn_outputs {
242 for (idx, output) in outputs.iter().enumerate() {
243 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
250 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
251 let block_hash = header.bitcoin_hash();
252 let mut monitors = self.monitors.lock().unwrap();
253 for monitor in monitors.values_mut() {
254 monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
259 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T, F>
260 where T::Target: BroadcasterInterface,
261 F::Target: FeeEstimator
263 /// Creates a new object which can be used to monitor several channels given the chain
264 /// interface with which to register to receive notifications.
265 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: T, logger: Arc<Logger>, feeest: F) -> SimpleManyChannelMonitor<Key, ChanSigner, T, F> {
266 let res = SimpleManyChannelMonitor {
267 monitors: Mutex::new(HashMap::new()),
271 fee_estimator: feeest,
277 /// Adds or updates the monitor which monitors the channel referred to by the given key.
278 pub fn add_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
279 let mut monitors = self.monitors.lock().unwrap();
280 let entry = match monitors.entry(key) {
281 hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given key is already present")),
282 hash_map::Entry::Vacant(e) => e,
284 match monitor.key_storage {
285 Storage::Local { ref funding_info, .. } => {
288 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
290 &Some((ref outpoint, ref script)) => {
291 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
292 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
293 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
297 Storage::Watchtower { .. } => {
298 self.chain_monitor.watch_all_txn();
301 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
302 for (idx, script) in outputs.iter().enumerate() {
303 self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script);
306 entry.insert(monitor);
310 /// Updates the monitor which monitors the channel referred to by the given key.
311 pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
312 let mut monitors = self.monitors.lock().unwrap();
313 match monitors.get_mut(&key) {
314 Some(orig_monitor) => {
315 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage));
316 orig_monitor.update_monitor(update)
318 None => Err(MonitorUpdateError("No such monitor registered"))
323 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner, T, F>
324 where T::Target: BroadcasterInterface,
325 F::Target: FeeEstimator
327 fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
328 match self.add_monitor_by_key(funding_txo, monitor) {
330 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
334 fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
335 match self.update_monitor_by_key(funding_txo, update) {
337 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
341 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
342 let mut pending_htlcs_updated = Vec::new();
343 for chan in self.monitors.lock().unwrap().values_mut() {
344 pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated());
346 pending_htlcs_updated
350 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
351 where T::Target: BroadcasterInterface,
352 F::Target: FeeEstimator
354 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
355 let mut pending_events = Vec::new();
356 for chan in self.monitors.lock().unwrap().values_mut() {
357 pending_events.append(&mut chan.get_and_clear_pending_events());
363 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
364 /// instead claiming it in its own individual transaction.
365 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
366 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
367 /// HTLC-Success transaction.
368 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
369 /// transaction confirmed (and we use it in a few more, equivalent, places).
370 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
371 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
372 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
373 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
374 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
375 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
376 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
377 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
378 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
379 /// accurate block height.
380 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
381 /// with at worst this delay, so we are not only using this value as a mercy for them but also
382 /// us as a safeguard to delay with enough time.
383 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
384 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
385 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
386 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
387 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
388 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
389 /// keeping bumping another claim tx to solve the outpoint.
390 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
392 enum Storage<ChanSigner: ChannelKeys> {
395 funding_key: SecretKey,
396 revocation_base_key: SecretKey,
397 htlc_base_key: SecretKey,
398 delayed_payment_base_key: SecretKey,
399 payment_base_key: SecretKey,
400 shutdown_pubkey: PublicKey,
401 funding_info: Option<(OutPoint, Script)>,
402 current_remote_commitment_txid: Option<Sha256dHash>,
403 prev_remote_commitment_txid: Option<Sha256dHash>,
406 revocation_base_key: PublicKey,
407 htlc_base_key: PublicKey,
411 #[cfg(any(test, feature = "fuzztarget"))]
412 impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
413 fn eq(&self, other: &Self) -> bool {
415 Storage::Local { ref keys, .. } => {
418 Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
419 Storage::Watchtower { .. } => false,
422 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
423 let (rbk, hbk) = (revocation_base_key, htlc_base_key);
425 Storage::Local { .. } => false,
426 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
427 revocation_base_key == rbk && htlc_base_key == hbk,
434 #[derive(Clone, PartialEq)]
435 struct LocalSignedTx {
436 /// txid of the transaction in tx, just used to make comparison faster
438 tx: LocalCommitmentTransaction,
439 revocation_key: PublicKey,
440 a_htlc_key: PublicKey,
441 b_htlc_key: PublicKey,
442 delayed_payment_key: PublicKey,
443 per_commitment_point: PublicKey,
445 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
449 enum InputDescriptors {
454 RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
457 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
458 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
459 /// a new bumped one in case of lenghty confirmation delay
460 #[derive(Clone, PartialEq)]
464 pubkey: Option<PublicKey>,
472 preimage: Option<PaymentPreimage>,
478 sigs: (Signature, Signature),
479 preimage: Option<PaymentPreimage>,
484 impl Writeable for InputMaterial {
485 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
487 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
488 writer.write_all(&[0; 1])?;
489 script.write(writer)?;
490 pubkey.write(writer)?;
491 writer.write_all(&key[..])?;
492 is_htlc.write(writer)?;
493 writer.write_all(&byte_utils::be64_to_array(*amount))?;
495 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
496 writer.write_all(&[1; 1])?;
497 script.write(writer)?;
499 preimage.write(writer)?;
500 writer.write_all(&byte_utils::be64_to_array(*amount))?;
501 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
503 &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
504 writer.write_all(&[2; 1])?;
505 script.write(writer)?;
506 sigs.0.write(writer)?;
507 sigs.1.write(writer)?;
508 preimage.write(writer)?;
509 writer.write_all(&byte_utils::be64_to_array(*amount))?;
516 impl Readable for InputMaterial {
517 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
518 let input_material = match <u8 as Readable>::read(reader)? {
520 let script = Readable::read(reader)?;
521 let pubkey = Readable::read(reader)?;
522 let key = Readable::read(reader)?;
523 let is_htlc = Readable::read(reader)?;
524 let amount = Readable::read(reader)?;
525 InputMaterial::Revoked {
534 let script = Readable::read(reader)?;
535 let key = Readable::read(reader)?;
536 let preimage = Readable::read(reader)?;
537 let amount = Readable::read(reader)?;
538 let locktime = Readable::read(reader)?;
539 InputMaterial::RemoteHTLC {
548 let script = Readable::read(reader)?;
549 let their_sig = Readable::read(reader)?;
550 let our_sig = Readable::read(reader)?;
551 let preimage = Readable::read(reader)?;
552 let amount = Readable::read(reader)?;
553 InputMaterial::LocalHTLC {
555 sigs: (their_sig, our_sig),
560 _ => return Err(DecodeError::InvalidValue),
566 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
567 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
568 #[derive(Clone, PartialEq)]
570 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
571 /// bump-txn candidate buffer.
573 claim_request: Sha256dHash,
575 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
576 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
577 /// only win from it, so it's never an OnchainEvent
579 htlc_update: (HTLCSource, PaymentHash),
581 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
582 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
583 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
584 ContentiousOutpoint {
585 outpoint: BitcoinOutPoint,
586 input_material: InputMaterial,
590 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
591 #[derive(Clone, PartialEq)]
592 pub struct ClaimTxBumpMaterial {
593 // At every block tick, used to check if pending claiming tx is taking too
594 // much time for confirmation and we need to bump it.
596 // Tracked in case of reorg to wipe out now-superflous bump material
597 feerate_previous: u64,
598 // Soonest timelocks among set of outpoints claimed, used to compute
599 // a priority of not feerate
600 soonest_timelock: u32,
601 // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
602 per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
605 impl Writeable for ClaimTxBumpMaterial {
606 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
607 writer.write_all(&byte_utils::be32_to_array(self.height_timer))?;
608 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
609 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
610 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
611 for (outp, tx_material) in self.per_input_material.iter() {
613 tx_material.write(writer)?;
619 impl Readable for ClaimTxBumpMaterial {
620 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
621 let height_timer = Readable::read(reader)?;
622 let feerate_previous = Readable::read(reader)?;
623 let soonest_timelock = Readable::read(reader)?;
624 let per_input_material_len: u64 = Readable::read(reader)?;
625 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
626 for _ in 0 ..per_input_material_len {
627 let outpoint = Readable::read(reader)?;
628 let input_material = Readable::read(reader)?;
629 per_input_material.insert(outpoint, input_material);
631 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
635 const SERIALIZATION_VERSION: u8 = 1;
636 const MIN_SERIALIZATION_VERSION: u8 = 1;
638 #[cfg_attr(test, derive(PartialEq))]
640 pub(super) enum ChannelMonitorUpdateStep {
641 LatestLocalCommitmentTXInfo {
642 // TODO: We really need to not be generating a fully-signed transaction in Channel and
643 // passing it here, we need to hold off so that the ChanSigner can enforce a
644 // only-sign-local-state-for-broadcast once invariant:
645 commitment_tx: LocalCommitmentTransaction,
646 local_keys: chan_utils::TxCreationKeys,
648 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
650 LatestRemoteCommitmentTXInfo {
651 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
652 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
653 commitment_number: u64,
654 their_revocation_point: PublicKey,
657 payment_preimage: PaymentPreimage,
663 /// Indicates our channel is likely a stale version, we're closing, but this update should
664 /// allow us to spend what is ours if our counterparty broadcasts their latest state.
665 RescueRemoteCommitmentTXInfo {
666 their_current_per_commitment_point: PublicKey,
670 impl Writeable for ChannelMonitorUpdateStep {
671 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
673 &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
675 commitment_tx.write(w)?;
676 local_keys.write(w)?;
677 feerate_per_kw.write(w)?;
678 (htlc_outputs.len() as u64).write(w)?;
679 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
685 &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
687 unsigned_commitment_tx.write(w)?;
688 commitment_number.write(w)?;
689 their_revocation_point.write(w)?;
690 (htlc_outputs.len() as u64).write(w)?;
691 for &(ref output, ref source) in htlc_outputs.iter() {
693 source.as_ref().map(|b| b.as_ref()).write(w)?;
696 &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
698 payment_preimage.write(w)?;
700 &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
705 &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => {
707 their_current_per_commitment_point.write(w)?;
713 impl Readable for ChannelMonitorUpdateStep {
714 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
715 match Readable::read(r)? {
717 Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
718 commitment_tx: Readable::read(r)?,
719 local_keys: Readable::read(r)?,
720 feerate_per_kw: Readable::read(r)?,
722 let len: u64 = Readable::read(r)?;
723 let mut res = Vec::new();
725 res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
732 Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
733 unsigned_commitment_tx: Readable::read(r)?,
734 commitment_number: Readable::read(r)?,
735 their_revocation_point: Readable::read(r)?,
737 let len: u64 = Readable::read(r)?;
738 let mut res = Vec::new();
740 res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
747 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
748 payment_preimage: Readable::read(r)?,
752 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
753 idx: Readable::read(r)?,
754 secret: Readable::read(r)?,
758 Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo {
759 their_current_per_commitment_point: Readable::read(r)?,
762 _ => Err(DecodeError::InvalidValue),
767 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
768 /// on-chain transactions to ensure no loss of funds occurs.
770 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
771 /// information and are actively monitoring the chain.
773 /// Pending Events or updated HTLCs which have not yet been read out by
774 /// get_and_clear_pending_htlcs_updated or get_and_clear_pending_events are serialized to disk and
775 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
776 /// gotten are fully handled before re-serializing the new state.
777 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
778 latest_update_id: u64,
779 commitment_transaction_number_obscure_factor: u64,
781 key_storage: Storage<ChanSigner>,
782 their_htlc_base_key: Option<PublicKey>,
783 their_delayed_payment_base_key: Option<PublicKey>,
784 funding_redeemscript: Option<Script>,
785 channel_value_satoshis: Option<u64>,
786 // first is the idx of the first of the two revocation points
787 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
789 our_to_self_delay: u16,
790 their_to_self_delay: Option<u16>,
792 commitment_secrets: CounterpartyCommitmentSecrets,
793 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
794 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
795 /// Nor can we figure out their commitment numbers without the commitment transaction they are
796 /// spending. Thus, in order to claim them via revocation key, we track all the remote
797 /// commitment transactions which we find on-chain, mapping them to the commitment number which
798 /// can be used to derive the revocation key and claim the transactions.
799 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
800 /// Cache used to make pruning of payment_preimages faster.
801 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
802 /// remote transactions (ie should remain pretty small).
803 /// Serialized to disk but should generally not be sent to Watchtowers.
804 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
806 // We store two local commitment transactions to avoid any race conditions where we may update
807 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
808 // various monitors for one channel being out of sync, and us broadcasting a local
809 // transaction for which we have deleted claim information on some watchtowers.
810 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
811 current_local_signed_commitment_tx: Option<LocalSignedTx>,
813 // Used just for ChannelManager to make sure it has the latest channel data during
815 current_remote_commitment_number: u64,
817 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
819 pending_htlcs_updated: Vec<HTLCUpdate>,
820 pending_events: Vec<events::Event>,
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 update_monitor 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.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
935 self.destination_script != other.destination_script ||
936 self.to_remote_rescue != other.to_remote_rescue ||
937 self.pending_claim_requests != other.pending_claim_requests ||
938 self.claimable_outpoints != other.claimable_outpoints ||
939 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
940 self.outputs_to_watch != other.outputs_to_watch
949 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
950 /// Serializes into a vec, with various modes for the exposed pub fns
951 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
952 //TODO: We still write out all the serialization here manually instead of using the fancy
953 //serialization framework we have, we should migrate things over to it.
954 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
955 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
957 self.latest_update_id.write(writer)?;
959 // Set in initial Channel-object creation, so should always be set by now:
960 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
962 match self.key_storage {
963 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 } => {
964 writer.write_all(&[0; 1])?;
966 writer.write_all(&funding_key[..])?;
967 writer.write_all(&revocation_base_key[..])?;
968 writer.write_all(&htlc_base_key[..])?;
969 writer.write_all(&delayed_payment_base_key[..])?;
970 writer.write_all(&payment_base_key[..])?;
971 writer.write_all(&shutdown_pubkey.serialize())?;
973 &Some((ref outpoint, ref script)) => {
974 writer.write_all(&outpoint.txid[..])?;
975 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
976 script.write(writer)?;
979 debug_assert!(false, "Try to serialize a useless Local monitor !");
982 current_remote_commitment_txid.write(writer)?;
983 prev_remote_commitment_txid.write(writer)?;
985 Storage::Watchtower { .. } => unimplemented!(),
988 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
989 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
990 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
991 self.channel_value_satoshis.unwrap().write(writer)?;
993 match self.their_cur_revocation_points {
994 Some((idx, pubkey, second_option)) => {
995 writer.write_all(&byte_utils::be48_to_array(idx))?;
996 writer.write_all(&pubkey.serialize())?;
997 match second_option {
998 Some(second_pubkey) => {
999 writer.write_all(&second_pubkey.serialize())?;
1002 writer.write_all(&[0; 33])?;
1007 writer.write_all(&byte_utils::be48_to_array(0))?;
1011 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
1012 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
1014 self.commitment_secrets.write(writer)?;
1016 macro_rules! serialize_htlc_in_commitment {
1017 ($htlc_output: expr) => {
1018 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1019 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1020 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1021 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1022 $htlc_output.transaction_output_index.write(writer)?;
1026 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
1027 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
1028 writer.write_all(&txid[..])?;
1029 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1030 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1031 serialize_htlc_in_commitment!(htlc_output);
1032 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1036 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
1037 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
1038 writer.write_all(&txid[..])?;
1039 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1040 (txouts.len() as u64).write(writer)?;
1041 for script in txouts.iter() {
1042 script.write(writer)?;
1046 if for_local_storage {
1047 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
1048 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
1049 writer.write_all(&payment_hash.0[..])?;
1050 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1053 writer.write_all(&byte_utils::be64_to_array(0))?;
1056 macro_rules! serialize_local_tx {
1057 ($local_tx: expr) => {
1058 $local_tx.tx.write(writer)?;
1059 writer.write_all(&$local_tx.revocation_key.serialize())?;
1060 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
1061 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
1062 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
1063 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
1065 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
1066 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
1067 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
1068 serialize_htlc_in_commitment!(htlc_output);
1069 if let &Some(ref their_sig) = sig {
1071 writer.write_all(&their_sig.serialize_compact())?;
1075 htlc_source.write(writer)?;
1080 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
1081 writer.write_all(&[1; 1])?;
1082 serialize_local_tx!(prev_local_tx);
1084 writer.write_all(&[0; 1])?;
1087 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1088 writer.write_all(&[1; 1])?;
1089 serialize_local_tx!(cur_local_tx);
1091 writer.write_all(&[0; 1])?;
1094 if for_local_storage {
1095 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1097 writer.write_all(&byte_utils::be48_to_array(0))?;
1100 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1101 for payment_preimage in self.payment_preimages.values() {
1102 writer.write_all(&payment_preimage.0[..])?;
1105 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
1106 for data in self.pending_htlcs_updated.iter() {
1107 data.write(writer)?;
1110 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
1111 for event in self.pending_events.iter() {
1112 event.write(writer)?;
1115 self.last_block_hash.write(writer)?;
1116 self.destination_script.write(writer)?;
1117 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1118 writer.write_all(&[1; 1])?;
1119 to_remote_script.write(writer)?;
1120 local_key.write(writer)?;
1122 writer.write_all(&[0; 1])?;
1125 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
1126 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
1127 ancestor_claim_txid.write(writer)?;
1128 claim_tx_data.write(writer)?;
1131 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
1132 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
1133 outp.write(writer)?;
1134 claim_and_height.0.write(writer)?;
1135 claim_and_height.1.write(writer)?;
1138 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1139 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1140 writer.write_all(&byte_utils::be32_to_array(**target))?;
1141 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1142 for ev in events.iter() {
1144 OnchainEvent::Claim { ref claim_request } => {
1145 writer.write_all(&[0; 1])?;
1146 claim_request.write(writer)?;
1148 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1149 writer.write_all(&[1; 1])?;
1150 htlc_update.0.write(writer)?;
1151 htlc_update.1.write(writer)?;
1153 OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
1154 writer.write_all(&[2; 1])?;
1155 outpoint.write(writer)?;
1156 input_material.write(writer)?;
1162 (self.outputs_to_watch.len() as u64).write(writer)?;
1163 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1164 txid.write(writer)?;
1165 (output_scripts.len() as u64).write(writer)?;
1166 for script in output_scripts.iter() {
1167 script.write(writer)?;
1174 /// Writes this monitor into the given writer, suitable for writing to disk.
1176 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1177 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1178 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1179 /// common block that appears on your best chain as well as on the chain which contains the
1180 /// last block hash returned) upon deserializing the object!
1181 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1182 self.write(writer, true)
1185 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1187 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1188 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1189 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1190 /// common block that appears on your best chain as well as on the chain which contains the
1191 /// last block hash returned) upon deserializing the object!
1192 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1193 self.write(writer, false)
1197 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1198 pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1199 our_to_self_delay: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1200 their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey,
1201 their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1202 commitment_transaction_number_obscure_factor: u64,
1203 logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
1205 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1206 let funding_key = keys.funding_key().clone();
1207 let revocation_base_key = keys.revocation_base_key().clone();
1208 let htlc_base_key = keys.htlc_base_key().clone();
1209 let delayed_payment_base_key = keys.delayed_payment_base_key().clone();
1210 let payment_base_key = keys.payment_base_key().clone();
1212 latest_update_id: 0,
1213 commitment_transaction_number_obscure_factor,
1215 key_storage: Storage::Local {
1218 revocation_base_key,
1220 delayed_payment_base_key,
1222 shutdown_pubkey: shutdown_pubkey.clone(),
1223 funding_info: Some(funding_info),
1224 current_remote_commitment_txid: None,
1225 prev_remote_commitment_txid: None,
1227 their_htlc_base_key: Some(their_htlc_base_key.clone()),
1228 their_delayed_payment_base_key: Some(their_delayed_payment_base_key.clone()),
1229 funding_redeemscript: Some(funding_redeemscript),
1230 channel_value_satoshis: Some(channel_value_satoshis),
1231 their_cur_revocation_points: None,
1233 our_to_self_delay: our_to_self_delay,
1234 their_to_self_delay: Some(their_to_self_delay),
1236 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1237 remote_claimable_outpoints: HashMap::new(),
1238 remote_commitment_txn_on_chain: HashMap::new(),
1239 remote_hash_commitment_number: HashMap::new(),
1241 prev_local_signed_commitment_tx: None,
1242 current_local_signed_commitment_tx: None,
1243 current_remote_commitment_number: 1 << 48,
1245 payment_preimages: HashMap::new(),
1246 pending_htlcs_updated: Vec::new(),
1247 pending_events: Vec::new(),
1249 destination_script: destination_script.clone(),
1250 to_remote_rescue: None,
1252 pending_claim_requests: HashMap::new(),
1254 claimable_outpoints: HashMap::new(),
1256 onchain_events_waiting_threshold_conf: HashMap::new(),
1257 outputs_to_watch: HashMap::new(),
1259 last_block_hash: Default::default(),
1260 secp_ctx: Secp256k1::new(),
1265 fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
1266 let mut tx_weight = 2; // count segwit flags
1268 // We use expected weight (and not actual) as signatures and time lock delays may vary
1269 tx_weight += match inp {
1270 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1271 &InputDescriptors::RevokedOfferedHTLC => {
1272 1 + 1 + 73 + 1 + 33 + 1 + 133
1274 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1275 &InputDescriptors::RevokedReceivedHTLC => {
1276 1 + 1 + 73 + 1 + 33 + 1 + 139
1278 // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
1279 &InputDescriptors::OfferedHTLC => {
1280 1 + 1 + 73 + 1 + 32 + 1 + 133
1282 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1283 &InputDescriptors::ReceivedHTLC => {
1284 1 + 1 + 73 + 1 + 1 + 1 + 139
1286 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
1287 &InputDescriptors::RevokedOutput => {
1288 1 + 1 + 73 + 1 + 1 + 1 + 77
1295 fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
1296 if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
1297 return current_height + 1
1298 } else if timelock_expiration - current_height <= 15 {
1299 return current_height + 3
1304 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1305 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1306 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1307 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1308 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1309 return Err(MonitorUpdateError("Previous secret did not match new one"));
1312 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1313 // events for now-revoked/fulfilled HTLCs.
1314 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1315 if let Some(txid) = prev_remote_commitment_txid.take() {
1316 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1322 if !self.payment_preimages.is_empty() {
1323 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1324 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1325 let min_idx = self.get_min_seen_secret();
1326 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1328 self.payment_preimages.retain(|&k, _| {
1329 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1330 if k == htlc.payment_hash {
1334 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1335 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1336 if k == htlc.payment_hash {
1341 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1348 remote_hash_commitment_number.remove(&k);
1357 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1358 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1359 /// possibly future revocation/preimage information) to claim outputs where possible.
1360 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1361 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) {
1362 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1363 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1364 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1366 for &(ref htlc, _) in &htlc_outputs {
1367 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1370 let new_txid = unsigned_commitment_tx.txid();
1371 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1372 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1373 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1374 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1375 *current_remote_commitment_txid = Some(new_txid);
1377 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1378 self.current_remote_commitment_number = commitment_number;
1379 //TODO: Merge this into the other per-remote-transaction output storage stuff
1380 match self.their_cur_revocation_points {
1381 Some(old_points) => {
1382 if old_points.0 == commitment_number + 1 {
1383 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1384 } else if old_points.0 == commitment_number + 2 {
1385 if let Some(old_second_point) = old_points.2 {
1386 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1388 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1391 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1395 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1400 pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1401 match self.key_storage {
1402 Storage::Local { ref payment_base_key, ref keys, .. } => {
1403 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1404 let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1405 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1407 if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1408 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1412 Storage::Watchtower { .. } => {}
1416 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1417 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1418 /// is important that any clones of this channel monitor (including remote clones) by kept
1419 /// up-to-date as our local commitment transaction is updated.
1420 /// Panics if set_their_to_self_delay has never been called.
1421 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> {
1422 if self.their_to_self_delay.is_none() {
1423 return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1425 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1426 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1427 txid: commitment_tx.txid(),
1429 revocation_key: local_keys.revocation_key,
1430 a_htlc_key: local_keys.a_htlc_key,
1431 b_htlc_key: local_keys.b_htlc_key,
1432 delayed_payment_key: local_keys.a_delayed_payment_key,
1433 per_commitment_point: local_keys.per_commitment_point,
1440 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1441 /// commitment_tx_infos which contain the payment hash have been revoked.
1442 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1443 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1446 /// Used in Channel to cheat wrt the update_ids since it plays games, will be removed soon!
1447 pub(super) fn update_monitor_ooo(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1448 for update in updates.updates.drain(..) {
1450 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1451 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1452 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1453 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1454 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1455 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1456 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1457 self.provide_secret(idx, secret)?,
1458 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1459 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1462 self.latest_update_id = updates.update_id;
1466 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1469 /// panics if the given update is not the next update by update_id.
1470 pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1471 if self.latest_update_id + 1 != updates.update_id {
1472 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1474 for update in updates.updates.drain(..) {
1476 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1477 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1478 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1479 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1480 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1481 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1482 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1483 self.provide_secret(idx, secret)?,
1484 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1485 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1488 self.latest_update_id = updates.update_id;
1492 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1494 pub fn get_latest_update_id(&self) -> u64 {
1495 self.latest_update_id
1498 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1499 pub fn get_funding_txo(&self) -> Option<OutPoint> {
1500 match self.key_storage {
1501 Storage::Local { ref funding_info, .. } => {
1502 match funding_info {
1503 &Some((outpoint, _)) => Some(outpoint),
1507 Storage::Watchtower { .. } => {
1513 /// Gets a list of txids, with their output scripts (in the order they appear in the
1514 /// transaction), which we must learn about spends of via block_connected().
1515 pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1516 &self.outputs_to_watch
1519 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1520 /// Generally useful when deserializing as during normal operation the return values of
1521 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1522 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1523 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1524 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1525 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1526 for (idx, output) in outputs.iter().enumerate() {
1527 res.push(((*txid).clone(), idx as u32, output));
1533 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1534 /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1535 pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1536 let mut ret = Vec::new();
1537 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1541 /// Gets the list of pending events which were generated by previous actions, clearing the list
1544 /// This is called by ManyChannelMonitor::get_and_clear_pending_events() and is equivalent to
1545 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1546 /// no internal locking in ChannelMonitors.
1547 pub fn get_and_clear_pending_events(&mut self) -> Vec<events::Event> {
1548 let mut ret = Vec::new();
1549 mem::swap(&mut ret, &mut self.pending_events);
1553 /// Can only fail if idx is < get_min_seen_secret
1554 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1555 self.commitment_secrets.get_secret(idx)
1558 pub(super) fn get_min_seen_secret(&self) -> u64 {
1559 self.commitment_secrets.get_min_seen_secret()
1562 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1563 self.current_remote_commitment_number
1566 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1567 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1568 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)
1569 } else { 0xffff_ffff_ffff }
1572 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1573 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1574 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1575 /// HTLC-Success/HTLC-Timeout transactions.
1576 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1577 /// revoked remote commitment tx
1578 fn check_spend_remote_transaction<F: Deref>(&mut self, tx: &Transaction, height: u32, fee_estimator: F) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>)
1579 where F::Target: FeeEstimator
1581 // Most secp and related errors trying to create keys means we have no hope of constructing
1582 // a spend transaction...so we return no transactions to broadcast
1583 let mut txn_to_broadcast = Vec::new();
1584 let mut watch_outputs = Vec::new();
1585 let mut spendable_outputs = Vec::new();
1587 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1588 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1590 macro_rules! ignore_error {
1591 ( $thing : expr ) => {
1594 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1599 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);
1600 if commitment_number >= self.get_min_seen_secret() {
1601 let secret = self.get_secret(commitment_number).unwrap();
1602 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1603 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1604 Storage::Local { ref keys, ref payment_base_key, .. } => {
1605 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1606 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1607 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1608 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1610 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1611 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1612 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1613 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1617 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()));
1618 let a_htlc_key = match self.their_htlc_base_key {
1619 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1620 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)),
1623 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1624 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1626 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1627 // Note that the Network here is ignored as we immediately drop the address for the
1628 // script_pubkey version.
1629 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1630 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1633 let mut total_value = 0;
1634 let mut inputs = Vec::new();
1635 let mut inputs_info = Vec::new();
1636 let mut inputs_desc = Vec::new();
1638 for (idx, outp) in tx.output.iter().enumerate() {
1639 if outp.script_pubkey == revokeable_p2wsh {
1641 previous_output: BitcoinOutPoint {
1642 txid: commitment_txid,
1645 script_sig: Script::new(),
1646 sequence: 0xfffffffd,
1647 witness: Vec::new(),
1649 inputs_desc.push(InputDescriptors::RevokedOutput);
1650 inputs_info.push((None, outp.value, self.our_to_self_delay as u32));
1651 total_value += outp.value;
1652 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1653 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1654 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1655 key: local_payment_key.unwrap(),
1656 output: outp.clone(),
1661 macro_rules! sign_input {
1662 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1664 let (sig, redeemscript, revocation_key) = match self.key_storage {
1665 Storage::Local { ref revocation_base_key, .. } => {
1666 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1667 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1668 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1670 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1671 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1672 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript, revocation_key)
1674 Storage::Watchtower { .. } => {
1678 $input.witness.push(sig.serialize_der().to_vec());
1679 $input.witness[0].push(SigHashType::All as u8);
1680 if $htlc_idx.is_none() {
1681 $input.witness.push(vec!(1));
1683 $input.witness.push(revocation_pubkey.serialize().to_vec());
1685 $input.witness.push(redeemscript.clone().into_bytes());
1686 (redeemscript, revocation_key)
1691 if let Some(ref per_commitment_data) = per_commitment_option {
1692 inputs.reserve_exact(per_commitment_data.len());
1694 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1695 if let Some(transaction_output_index) = htlc.transaction_output_index {
1696 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1697 if transaction_output_index as usize >= tx.output.len() ||
1698 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1699 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1700 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1703 previous_output: BitcoinOutPoint {
1704 txid: commitment_txid,
1705 vout: transaction_output_index,
1707 script_sig: Script::new(),
1708 sequence: 0xfffffffd,
1709 witness: Vec::new(),
1711 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1713 inputs_desc.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1714 inputs_info.push((Some(idx), tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1715 total_value += tx.output[transaction_output_index as usize].value;
1717 let mut single_htlc_tx = Transaction {
1721 output: vec!(TxOut {
1722 script_pubkey: self.destination_script.clone(),
1723 value: htlc.amount_msat / 1000,
1726 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1727 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1728 let mut used_feerate;
1729 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1730 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1731 let (redeemscript, revocation_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1732 assert!(predicted_weight >= single_htlc_tx.get_weight());
1733 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);
1734 let mut per_input_material = HashMap::with_capacity(1);
1735 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 });
1736 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1737 hash_map::Entry::Occupied(_) => {},
1738 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1740 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1741 hash_map::Entry::Occupied(_) => {},
1742 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1744 txn_to_broadcast.push(single_htlc_tx);
1751 if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1752 // We're definitely a remote commitment transaction!
1753 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());
1754 watch_outputs.append(&mut tx.output.clone());
1755 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1757 macro_rules! check_htlc_fails {
1758 ($txid: expr, $commitment_tx: expr) => {
1759 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1760 for &(ref htlc, ref source_option) in outpoints.iter() {
1761 if let &Some(ref source) = source_option {
1762 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);
1763 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1764 hash_map::Entry::Occupied(mut entry) => {
1765 let e = entry.get_mut();
1766 e.retain(|ref event| {
1768 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1769 return htlc_update.0 != **source
1774 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1776 hash_map::Entry::Vacant(entry) => {
1777 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1785 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1786 if let &Some(ref txid) = current_remote_commitment_txid {
1787 check_htlc_fails!(txid, "current");
1789 if let &Some(ref txid) = prev_remote_commitment_txid {
1790 check_htlc_fails!(txid, "remote");
1793 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1795 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1797 let outputs = vec!(TxOut {
1798 script_pubkey: self.destination_script.clone(),
1801 let mut spend_tx = Transaction {
1808 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1810 let mut used_feerate;
1811 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1812 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1815 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1817 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1818 let mut soonest_timelock = ::std::u32::MAX;
1819 for info in inputs_info.iter() {
1820 if info.2 <= soonest_timelock {
1821 soonest_timelock = info.2;
1824 let height_timer = Self::get_height_timer(height, soonest_timelock);
1825 let spend_txid = spend_tx.txid();
1826 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1827 let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1);
1828 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);
1829 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 });
1830 match self.claimable_outpoints.entry(input.previous_output) {
1831 hash_map::Entry::Occupied(_) => {},
1832 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1835 match self.pending_claim_requests.entry(spend_txid) {
1836 hash_map::Entry::Occupied(_) => {},
1837 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1840 assert!(predicted_weight >= spend_tx.get_weight());
1842 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1843 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1844 output: spend_tx.output[0].clone(),
1846 txn_to_broadcast.push(spend_tx);
1847 } else if let Some(per_commitment_data) = per_commitment_option {
1848 // While this isn't useful yet, there is a potential race where if a counterparty
1849 // revokes a state at the same time as the commitment transaction for that state is
1850 // confirmed, and the watchtower receives the block before the user, the user could
1851 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1852 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1853 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1855 watch_outputs.append(&mut tx.output.clone());
1856 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1858 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1860 macro_rules! check_htlc_fails {
1861 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1862 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1863 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1864 if let &Some(ref source) = source_option {
1865 // Check if the HTLC is present in the commitment transaction that was
1866 // broadcast, but not if it was below the dust limit, which we should
1867 // fail backwards immediately as there is no way for us to learn the
1868 // payment_preimage.
1869 // Note that if the dust limit were allowed to change between
1870 // commitment transactions we'd want to be check whether *any*
1871 // broadcastable commitment transaction has the HTLC in it, but it
1872 // cannot currently change after channel initialization, so we don't
1874 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1875 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1879 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);
1880 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1881 hash_map::Entry::Occupied(mut entry) => {
1882 let e = entry.get_mut();
1883 e.retain(|ref event| {
1885 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1886 return htlc_update.0 != **source
1891 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1893 hash_map::Entry::Vacant(entry) => {
1894 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1902 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1903 if let &Some(ref txid) = current_remote_commitment_txid {
1904 check_htlc_fails!(txid, "current", 'current_loop);
1906 if let &Some(ref txid) = prev_remote_commitment_txid {
1907 check_htlc_fails!(txid, "previous", 'prev_loop);
1911 if let Some(revocation_points) = self.their_cur_revocation_points {
1912 let revocation_point_option =
1913 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1914 else if let Some(point) = revocation_points.2.as_ref() {
1915 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1917 if let Some(revocation_point) = revocation_point_option {
1918 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1919 Storage::Local { ref keys, .. } => {
1920 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1921 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)))
1923 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1924 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1925 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1928 let a_htlc_key = match self.their_htlc_base_key {
1929 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1930 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1933 for (idx, outp) in tx.output.iter().enumerate() {
1934 if outp.script_pubkey.is_v0_p2wpkh() {
1935 match self.key_storage {
1936 Storage::Local { ref payment_base_key, .. } => {
1937 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1938 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1939 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1941 output: outp.clone(),
1945 Storage::Watchtower { .. } => {}
1947 break; // Only to_remote ouput is claimable
1951 let mut total_value = 0;
1952 let mut inputs = Vec::new();
1953 let mut inputs_desc = Vec::new();
1954 let mut inputs_info = Vec::new();
1956 macro_rules! sign_input {
1957 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr, $idx: expr) => {
1959 let (sig, redeemscript, htlc_key) = match self.key_storage {
1960 Storage::Local { ref htlc_base_key, .. } => {
1961 let htlc = &per_commitment_option.unwrap()[$idx as usize].0;
1962 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1963 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1964 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1965 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript, htlc_key)
1967 Storage::Watchtower { .. } => {
1971 $input.witness.push(sig.serialize_der().to_vec());
1972 $input.witness[0].push(SigHashType::All as u8);
1973 $input.witness.push($preimage);
1974 $input.witness.push(redeemscript.clone().into_bytes());
1975 (redeemscript, htlc_key)
1980 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1981 if let Some(transaction_output_index) = htlc.transaction_output_index {
1982 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1983 if transaction_output_index as usize >= tx.output.len() ||
1984 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1985 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1986 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1988 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1991 previous_output: BitcoinOutPoint {
1992 txid: commitment_txid,
1993 vout: transaction_output_index,
1995 script_sig: Script::new(),
1996 sequence: 0xff_ff_ff_fd,
1997 witness: Vec::new(),
1999 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
2001 inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
2002 inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry, idx));
2003 total_value += tx.output[transaction_output_index as usize].value;
2005 let mut single_htlc_tx = Transaction {
2009 output: vec!(TxOut {
2010 script_pubkey: self.destination_script.clone(),
2011 value: htlc.amount_msat / 1000,
2014 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
2015 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2016 let mut used_feerate;
2017 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
2018 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
2019 let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec(), idx);
2020 assert!(predicted_weight >= single_htlc_tx.get_weight());
2021 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2022 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
2023 output: single_htlc_tx.output[0].clone(),
2025 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);
2026 let mut per_input_material = HashMap::with_capacity(1);
2027 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 });
2028 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
2029 hash_map::Entry::Occupied(_) => {},
2030 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
2032 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
2033 hash_map::Entry::Occupied(_) => {},
2034 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material}); }
2036 txn_to_broadcast.push(single_htlc_tx);
2042 // TODO: If the HTLC has already expired, potentially merge it with the
2043 // rest of the claim transaction, as above.
2045 previous_output: BitcoinOutPoint {
2046 txid: commitment_txid,
2047 vout: transaction_output_index,
2049 script_sig: Script::new(),
2050 sequence: 0xff_ff_ff_fd,
2051 witness: Vec::new(),
2053 let mut timeout_tx = Transaction {
2055 lock_time: htlc.cltv_expiry,
2057 output: vec!(TxOut {
2058 script_pubkey: self.destination_script.clone(),
2059 value: htlc.amount_msat / 1000,
2062 let predicted_weight = timeout_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]);
2063 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2064 let mut used_feerate;
2065 if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
2066 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
2067 let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0], idx);
2068 assert!(predicted_weight >= timeout_tx.get_weight());
2069 //TODO: track SpendableOutputDescriptor
2070 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);
2071 let mut per_input_material = HashMap::with_capacity(1);
2072 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 });
2073 match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) {
2074 hash_map::Entry::Occupied(_) => {},
2075 hash_map::Entry::Vacant(entry) => { entry.insert((timeout_tx.txid(), height)); }
2077 match self.pending_claim_requests.entry(timeout_tx.txid()) {
2078 hash_map::Entry::Occupied(_) => {},
2079 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
2082 txn_to_broadcast.push(timeout_tx);
2087 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
2089 let outputs = vec!(TxOut {
2090 script_pubkey: self.destination_script.clone(),
2093 let mut spend_tx = Transaction {
2100 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
2102 let mut used_feerate;
2103 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2104 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
2107 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2109 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
2110 let mut soonest_timelock = ::std::u32::MAX;
2111 for info in inputs_info.iter() {
2112 if info.2 <= soonest_timelock {
2113 soonest_timelock = info.2;
2116 let height_timer = Self::get_height_timer(height, soonest_timelock);
2117 let spend_txid = spend_tx.txid();
2118 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
2119 let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec(), info.3);
2120 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);
2121 per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
2122 match self.claimable_outpoints.entry(input.previous_output) {
2123 hash_map::Entry::Occupied(_) => {},
2124 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
2127 match self.pending_claim_requests.entry(spend_txid) {
2128 hash_map::Entry::Occupied(_) => {},
2129 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
2131 assert!(predicted_weight >= spend_tx.get_weight());
2132 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2133 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
2134 output: spend_tx.output[0].clone(),
2136 txn_to_broadcast.push(spend_tx);
2139 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
2140 for (idx, outp) in tx.output.iter().enumerate() {
2141 if to_remote_rescue == &outp.script_pubkey {
2142 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
2143 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
2144 key: local_key.clone(),
2145 output: outp.clone(),
2151 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
2154 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
2155 fn check_spend_remote_htlc<F: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, fee_estimator: F) -> (Option<Transaction>, Option<SpendableOutputDescriptor>)
2156 where F::Target: FeeEstimator
2158 //TODO: send back new outputs to guarantee pending_claim_request consistency
2159 if tx.input.len() != 1 || tx.output.len() != 1 {
2163 macro_rules! ignore_error {
2164 ( $thing : expr ) => {
2167 Err(_) => return (None, None)
2172 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
2173 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2174 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2175 let revocation_pubkey = match self.key_storage {
2176 Storage::Local { ref keys, .. } => {
2177 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint))
2179 Storage::Watchtower { ref revocation_base_key, .. } => {
2180 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
2183 let delayed_key = match self.their_delayed_payment_base_key {
2184 None => return (None, None),
2185 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
2187 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
2188 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2189 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2191 let mut inputs = Vec::new();
2194 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
2196 previous_output: BitcoinOutPoint {
2200 script_sig: Script::new(),
2201 sequence: 0xfffffffd,
2202 witness: Vec::new(),
2204 amount = tx.output[0].value;
2207 if !inputs.is_empty() {
2208 let outputs = vec!(TxOut {
2209 script_pubkey: self.destination_script.clone(),
2213 let mut spend_tx = Transaction {
2219 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
2220 let mut used_feerate;
2221 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2222 return (None, None);
2225 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2227 let (sig, revocation_key) = match self.key_storage {
2228 Storage::Local { ref revocation_base_key, .. } => {
2229 let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
2230 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
2231 (self.secp_ctx.sign(&sighash, &revocation_key), revocation_key)
2233 Storage::Watchtower { .. } => {
2237 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
2238 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
2239 spend_tx.input[0].witness.push(vec!(1));
2240 spend_tx.input[0].witness.push(redeemscript.clone().into_bytes());
2242 assert!(predicted_weight >= spend_tx.get_weight());
2243 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
2244 let output = spend_tx.output[0].clone();
2245 let height_timer = Self::get_height_timer(height, height + self.our_to_self_delay as u32);
2246 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);
2247 let mut per_input_material = HashMap::with_capacity(1);
2248 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 });
2249 match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) {
2250 hash_map::Entry::Occupied(_) => {},
2251 hash_map::Entry::Vacant(entry) => { entry.insert((spend_tx.txid(), height)); }
2253 match self.pending_claim_requests.entry(spend_tx.txid()) {
2254 hash_map::Entry::Occupied(_) => {},
2255 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 }); }
2257 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
2258 } else { (None, None) }
2261 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)>) {
2262 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
2263 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2264 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2265 let mut pending_claims = Vec::with_capacity(local_tx.htlc_outputs.len());
2267 macro_rules! add_dynamic_output {
2268 ($father_tx: expr, $vout: expr) => {
2269 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
2270 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
2271 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
2272 key: local_delayedkey,
2273 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
2274 to_self_delay: self.our_to_self_delay,
2275 output: $father_tx.output[$vout as usize].clone(),
2281 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
2282 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2283 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
2284 if output.script_pubkey == revokeable_p2wsh {
2285 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
2290 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
2291 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
2292 if let Some(transaction_output_index) = htlc.transaction_output_index {
2293 if let &Some(ref their_sig) = sigs {
2295 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
2296 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);
2297 let (our_sig, htlc_script) = match
2298 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) {
2303 add_dynamic_output!(htlc_timeout_tx, 0);
2304 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2305 let mut per_input_material = HashMap::with_capacity(1);
2306 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});
2307 //TODO: with option_simplified_commitment track outpoint too
2308 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);
2309 pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2310 res.push(htlc_timeout_tx);
2312 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2313 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
2314 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);
2315 let (our_sig, htlc_script) = match
2316 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) {
2321 add_dynamic_output!(htlc_success_tx, 0);
2322 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2323 let mut per_input_material = HashMap::with_capacity(1);
2324 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});
2325 //TODO: with option_simplified_commitment track outpoint too
2326 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);
2327 pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2328 res.push(htlc_success_tx);
2331 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
2332 } else { panic!("Should have sigs for non-dust local tx outputs!") }
2337 (res, spendable_outputs, watch_outputs, pending_claims)
2340 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2341 /// revoked using data in local_claimable_outpoints.
2342 /// Should not be used if check_spend_revoked_transaction succeeds.
2343 fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
2344 let commitment_txid = tx.txid();
2345 let mut local_txn = Vec::new();
2346 let mut spendable_outputs = Vec::new();
2347 let mut watch_outputs = Vec::new();
2349 macro_rules! wait_threshold_conf {
2350 ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
2351 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);
2352 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
2353 hash_map::Entry::Occupied(mut entry) => {
2354 let e = entry.get_mut();
2355 e.retain(|ref event| {
2357 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2358 return htlc_update.0 != $source
2363 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
2365 hash_map::Entry::Vacant(entry) => {
2366 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
2372 macro_rules! append_onchain_update {
2373 ($updates: expr) => {
2374 local_txn.append(&mut $updates.0);
2375 spendable_outputs.append(&mut $updates.1);
2376 watch_outputs.append(&mut $updates.2);
2377 for claim in $updates.3 {
2378 match self.pending_claim_requests.entry(claim.0) {
2379 hash_map::Entry::Occupied(_) => {},
2380 hash_map::Entry::Vacant(entry) => { entry.insert(claim.1); }
2386 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2387 let mut is_local_tx = false;
2389 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2390 if local_tx.txid == commitment_txid {
2391 match self.key_storage {
2392 Storage::Local { ref funding_key, .. } => {
2393 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2399 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2400 if local_tx.txid == commitment_txid {
2402 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
2403 assert!(local_tx.tx.has_local_sig());
2404 match self.key_storage {
2405 Storage::Local { ref delayed_payment_base_key, .. } => {
2406 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2407 append_onchain_update!(res);
2409 Storage::Watchtower { .. } => { }
2413 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
2414 if local_tx.txid == commitment_txid {
2415 match self.key_storage {
2416 Storage::Local { ref funding_key, .. } => {
2417 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2423 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2424 if local_tx.txid == commitment_txid {
2426 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
2427 assert!(local_tx.tx.has_local_sig());
2428 match self.key_storage {
2429 Storage::Local { ref delayed_payment_base_key, .. } => {
2430 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2431 append_onchain_update!(res);
2433 Storage::Watchtower { .. } => { }
2438 macro_rules! fail_dust_htlcs_after_threshold_conf {
2439 ($local_tx: expr) => {
2440 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
2441 if htlc.transaction_output_index.is_none() {
2442 if let &Some(ref source) = source {
2443 wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
2451 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2452 fail_dust_htlcs_after_threshold_conf!(local_tx);
2454 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2455 fail_dust_htlcs_after_threshold_conf!(local_tx);
2459 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
2462 /// Generate a spendable output event when closing_transaction get registered onchain.
2463 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
2464 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
2465 match self.key_storage {
2466 Storage::Local { ref shutdown_pubkey, .. } => {
2467 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
2468 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
2469 for (idx, output) in tx.output.iter().enumerate() {
2470 if shutdown_script == output.script_pubkey {
2471 return Some(SpendableOutputDescriptor::StaticOutput {
2472 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
2473 output: output.clone(),
2478 Storage::Watchtower { .. } => {
2479 //TODO: we need to ensure an offline client will generate the event when it
2480 // comes back online after only the watchtower saw the transaction
2487 /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
2488 /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
2489 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
2490 /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
2491 /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
2492 /// broadcast them if remote don't close channel with his higher commitment transaction after a
2493 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
2494 /// out-of-band the other node operator to coordinate with him if option is available to you.
2495 /// In any-case, choice is up to the user.
2496 pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
2497 log_trace!(self, "Getting signed latest local commitment transaction!");
2498 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2499 match self.key_storage {
2500 Storage::Local { ref funding_key, .. } => {
2501 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2506 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2507 let mut res = vec![local_tx.tx.with_valid_witness().clone()];
2508 match self.key_storage {
2509 Storage::Local { ref delayed_payment_base_key, .. } => {
2510 res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
2511 // 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.
2512 // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
2514 _ => panic!("Can only broadcast by local channelmonitor"),
2522 /// Called by SimpleManyChannelMonitor::block_connected, which implements
2523 /// ChainListener::block_connected.
2524 /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
2525 /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
2527 fn block_connected<B: Deref, F: Deref>(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)-> Vec<(Sha256dHash, Vec<TxOut>)>
2528 where B::Target: BroadcasterInterface,
2529 F::Target: FeeEstimator
2531 for tx in txn_matched {
2532 let mut output_val = 0;
2533 for out in tx.output.iter() {
2534 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2535 output_val += out.value;
2536 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2540 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2541 let mut watch_outputs = Vec::new();
2542 let mut spendable_outputs = Vec::new();
2543 let mut bump_candidates = HashSet::new();
2544 for tx in txn_matched {
2545 if tx.input.len() == 1 {
2546 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2547 // commitment transactions and HTLC transactions will all only ever have one input,
2548 // which is an easy way to filter out any potential non-matching txn for lazy
2550 let prevout = &tx.input[0].previous_output;
2551 let mut txn: Vec<Transaction> = Vec::new();
2552 let funding_txo = match self.key_storage {
2553 Storage::Local { ref funding_info, .. } => {
2554 funding_info.clone()
2556 Storage::Watchtower { .. } => {
2560 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) {
2561 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2562 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, &*fee_estimator);
2564 spendable_outputs.append(&mut spendable_output);
2565 if !new_outputs.1.is_empty() {
2566 watch_outputs.push(new_outputs);
2569 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2570 spendable_outputs.append(&mut spendable_output);
2572 if !new_outputs.1.is_empty() {
2573 watch_outputs.push(new_outputs);
2577 if !funding_txo.is_none() && txn.is_empty() {
2578 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2579 spendable_outputs.push(spendable_output);
2583 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2584 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, &*fee_estimator);
2585 if let Some(tx) = tx {
2588 if let Some(spendable_output) = spendable_output {
2589 spendable_outputs.push(spendable_output);
2593 for tx in txn.iter() {
2594 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2595 broadcaster.broadcast_transaction(tx);
2598 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2599 // can also be resolved in a few other ways which can have more than one output. Thus,
2600 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2601 self.is_resolving_htlc_output(&tx, height);
2603 // Scan all input to verify is one of the outpoint spent is of interest for us
2604 let mut claimed_outputs_material = Vec::new();
2605 for inp in &tx.input {
2606 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2607 // If outpoint has claim request pending on it...
2608 if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2609 //... we need to verify equality between transaction outpoints and claim request
2610 // outpoints to know if transaction is the original claim or a bumped one issued
2612 let mut set_equality = true;
2613 if claim_material.per_input_material.len() != tx.input.len() {
2614 set_equality = false;
2616 for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2617 if *claim_inp != tx_inp.previous_output {
2618 set_equality = false;
2623 macro_rules! clean_claim_request_after_safety_delay {
2625 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2626 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2627 hash_map::Entry::Occupied(mut entry) => {
2628 if !entry.get().contains(&new_event) {
2629 entry.get_mut().push(new_event);
2632 hash_map::Entry::Vacant(entry) => {
2633 entry.insert(vec![new_event]);
2639 // If this is our transaction (or our counterparty spent all the outputs
2640 // before we could anyway with same inputs order than us), wait for
2641 // ANTI_REORG_DELAY and clean the RBF tracking map.
2643 clean_claim_request_after_safety_delay!();
2644 } else { // If false, generate new claim request with update outpoint set
2645 for input in tx.input.iter() {
2646 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2647 claimed_outputs_material.push((input.previous_output, input_material));
2649 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2650 if claim_material.per_input_material.is_empty() {
2651 clean_claim_request_after_safety_delay!();
2654 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2655 bump_candidates.insert(first_claim_txid_height.0.clone());
2657 break; //No need to iterate further, either tx is our or their
2659 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2663 for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2664 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2665 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2666 hash_map::Entry::Occupied(mut entry) => {
2667 if !entry.get().contains(&new_event) {
2668 entry.get_mut().push(new_event);
2671 hash_map::Entry::Vacant(entry) => {
2672 entry.insert(vec![new_event]);
2677 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2678 self.would_broadcast_at_height(height)
2680 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2681 if should_broadcast {
2682 match self.key_storage {
2683 Storage::Local { ref funding_key, .. } => {
2684 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2690 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2691 if should_broadcast {
2692 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2693 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2694 match self.key_storage {
2695 Storage::Local { ref delayed_payment_base_key, .. } => {
2696 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2697 spendable_outputs.append(&mut spendable_output);
2698 if !new_outputs.is_empty() {
2699 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2702 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2703 broadcaster.broadcast_transaction(&tx);
2706 Storage::Watchtower { .. } => { },
2710 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2713 OnchainEvent::Claim { claim_request } => {
2714 // We may remove a whole set of claim outpoints here, as these one may have
2715 // been aggregated in a single tx and claimed so atomically
2716 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2717 for outpoint in bump_material.per_input_material.keys() {
2718 self.claimable_outpoints.remove(&outpoint);
2722 OnchainEvent::HTLCUpdate { htlc_update } => {
2723 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2724 self.pending_htlcs_updated.push(HTLCUpdate {
2725 payment_hash: htlc_update.1,
2726 payment_preimage: None,
2727 source: htlc_update.0,
2730 OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2731 self.claimable_outpoints.remove(&outpoint);
2736 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2737 if cached_claim_datas.height_timer == height {
2738 bump_candidates.insert(first_claim_txid.clone());
2741 for first_claim_txid in bump_candidates.iter() {
2742 if let Some((new_timer, new_feerate)) = {
2743 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2744 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, &*fee_estimator) {
2745 broadcaster.broadcast_transaction(&bump_tx);
2746 Some((new_timer, new_feerate))
2748 } else { unreachable!(); }
2750 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2751 claim_material.height_timer = new_timer;
2752 claim_material.feerate_previous = new_feerate;
2753 } else { unreachable!(); }
2756 self.last_block_hash = block_hash.clone();
2757 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2758 self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2761 if spendable_outputs.len() > 0 {
2762 self.pending_events.push(events::Event::SpendableOutputs {
2763 outputs: spendable_outputs,
2770 fn block_disconnected<B: Deref, F: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)
2771 where B::Target: BroadcasterInterface,
2772 F::Target: FeeEstimator
2774 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2775 let mut bump_candidates = HashMap::new();
2776 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2778 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2779 //- our claim tx on a commitment tx output
2780 //- resurect outpoint back in its claimable set and regenerate tx
2783 OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2784 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2785 if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2786 claim_material.per_input_material.insert(outpoint, input_material);
2787 // Using a HashMap guarantee us than if we have multiple outpoints getting
2788 // resurrected only one bump claim tx is going to be broadcast
2789 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2797 for (_, claim_material) in bump_candidates.iter_mut() {
2798 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, &*fee_estimator) {
2799 claim_material.height_timer = new_timer;
2800 claim_material.feerate_previous = new_feerate;
2801 broadcaster.broadcast_transaction(&bump_tx);
2804 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2805 self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2807 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2808 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2809 let mut remove_request = Vec::new();
2810 self.claimable_outpoints.retain(|_, ref v|
2812 remove_request.push(v.0.clone());
2815 for req in remove_request {
2816 self.pending_claim_requests.remove(&req);
2818 self.last_block_hash = block_hash.clone();
2821 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2822 // We need to consider all HTLCs which are:
2823 // * in any unrevoked remote commitment transaction, as they could broadcast said
2824 // transactions and we'd end up in a race, or
2825 // * are in our latest local commitment transaction, as this is the thing we will
2826 // broadcast if we go on-chain.
2827 // Note that we consider HTLCs which were below dust threshold here - while they don't
2828 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2829 // to the source, and if we don't fail the channel we will have to ensure that the next
2830 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2831 // easier to just fail the channel as this case should be rare enough anyway.
2832 macro_rules! scan_commitment {
2833 ($htlcs: expr, $local_tx: expr) => {
2834 for ref htlc in $htlcs {
2835 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2836 // chain with enough room to claim the HTLC without our counterparty being able to
2837 // time out the HTLC first.
2838 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2839 // concern is being able to claim the corresponding inbound HTLC (on another
2840 // channel) before it expires. In fact, we don't even really care if our
2841 // counterparty here claims such an outbound HTLC after it expired as long as we
2842 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2843 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2844 // we give ourselves a few blocks of headroom after expiration before going
2845 // on-chain for an expired HTLC.
2846 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2847 // from us until we've reached the point where we go on-chain with the
2848 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2849 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2850 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2851 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2852 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2853 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2854 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2855 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2856 // The final, above, condition is checked for statically in channelmanager
2857 // with CHECK_CLTV_EXPIRY_SANITY_2.
2858 let htlc_outbound = $local_tx == htlc.offered;
2859 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2860 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2861 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2868 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2869 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2872 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2873 if let &Some(ref txid) = current_remote_commitment_txid {
2874 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2875 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2878 if let &Some(ref txid) = prev_remote_commitment_txid {
2879 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2880 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2888 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2889 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2890 fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2891 'outer_loop: for input in &tx.input {
2892 let mut payment_data = None;
2893 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2894 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2895 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2896 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2898 macro_rules! log_claim {
2899 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2900 // We found the output in question, but aren't failing it backwards
2901 // as we have no corresponding source and no valid remote commitment txid
2902 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2903 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2904 let outbound_htlc = $local_tx == $htlc.offered;
2905 if ($local_tx && revocation_sig_claim) ||
2906 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2907 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2908 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2909 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2910 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2912 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2913 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2914 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2915 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2920 macro_rules! check_htlc_valid_remote {
2921 ($remote_txid: expr, $htlc_output: expr) => {
2922 if let &Some(txid) = $remote_txid {
2923 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2924 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2925 if let &Some(ref source) = pending_source {
2926 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2927 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2936 macro_rules! scan_commitment {
2937 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2938 for (ref htlc_output, source_option) in $htlcs {
2939 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2940 if let Some(ref source) = source_option {
2941 log_claim!($tx_info, $local_tx, htlc_output, true);
2942 // We have a resolution of an HTLC either from one of our latest
2943 // local commitment transactions or an unrevoked remote commitment
2944 // transaction. This implies we either learned a preimage, the HTLC
2945 // has timed out, or we screwed up. In any case, we should now
2946 // resolve the source HTLC with the original sender.
2947 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2948 } else if !$local_tx {
2949 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2950 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2952 if payment_data.is_none() {
2953 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2954 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2958 if payment_data.is_none() {
2959 log_claim!($tx_info, $local_tx, htlc_output, false);
2960 continue 'outer_loop;
2967 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2968 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2969 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2970 "our latest local commitment tx", true);
2973 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2974 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2975 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2976 "our previous local commitment tx", true);
2979 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2980 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2981 "remote commitment tx", false);
2984 // Check that scan_commitment, above, decided there is some source worth relaying an
2985 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2986 if let Some((source, payment_hash)) = payment_data {
2987 let mut payment_preimage = PaymentPreimage([0; 32]);
2988 if accepted_preimage_claim {
2989 payment_preimage.0.copy_from_slice(&input.witness[3]);
2990 self.pending_htlcs_updated.push(HTLCUpdate {
2992 payment_preimage: Some(payment_preimage),
2995 } else if offered_preimage_claim {
2996 payment_preimage.0.copy_from_slice(&input.witness[1]);
2997 self.pending_htlcs_updated.push(HTLCUpdate {
2999 payment_preimage: Some(payment_preimage),
3003 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);
3004 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
3005 hash_map::Entry::Occupied(mut entry) => {
3006 let e = entry.get_mut();
3007 e.retain(|ref event| {
3009 OnchainEvent::HTLCUpdate { ref htlc_update } => {
3010 return htlc_update.0 != source
3015 e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
3017 hash_map::Entry::Vacant(entry) => {
3018 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
3026 /// 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
3027 /// (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.
3028 fn bump_claim_tx<F: Deref>(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F) -> Option<(u32, u64, Transaction)>
3029 where F::Target: FeeEstimator
3031 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
3032 let mut inputs = Vec::new();
3033 for outp in cached_claim_datas.per_input_material.keys() {
3035 previous_output: *outp,
3036 script_sig: Script::new(),
3037 sequence: 0xfffffffd,
3038 witness: Vec::new(),
3041 let mut bumped_tx = Transaction {
3045 output: vec![TxOut {
3046 script_pubkey: self.destination_script.clone(),
3051 macro_rules! RBF_bump {
3052 ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
3054 let mut used_feerate;
3055 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
3056 let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
3057 let mut value = $amount;
3058 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
3059 // Overflow check is done in subtract_high_prio_fee
3062 log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
3065 // ...else just increase the previous feerate by 25% (because that's a nice number)
3067 let fee = $old_feerate * $predicted_weight / 750;
3069 log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
3075 let previous_fee = $old_feerate * $predicted_weight / 1000;
3076 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
3077 // BIP 125 Opt-in Full Replace-by-Fee Signaling
3078 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
3079 // * 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.
3080 let new_fee = if new_fee < previous_fee + min_relay_fee {
3081 new_fee + previous_fee + min_relay_fee - new_fee
3085 Some((new_fee, new_fee * 1000 / $predicted_weight))
3090 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
3091 let mut inputs_witnesses_weight = 0;
3093 for per_outp_material in cached_claim_datas.per_input_material.values() {
3094 match per_outp_material {
3095 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
3096 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!() });
3099 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
3100 inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
3103 &InputMaterial::LocalHTLC { .. } => { return None; }
3107 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
3109 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
3110 // If new computed fee is superior at the whole claimable amount burn all in fees
3112 bumped_tx.output[0].value = 0;
3114 bumped_tx.output[0].value = amt - new_fee;
3116 new_feerate = feerate;
3120 assert!(new_feerate != 0);
3122 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
3123 match per_outp_material {
3124 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
3125 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3126 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3127 let sig = self.secp_ctx.sign(&sighash, &key);
3128 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3129 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3131 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
3133 bumped_tx.input[i].witness.push(vec!(1));
3135 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3136 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);
3138 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
3139 if !preimage.is_some() { bumped_tx.lock_time = *locktime };
3140 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3141 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3142 let sig = self.secp_ctx.sign(&sighash, &key);
3143 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3144 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3145 if let &Some(preimage) = preimage {
3146 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
3148 bumped_tx.input[i].witness.push(vec![0]);
3150 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3151 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);
3153 &InputMaterial::LocalHTLC { .. } => {
3154 //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
3155 // RBF them. Need a Lightning specs change and package relay modification :
3156 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
3161 assert!(predicted_weight >= bumped_tx.get_weight());
3162 Some((new_timer, new_feerate, bumped_tx))
3166 const MAX_ALLOC_SIZE: usize = 64*1024;
3168 impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
3169 fn read<R: ::std::io::Read>(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
3170 let secp_ctx = Secp256k1::new();
3171 macro_rules! unwrap_obj {
3175 Err(_) => return Err(DecodeError::InvalidValue),
3180 let _ver: u8 = Readable::read(reader)?;
3181 let min_ver: u8 = Readable::read(reader)?;
3182 if min_ver > SERIALIZATION_VERSION {
3183 return Err(DecodeError::UnknownVersion);
3186 let latest_update_id: u64 = Readable::read(reader)?;
3187 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3189 let key_storage = match <u8 as Readable>::read(reader)? {
3191 let keys = Readable::read(reader)?;
3192 let funding_key = Readable::read(reader)?;
3193 let revocation_base_key = Readable::read(reader)?;
3194 let htlc_base_key = Readable::read(reader)?;
3195 let delayed_payment_base_key = Readable::read(reader)?;
3196 let payment_base_key = Readable::read(reader)?;
3197 let shutdown_pubkey = Readable::read(reader)?;
3198 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3199 // barely-init'd ChannelMonitors that we can't do anything with.
3200 let outpoint = OutPoint {
3201 txid: Readable::read(reader)?,
3202 index: Readable::read(reader)?,
3204 let funding_info = Some((outpoint, Readable::read(reader)?));
3205 let current_remote_commitment_txid = Readable::read(reader)?;
3206 let prev_remote_commitment_txid = Readable::read(reader)?;
3210 revocation_base_key,
3212 delayed_payment_base_key,
3216 current_remote_commitment_txid,
3217 prev_remote_commitment_txid,
3220 _ => return Err(DecodeError::InvalidValue),
3223 let their_htlc_base_key = Some(Readable::read(reader)?);
3224 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3225 let funding_redeemscript = Some(Readable::read(reader)?);
3226 let channel_value_satoshis = Some(Readable::read(reader)?);
3228 let their_cur_revocation_points = {
3229 let first_idx = <U48 as Readable>::read(reader)?.0;
3233 let first_point = Readable::read(reader)?;
3234 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3235 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3236 Some((first_idx, first_point, None))
3238 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3243 let our_to_self_delay: u16 = Readable::read(reader)?;
3244 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3246 let commitment_secrets = Readable::read(reader)?;
3248 macro_rules! read_htlc_in_commitment {
3251 let offered: bool = Readable::read(reader)?;
3252 let amount_msat: u64 = Readable::read(reader)?;
3253 let cltv_expiry: u32 = Readable::read(reader)?;
3254 let payment_hash: PaymentHash = Readable::read(reader)?;
3255 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3257 HTLCOutputInCommitment {
3258 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3264 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3265 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3266 for _ in 0..remote_claimable_outpoints_len {
3267 let txid: Sha256dHash = Readable::read(reader)?;
3268 let htlcs_count: u64 = Readable::read(reader)?;
3269 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3270 for _ in 0..htlcs_count {
3271 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3273 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3274 return Err(DecodeError::InvalidValue);
3278 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3279 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3280 for _ in 0..remote_commitment_txn_on_chain_len {
3281 let txid: Sha256dHash = Readable::read(reader)?;
3282 let commitment_number = <U48 as Readable>::read(reader)?.0;
3283 let outputs_count = <u64 as Readable>::read(reader)?;
3284 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3285 for _ in 0..outputs_count {
3286 outputs.push(Readable::read(reader)?);
3288 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3289 return Err(DecodeError::InvalidValue);
3293 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3294 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3295 for _ in 0..remote_hash_commitment_number_len {
3296 let payment_hash: PaymentHash = Readable::read(reader)?;
3297 let commitment_number = <U48 as Readable>::read(reader)?.0;
3298 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3299 return Err(DecodeError::InvalidValue);
3303 macro_rules! read_local_tx {
3306 let tx = <LocalCommitmentTransaction as Readable>::read(reader)?;
3307 let revocation_key = Readable::read(reader)?;
3308 let a_htlc_key = Readable::read(reader)?;
3309 let b_htlc_key = Readable::read(reader)?;
3310 let delayed_payment_key = Readable::read(reader)?;
3311 let per_commitment_point = Readable::read(reader)?;
3312 let feerate_per_kw: u64 = Readable::read(reader)?;
3314 let htlcs_len: u64 = Readable::read(reader)?;
3315 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3316 for _ in 0..htlcs_len {
3317 let htlc = read_htlc_in_commitment!();
3318 let sigs = match <u8 as Readable>::read(reader)? {
3320 1 => Some(Readable::read(reader)?),
3321 _ => return Err(DecodeError::InvalidValue),
3323 htlcs.push((htlc, sigs, Readable::read(reader)?));
3328 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3335 let prev_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
3338 Some(read_local_tx!())
3340 _ => return Err(DecodeError::InvalidValue),
3343 let current_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
3346 Some(read_local_tx!())
3348 _ => return Err(DecodeError::InvalidValue),
3351 let current_remote_commitment_number = <U48 as Readable>::read(reader)?.0;
3353 let payment_preimages_len: u64 = Readable::read(reader)?;
3354 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3355 for _ in 0..payment_preimages_len {
3356 let preimage: PaymentPreimage = Readable::read(reader)?;
3357 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3358 if let Some(_) = payment_preimages.insert(hash, preimage) {
3359 return Err(DecodeError::InvalidValue);
3363 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
3364 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
3365 for _ in 0..pending_htlcs_updated_len {
3366 pending_htlcs_updated.push(Readable::read(reader)?);
3369 let pending_events_len: u64 = Readable::read(reader)?;
3370 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<events::Event>()));
3371 for _ in 0..pending_events_len {
3372 if let Some(event) = MaybeReadable::read(reader)? {
3373 pending_events.push(event);
3377 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3378 let destination_script = Readable::read(reader)?;
3379 let to_remote_rescue = match <u8 as Readable>::read(reader)? {
3382 let to_remote_script = Readable::read(reader)?;
3383 let local_key = Readable::read(reader)?;
3384 Some((to_remote_script, local_key))
3386 _ => return Err(DecodeError::InvalidValue),
3389 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3390 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3391 for _ in 0..pending_claim_requests_len {
3392 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3395 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3396 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3397 for _ in 0..claimable_outpoints_len {
3398 let outpoint = Readable::read(reader)?;
3399 let ancestor_claim_txid = Readable::read(reader)?;
3400 let height = Readable::read(reader)?;
3401 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3404 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3405 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3406 for _ in 0..waiting_threshold_conf_len {
3407 let height_target = Readable::read(reader)?;
3408 let events_len: u64 = Readable::read(reader)?;
3409 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3410 for _ in 0..events_len {
3411 let ev = match <u8 as Readable>::read(reader)? {
3413 let claim_request = Readable::read(reader)?;
3414 OnchainEvent::Claim {
3419 let htlc_source = Readable::read(reader)?;
3420 let hash = Readable::read(reader)?;
3421 OnchainEvent::HTLCUpdate {
3422 htlc_update: (htlc_source, hash)
3426 let outpoint = Readable::read(reader)?;
3427 let input_material = Readable::read(reader)?;
3428 OnchainEvent::ContentiousOutpoint {
3433 _ => return Err(DecodeError::InvalidValue),
3437 onchain_events_waiting_threshold_conf.insert(height_target, events);
3440 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3441 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>>())));
3442 for _ in 0..outputs_to_watch_len {
3443 let txid = Readable::read(reader)?;
3444 let outputs_len: u64 = Readable::read(reader)?;
3445 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
3446 for _ in 0..outputs_len {
3447 outputs.push(Readable::read(reader)?);
3449 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3450 return Err(DecodeError::InvalidValue);
3454 Ok((last_block_hash.clone(), ChannelMonitor {
3456 commitment_transaction_number_obscure_factor,
3459 their_htlc_base_key,
3460 their_delayed_payment_base_key,
3461 funding_redeemscript,
3462 channel_value_satoshis,
3463 their_cur_revocation_points,
3466 their_to_self_delay,
3469 remote_claimable_outpoints,
3470 remote_commitment_txn_on_chain,
3471 remote_hash_commitment_number,
3473 prev_local_signed_commitment_tx,
3474 current_local_signed_commitment_tx,
3475 current_remote_commitment_number,
3478 pending_htlcs_updated,
3484 pending_claim_requests,
3486 claimable_outpoints,
3488 onchain_events_waiting_threshold_conf,
3501 use bitcoin::blockdata::script::{Script, Builder};
3502 use bitcoin::blockdata::opcodes;
3503 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3504 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3505 use bitcoin::util::bip143;
3506 use bitcoin_hashes::Hash;
3507 use bitcoin_hashes::sha256::Hash as Sha256;
3508 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3509 use bitcoin_hashes::hex::FromHex;
3511 use chain::transaction::OutPoint;
3512 use ln::channelmanager::{PaymentPreimage, PaymentHash};
3513 use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3515 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3516 use util::test_utils::TestLogger;
3517 use secp256k1::key::{SecretKey,PublicKey};
3518 use secp256k1::Secp256k1;
3519 use rand::{thread_rng,Rng};
3521 use chain::keysinterface::InMemoryChannelKeys;
3524 fn test_prune_preimages() {
3525 let secp_ctx = Secp256k1::new();
3526 let logger = Arc::new(TestLogger::new());
3528 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3529 macro_rules! dummy_keys {
3533 per_commitment_point: dummy_key.clone(),
3534 revocation_key: dummy_key.clone(),
3535 a_htlc_key: dummy_key.clone(),
3536 b_htlc_key: dummy_key.clone(),
3537 a_delayed_payment_key: dummy_key.clone(),
3538 b_payment_key: dummy_key.clone(),
3543 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3545 let mut preimages = Vec::new();
3547 let mut rng = thread_rng();
3549 let mut preimage = PaymentPreimage([0; 32]);
3550 rng.fill_bytes(&mut preimage.0[..]);
3551 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3552 preimages.push((preimage, hash));
3556 macro_rules! preimages_slice_to_htlc_outputs {
3557 ($preimages_slice: expr) => {
3559 let mut res = Vec::new();
3560 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3561 res.push((HTLCOutputInCommitment {
3565 payment_hash: preimage.1.clone(),
3566 transaction_output_index: Some(idx as u32),
3573 macro_rules! preimages_to_local_htlcs {
3574 ($preimages_slice: expr) => {
3576 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3577 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3583 macro_rules! test_preimages_exist {
3584 ($preimages_slice: expr, $monitor: expr) => {
3585 for preimage in $preimages_slice {
3586 assert!($monitor.payment_preimages.contains_key(&preimage.1));
3591 let keys = InMemoryChannelKeys::new(
3593 SecretKey::from_slice(&[41; 32]).unwrap(),
3594 SecretKey::from_slice(&[41; 32]).unwrap(),
3595 SecretKey::from_slice(&[41; 32]).unwrap(),
3596 SecretKey::from_slice(&[41; 32]).unwrap(),
3597 SecretKey::from_slice(&[41; 32]).unwrap(),
3602 // Prune with one old state and a local commitment tx holding a few overlaps with the
3604 let mut monitor = ChannelMonitor::new(keys,
3605 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
3606 (OutPoint { txid: Sha256dHash::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3607 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3608 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3609 0, Script::new(), 46, 0, logger.clone());
3611 monitor.their_to_self_delay = Some(10);
3613 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
3614 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3615 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3616 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3617 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3618 for &(ref preimage, ref hash) in preimages.iter() {
3619 monitor.provide_payment_preimage(hash, preimage);
3622 // Now provide a secret, pruning preimages 10-15
3623 let mut secret = [0; 32];
3624 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3625 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3626 assert_eq!(monitor.payment_preimages.len(), 15);
3627 test_preimages_exist!(&preimages[0..10], monitor);
3628 test_preimages_exist!(&preimages[15..20], monitor);
3630 // Now provide a further secret, pruning preimages 15-17
3631 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3632 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3633 assert_eq!(monitor.payment_preimages.len(), 13);
3634 test_preimages_exist!(&preimages[0..10], monitor);
3635 test_preimages_exist!(&preimages[17..20], monitor);
3637 // Now update local commitment tx info, pruning only element 18 as we still care about the
3638 // previous commitment tx's preimages too
3639 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
3640 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3641 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3642 assert_eq!(monitor.payment_preimages.len(), 12);
3643 test_preimages_exist!(&preimages[0..10], monitor);
3644 test_preimages_exist!(&preimages[18..20], monitor);
3646 // But if we do it again, we'll prune 5-10
3647 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
3648 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3649 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3650 assert_eq!(monitor.payment_preimages.len(), 5);
3651 test_preimages_exist!(&preimages[0..5], monitor);
3655 fn test_claim_txn_weight_computation() {
3656 // We test Claim txn weight, knowing that we want expected weigth and
3657 // not actual case to avoid sigs and time-lock delays hell variances.
3659 let secp_ctx = Secp256k1::new();
3660 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3661 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3662 let mut sum_actual_sigs = 0;
3664 macro_rules! sign_input {
3665 ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3666 let htlc = HTLCOutputInCommitment {
3667 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3669 cltv_expiry: 2 << 16,
3670 payment_hash: PaymentHash([1; 32]),
3671 transaction_output_index: Some($idx),
3673 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) };
3674 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3675 let sig = secp_ctx.sign(&sighash, &privkey);
3676 $input.witness.push(sig.serialize_der().to_vec());
3677 $input.witness[0].push(SigHashType::All as u8);
3678 sum_actual_sigs += $input.witness[0].len();
3679 if *$input_type == InputDescriptors::RevokedOutput {
3680 $input.witness.push(vec!(1));
3681 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3682 $input.witness.push(pubkey.clone().serialize().to_vec());
3683 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3684 $input.witness.push(vec![0]);
3686 $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3688 $input.witness.push(redeem_script.into_bytes());
3689 println!("witness[0] {}", $input.witness[0].len());
3690 println!("witness[1] {}", $input.witness[1].len());
3691 println!("witness[2] {}", $input.witness[2].len());
3695 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3696 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3698 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3699 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3701 claim_tx.input.push(TxIn {
3702 previous_output: BitcoinOutPoint {
3706 script_sig: Script::new(),
3707 sequence: 0xfffffffd,
3708 witness: Vec::new(),
3711 claim_tx.output.push(TxOut {
3712 script_pubkey: script_pubkey.clone(),
3715 let base_weight = claim_tx.get_weight();
3716 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3717 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3718 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3719 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3721 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));
3723 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3724 claim_tx.input.clear();
3725 sum_actual_sigs = 0;
3727 claim_tx.input.push(TxIn {
3728 previous_output: BitcoinOutPoint {
3732 script_sig: Script::new(),
3733 sequence: 0xfffffffd,
3734 witness: Vec::new(),
3737 let base_weight = claim_tx.get_weight();
3738 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3739 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3740 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3741 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3743 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));
3745 // Justice tx with 1 revoked HTLC-Success tx output
3746 claim_tx.input.clear();
3747 sum_actual_sigs = 0;
3748 claim_tx.input.push(TxIn {
3749 previous_output: BitcoinOutPoint {
3753 script_sig: Script::new(),
3754 sequence: 0xfffffffd,
3755 witness: Vec::new(),
3757 let base_weight = claim_tx.get_weight();
3758 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3759 let inputs_des = vec![InputDescriptors::RevokedOutput];
3760 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3761 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3763 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));
3766 // Further testing is done in the ChannelManager integration tests.