1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
13 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
14 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15 //! be made in responding to certain messages, see [`chain::Watch`] for more.
17 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20 //! security-domain-separated system design, you should consider having multiple paths for
21 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
23 use bitcoin::blockdata::block::BlockHeader;
24 use bitcoin::blockdata::transaction::{OutPoint as BitcoinOutPoint, TxOut, Transaction};
25 use bitcoin::blockdata::script::{Script, Builder};
26 use bitcoin::blockdata::opcodes;
28 use bitcoin::hashes::Hash;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
32 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
33 use bitcoin::secp256k1::{SecretKey, PublicKey};
34 use bitcoin::secp256k1;
36 use crate::ln::{PaymentHash, PaymentPreimage};
37 use crate::ln::msgs::DecodeError;
38 use crate::ln::chan_utils;
39 use crate::ln::chan_utils::{CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys};
40 use crate::ln::channelmanager::{HTLCSource, SentHTLCId};
42 use crate::chain::{BestBlock, WatchedOutput};
43 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
44 use crate::chain::transaction::{OutPoint, TransactionData};
45 use crate::sign::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, WriteableEcdsaChannelSigner, SignerProvider, EntropySource};
46 use crate::chain::onchaintx::{ClaimEvent, OnchainTxHandler};
47 use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
48 use crate::chain::Filter;
49 use crate::util::logger::Logger;
50 use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48};
51 use crate::util::byte_utils;
52 use crate::events::{Event, EventHandler};
53 use crate::events::bump_transaction::{ChannelDerivationParameters, AnchorDescriptor, HTLCDescriptor, BumpTransactionEvent};
55 use crate::prelude::*;
57 use crate::io::{self, Error};
58 use core::convert::TryInto;
60 use crate::sync::{Mutex, LockTestExt};
62 /// An update generated by the underlying channel itself which contains some new information the
63 /// [`ChannelMonitor`] should be made aware of.
65 /// Because this represents only a small number of updates to the underlying state, it is generally
66 /// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction
67 /// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment
68 /// transaction), a single update may reach upwards of 1 MiB in serialized size.
69 #[derive(Clone, PartialEq, Eq)]
71 pub struct ChannelMonitorUpdate {
72 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
73 /// The sequence number of this update. Updates *must* be replayed in-order according to this
74 /// sequence number (and updates may panic if they are not). The update_id values are strictly
75 /// increasing and increase by one for each new update, with two exceptions specified below.
77 /// This sequence number is also used to track up to which points updates which returned
78 /// [`ChannelMonitorUpdateStatus::InProgress`] have been applied to all copies of a given
79 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
81 /// The only instances we allow where update_id values are not strictly increasing have a
82 /// special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. This update ID is used for updates that
83 /// will force close the channel by broadcasting the latest commitment transaction or
84 /// special post-force-close updates, like providing preimages necessary to claim outputs on the
85 /// broadcast commitment transaction. See its docs for more details.
87 /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
91 /// The update ID used for a [`ChannelMonitorUpdate`] that is either:
93 /// (1) attempting to force close the channel by broadcasting our latest commitment transaction or
94 /// (2) providing a preimage (after the channel has been force closed) from a forward link that
95 /// allows us to spend an HTLC output on this channel's (the backward link's) broadcasted
96 /// commitment transaction.
98 /// No other [`ChannelMonitorUpdate`]s are allowed after force-close.
99 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
101 impl Writeable for ChannelMonitorUpdate {
102 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
103 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
104 self.update_id.write(w)?;
105 (self.updates.len() as u64).write(w)?;
106 for update_step in self.updates.iter() {
107 update_step.write(w)?;
109 write_tlv_fields!(w, {});
113 impl Readable for ChannelMonitorUpdate {
114 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
115 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
116 let update_id: u64 = Readable::read(r)?;
117 let len: u64 = Readable::read(r)?;
118 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
120 if let Some(upd) = MaybeReadable::read(r)? {
124 read_tlv_fields!(r, {});
125 Ok(Self { update_id, updates })
129 /// An event to be processed by the ChannelManager.
130 #[derive(Clone, PartialEq, Eq)]
131 pub enum MonitorEvent {
132 /// A monitor event containing an HTLCUpdate.
133 HTLCEvent(HTLCUpdate),
135 /// A monitor event that the Channel's commitment transaction was confirmed.
136 CommitmentTxConfirmed(OutPoint),
138 /// Indicates a [`ChannelMonitor`] update has completed. See
139 /// [`ChannelMonitorUpdateStatus::InProgress`] for more information on how this is used.
141 /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
143 /// The funding outpoint of the [`ChannelMonitor`] that was updated
144 funding_txo: OutPoint,
145 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
146 /// [`ChannelMonitor::get_latest_update_id`].
148 /// Note that this should only be set to a given update's ID if all previous updates for the
149 /// same [`ChannelMonitor`] have been applied and persisted.
150 monitor_update_id: u64,
153 /// Indicates a [`ChannelMonitor`] update has failed. See
154 /// [`ChannelMonitorUpdateStatus::PermanentFailure`] for more information on how this is used.
156 /// [`ChannelMonitorUpdateStatus::PermanentFailure`]: super::ChannelMonitorUpdateStatus::PermanentFailure
157 UpdateFailed(OutPoint),
159 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
160 // Note that Completed and UpdateFailed are currently never serialized to disk as they are
161 // generated only in ChainMonitor
163 (0, funding_txo, required),
164 (2, monitor_update_id, required),
168 (4, CommitmentTxConfirmed),
172 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
173 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
174 /// preimage claim backward will lead to loss of funds.
175 #[derive(Clone, PartialEq, Eq)]
176 pub struct HTLCUpdate {
177 pub(crate) payment_hash: PaymentHash,
178 pub(crate) payment_preimage: Option<PaymentPreimage>,
179 pub(crate) source: HTLCSource,
180 pub(crate) htlc_value_satoshis: Option<u64>,
182 impl_writeable_tlv_based!(HTLCUpdate, {
183 (0, payment_hash, required),
184 (1, htlc_value_satoshis, option),
185 (2, source, required),
186 (4, payment_preimage, option),
189 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
190 /// instead claiming it in its own individual transaction.
191 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
192 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
193 /// HTLC-Success transaction.
194 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
195 /// transaction confirmed (and we use it in a few more, equivalent, places).
196 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
197 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
198 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
199 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
200 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
201 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
202 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
203 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
204 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
205 /// accurate block height.
206 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
207 /// with at worst this delay, so we are not only using this value as a mercy for them but also
208 /// us as a safeguard to delay with enough time.
209 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
210 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
211 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
214 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
215 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
216 /// by a [`ChannelMonitor`] may be incorrect.
217 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
218 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
219 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
220 // keep bumping another claim tx to solve the outpoint.
221 pub const ANTI_REORG_DELAY: u32 = 6;
222 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
223 /// refuse to accept a new HTLC.
225 /// This is used for a few separate purposes:
226 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
227 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
229 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
230 /// condition with the above), we will fail this HTLC without telling the user we received it,
232 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
233 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
235 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
236 /// in a race condition between the user connecting a block (which would fail it) and the user
237 /// providing us the preimage (which would claim it).
238 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
240 // TODO(devrandom) replace this with HolderCommitmentTransaction
241 #[derive(Clone, PartialEq, Eq)]
242 struct HolderSignedTx {
243 /// txid of the transaction in tx, just used to make comparison faster
245 revocation_key: PublicKey,
246 a_htlc_key: PublicKey,
247 b_htlc_key: PublicKey,
248 delayed_payment_key: PublicKey,
249 per_commitment_point: PublicKey,
250 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
251 to_self_value_sat: u64,
254 impl_writeable_tlv_based!(HolderSignedTx, {
256 // Note that this is filled in with data from OnchainTxHandler if it's missing.
257 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
258 (1, to_self_value_sat, (default_value, u64::max_value())),
259 (2, revocation_key, required),
260 (4, a_htlc_key, required),
261 (6, b_htlc_key, required),
262 (8, delayed_payment_key, required),
263 (10, per_commitment_point, required),
264 (12, feerate_per_kw, required),
265 (14, htlc_outputs, required_vec)
268 impl HolderSignedTx {
269 fn non_dust_htlcs(&self) -> Vec<HTLCOutputInCommitment> {
270 self.htlc_outputs.iter().filter_map(|(htlc, _, _)| {
271 if let Some(_) = htlc.transaction_output_index {
281 /// We use this to track static counterparty commitment transaction data and to generate any
282 /// justice or 2nd-stage preimage/timeout transactions.
283 #[derive(Clone, PartialEq, Eq)]
284 struct CounterpartyCommitmentParameters {
285 counterparty_delayed_payment_base_key: PublicKey,
286 counterparty_htlc_base_key: PublicKey,
287 on_counterparty_tx_csv: u16,
290 impl Writeable for CounterpartyCommitmentParameters {
291 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
292 w.write_all(&(0 as u64).to_be_bytes())?;
293 write_tlv_fields!(w, {
294 (0, self.counterparty_delayed_payment_base_key, required),
295 (2, self.counterparty_htlc_base_key, required),
296 (4, self.on_counterparty_tx_csv, required),
301 impl Readable for CounterpartyCommitmentParameters {
302 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
303 let counterparty_commitment_transaction = {
304 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
305 // used. Read it for compatibility.
306 let per_htlc_len: u64 = Readable::read(r)?;
307 for _ in 0..per_htlc_len {
308 let _txid: Txid = Readable::read(r)?;
309 let htlcs_count: u64 = Readable::read(r)?;
310 for _ in 0..htlcs_count {
311 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
315 let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
316 let mut counterparty_htlc_base_key = RequiredWrapper(None);
317 let mut on_counterparty_tx_csv: u16 = 0;
318 read_tlv_fields!(r, {
319 (0, counterparty_delayed_payment_base_key, required),
320 (2, counterparty_htlc_base_key, required),
321 (4, on_counterparty_tx_csv, required),
323 CounterpartyCommitmentParameters {
324 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
325 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
326 on_counterparty_tx_csv,
329 Ok(counterparty_commitment_transaction)
333 /// An entry for an [`OnchainEvent`], stating the block height and hash when the event was
334 /// observed, as well as the transaction causing it.
336 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
337 #[derive(Clone, PartialEq, Eq)]
338 struct OnchainEventEntry {
341 block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
343 transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
346 impl OnchainEventEntry {
347 fn confirmation_threshold(&self) -> u32 {
348 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
350 OnchainEvent::MaturingOutput {
351 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
353 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
354 // it's broadcastable when we see the previous block.
355 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
357 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
358 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
359 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
360 // it's broadcastable when we see the previous block.
361 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
368 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
369 best_block.height() >= self.confirmation_threshold()
373 /// The (output index, sats value) for the counterparty's output in a commitment transaction.
375 /// This was added as an `Option` in 0.0.110.
376 type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>;
378 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
379 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
380 #[derive(Clone, PartialEq, Eq)]
382 /// An outbound HTLC failing after a transaction is confirmed. Used
383 /// * when an outbound HTLC output is spent by us after the HTLC timed out
384 /// * an outbound HTLC which was not present in the commitment transaction which appeared
385 /// on-chain (either because it was not fully committed to or it was dust).
386 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
387 /// appearing only as an `HTLCSpendConfirmation`, below.
390 payment_hash: PaymentHash,
391 htlc_value_satoshis: Option<u64>,
392 /// None in the second case, above, ie when there is no relevant output in the commitment
393 /// transaction which appeared on chain.
394 commitment_tx_output_idx: Option<u32>,
396 /// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the
397 /// [`SpendableOutputDescriptor`].
399 descriptor: SpendableOutputDescriptor,
401 /// A spend of the funding output, either a commitment transaction or a cooperative closing
403 FundingSpendConfirmation {
404 /// The CSV delay for the output of the funding spend transaction (implying it is a local
405 /// commitment transaction, and this is the delay on the to_self output).
406 on_local_output_csv: Option<u16>,
407 /// If the funding spend transaction was a known remote commitment transaction, we track
408 /// the output index and amount of the counterparty's `to_self` output here.
410 /// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
411 /// counterparty output.
412 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
414 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
415 /// is constructed. This is used when
416 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
417 /// immediately claim the HTLC on the inbound edge and track the resolution here,
418 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
419 /// * an inbound HTLC is claimed by us (with a preimage).
420 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
422 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by an
423 /// HTLC-Success/HTLC-Failure transaction (and is still claimable with a revocation
425 HTLCSpendConfirmation {
426 commitment_tx_output_idx: u32,
427 /// If the claim was made by either party with a preimage, this is filled in
428 preimage: Option<PaymentPreimage>,
429 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
430 /// we set this to the output CSV value which we will have to wait until to spend the
431 /// output (and generate a SpendableOutput event).
432 on_to_local_output_csv: Option<u16>,
436 impl Writeable for OnchainEventEntry {
437 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
438 write_tlv_fields!(writer, {
439 (0, self.txid, required),
440 (1, self.transaction, option),
441 (2, self.height, required),
442 (3, self.block_hash, option),
443 (4, self.event, required),
449 impl MaybeReadable for OnchainEventEntry {
450 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
451 let mut txid = Txid::all_zeros();
452 let mut transaction = None;
453 let mut block_hash = None;
455 let mut event = UpgradableRequired(None);
456 read_tlv_fields!(reader, {
458 (1, transaction, option),
459 (2, height, required),
460 (3, block_hash, option),
461 (4, event, upgradable_required),
463 Ok(Some(Self { txid, transaction, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
467 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
469 (0, source, required),
470 (1, htlc_value_satoshis, option),
471 (2, payment_hash, required),
472 (3, commitment_tx_output_idx, option),
474 (1, MaturingOutput) => {
475 (0, descriptor, required),
477 (3, FundingSpendConfirmation) => {
478 (0, on_local_output_csv, option),
479 (1, commitment_tx_to_counterparty_output, option),
481 (5, HTLCSpendConfirmation) => {
482 (0, commitment_tx_output_idx, required),
483 (2, preimage, option),
484 (4, on_to_local_output_csv, option),
489 #[derive(Clone, PartialEq, Eq)]
490 pub(crate) enum ChannelMonitorUpdateStep {
491 LatestHolderCommitmentTXInfo {
492 commitment_tx: HolderCommitmentTransaction,
493 /// Note that LDK after 0.0.115 supports this only containing dust HTLCs (implying the
494 /// `Signature` field is never filled in). At that point, non-dust HTLCs are implied by the
495 /// HTLC fields in `commitment_tx` and the sources passed via `nondust_htlc_sources`.
496 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
497 claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
498 nondust_htlc_sources: Vec<HTLCSource>,
500 LatestCounterpartyCommitmentTXInfo {
501 commitment_txid: Txid,
502 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
503 commitment_number: u64,
504 their_per_commitment_point: PublicKey,
505 feerate_per_kw: Option<u32>,
506 to_broadcaster_value_sat: Option<u64>,
507 to_countersignatory_value_sat: Option<u64>,
510 payment_preimage: PaymentPreimage,
516 /// Used to indicate that the no future updates will occur, and likely that the latest holder
517 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
519 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
520 /// think we've fallen behind!
521 should_broadcast: bool,
524 scriptpubkey: Script,
528 impl ChannelMonitorUpdateStep {
529 fn variant_name(&self) -> &'static str {
531 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
532 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
533 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
534 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
535 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
536 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
541 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
542 (0, LatestHolderCommitmentTXInfo) => {
543 (0, commitment_tx, required),
544 (1, claimed_htlcs, optional_vec),
545 (2, htlc_outputs, required_vec),
546 (4, nondust_htlc_sources, optional_vec),
548 (1, LatestCounterpartyCommitmentTXInfo) => {
549 (0, commitment_txid, required),
550 (1, feerate_per_kw, option),
551 (2, commitment_number, required),
552 (3, to_broadcaster_value_sat, option),
553 (4, their_per_commitment_point, required),
554 (5, to_countersignatory_value_sat, option),
555 (6, htlc_outputs, required_vec),
557 (2, PaymentPreimage) => {
558 (0, payment_preimage, required),
560 (3, CommitmentSecret) => {
562 (2, secret, required),
564 (4, ChannelForceClosed) => {
565 (0, should_broadcast, required),
567 (5, ShutdownScript) => {
568 (0, scriptpubkey, required),
572 /// Details about the balance(s) available for spending once the channel appears on chain.
574 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
576 #[derive(Clone, Debug, PartialEq, Eq)]
577 #[cfg_attr(test, derive(PartialOrd, Ord))]
579 /// The channel is not yet closed (or the commitment or closing transaction has not yet
580 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
581 /// force-closed now.
582 ClaimableOnChannelClose {
583 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
584 /// required to do so.
585 amount_satoshis: u64,
587 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
588 /// we consider it spendable.
589 ClaimableAwaitingConfirmations {
590 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
591 /// were spent in broadcasting the transaction.
592 amount_satoshis: u64,
593 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
595 confirmation_height: u32,
597 /// The channel has been closed, and the given balance should be ours but awaiting spending
598 /// transaction confirmation. If the spending transaction does not confirm in time, it is
599 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
601 /// Once the spending transaction confirms, before it has reached enough confirmations to be
602 /// considered safe from chain reorganizations, the balance will instead be provided via
603 /// [`Balance::ClaimableAwaitingConfirmations`].
604 ContentiousClaimable {
605 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
606 /// required to do so.
607 amount_satoshis: u64,
608 /// The height at which the counterparty may be able to claim the balance if we have not
611 /// The payment hash that locks this HTLC.
612 payment_hash: PaymentHash,
613 /// The preimage that can be used to claim this HTLC.
614 payment_preimage: PaymentPreimage,
616 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
617 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
618 /// likely to be claimed by our counterparty before we do.
619 MaybeTimeoutClaimableHTLC {
620 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
621 /// which will be required to do so.
622 amount_satoshis: u64,
623 /// The height at which we will be able to claim the balance if our counterparty has not
625 claimable_height: u32,
626 /// The payment hash whose preimage our counterparty needs to claim this HTLC.
627 payment_hash: PaymentHash,
629 /// HTLCs which we received from our counterparty which are claimable with a preimage which we
630 /// do not currently have. This will only be claimable if we receive the preimage from the node
631 /// to which we forwarded this HTLC before the timeout.
632 MaybePreimageClaimableHTLC {
633 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
634 /// which will be required to do so.
635 amount_satoshis: u64,
636 /// The height at which our counterparty will be able to claim the balance if we have not
637 /// yet received the preimage and claimed it ourselves.
639 /// The payment hash whose preimage we need to claim this HTLC.
640 payment_hash: PaymentHash,
642 /// The channel has been closed, and our counterparty broadcasted a revoked commitment
645 /// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
646 /// following amount.
647 CounterpartyRevokedOutputClaimable {
648 /// The amount, in satoshis, of the output which we can claim.
650 /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
651 /// were already spent.
652 amount_satoshis: u64,
657 /// The amount claimable, in satoshis. This excludes balances that we are unsure if we are able
658 /// to claim, this is because we are waiting for a preimage or for a timeout to expire. For more
659 /// information on these balances see [`Balance::MaybeTimeoutClaimableHTLC`] and
660 /// [`Balance::MaybePreimageClaimableHTLC`].
662 /// On-chain fees required to claim the balance are not included in this amount.
663 pub fn claimable_amount_satoshis(&self) -> u64 {
665 Balance::ClaimableOnChannelClose { amount_satoshis, .. }|
666 Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
667 Balance::ContentiousClaimable { amount_satoshis, .. }|
668 Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
670 Balance::MaybeTimeoutClaimableHTLC { .. }|
671 Balance::MaybePreimageClaimableHTLC { .. }
677 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
678 #[derive(Clone, PartialEq, Eq)]
679 struct IrrevocablyResolvedHTLC {
680 commitment_tx_output_idx: Option<u32>,
681 /// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC
682 /// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
684 resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
685 resolving_tx: Option<Transaction>,
686 /// Only set if the HTLC claim was ours using a payment preimage
687 payment_preimage: Option<PaymentPreimage>,
690 // In LDK versions prior to 0.0.111 commitment_tx_output_idx was not Option-al and
691 // IrrevocablyResolvedHTLC objects only existed for non-dust HTLCs. This was a bug, but to maintain
692 // backwards compatibility we must ensure we always write out a commitment_tx_output_idx field,
693 // using `u32::max_value()` as a sentinal to indicate the HTLC was dust.
694 impl Writeable for IrrevocablyResolvedHTLC {
695 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
696 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::max_value());
697 write_tlv_fields!(writer, {
698 (0, mapped_commitment_tx_output_idx, required),
699 (1, self.resolving_txid, option),
700 (2, self.payment_preimage, option),
701 (3, self.resolving_tx, option),
707 impl Readable for IrrevocablyResolvedHTLC {
708 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
709 let mut mapped_commitment_tx_output_idx = 0;
710 let mut resolving_txid = None;
711 let mut payment_preimage = None;
712 let mut resolving_tx = None;
713 read_tlv_fields!(reader, {
714 (0, mapped_commitment_tx_output_idx, required),
715 (1, resolving_txid, option),
716 (2, payment_preimage, option),
717 (3, resolving_tx, option),
720 commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::max_value() { None } else { Some(mapped_commitment_tx_output_idx) },
728 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
729 /// on-chain transactions to ensure no loss of funds occurs.
731 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
732 /// information and are actively monitoring the chain.
734 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
735 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
736 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
737 /// returned block hash and the the current chain and then reconnecting blocks to get to the
738 /// best chain) upon deserializing the object!
739 pub struct ChannelMonitor<Signer: WriteableEcdsaChannelSigner> {
741 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
743 pub(super) inner: Mutex<ChannelMonitorImpl<Signer>>,
746 impl<Signer: WriteableEcdsaChannelSigner> Clone for ChannelMonitor<Signer> where Signer: Clone {
747 fn clone(&self) -> Self {
748 let inner = self.inner.lock().unwrap().clone();
749 ChannelMonitor::from_impl(inner)
753 #[derive(Clone, PartialEq)]
754 pub(crate) struct ChannelMonitorImpl<Signer: WriteableEcdsaChannelSigner> {
755 latest_update_id: u64,
756 commitment_transaction_number_obscure_factor: u64,
758 destination_script: Script,
759 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
760 counterparty_payment_script: Script,
761 shutdown_script: Option<Script>,
763 channel_keys_id: [u8; 32],
764 holder_revocation_basepoint: PublicKey,
765 funding_info: (OutPoint, Script),
766 current_counterparty_commitment_txid: Option<Txid>,
767 prev_counterparty_commitment_txid: Option<Txid>,
769 counterparty_commitment_params: CounterpartyCommitmentParameters,
770 funding_redeemscript: Script,
771 channel_value_satoshis: u64,
772 // first is the idx of the first of the two per-commitment points
773 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
775 on_holder_tx_csv: u16,
777 commitment_secrets: CounterpartyCommitmentSecrets,
778 /// The set of outpoints in each counterparty commitment transaction. We always need at least
779 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
780 /// transaction broadcast as we need to be able to construct the witness script in all cases.
781 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
782 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
783 /// Nor can we figure out their commitment numbers without the commitment transaction they are
784 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
785 /// commitment transactions which we find on-chain, mapping them to the commitment number which
786 /// can be used to derive the revocation key and claim the transactions.
787 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
788 /// Cache used to make pruning of payment_preimages faster.
789 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
790 /// counterparty transactions (ie should remain pretty small).
791 /// Serialized to disk but should generally not be sent to Watchtowers.
792 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
794 counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
796 // We store two holder commitment transactions to avoid any race conditions where we may update
797 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
798 // various monitors for one channel being out of sync, and us broadcasting a holder
799 // transaction for which we have deleted claim information on some watchtowers.
800 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
801 current_holder_commitment_tx: HolderSignedTx,
803 // Used just for ChannelManager to make sure it has the latest channel data during
805 current_counterparty_commitment_number: u64,
806 // Used just for ChannelManager to make sure it has the latest channel data during
808 current_holder_commitment_number: u64,
810 /// The set of payment hashes from inbound payments for which we know the preimage. Payment
811 /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
812 /// remote commitment transactions are automatically removed when commitment transactions are
814 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
816 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
817 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
818 // presumably user implementations thereof as well) where we update the in-memory channel
819 // object, then before the persistence finishes (as it's all under a read-lock), we return
820 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
821 // the pre-event state here, but have processed the event in the `ChannelManager`.
822 // Note that because the `event_lock` in `ChainMonitor` is only taken in
823 // block/transaction-connected events and *not* during block/transaction-disconnected events,
824 // we further MUST NOT generate events during block/transaction-disconnection.
825 pending_monitor_events: Vec<MonitorEvent>,
827 pub(super) pending_events: Vec<Event>,
828 pub(super) is_processing_pending_events: bool,
830 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
831 // which to take actions once they reach enough confirmations. Each entry includes the
832 // transaction's id and the height when the transaction was confirmed on chain.
833 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
835 // If we get serialized out and re-read, we need to make sure that the chain monitoring
836 // interface knows about the TXOs that we want to be notified of spends of. We could probably
837 // be smart and derive them from the above storage fields, but its much simpler and more
838 // Obviously Correct (tm) if we just keep track of them explicitly.
839 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
842 pub onchain_tx_handler: OnchainTxHandler<Signer>,
844 onchain_tx_handler: OnchainTxHandler<Signer>,
846 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
847 // channel has been force-closed. After this is set, no further holder commitment transaction
848 // updates may occur, and we panic!() if one is provided.
849 lockdown_from_offchain: bool,
851 // Set once we've signed a holder commitment transaction and handed it over to our
852 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
853 // may occur, and we fail any such monitor updates.
855 // In case of update rejection due to a locally already signed commitment transaction, we
856 // nevertheless store update content to track in case of concurrent broadcast by another
857 // remote monitor out-of-order with regards to the block view.
858 holder_tx_signed: bool,
860 // If a spend of the funding output is seen, we set this to true and reject any further
861 // updates. This prevents any further changes in the offchain state no matter the order
862 // of block connection between ChannelMonitors and the ChannelManager.
863 funding_spend_seen: bool,
865 /// Set to `Some` of the confirmed transaction spending the funding input of the channel after
866 /// reaching `ANTI_REORG_DELAY` confirmations.
867 funding_spend_confirmed: Option<Txid>,
869 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
870 /// The set of HTLCs which have been either claimed or failed on chain and have reached
871 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
872 /// spending CSV for revocable outputs).
873 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
875 /// The set of `SpendableOutput` events which we have already passed upstream to be claimed.
876 /// These are tracked explicitly to ensure that we don't generate the same events redundantly
877 /// if users duplicatively confirm old transactions. Specifically for transactions claiming a
878 /// revoked remote outpoint we otherwise have no tracking at all once they've reached
879 /// [`ANTI_REORG_DELAY`], so we have to track them here.
880 spendable_txids_confirmed: Vec<Txid>,
882 // We simply modify best_block in Channel's block_connected so that serialization is
883 // consistent but hopefully the users' copy handles block_connected in a consistent way.
884 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
885 // their best_block from its state and not based on updated copies that didn't run through
886 // the full block_connected).
887 best_block: BestBlock,
889 /// The node_id of our counterparty
890 counterparty_node_id: Option<PublicKey>,
893 /// Transaction outputs to watch for on-chain spends.
894 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
896 impl<Signer: WriteableEcdsaChannelSigner> PartialEq for ChannelMonitor<Signer> where Signer: PartialEq {
897 fn eq(&self, other: &Self) -> bool {
898 // We need some kind of total lockorder. Absent a better idea, we sort by position in
899 // memory and take locks in that order (assuming that we can't move within memory while a
901 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
902 let a = if ord { self.inner.unsafe_well_ordered_double_lock_self() } else { other.inner.unsafe_well_ordered_double_lock_self() };
903 let b = if ord { other.inner.unsafe_well_ordered_double_lock_self() } else { self.inner.unsafe_well_ordered_double_lock_self() };
908 impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
909 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
910 self.inner.lock().unwrap().write(writer)
914 // These are also used for ChannelMonitorUpdate, above.
915 const SERIALIZATION_VERSION: u8 = 1;
916 const MIN_SERIALIZATION_VERSION: u8 = 1;
918 impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
919 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
920 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
922 self.latest_update_id.write(writer)?;
924 // Set in initial Channel-object creation, so should always be set by now:
925 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
927 self.destination_script.write(writer)?;
928 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
929 writer.write_all(&[0; 1])?;
930 broadcasted_holder_revokable_script.0.write(writer)?;
931 broadcasted_holder_revokable_script.1.write(writer)?;
932 broadcasted_holder_revokable_script.2.write(writer)?;
934 writer.write_all(&[1; 1])?;
937 self.counterparty_payment_script.write(writer)?;
938 match &self.shutdown_script {
939 Some(script) => script.write(writer)?,
940 None => Script::new().write(writer)?,
943 self.channel_keys_id.write(writer)?;
944 self.holder_revocation_basepoint.write(writer)?;
945 writer.write_all(&self.funding_info.0.txid[..])?;
946 writer.write_all(&self.funding_info.0.index.to_be_bytes())?;
947 self.funding_info.1.write(writer)?;
948 self.current_counterparty_commitment_txid.write(writer)?;
949 self.prev_counterparty_commitment_txid.write(writer)?;
951 self.counterparty_commitment_params.write(writer)?;
952 self.funding_redeemscript.write(writer)?;
953 self.channel_value_satoshis.write(writer)?;
955 match self.their_cur_per_commitment_points {
956 Some((idx, pubkey, second_option)) => {
957 writer.write_all(&byte_utils::be48_to_array(idx))?;
958 writer.write_all(&pubkey.serialize())?;
959 match second_option {
960 Some(second_pubkey) => {
961 writer.write_all(&second_pubkey.serialize())?;
964 writer.write_all(&[0; 33])?;
969 writer.write_all(&byte_utils::be48_to_array(0))?;
973 writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?;
975 self.commitment_secrets.write(writer)?;
977 macro_rules! serialize_htlc_in_commitment {
978 ($htlc_output: expr) => {
979 writer.write_all(&[$htlc_output.offered as u8; 1])?;
980 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
981 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
982 writer.write_all(&$htlc_output.payment_hash.0[..])?;
983 $htlc_output.transaction_output_index.write(writer)?;
987 writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?;
988 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
989 writer.write_all(&txid[..])?;
990 writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
991 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
992 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
993 || Some(**txid) == self.prev_counterparty_commitment_txid,
994 "HTLC Sources for all revoked commitment transactions should be none!");
995 serialize_htlc_in_commitment!(htlc_output);
996 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1000 writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?;
1001 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
1002 writer.write_all(&txid[..])?;
1003 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1006 writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?;
1007 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1008 writer.write_all(&payment_hash.0[..])?;
1009 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1012 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1013 writer.write_all(&[1; 1])?;
1014 prev_holder_tx.write(writer)?;
1016 writer.write_all(&[0; 1])?;
1019 self.current_holder_commitment_tx.write(writer)?;
1021 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1022 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1024 writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?;
1025 for payment_preimage in self.payment_preimages.values() {
1026 writer.write_all(&payment_preimage.0[..])?;
1029 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
1030 MonitorEvent::HTLCEvent(_) => true,
1031 MonitorEvent::CommitmentTxConfirmed(_) => true,
1033 }).count() as u64).to_be_bytes())?;
1034 for event in self.pending_monitor_events.iter() {
1036 MonitorEvent::HTLCEvent(upd) => {
1040 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
1041 _ => {}, // Covered in the TLV writes below
1045 writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?;
1046 for event in self.pending_events.iter() {
1047 event.write(writer)?;
1050 self.best_block.block_hash().write(writer)?;
1051 writer.write_all(&self.best_block.height().to_be_bytes())?;
1053 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
1054 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
1055 entry.write(writer)?;
1058 (self.outputs_to_watch.len() as u64).write(writer)?;
1059 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
1060 txid.write(writer)?;
1061 (idx_scripts.len() as u64).write(writer)?;
1062 for (idx, script) in idx_scripts.iter() {
1064 script.write(writer)?;
1067 self.onchain_tx_handler.write(writer)?;
1069 self.lockdown_from_offchain.write(writer)?;
1070 self.holder_tx_signed.write(writer)?;
1072 write_tlv_fields!(writer, {
1073 (1, self.funding_spend_confirmed, option),
1074 (3, self.htlcs_resolved_on_chain, required_vec),
1075 (5, self.pending_monitor_events, required_vec),
1076 (7, self.funding_spend_seen, required),
1077 (9, self.counterparty_node_id, option),
1078 (11, self.confirmed_commitment_tx_counterparty_output, option),
1079 (13, self.spendable_txids_confirmed, required_vec),
1080 (15, self.counterparty_fulfilled_htlcs, required),
1087 macro_rules! _process_events_body {
1088 ($self_opt: expr, $event_to_handle: expr, $handle_event: expr) => {
1090 let (pending_events, repeated_events);
1091 if let Some(us) = $self_opt {
1092 let mut inner = us.inner.lock().unwrap();
1093 if inner.is_processing_pending_events {
1096 inner.is_processing_pending_events = true;
1098 pending_events = inner.pending_events.clone();
1099 repeated_events = inner.get_repeated_events();
1101 let num_events = pending_events.len();
1103 for event in pending_events.into_iter().chain(repeated_events.into_iter()) {
1104 $event_to_handle = event;
1108 if let Some(us) = $self_opt {
1109 let mut inner = us.inner.lock().unwrap();
1110 inner.pending_events.drain(..num_events);
1111 inner.is_processing_pending_events = false;
1112 if !inner.pending_events.is_empty() {
1113 // If there's more events to process, go ahead and do so.
1121 pub(super) use _process_events_body as process_events_body;
1123 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1124 /// For lockorder enforcement purposes, we need to have a single site which constructs the
1125 /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1126 /// PartialEq implementation) we may decide a lockorder violation has occurred.
1127 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1128 ChannelMonitor { inner: Mutex::new(imp) }
1131 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
1132 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1133 channel_parameters: &ChannelTransactionParameters,
1134 funding_redeemscript: Script, channel_value_satoshis: u64,
1135 commitment_transaction_number_obscure_factor: u64,
1136 initial_holder_commitment_tx: HolderCommitmentTransaction,
1137 best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
1139 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1140 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1141 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1143 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1144 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1145 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1146 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1148 let channel_keys_id = keys.channel_keys_id();
1149 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1151 // block for Rust 1.34 compat
1152 let (holder_commitment_tx, current_holder_commitment_number) = {
1153 let trusted_tx = initial_holder_commitment_tx.trust();
1154 let txid = trusted_tx.txid();
1156 let tx_keys = trusted_tx.keys();
1157 let holder_commitment_tx = HolderSignedTx {
1159 revocation_key: tx_keys.revocation_key,
1160 a_htlc_key: tx_keys.broadcaster_htlc_key,
1161 b_htlc_key: tx_keys.countersignatory_htlc_key,
1162 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1163 per_commitment_point: tx_keys.per_commitment_point,
1164 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1165 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1166 feerate_per_kw: trusted_tx.feerate_per_kw(),
1168 (holder_commitment_tx, trusted_tx.commitment_number())
1171 let onchain_tx_handler =
1172 OnchainTxHandler::new(destination_script.clone(), keys,
1173 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx);
1175 let mut outputs_to_watch = HashMap::new();
1176 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1178 Self::from_impl(ChannelMonitorImpl {
1179 latest_update_id: 0,
1180 commitment_transaction_number_obscure_factor,
1182 destination_script: destination_script.clone(),
1183 broadcasted_holder_revokable_script: None,
1184 counterparty_payment_script,
1188 holder_revocation_basepoint,
1190 current_counterparty_commitment_txid: None,
1191 prev_counterparty_commitment_txid: None,
1193 counterparty_commitment_params,
1194 funding_redeemscript,
1195 channel_value_satoshis,
1196 their_cur_per_commitment_points: None,
1198 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1200 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1201 counterparty_claimable_outpoints: HashMap::new(),
1202 counterparty_commitment_txn_on_chain: HashMap::new(),
1203 counterparty_hash_commitment_number: HashMap::new(),
1204 counterparty_fulfilled_htlcs: HashMap::new(),
1206 prev_holder_signed_commitment_tx: None,
1207 current_holder_commitment_tx: holder_commitment_tx,
1208 current_counterparty_commitment_number: 1 << 48,
1209 current_holder_commitment_number,
1211 payment_preimages: HashMap::new(),
1212 pending_monitor_events: Vec::new(),
1213 pending_events: Vec::new(),
1214 is_processing_pending_events: false,
1216 onchain_events_awaiting_threshold_conf: Vec::new(),
1221 lockdown_from_offchain: false,
1222 holder_tx_signed: false,
1223 funding_spend_seen: false,
1224 funding_spend_confirmed: None,
1225 confirmed_commitment_tx_counterparty_output: None,
1226 htlcs_resolved_on_chain: Vec::new(),
1227 spendable_txids_confirmed: Vec::new(),
1230 counterparty_node_id: Some(counterparty_node_id),
1235 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1236 self.inner.lock().unwrap().provide_secret(idx, secret)
1239 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1240 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1241 /// possibly future revocation/preimage information) to claim outputs where possible.
1242 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1243 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1246 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1247 commitment_number: u64,
1248 their_per_commitment_point: PublicKey,
1250 ) where L::Target: Logger {
1251 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1252 txid, htlc_outputs, commitment_number, their_per_commitment_point, logger)
1256 fn provide_latest_holder_commitment_tx(
1257 &self, holder_commitment_tx: HolderCommitmentTransaction,
1258 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1259 ) -> Result<(), ()> {
1260 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new()).map_err(|_| ())
1263 /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1264 /// off-chain state with a new commitment transaction.
1265 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1267 payment_hash: &PaymentHash,
1268 payment_preimage: &PaymentPreimage,
1270 fee_estimator: &LowerBoundedFeeEstimator<F>,
1273 B::Target: BroadcasterInterface,
1274 F::Target: FeeEstimator,
1277 self.inner.lock().unwrap().provide_payment_preimage(
1278 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1281 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1284 /// panics if the given update is not the next update by update_id.
1285 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1287 updates: &ChannelMonitorUpdate,
1293 B::Target: BroadcasterInterface,
1294 F::Target: FeeEstimator,
1297 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1300 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1302 pub fn get_latest_update_id(&self) -> u64 {
1303 self.inner.lock().unwrap().get_latest_update_id()
1306 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1307 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1308 self.inner.lock().unwrap().get_funding_txo().clone()
1311 /// Gets a list of txids, with their output scripts (in the order they appear in the
1312 /// transaction), which we must learn about spends of via block_connected().
1313 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1314 self.inner.lock().unwrap().get_outputs_to_watch()
1315 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1318 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1319 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1320 /// have been registered.
1321 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1322 let lock = self.inner.lock().unwrap();
1323 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1324 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1325 for (index, script_pubkey) in outputs.iter() {
1326 assert!(*index <= u16::max_value() as u32);
1327 filter.register_output(WatchedOutput {
1329 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1330 script_pubkey: script_pubkey.clone(),
1336 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1337 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1338 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1339 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1342 /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
1344 /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
1345 /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
1346 /// within each channel. As the confirmation of a commitment transaction may be critical to the
1347 /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
1348 /// environment with spotty connections, like on mobile.
1350 /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
1351 /// order to handle these events.
1353 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
1354 /// [`BumpTransaction`]: crate::events::Event::BumpTransaction
1355 pub fn process_pending_events<H: Deref>(&self, handler: &H) where H::Target: EventHandler {
1357 process_events_body!(Some(self), ev, handler.handle_event(ev));
1360 /// Processes any events asynchronously.
1362 /// See [`Self::process_pending_events`] for more information.
1363 pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
1367 process_events_body!(Some(self), ev, { handler(ev).await });
1371 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1372 let mut ret = Vec::new();
1373 let mut lck = self.inner.lock().unwrap();
1374 mem::swap(&mut ret, &mut lck.pending_events);
1375 ret.append(&mut lck.get_repeated_events());
1379 /// Gets all of the counterparty commitment transactions provided by the given update. This
1380 /// may be empty if the update doesn't include any new counterparty commitments. Returned
1381 /// commitment transactions are unsigned.
1383 /// This is provided so that watchtower clients in the persistence pipeline are able to build
1384 /// justice transactions for each counterparty commitment upon each update. It's intended to be
1385 /// used within an implementation of [`Persist::update_persisted_channel`], which is provided
1386 /// with a monitor and an update.
1388 /// It is expected that a watchtower client may use this method to retrieve the latest counterparty
1389 /// commitment transaction(s), and then hold the necessary data until a later update in which
1390 /// the monitor has been updated with the corresponding revocation data, at which point the
1391 /// monitor can sign the justice transaction.
1393 /// This will only return a non-empty list for monitor updates that have been created after
1394 /// upgrading to LDK 0.0.117+. Note that no restriction lies on the monitors themselves, which
1395 /// may have been created prior to upgrading.
1397 /// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel
1398 pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
1399 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
1402 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1403 self.inner.lock().unwrap().get_min_seen_secret()
1406 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1407 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1410 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1411 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1414 /// Gets the `node_id` of the counterparty for this channel.
1416 /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1418 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1419 self.inner.lock().unwrap().counterparty_node_id
1422 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1423 /// the Channel was out-of-date.
1425 /// You may also use this to broadcast the latest local commitment transaction, either because
1426 /// a monitor update failed with [`ChannelMonitorUpdateStatus::PermanentFailure`] or because we've
1427 /// fallen behind (i.e. we've received proof that our counterparty side knows a revocation
1428 /// secret we gave them that they shouldn't know).
1430 /// Broadcasting these transactions in the second case is UNSAFE, as they allow counterparty
1431 /// side to punish you. Nevertheless you may want to broadcast them if counterparty doesn't
1432 /// close channel with their commitment transaction after a substantial amount of time. Best
1433 /// may be to contact the other node operator out-of-band to coordinate other options available
1434 /// to you. In any-case, the choice is up to you.
1436 /// [`ChannelMonitorUpdateStatus::PermanentFailure`]: super::ChannelMonitorUpdateStatus::PermanentFailure
1437 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1438 where L::Target: Logger {
1439 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1442 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1443 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1444 /// revoked commitment transaction.
1445 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1446 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1447 where L::Target: Logger {
1448 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1451 /// Processes transactions in a newly connected block, which may result in any of the following:
1452 /// - update the monitor's state against resolved HTLCs
1453 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1454 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1455 /// - detect settled outputs for later spending
1456 /// - schedule and bump any in-flight claims
1458 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1459 /// [`get_outputs_to_watch`].
1461 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1462 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1464 header: &BlockHeader,
1465 txdata: &TransactionData,
1470 ) -> Vec<TransactionOutputs>
1472 B::Target: BroadcasterInterface,
1473 F::Target: FeeEstimator,
1476 self.inner.lock().unwrap().block_connected(
1477 header, txdata, height, broadcaster, fee_estimator, logger)
1480 /// Determines if the disconnected block contained any transactions of interest and updates
1482 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1484 header: &BlockHeader,
1490 B::Target: BroadcasterInterface,
1491 F::Target: FeeEstimator,
1494 self.inner.lock().unwrap().block_disconnected(
1495 header, height, broadcaster, fee_estimator, logger)
1498 /// Processes transactions confirmed in a block with the given header and height, returning new
1499 /// outputs to watch. See [`block_connected`] for details.
1501 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1502 /// blocks. See [`chain::Confirm`] for calling expectations.
1504 /// [`block_connected`]: Self::block_connected
1505 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1507 header: &BlockHeader,
1508 txdata: &TransactionData,
1513 ) -> Vec<TransactionOutputs>
1515 B::Target: BroadcasterInterface,
1516 F::Target: FeeEstimator,
1519 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1520 self.inner.lock().unwrap().transactions_confirmed(
1521 header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
1524 /// Processes a transaction that was reorganized out of the chain.
1526 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1527 /// than blocks. See [`chain::Confirm`] for calling expectations.
1529 /// [`block_disconnected`]: Self::block_disconnected
1530 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1537 B::Target: BroadcasterInterface,
1538 F::Target: FeeEstimator,
1541 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1542 self.inner.lock().unwrap().transaction_unconfirmed(
1543 txid, broadcaster, &bounded_fee_estimator, logger);
1546 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1547 /// [`block_connected`] for details.
1549 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1550 /// blocks. See [`chain::Confirm`] for calling expectations.
1552 /// [`block_connected`]: Self::block_connected
1553 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1555 header: &BlockHeader,
1560 ) -> Vec<TransactionOutputs>
1562 B::Target: BroadcasterInterface,
1563 F::Target: FeeEstimator,
1566 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1567 self.inner.lock().unwrap().best_block_updated(
1568 header, height, broadcaster, &bounded_fee_estimator, logger)
1571 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1572 pub fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
1573 let inner = self.inner.lock().unwrap();
1574 let mut txids: Vec<(Txid, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
1576 .map(|entry| (entry.txid, entry.block_hash))
1577 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1579 txids.sort_unstable();
1584 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1585 /// [`chain::Confirm`] interfaces.
1586 pub fn current_best_block(&self) -> BestBlock {
1587 self.inner.lock().unwrap().best_block.clone()
1590 /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
1591 /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
1592 /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
1593 /// invoking this every 30 seconds, or lower if running in an environment with spotty
1594 /// connections, like on mobile.
1595 pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
1596 &self, broadcaster: B, fee_estimator: F, logger: L,
1599 B::Target: BroadcasterInterface,
1600 F::Target: FeeEstimator,
1603 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1604 let mut inner = self.inner.lock().unwrap();
1605 let current_height = inner.best_block.height;
1606 inner.onchain_tx_handler.rebroadcast_pending_claims(
1607 current_height, &broadcaster, &fee_estimator, &logger,
1612 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
1613 /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1614 /// to one `Balance` for the HTLC.
1615 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1616 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1617 -> Option<Balance> {
1618 let htlc_commitment_tx_output_idx =
1619 if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1621 let mut htlc_spend_txid_opt = None;
1622 let mut htlc_spend_tx_opt = None;
1623 let mut holder_timeout_spend_pending = None;
1624 let mut htlc_spend_pending = None;
1625 let mut holder_delayed_output_pending = None;
1626 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1628 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1629 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1630 debug_assert!(htlc_spend_txid_opt.is_none());
1631 htlc_spend_txid_opt = Some(&event.txid);
1632 debug_assert!(htlc_spend_tx_opt.is_none());
1633 htlc_spend_tx_opt = event.transaction.as_ref();
1634 debug_assert!(holder_timeout_spend_pending.is_none());
1635 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1636 holder_timeout_spend_pending = Some(event.confirmation_threshold());
1638 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1639 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1640 debug_assert!(htlc_spend_txid_opt.is_none());
1641 htlc_spend_txid_opt = Some(&event.txid);
1642 debug_assert!(htlc_spend_tx_opt.is_none());
1643 htlc_spend_tx_opt = event.transaction.as_ref();
1644 debug_assert!(htlc_spend_pending.is_none());
1645 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1647 OnchainEvent::MaturingOutput {
1648 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1649 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx => {
1650 debug_assert!(holder_delayed_output_pending.is_none());
1651 holder_delayed_output_pending = Some(event.confirmation_threshold());
1656 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1657 .find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
1658 debug_assert!(htlc_spend_txid_opt.is_none());
1659 htlc_spend_txid_opt = v.resolving_txid.as_ref();
1660 debug_assert!(htlc_spend_tx_opt.is_none());
1661 htlc_spend_tx_opt = v.resolving_tx.as_ref();
1664 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1666 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
1667 let htlc_output_to_spend =
1668 if let Some(txid) = htlc_spend_txid_opt {
1669 // Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
1670 // are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
1671 // locate the correct output by ensuring its adjacent input spends the HTLC output
1672 // in the commitment.
1673 if let Some(ref tx) = htlc_spend_tx_opt {
1674 let htlc_input_idx_opt = tx.input.iter().enumerate()
1675 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
1676 .map(|(idx, _)| idx as u32);
1677 debug_assert!(htlc_input_idx_opt.is_some());
1678 BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
1680 debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
1681 BitcoinOutPoint::new(*txid, 0)
1684 htlc_commitment_outpoint
1686 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1688 if let Some(conf_thresh) = holder_delayed_output_pending {
1689 debug_assert!(holder_commitment);
1690 return Some(Balance::ClaimableAwaitingConfirmations {
1691 amount_satoshis: htlc.amount_msat / 1000,
1692 confirmation_height: conf_thresh,
1694 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
1695 // Funding transaction spends should be fully confirmed by the time any
1696 // HTLC transactions are resolved, unless we're talking about a holder
1697 // commitment tx, whose resolution is delayed until the CSV timeout is
1698 // reached, even though HTLCs may be resolved after only
1699 // ANTI_REORG_DELAY confirmations.
1700 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
1701 } else if counterparty_revoked_commitment {
1702 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1703 if let OnchainEvent::MaturingOutput {
1704 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1706 if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1707 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1708 tx.txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
1710 Some(inp.previous_output.txid) == confirmed_txid &&
1711 inp.previous_output.vout == htlc_commitment_tx_output_idx
1713 })).unwrap_or(false) {
1718 if htlc_output_claim_pending.is_some() {
1719 // We already push `Balance`s onto the `res` list for every
1720 // `StaticOutput` in a `MaturingOutput` in the revoked
1721 // counterparty commitment transaction case generally, so don't
1722 // need to do so again here.
1724 debug_assert!(holder_timeout_spend_pending.is_none(),
1725 "HTLCUpdate OnchainEvents should never appear for preimage claims");
1726 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1727 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1728 return Some(Balance::CounterpartyRevokedOutputClaimable {
1729 amount_satoshis: htlc.amount_msat / 1000,
1732 } else if htlc.offered == holder_commitment {
1733 // If the payment was outbound, check if there's an HTLCUpdate
1734 // indicating we have spent this HTLC with a timeout, claiming it back
1735 // and awaiting confirmations on it.
1736 if let Some(conf_thresh) = holder_timeout_spend_pending {
1737 return Some(Balance::ClaimableAwaitingConfirmations {
1738 amount_satoshis: htlc.amount_msat / 1000,
1739 confirmation_height: conf_thresh,
1742 return Some(Balance::MaybeTimeoutClaimableHTLC {
1743 amount_satoshis: htlc.amount_msat / 1000,
1744 claimable_height: htlc.cltv_expiry,
1745 payment_hash: htlc.payment_hash,
1748 } else if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1749 // Otherwise (the payment was inbound), only expose it as claimable if
1750 // we know the preimage.
1751 // Note that if there is a pending claim, but it did not use the
1752 // preimage, we lost funds to our counterparty! We will then continue
1753 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1754 debug_assert!(holder_timeout_spend_pending.is_none());
1755 if let Some((conf_thresh, true)) = htlc_spend_pending {
1756 return Some(Balance::ClaimableAwaitingConfirmations {
1757 amount_satoshis: htlc.amount_msat / 1000,
1758 confirmation_height: conf_thresh,
1761 return Some(Balance::ContentiousClaimable {
1762 amount_satoshis: htlc.amount_msat / 1000,
1763 timeout_height: htlc.cltv_expiry,
1764 payment_hash: htlc.payment_hash,
1765 payment_preimage: *payment_preimage,
1768 } else if htlc_resolved.is_none() {
1769 return Some(Balance::MaybePreimageClaimableHTLC {
1770 amount_satoshis: htlc.amount_msat / 1000,
1771 expiry_height: htlc.cltv_expiry,
1772 payment_hash: htlc.payment_hash,
1779 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1780 /// Gets the balances in this channel which are either claimable by us if we were to
1781 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1784 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1785 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1786 /// balance, or until our counterparty has claimed the balance and accrued several
1787 /// confirmations on the claim transaction.
1789 /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1790 /// LDK prior to 0.0.111, balances may not be fully captured if our counterparty broadcasted
1791 /// a revoked state.
1793 /// See [`Balance`] for additional details on the types of claimable balances which
1794 /// may be returned here and their meanings.
1795 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1796 let mut res = Vec::new();
1797 let us = self.inner.lock().unwrap();
1799 let mut confirmed_txid = us.funding_spend_confirmed;
1800 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
1801 let mut pending_commitment_tx_conf_thresh = None;
1802 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1803 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1806 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
1807 Some((event.txid, event.confirmation_threshold()))
1810 if let Some((txid, conf_thresh)) = funding_spend_pending {
1811 debug_assert!(us.funding_spend_confirmed.is_none(),
1812 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1813 confirmed_txid = Some(txid);
1814 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1817 macro_rules! walk_htlcs {
1818 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
1819 for htlc in $htlc_iter {
1820 if htlc.transaction_output_index.is_some() {
1822 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
1830 if let Some(txid) = confirmed_txid {
1831 let mut found_commitment_tx = false;
1832 if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1833 // First look for the to_remote output back to us.
1834 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1835 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1836 if let OnchainEvent::MaturingOutput {
1837 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1839 Some(descriptor.output.value)
1842 res.push(Balance::ClaimableAwaitingConfirmations {
1843 amount_satoshis: value,
1844 confirmation_height: conf_thresh,
1847 // If a counterparty commitment transaction is awaiting confirmation, we
1848 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1849 // confirmation with the same height or have never met our dust amount.
1852 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1853 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1855 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1856 // The counterparty broadcasted a revoked state!
1857 // Look for any StaticOutputs first, generating claimable balances for those.
1858 // If any match the confirmed counterparty revoked to_self output, skip
1859 // generating a CounterpartyRevokedOutputClaimable.
1860 let mut spent_counterparty_output = false;
1861 for event in us.onchain_events_awaiting_threshold_conf.iter() {
1862 if let OnchainEvent::MaturingOutput {
1863 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1865 res.push(Balance::ClaimableAwaitingConfirmations {
1866 amount_satoshis: output.value,
1867 confirmation_height: event.confirmation_threshold(),
1869 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1870 if event.transaction.as_ref().map(|tx|
1871 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1872 ).unwrap_or(false) {
1873 spent_counterparty_output = true;
1879 if spent_counterparty_output {
1880 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1881 let output_spendable = us.onchain_tx_handler
1882 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1883 if output_spendable {
1884 res.push(Balance::CounterpartyRevokedOutputClaimable {
1885 amount_satoshis: amt,
1889 // Counterparty output is missing, either it was broadcasted on a
1890 // previous version of LDK or the counterparty hadn't met dust.
1893 found_commitment_tx = true;
1894 } else if txid == us.current_holder_commitment_tx.txid {
1895 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1896 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1897 res.push(Balance::ClaimableAwaitingConfirmations {
1898 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1899 confirmation_height: conf_thresh,
1902 found_commitment_tx = true;
1903 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1904 if txid == prev_commitment.txid {
1905 walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1906 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1907 res.push(Balance::ClaimableAwaitingConfirmations {
1908 amount_satoshis: prev_commitment.to_self_value_sat,
1909 confirmation_height: conf_thresh,
1912 found_commitment_tx = true;
1915 if !found_commitment_tx {
1916 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1917 // We blindly assume this is a cooperative close transaction here, and that
1918 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1919 // the amount we can claim as we'll punish a misbehaving counterparty.
1920 res.push(Balance::ClaimableAwaitingConfirmations {
1921 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1922 confirmation_height: conf_thresh,
1927 let mut claimable_inbound_htlc_value_sat = 0;
1928 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1929 if htlc.transaction_output_index.is_none() { continue; }
1931 res.push(Balance::MaybeTimeoutClaimableHTLC {
1932 amount_satoshis: htlc.amount_msat / 1000,
1933 claimable_height: htlc.cltv_expiry,
1934 payment_hash: htlc.payment_hash,
1936 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1937 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1939 // As long as the HTLC is still in our latest commitment state, treat
1940 // it as potentially claimable, even if it has long-since expired.
1941 res.push(Balance::MaybePreimageClaimableHTLC {
1942 amount_satoshis: htlc.amount_msat / 1000,
1943 expiry_height: htlc.cltv_expiry,
1944 payment_hash: htlc.payment_hash,
1948 res.push(Balance::ClaimableOnChannelClose {
1949 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1956 /// Gets the set of outbound HTLCs which can be (or have been) resolved by this
1957 /// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
1958 /// to the `ChannelManager` having been persisted.
1960 /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes
1961 /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
1962 /// event from this `ChannelMonitor`).
1963 pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
1964 let mut res = HashMap::new();
1965 // Just examine the available counterparty commitment transactions. See docs on
1966 // `fail_unbroadcast_htlcs`, below, for justification.
1967 let us = self.inner.lock().unwrap();
1968 macro_rules! walk_counterparty_commitment {
1970 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1971 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1972 if let &Some(ref source) = source_option {
1973 res.insert((**source).clone(), (htlc.clone(),
1974 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned()));
1980 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1981 walk_counterparty_commitment!(txid);
1983 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1984 walk_counterparty_commitment!(txid);
1989 /// Gets the set of outbound HTLCs which are pending resolution in this channel or which were
1990 /// resolved with a preimage from our counterparty.
1992 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1994 /// Currently, the preimage is unused, however if it is present in the relevant internal state
1995 /// an HTLC is always included even if it has been resolved.
1996 pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
1997 let us = self.inner.lock().unwrap();
1998 // We're only concerned with the confirmation count of HTLC transactions, and don't
1999 // actually care how many confirmations a commitment transaction may or may not have. Thus,
2000 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
2001 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2002 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2003 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2009 if confirmed_txid.is_none() {
2010 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
2011 // closed), just get the full set.
2013 return self.get_all_current_outbound_htlcs();
2016 let mut res = HashMap::new();
2017 macro_rules! walk_htlcs {
2018 ($holder_commitment: expr, $htlc_iter: expr) => {
2019 for (htlc, source) in $htlc_iter {
2020 if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc.transaction_output_index) {
2021 // We should assert that funding_spend_confirmed is_some() here, but we
2022 // have some unit tests which violate HTLC transaction CSVs entirely and
2024 // TODO: Once tests all connect transactions at consensus-valid times, we
2025 // should assert here like we do in `get_claimable_balances`.
2026 } else if htlc.offered == $holder_commitment {
2027 // If the payment was outbound, check if there's an HTLCUpdate
2028 // indicating we have spent this HTLC with a timeout, claiming it back
2029 // and awaiting confirmations on it.
2030 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2031 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
2032 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
2033 // before considering it "no longer pending" - this matches when we
2034 // provide the ChannelManager an HTLC failure event.
2035 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
2036 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
2037 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
2038 // If the HTLC was fulfilled with a preimage, we consider the HTLC
2039 // immediately non-pending, matching when we provide ChannelManager
2041 Some(commitment_tx_output_idx) == htlc.transaction_output_index
2044 let counterparty_resolved_preimage_opt =
2045 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned();
2046 if !htlc_update_confd || counterparty_resolved_preimage_opt.is_some() {
2047 res.insert(source.clone(), (htlc.clone(), counterparty_resolved_preimage_opt));
2054 let txid = confirmed_txid.unwrap();
2055 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2056 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
2057 if let &Some(ref source) = b {
2058 Some((a, &**source))
2061 } else if txid == us.current_holder_commitment_tx.txid {
2062 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
2063 if let Some(source) = c { Some((a, source)) } else { None }
2065 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2066 if txid == prev_commitment.txid {
2067 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
2068 if let Some(source) = c { Some((a, source)) } else { None }
2076 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
2077 self.inner.lock().unwrap().payment_preimages.clone()
2081 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
2082 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
2083 /// after ANTI_REORG_DELAY blocks.
2085 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
2086 /// are the commitment transactions which are generated by us. The off-chain state machine in
2087 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
2088 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
2089 /// included in a remote commitment transaction are failed back if they are not present in the
2090 /// broadcasted commitment transaction.
2092 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
2093 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
2094 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
2095 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
2096 macro_rules! fail_unbroadcast_htlcs {
2097 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2098 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2099 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
2101 macro_rules! check_htlc_fails {
2102 ($txid: expr, $commitment_tx: expr) => {
2103 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
2104 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2105 if let &Some(ref source) = source_option {
2106 // Check if the HTLC is present in the commitment transaction that was
2107 // broadcast, but not if it was below the dust limit, which we should
2108 // fail backwards immediately as there is no way for us to learn the
2109 // payment_preimage.
2110 // Note that if the dust limit were allowed to change between
2111 // commitment transactions we'd want to be check whether *any*
2112 // broadcastable commitment transaction has the HTLC in it, but it
2113 // cannot currently change after channel initialization, so we don't
2115 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2117 let mut matched_htlc = false;
2118 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2119 if broadcast_htlc.transaction_output_index.is_some() &&
2120 (Some(&**source) == *broadcast_source ||
2121 (broadcast_source.is_none() &&
2122 broadcast_htlc.payment_hash == htlc.payment_hash &&
2123 broadcast_htlc.amount_msat == htlc.amount_msat)) {
2124 matched_htlc = true;
2128 if matched_htlc { continue; }
2129 if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2132 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2133 if entry.height != $commitment_tx_conf_height { return true; }
2135 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2136 *update_source != **source
2141 let entry = OnchainEventEntry {
2142 txid: $commitment_txid_confirmed,
2143 transaction: Some($commitment_tx_confirmed.clone()),
2144 height: $commitment_tx_conf_height,
2145 block_hash: Some(*$commitment_tx_conf_hash),
2146 event: OnchainEvent::HTLCUpdate {
2147 source: (**source).clone(),
2148 payment_hash: htlc.payment_hash.clone(),
2149 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2150 commitment_tx_output_idx: None,
2153 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2154 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2155 $commitment_txid_confirmed, entry.confirmation_threshold());
2156 $self.onchain_events_awaiting_threshold_conf.push(entry);
2162 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2163 check_htlc_fails!(txid, "current");
2165 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2166 check_htlc_fails!(txid, "previous");
2171 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
2172 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
2173 // in-line tests later.
2176 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2177 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2178 ret[131] = opcodes::all::OP_DROP.to_u8();
2179 ret[132] = opcodes::all::OP_DROP.to_u8();
2180 ret[133] = opcodes::all::OP_DROP.to_u8();
2181 ret[134] = opcodes::all::OP_DROP.to_u8();
2182 ret[135] = opcodes::OP_TRUE.to_u8();
2187 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2188 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2191 impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2192 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
2193 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
2194 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
2195 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2196 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2197 return Err("Previous secret did not match new one");
2200 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
2201 // events for now-revoked/fulfilled HTLCs.
2202 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2203 if self.current_counterparty_commitment_txid.unwrap() != txid {
2204 let cur_claimables = self.counterparty_claimable_outpoints.get(
2205 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2206 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2207 if let Some(source) = source_opt {
2208 if !cur_claimables.iter()
2209 .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2211 self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2215 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2219 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2223 if !self.payment_preimages.is_empty() {
2224 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2225 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2226 let min_idx = self.get_min_seen_secret();
2227 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2229 self.payment_preimages.retain(|&k, _| {
2230 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2231 if k == htlc.payment_hash {
2235 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2236 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2237 if k == htlc.payment_hash {
2242 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2249 counterparty_hash_commitment_number.remove(&k);
2258 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_per_commitment_point: PublicKey, logger: &L) where L::Target: Logger {
2259 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2260 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2261 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2263 for &(ref htlc, _) in &htlc_outputs {
2264 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2267 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2268 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2269 self.current_counterparty_commitment_txid = Some(txid);
2270 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2271 self.current_counterparty_commitment_number = commitment_number;
2272 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2273 match self.their_cur_per_commitment_points {
2274 Some(old_points) => {
2275 if old_points.0 == commitment_number + 1 {
2276 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2277 } else if old_points.0 == commitment_number + 2 {
2278 if let Some(old_second_point) = old_points.2 {
2279 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2281 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2284 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2288 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2291 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2292 for htlc in htlc_outputs {
2293 if htlc.0.transaction_output_index.is_some() {
2299 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2300 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2301 /// is important that any clones of this channel monitor (including remote clones) by kept
2302 /// up-to-date as our holder commitment transaction is updated.
2303 /// Panics if set_on_holder_tx_csv has never been called.
2304 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, mut htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], nondust_htlc_sources: Vec<HTLCSource>) -> Result<(), &'static str> {
2305 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
2306 // If we have non-dust HTLCs in htlc_outputs, ensure they match the HTLCs in the
2307 // `holder_commitment_tx`. In the future, we'll no longer provide the redundant data
2308 // and just pass in source data via `nondust_htlc_sources`.
2309 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
2310 for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
2311 debug_assert_eq!(a, b);
2313 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
2314 for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
2315 debug_assert_eq!(a, b);
2317 debug_assert!(nondust_htlc_sources.is_empty());
2319 // If we don't have any non-dust HTLCs in htlc_outputs, assume they were all passed via
2320 // `nondust_htlc_sources`, building up the final htlc_outputs by combining
2321 // `nondust_htlc_sources` and the `holder_commitment_tx`
2322 #[cfg(debug_assertions)] {
2324 for htlc in holder_commitment_tx.trust().htlcs().iter() {
2325 assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
2326 prev = htlc.transaction_output_index.unwrap() as i32;
2329 debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
2330 debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
2331 debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
2333 let mut sources_iter = nondust_htlc_sources.into_iter();
2335 for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
2336 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
2339 let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
2340 #[cfg(debug_assertions)] {
2341 assert!(source.possibly_matches_output(htlc));
2343 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
2345 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
2348 debug_assert!(sources_iter.next().is_none());
2351 let trusted_tx = holder_commitment_tx.trust();
2352 let txid = trusted_tx.txid();
2353 let tx_keys = trusted_tx.keys();
2354 self.current_holder_commitment_number = trusted_tx.commitment_number();
2355 let mut new_holder_commitment_tx = HolderSignedTx {
2357 revocation_key: tx_keys.revocation_key,
2358 a_htlc_key: tx_keys.broadcaster_htlc_key,
2359 b_htlc_key: tx_keys.countersignatory_htlc_key,
2360 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2361 per_commitment_point: tx_keys.per_commitment_point,
2363 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2364 feerate_per_kw: trusted_tx.feerate_per_kw(),
2366 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2367 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2368 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2369 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2370 #[cfg(debug_assertions)] {
2371 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
2372 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2373 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
2374 if let Some(source) = source_opt {
2375 SentHTLCId::from_source(source) == *claimed_htlc_id
2379 self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
2381 if self.holder_tx_signed {
2382 return Err("Latest holder commitment signed has already been signed, update is rejected");
2387 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2388 /// commitment_tx_infos which contain the payment hash have been revoked.
2389 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2390 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2391 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
2392 where B::Target: BroadcasterInterface,
2393 F::Target: FeeEstimator,
2396 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2398 // If the channel is force closed, try to claim the output from this preimage.
2399 // First check if a counterparty commitment transaction has been broadcasted:
2400 macro_rules! claim_htlcs {
2401 ($commitment_number: expr, $txid: expr) => {
2402 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2403 self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2406 if let Some(txid) = self.current_counterparty_commitment_txid {
2407 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2408 claim_htlcs!(*commitment_number, txid);
2412 if let Some(txid) = self.prev_counterparty_commitment_txid {
2413 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2414 claim_htlcs!(*commitment_number, txid);
2419 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2420 // claiming the HTLC output from each of the holder commitment transactions.
2421 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2422 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2423 // holder commitment transactions.
2424 if self.broadcasted_holder_revokable_script.is_some() {
2425 // Assume that the broadcasted commitment transaction confirmed in the current best
2426 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2428 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2429 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2430 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
2431 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
2432 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2437 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
2438 where B::Target: BroadcasterInterface,
2441 let commit_txs = self.get_latest_holder_commitment_txn(logger);
2442 let mut txs = vec![];
2443 for tx in commit_txs.iter() {
2444 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
2447 broadcaster.broadcast_transactions(&txs);
2448 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2451 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
2452 where B::Target: BroadcasterInterface,
2453 F::Target: FeeEstimator,
2456 if self.latest_update_id == CLOSED_CHANNEL_UPDATE_ID && updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2457 log_info!(logger, "Applying post-force-closed update to monitor {} with {} change(s).",
2458 log_funding_info!(self), updates.updates.len());
2459 } else if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2460 log_info!(logger, "Applying force close update to monitor {} with {} change(s).",
2461 log_funding_info!(self), updates.updates.len());
2463 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
2464 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2466 // ChannelMonitor updates may be applied after force close if we receive a preimage for a
2467 // broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
2468 // is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
2469 // sentinel value instead.
2471 // The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
2472 // thinks the channel needs to have its commitment transaction broadcast, so we'll allow
2474 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2475 assert_eq!(updates.updates.len(), 1);
2476 match updates.updates[0] {
2477 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
2478 // We should have already seen a `ChannelForceClosed` update if we're trying to
2479 // provide a preimage at this point.
2480 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
2481 debug_assert_eq!(self.latest_update_id, CLOSED_CHANNEL_UPDATE_ID),
2483 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2484 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2487 } else if self.latest_update_id + 1 != updates.update_id {
2488 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2490 let mut ret = Ok(());
2491 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2492 for update in updates.updates.iter() {
2494 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
2495 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2496 if self.lockdown_from_offchain { panic!(); }
2497 if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone()) {
2498 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2499 log_error!(logger, " {}", e);
2503 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
2504 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2505 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2507 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2508 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2509 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2511 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2512 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2513 if let Err(e) = self.provide_secret(*idx, *secret) {
2514 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2515 log_error!(logger, " {}", e);
2519 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2520 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2521 self.lockdown_from_offchain = true;
2522 if *should_broadcast {
2523 // There's no need to broadcast our commitment transaction if we've seen one
2524 // confirmed (even with 1 confirmation) as it'll be rejected as
2525 // duplicate/conflicting.
2526 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
2527 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
2528 OnchainEvent::FundingSpendConfirmation { .. } => true,
2531 if detected_funding_spend {
2532 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
2535 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2536 // If the channel supports anchor outputs, we'll need to emit an external
2537 // event to be consumed such that a child transaction is broadcast with a
2538 // high enough feerate for the parent commitment transaction to confirm.
2539 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
2540 let funding_output = HolderFundingOutput::build(
2541 self.funding_redeemscript.clone(), self.channel_value_satoshis,
2542 self.onchain_tx_handler.channel_type_features().clone(),
2544 let best_block_height = self.best_block.height();
2545 let commitment_package = PackageTemplate::build_package(
2546 self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
2547 PackageSolvingData::HolderFundingOutput(funding_output),
2548 best_block_height, best_block_height
2550 self.onchain_tx_handler.update_claims_view_from_requests(
2551 vec![commitment_package], best_block_height, best_block_height,
2552 broadcaster, &bounded_fee_estimator, logger,
2555 } else if !self.holder_tx_signed {
2556 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
2557 log_error!(logger, " in channel monitor for channel {}!", log_bytes!(self.funding_info.0.to_channel_id()));
2558 log_error!(logger, " Read the docs for ChannelMonitor::get_latest_holder_commitment_txn and take manual action!");
2560 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2561 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2562 // shouldn't print the scary warning above.
2563 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2566 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2567 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2568 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2569 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2575 #[cfg(debug_assertions)] {
2576 self.counterparty_commitment_txs_from_update(updates);
2579 // If the updates succeeded and we were in an already closed channel state, then there's no
2580 // need to refuse any updates we expect to receive afer seeing a confirmed commitment.
2581 if ret.is_ok() && updates.update_id == CLOSED_CHANNEL_UPDATE_ID && self.latest_update_id == updates.update_id {
2585 self.latest_update_id = updates.update_id;
2587 // Refuse updates after we've detected a spend onchain, but only if we haven't processed a
2588 // force closed monitor update yet.
2589 if ret.is_ok() && self.funding_spend_seen && self.latest_update_id != CLOSED_CHANNEL_UPDATE_ID {
2590 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2595 pub fn get_latest_update_id(&self) -> u64 {
2596 self.latest_update_id
2599 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2603 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2604 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2605 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2606 // its trivial to do, double-check that here.
2607 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2608 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2610 &self.outputs_to_watch
2613 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2614 let mut ret = Vec::new();
2615 mem::swap(&mut ret, &mut self.pending_monitor_events);
2619 /// Gets the set of events that are repeated regularly (e.g. those which RBF bump
2620 /// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
2621 /// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
2622 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
2623 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
2624 let mut ret = Vec::with_capacity(pending_claim_events.len());
2625 for (claim_id, claim_event) in pending_claim_events {
2627 ClaimEvent::BumpCommitment {
2628 package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
2630 let commitment_txid = commitment_tx.txid();
2631 debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
2632 let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
2633 let commitment_tx_fee_satoshis = self.channel_value_satoshis -
2634 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value);
2635 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
2637 package_target_feerate_sat_per_1000_weight,
2639 commitment_tx_fee_satoshis,
2640 anchor_descriptor: AnchorDescriptor {
2641 channel_derivation_parameters: ChannelDerivationParameters {
2642 keys_id: self.channel_keys_id,
2643 value_satoshis: self.channel_value_satoshis,
2644 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
2646 outpoint: BitcoinOutPoint {
2647 txid: commitment_txid,
2648 vout: anchor_output_idx,
2654 ClaimEvent::BumpHTLC {
2655 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
2657 let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
2659 htlc_descriptors.push(HTLCDescriptor {
2660 channel_derivation_parameters: ChannelDerivationParameters {
2661 keys_id: self.channel_keys_id,
2662 value_satoshis: self.channel_value_satoshis,
2663 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
2665 commitment_txid: htlc.commitment_txid,
2666 per_commitment_number: htlc.per_commitment_number,
2667 per_commitment_point: self.onchain_tx_handler.signer.get_per_commitment_point(
2668 htlc.per_commitment_number, &self.onchain_tx_handler.secp_ctx,
2671 preimage: htlc.preimage,
2672 counterparty_sig: htlc.counterparty_sig,
2675 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
2677 target_feerate_sat_per_1000_weight,
2687 fn build_counterparty_commitment_tx(
2688 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
2689 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
2690 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
2691 ) -> CommitmentTransaction {
2692 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
2693 .counterparty_parameters.as_ref().unwrap().pubkeys;
2694 let countersignatory_keys =
2695 &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
2697 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
2698 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
2699 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
2700 &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
2701 let channel_parameters =
2702 &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
2704 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
2705 to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
2706 countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
2710 pub(crate) fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
2711 update.updates.iter().filter_map(|update| {
2713 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
2714 ref htlc_outputs, commitment_number, their_per_commitment_point,
2715 feerate_per_kw: Some(feerate_per_kw),
2716 to_broadcaster_value_sat: Some(to_broadcaster_value),
2717 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
2719 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
2720 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
2721 }).collect::<Vec<_>>();
2723 let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
2724 &their_per_commitment_point, to_broadcaster_value,
2725 to_countersignatory_value, feerate_per_kw, nondust_htlcs);
2727 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
2736 /// Can only fail if idx is < get_min_seen_secret
2737 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2738 self.commitment_secrets.get_secret(idx)
2741 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2742 self.commitment_secrets.get_min_seen_secret()
2745 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2746 self.current_counterparty_commitment_number
2749 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2750 self.current_holder_commitment_number
2753 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2754 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2755 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2756 /// HTLC-Success/HTLC-Timeout transactions.
2758 /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
2759 /// general information about the output that is to the counterparty in the commitment
2761 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
2762 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
2763 where L::Target: Logger {
2764 // Most secp and related errors trying to create keys means we have no hope of constructing
2765 // a spend transaction...so we return no transactions to broadcast
2766 let mut claimable_outpoints = Vec::new();
2767 let mut watch_outputs = Vec::new();
2768 let mut to_counterparty_output_info = None;
2770 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2771 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2773 macro_rules! ignore_error {
2774 ( $thing : expr ) => {
2777 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2782 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (tx.lock_time.0 as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
2783 if commitment_number >= self.get_min_seen_secret() {
2784 let secret = self.get_secret(commitment_number).unwrap();
2785 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2786 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
2787 let revocation_pubkey = chan_utils::derive_public_revocation_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint);
2788 let delayed_key = chan_utils::derive_public_key(&self.onchain_tx_handler.secp_ctx, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key);
2790 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2791 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2793 // First, process non-htlc outputs (to_holder & to_counterparty)
2794 for (idx, outp) in tx.output.iter().enumerate() {
2795 if outp.script_pubkey == revokeable_p2wsh {
2796 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv, self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2797 let justice_package = PackageTemplate::build_package(commitment_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, height);
2798 claimable_outpoints.push(justice_package);
2799 to_counterparty_output_info =
2800 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
2804 // Then, try to find revoked htlc outputs
2805 if let Some(ref per_commitment_data) = per_commitment_option {
2806 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2807 if let Some(transaction_output_index) = htlc.transaction_output_index {
2808 if transaction_output_index as usize >= tx.output.len() ||
2809 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2810 // per_commitment_data is corrupt or our commitment signing key leaked!
2811 return (claimable_outpoints, (commitment_txid, watch_outputs),
2812 to_counterparty_output_info);
2814 let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone(), &self.onchain_tx_handler.channel_transaction_parameters.channel_type_features);
2815 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, height);
2816 claimable_outpoints.push(justice_package);
2821 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2822 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2823 // We're definitely a counterparty commitment transaction!
2824 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2825 for (idx, outp) in tx.output.iter().enumerate() {
2826 watch_outputs.push((idx as u32, outp.clone()));
2828 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2830 if let Some(per_commitment_data) = per_commitment_option {
2831 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
2832 block_hash, per_commitment_data.iter().map(|(htlc, htlc_source)|
2833 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2836 debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2837 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
2838 block_hash, [].iter().map(|reference| *reference), logger);
2841 } else if let Some(per_commitment_data) = per_commitment_option {
2842 // While this isn't useful yet, there is a potential race where if a counterparty
2843 // revokes a state at the same time as the commitment transaction for that state is
2844 // confirmed, and the watchtower receives the block before the user, the user could
2845 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2846 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2847 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2849 for (idx, outp) in tx.output.iter().enumerate() {
2850 watch_outputs.push((idx as u32, outp.clone()));
2852 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2854 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2855 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
2856 per_commitment_data.iter().map(|(htlc, htlc_source)|
2857 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2860 let (htlc_claim_reqs, counterparty_output_info) =
2861 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
2862 to_counterparty_output_info = counterparty_output_info;
2863 for req in htlc_claim_reqs {
2864 claimable_outpoints.push(req);
2868 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2871 /// Returns the HTLC claim package templates and the counterparty output info
2872 fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
2873 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
2874 let mut claimable_outpoints = Vec::new();
2875 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
2877 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
2878 Some(outputs) => outputs,
2879 None => return (claimable_outpoints, to_counterparty_output_info),
2881 let per_commitment_points = match self.their_cur_per_commitment_points {
2882 Some(points) => points,
2883 None => return (claimable_outpoints, to_counterparty_output_info),
2886 let per_commitment_point =
2887 // If the counterparty commitment tx is the latest valid state, use their latest
2888 // per-commitment point
2889 if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
2890 else if let Some(point) = per_commitment_points.2.as_ref() {
2891 // If counterparty commitment tx is the state previous to the latest valid state, use
2892 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2893 // them to temporarily have two valid commitment txns from our viewpoint)
2894 if per_commitment_points.0 == commitment_number + 1 {
2896 } else { return (claimable_outpoints, to_counterparty_output_info); }
2897 } else { return (claimable_outpoints, to_counterparty_output_info); };
2899 if let Some(transaction) = tx {
2900 let revocation_pubkey = chan_utils::derive_public_revocation_key(
2901 &self.onchain_tx_handler.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint);
2902 let delayed_key = chan_utils::derive_public_key(&self.onchain_tx_handler.secp_ctx,
2903 &per_commitment_point,
2904 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key);
2905 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2906 self.counterparty_commitment_params.on_counterparty_tx_csv,
2907 &delayed_key).to_v0_p2wsh();
2908 for (idx, outp) in transaction.output.iter().enumerate() {
2909 if outp.script_pubkey == revokeable_p2wsh {
2910 to_counterparty_output_info =
2911 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2916 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2917 if let Some(transaction_output_index) = htlc.transaction_output_index {
2918 if let Some(transaction) = tx {
2919 if transaction_output_index as usize >= transaction.output.len() ||
2920 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2921 // per_commitment_data is corrupt or our commitment signing key leaked!
2922 return (claimable_outpoints, to_counterparty_output_info);
2925 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2926 if preimage.is_some() || !htlc.offered {
2927 let counterparty_htlc_outp = if htlc.offered {
2928 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2929 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2930 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2931 self.counterparty_commitment_params.counterparty_htlc_base_key,
2932 preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
2934 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2935 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2936 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2937 self.counterparty_commitment_params.counterparty_htlc_base_key,
2938 htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
2940 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry, 0);
2941 claimable_outpoints.push(counterparty_package);
2946 (claimable_outpoints, to_counterparty_output_info)
2949 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2950 fn check_spend_counterparty_htlc<L: Deref>(
2951 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
2952 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
2953 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2954 let per_commitment_key = match SecretKey::from_slice(&secret) {
2956 Err(_) => return (Vec::new(), None)
2958 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
2960 let htlc_txid = tx.txid();
2961 let mut claimable_outpoints = vec![];
2962 let mut outputs_to_watch = None;
2963 // Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
2964 // with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
2965 // counterparty can now aggregate multiple HTLCs into a single transaction thanks to
2966 // `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
2967 // confirmed revoked HTLC transaction (for more details, see
2968 // https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
2970 // We make sure we're not vulnerable to this case by checking all inputs of the transaction,
2971 // and claim those which spend the commitment transaction, have a witness of 5 elements, and
2972 // have a corresponding output at the same index within the transaction.
2973 for (idx, input) in tx.input.iter().enumerate() {
2974 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
2975 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
2976 let revk_outp = RevokedOutput::build(
2977 per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2978 self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
2979 tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
2982 let justice_package = PackageTemplate::build_package(
2983 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
2984 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, height
2986 claimable_outpoints.push(justice_package);
2987 if outputs_to_watch.is_none() {
2988 outputs_to_watch = Some((htlc_txid, vec![]));
2990 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
2993 (claimable_outpoints, outputs_to_watch)
2996 // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
2997 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2998 // script so we can detect whether a holder transaction has been seen on-chain.
2999 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
3000 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3002 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3003 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3005 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3006 if let Some(transaction_output_index) = htlc.transaction_output_index {
3007 let htlc_output = if htlc.offered {
3008 let htlc_output = HolderHTLCOutput::build_offered(
3009 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone()
3013 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
3016 // We can't build an HTLC-Success transaction without the preimage
3019 let htlc_output = HolderHTLCOutput::build_accepted(
3020 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone()
3024 let htlc_package = PackageTemplate::build_package(
3025 holder_tx.txid, transaction_output_index,
3026 PackageSolvingData::HolderHTLCOutput(htlc_output),
3027 htlc.cltv_expiry, conf_height
3029 claim_requests.push(htlc_package);
3033 (claim_requests, broadcasted_holder_revokable_script)
3036 // Returns holder HTLC outputs to watch and react to in case of spending.
3037 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3038 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3039 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3040 if let Some(transaction_output_index) = htlc.transaction_output_index {
3041 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3047 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
3048 /// revoked using data in holder_claimable_outpoints.
3049 /// Should not be used if check_spend_revoked_transaction succeeds.
3050 /// Returns None unless the transaction is definitely one of our commitment transactions.
3051 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
3052 let commitment_txid = tx.txid();
3053 let mut claim_requests = Vec::new();
3054 let mut watch_outputs = Vec::new();
3056 macro_rules! append_onchain_update {
3057 ($updates: expr, $to_watch: expr) => {
3058 claim_requests = $updates.0;
3059 self.broadcasted_holder_revokable_script = $updates.1;
3060 watch_outputs.append(&mut $to_watch);
3064 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
3065 let mut is_holder_tx = false;
3067 if self.current_holder_commitment_tx.txid == commitment_txid {
3068 is_holder_tx = true;
3069 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3070 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3071 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3072 append_onchain_update!(res, to_watch);
3073 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3074 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3075 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3076 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3077 if holder_tx.txid == commitment_txid {
3078 is_holder_tx = true;
3079 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3080 let res = self.get_broadcasted_holder_claims(holder_tx, height);
3081 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3082 append_onchain_update!(res, to_watch);
3083 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3084 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3090 Some((claim_requests, (commitment_txid, watch_outputs)))
3096 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
3097 log_debug!(logger, "Getting signed latest holder commitment transaction!");
3098 self.holder_tx_signed = true;
3099 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
3100 let txid = commitment_tx.txid();
3101 let mut holder_transactions = vec![commitment_tx];
3102 // When anchor outputs are present, the HTLC transactions are only valid once the commitment
3103 // transaction confirms.
3104 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3105 return holder_transactions;
3107 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3108 if let Some(vout) = htlc.0.transaction_output_index {
3109 let preimage = if !htlc.0.offered {
3110 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3111 // We can't build an HTLC-Success transaction without the preimage
3114 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
3115 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
3116 // current locktime requirements on-chain. We will broadcast them in
3117 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
3118 // Note that we add + 1 as transactions are broadcastable when they can be
3119 // confirmed in the next block.
3122 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
3123 &::bitcoin::OutPoint { txid, vout }, &preimage) {
3124 holder_transactions.push(htlc_tx);
3128 // 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.
3129 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
3133 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3134 /// Note that this includes possibly-locktimed-in-the-future transactions!
3135 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
3136 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3137 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3138 let txid = commitment_tx.txid();
3139 let mut holder_transactions = vec![commitment_tx];
3140 // When anchor outputs are present, the HTLC transactions are only final once the commitment
3141 // transaction confirms due to the CSV 1 encumberance.
3142 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3143 return holder_transactions;
3145 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3146 if let Some(vout) = htlc.0.transaction_output_index {
3147 let preimage = if !htlc.0.offered {
3148 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3149 // We can't build an HTLC-Success transaction without the preimage
3153 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
3154 &::bitcoin::OutPoint { txid, vout }, &preimage) {
3155 holder_transactions.push(htlc_tx);
3162 pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L) -> Vec<TransactionOutputs>
3163 where B::Target: BroadcasterInterface,
3164 F::Target: FeeEstimator,
3167 let block_hash = header.block_hash();
3168 self.best_block = BestBlock::new(block_hash, height);
3170 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3171 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3174 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3176 header: &BlockHeader,
3179 fee_estimator: &LowerBoundedFeeEstimator<F>,
3181 ) -> Vec<TransactionOutputs>
3183 B::Target: BroadcasterInterface,
3184 F::Target: FeeEstimator,
3187 let block_hash = header.block_hash();
3189 if height > self.best_block.height() {
3190 self.best_block = BestBlock::new(block_hash, height);
3191 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
3192 } else if block_hash != self.best_block.block_hash() {
3193 self.best_block = BestBlock::new(block_hash, height);
3194 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3195 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
3197 } else { Vec::new() }
3200 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3202 header: &BlockHeader,
3203 txdata: &TransactionData,
3206 fee_estimator: &LowerBoundedFeeEstimator<F>,
3208 ) -> Vec<TransactionOutputs>
3210 B::Target: BroadcasterInterface,
3211 F::Target: FeeEstimator,
3214 let txn_matched = self.filter_block(txdata);
3215 for tx in &txn_matched {
3216 let mut output_val = 0;
3217 for out in tx.output.iter() {
3218 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3219 output_val += out.value;
3220 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
3224 let block_hash = header.block_hash();
3226 let mut watch_outputs = Vec::new();
3227 let mut claimable_outpoints = Vec::new();
3228 'tx_iter: for tx in &txn_matched {
3229 let txid = tx.txid();
3230 // If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
3231 if Some(txid) == self.funding_spend_confirmed {
3232 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
3235 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
3236 if ev.txid == txid {
3237 if let Some(conf_hash) = ev.block_hash {
3238 assert_eq!(header.block_hash(), conf_hash,
3239 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
3240 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
3242 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
3246 for htlc in self.htlcs_resolved_on_chain.iter() {
3247 if Some(txid) == htlc.resolving_txid {
3248 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
3252 for spendable_txid in self.spendable_txids_confirmed.iter() {
3253 if txid == *spendable_txid {
3254 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
3259 if tx.input.len() == 1 {
3260 // Assuming our keys were not leaked (in which case we're screwed no matter what),
3261 // commitment transactions and HTLC transactions will all only ever have one input
3262 // (except for HTLC transactions for channels with anchor outputs), which is an easy
3263 // way to filter out any potential non-matching txn for lazy filters.
3264 let prevout = &tx.input[0].previous_output;
3265 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
3266 let mut balance_spendable_csv = None;
3267 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
3268 log_bytes!(self.funding_info.0.to_channel_id()), txid);
3269 self.funding_spend_seen = true;
3270 let mut commitment_tx_to_counterparty_output = None;
3271 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
3272 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
3273 self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
3274 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
3275 if !new_outputs.1.is_empty() {
3276 watch_outputs.push(new_outputs);
3278 claimable_outpoints.append(&mut new_outpoints);
3279 if new_outpoints.is_empty() {
3280 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
3281 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
3282 "A commitment transaction matched as both a counterparty and local commitment tx?");
3283 if !new_outputs.1.is_empty() {
3284 watch_outputs.push(new_outputs);
3286 claimable_outpoints.append(&mut new_outpoints);
3287 balance_spendable_csv = Some(self.on_holder_tx_csv);
3291 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3293 transaction: Some((*tx).clone()),
3295 block_hash: Some(block_hash),
3296 event: OnchainEvent::FundingSpendConfirmation {
3297 on_local_output_csv: balance_spendable_csv,
3298 commitment_tx_to_counterparty_output,
3303 if tx.input.len() >= 1 {
3304 // While all commitment transactions have one input, HTLC transactions may have more
3305 // if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
3306 // other ways which can have more than one output.
3307 for tx_input in &tx.input {
3308 let commitment_txid = tx_input.previous_output.txid;
3309 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
3310 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
3311 &tx, commitment_number, &commitment_txid, height, &logger
3313 claimable_outpoints.append(&mut new_outpoints);
3314 if let Some(new_outputs) = new_outputs_option {
3315 watch_outputs.push(new_outputs);
3317 // Since there may be multiple HTLCs for this channel (all spending the
3318 // same commitment tx) being claimed by the counterparty within the same
3319 // transaction, and `check_spend_counterparty_htlc` already checks all the
3320 // ones relevant to this channel, we can safely break from our loop.
3324 self.is_resolving_htlc_output(&tx, height, &block_hash, &logger);
3326 self.is_paying_spendable_output(&tx, height, &block_hash, &logger);
3330 if height > self.best_block.height() {
3331 self.best_block = BestBlock::new(block_hash, height);
3334 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
3337 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
3338 /// `self.best_block` before calling if a new best blockchain tip is available. More
3339 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
3340 /// complexity especially in
3341 /// `OnchainTx::update_claims_view_from_requests`/`OnchainTx::update_claims_view_from_matched_txn`.
3343 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
3344 /// confirmed at, even if it is not the current best height.
3345 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
3348 conf_hash: BlockHash,
3349 txn_matched: Vec<&Transaction>,
3350 mut watch_outputs: Vec<TransactionOutputs>,
3351 mut claimable_outpoints: Vec<PackageTemplate>,
3353 fee_estimator: &LowerBoundedFeeEstimator<F>,
3355 ) -> Vec<TransactionOutputs>
3357 B::Target: BroadcasterInterface,
3358 F::Target: FeeEstimator,
3361 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
3362 debug_assert!(self.best_block.height() >= conf_height);
3364 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
3365 if should_broadcast {
3366 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone(), self.channel_value_satoshis, self.onchain_tx_handler.channel_type_features().clone());
3367 let commitment_package = PackageTemplate::build_package(self.funding_info.0.txid.clone(), self.funding_info.0.index as u32, PackageSolvingData::HolderFundingOutput(funding_outp), self.best_block.height(), self.best_block.height());
3368 claimable_outpoints.push(commitment_package);
3369 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
3370 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
3371 self.holder_tx_signed = true;
3372 // We can't broadcast our HTLC transactions while the commitment transaction is
3373 // unconfirmed. We'll delay doing so until we detect the confirmed commitment in
3374 // `transactions_confirmed`.
3375 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3376 // Because we're broadcasting a commitment transaction, we should construct the package
3377 // assuming it gets confirmed in the next block. Sadly, we have code which considers
3378 // "not yet confirmed" things as discardable, so we cannot do that here.
3379 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
3380 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
3381 if !new_outputs.is_empty() {
3382 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
3384 claimable_outpoints.append(&mut new_outpoints);
3388 // Find which on-chain events have reached their confirmation threshold.
3389 let onchain_events_awaiting_threshold_conf =
3390 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
3391 let mut onchain_events_reaching_threshold_conf = Vec::new();
3392 for entry in onchain_events_awaiting_threshold_conf {
3393 if entry.has_reached_confirmation_threshold(&self.best_block) {
3394 onchain_events_reaching_threshold_conf.push(entry);
3396 self.onchain_events_awaiting_threshold_conf.push(entry);
3400 // Used to check for duplicate HTLC resolutions.
3401 #[cfg(debug_assertions)]
3402 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
3404 .filter_map(|entry| match &entry.event {
3405 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
3409 #[cfg(debug_assertions)]
3410 let mut matured_htlcs = Vec::new();
3412 // Produce actionable events from on-chain events having reached their threshold.
3413 for entry in onchain_events_reaching_threshold_conf.drain(..) {
3415 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
3416 // Check for duplicate HTLC resolutions.
3417 #[cfg(debug_assertions)]
3420 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
3421 "An unmature HTLC transaction conflicts with a maturing one; failed to \
3422 call either transaction_unconfirmed for the conflicting transaction \
3423 or block_disconnected for a block containing it.");
3425 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
3426 "A matured HTLC transaction conflicts with a maturing one; failed to \
3427 call either transaction_unconfirmed for the conflicting transaction \
3428 or block_disconnected for a block containing it.");
3429 matured_htlcs.push(source.clone());
3432 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
3433 &payment_hash, entry.txid);
3434 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3436 payment_preimage: None,
3437 source: source.clone(),
3438 htlc_value_satoshis,
3440 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3441 commitment_tx_output_idx,
3442 resolving_txid: Some(entry.txid),
3443 resolving_tx: entry.transaction,
3444 payment_preimage: None,
3447 OnchainEvent::MaturingOutput { descriptor } => {
3448 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
3449 self.pending_events.push(Event::SpendableOutputs {
3450 outputs: vec![descriptor],
3451 channel_id: Some(self.funding_info.0.to_channel_id()),
3453 self.spendable_txids_confirmed.push(entry.txid);
3455 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
3456 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
3457 commitment_tx_output_idx: Some(commitment_tx_output_idx),
3458 resolving_txid: Some(entry.txid),
3459 resolving_tx: entry.transaction,
3460 payment_preimage: preimage,
3463 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
3464 self.funding_spend_confirmed = Some(entry.txid);
3465 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
3470 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
3471 self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height(), broadcaster, fee_estimator, logger);
3473 // Determine new outputs to watch by comparing against previously known outputs to watch,
3474 // updating the latter in the process.
3475 watch_outputs.retain(|&(ref txid, ref txouts)| {
3476 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
3477 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
3481 // If we see a transaction for which we registered outputs previously,
3482 // make sure the registered scriptpubkey at the expected index match
3483 // the actual transaction output one. We failed this case before #653.
3484 for tx in &txn_matched {
3485 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
3486 for idx_and_script in outputs.iter() {
3487 assert!((idx_and_script.0 as usize) < tx.output.len());
3488 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
3496 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
3497 where B::Target: BroadcasterInterface,
3498 F::Target: FeeEstimator,
3501 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
3504 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
3505 //- maturing spendable output has transaction paying us has been disconnected
3506 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
3508 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3509 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
3511 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
3514 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
3518 fee_estimator: &LowerBoundedFeeEstimator<F>,
3521 B::Target: BroadcasterInterface,
3522 F::Target: FeeEstimator,
3525 let mut removed_height = None;
3526 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
3527 if entry.txid == *txid {
3528 removed_height = Some(entry.height);
3533 if let Some(removed_height) = removed_height {
3534 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
3535 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
3536 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
3541 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
3543 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
3546 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
3547 /// transactions thereof.
3548 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
3549 let mut matched_txn = HashSet::new();
3550 txdata.iter().filter(|&&(_, tx)| {
3551 let mut matches = self.spends_watched_output(tx);
3552 for input in tx.input.iter() {
3553 if matches { break; }
3554 if matched_txn.contains(&input.previous_output.txid) {
3559 matched_txn.insert(tx.txid());
3562 }).map(|(_, tx)| *tx).collect()
3565 /// Checks if a given transaction spends any watched outputs.
3566 fn spends_watched_output(&self, tx: &Transaction) -> bool {
3567 for input in tx.input.iter() {
3568 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
3569 for (idx, _script_pubkey) in outputs.iter() {
3570 if *idx == input.previous_output.vout {
3573 // If the expected script is a known type, check that the witness
3574 // appears to be spending the correct type (ie that the match would
3575 // actually succeed in BIP 158/159-style filters).
3576 if _script_pubkey.is_v0_p2wsh() {
3577 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
3578 // In at least one test we use a deliberately bogus witness
3579 // script which hit an old panic. Thus, we check for that here
3580 // and avoid the assert if its the expected bogus script.
3584 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
3585 } else if _script_pubkey.is_v0_p2wpkh() {
3586 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
3587 } else { panic!(); }
3598 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
3599 // There's no need to broadcast our commitment transaction if we've seen one confirmed (even
3600 // with 1 confirmation) as it'll be rejected as duplicate/conflicting.
3601 if self.funding_spend_confirmed.is_some() ||
3602 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
3603 OnchainEvent::FundingSpendConfirmation { .. } => true,
3609 // We need to consider all HTLCs which are:
3610 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
3611 // transactions and we'd end up in a race, or
3612 // * are in our latest holder commitment transaction, as this is the thing we will
3613 // broadcast if we go on-chain.
3614 // Note that we consider HTLCs which were below dust threshold here - while they don't
3615 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
3616 // to the source, and if we don't fail the channel we will have to ensure that the next
3617 // updates that peer sends us are update_fails, failing the channel if not. It's probably
3618 // easier to just fail the channel as this case should be rare enough anyway.
3619 let height = self.best_block.height();
3620 macro_rules! scan_commitment {
3621 ($htlcs: expr, $holder_tx: expr) => {
3622 for ref htlc in $htlcs {
3623 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
3624 // chain with enough room to claim the HTLC without our counterparty being able to
3625 // time out the HTLC first.
3626 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
3627 // concern is being able to claim the corresponding inbound HTLC (on another
3628 // channel) before it expires. In fact, we don't even really care if our
3629 // counterparty here claims such an outbound HTLC after it expired as long as we
3630 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
3631 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
3632 // we give ourselves a few blocks of headroom after expiration before going
3633 // on-chain for an expired HTLC.
3634 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
3635 // from us until we've reached the point where we go on-chain with the
3636 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
3637 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
3638 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
3639 // inbound_cltv == height + CLTV_CLAIM_BUFFER
3640 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
3641 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
3642 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
3643 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
3644 // The final, above, condition is checked for statically in channelmanager
3645 // with CHECK_CLTV_EXPIRY_SANITY_2.
3646 let htlc_outbound = $holder_tx == htlc.offered;
3647 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
3648 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
3649 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
3656 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
3658 if let Some(ref txid) = self.current_counterparty_commitment_txid {
3659 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3660 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3663 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
3664 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3665 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3672 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
3673 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
3674 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) where L::Target: Logger {
3675 'outer_loop: for input in &tx.input {
3676 let mut payment_data = None;
3677 let htlc_claim = HTLCClaim::from_witness(&input.witness);
3678 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
3679 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
3680 #[cfg(not(fuzzing))]
3681 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
3682 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
3683 #[cfg(not(fuzzing))]
3684 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
3686 let mut payment_preimage = PaymentPreimage([0; 32]);
3687 if offered_preimage_claim || accepted_preimage_claim {
3688 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3691 macro_rules! log_claim {
3692 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
3693 let outbound_htlc = $holder_tx == $htlc.offered;
3694 // HTLCs must either be claimed by a matching script type or through the
3696 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3697 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
3698 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3699 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
3700 // Further, only exactly one of the possible spend paths should have been
3701 // matched by any HTLC spend:
3702 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3703 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
3704 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
3705 revocation_sig_claim as u8, 1);
3706 if ($holder_tx && revocation_sig_claim) ||
3707 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
3708 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
3709 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3710 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
3711 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
3713 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
3714 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3715 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
3716 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
3721 macro_rules! check_htlc_valid_counterparty {
3722 ($counterparty_txid: expr, $htlc_output: expr) => {
3723 if let Some(txid) = $counterparty_txid {
3724 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
3725 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
3726 if let &Some(ref source) = pending_source {
3727 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
3728 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
3737 macro_rules! scan_commitment {
3738 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
3739 for (ref htlc_output, source_option) in $htlcs {
3740 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
3741 if let Some(ref source) = source_option {
3742 log_claim!($tx_info, $holder_tx, htlc_output, true);
3743 // We have a resolution of an HTLC either from one of our latest
3744 // holder commitment transactions or an unrevoked counterparty commitment
3745 // transaction. This implies we either learned a preimage, the HTLC
3746 // has timed out, or we screwed up. In any case, we should now
3747 // resolve the source HTLC with the original sender.
3748 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
3749 } else if !$holder_tx {
3750 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3751 if payment_data.is_none() {
3752 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3755 if payment_data.is_none() {
3756 log_claim!($tx_info, $holder_tx, htlc_output, false);
3757 let outbound_htlc = $holder_tx == htlc_output.offered;
3758 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3759 txid: tx.txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
3760 event: OnchainEvent::HTLCSpendConfirmation {
3761 commitment_tx_output_idx: input.previous_output.vout,
3762 preimage: if accepted_preimage_claim || offered_preimage_claim {
3763 Some(payment_preimage) } else { None },
3764 // If this is a payment to us (ie !outbound_htlc), wait for
3765 // the CSV delay before dropping the HTLC from claimable
3766 // balance if the claim was an HTLC-Success transaction (ie
3767 // accepted_preimage_claim).
3768 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
3769 Some(self.on_holder_tx_csv) } else { None },
3772 continue 'outer_loop;
3779 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3780 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3781 "our latest holder commitment tx", true);
3783 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3784 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3785 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3786 "our previous holder commitment tx", true);
3789 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3790 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3791 "counterparty commitment tx", false);
3794 // Check that scan_commitment, above, decided there is some source worth relaying an
3795 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3796 if let Some((source, payment_hash, amount_msat)) = payment_data {
3797 if accepted_preimage_claim {
3798 if !self.pending_monitor_events.iter().any(
3799 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3800 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3803 block_hash: Some(*block_hash),
3804 transaction: Some(tx.clone()),
3805 event: OnchainEvent::HTLCSpendConfirmation {
3806 commitment_tx_output_idx: input.previous_output.vout,
3807 preimage: Some(payment_preimage),
3808 on_to_local_output_csv: None,
3811 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3813 payment_preimage: Some(payment_preimage),
3815 htlc_value_satoshis: Some(amount_msat / 1000),
3818 } else if offered_preimage_claim {
3819 if !self.pending_monitor_events.iter().any(
3820 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3821 upd.source == source
3823 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3825 transaction: Some(tx.clone()),
3827 block_hash: Some(*block_hash),
3828 event: OnchainEvent::HTLCSpendConfirmation {
3829 commitment_tx_output_idx: input.previous_output.vout,
3830 preimage: Some(payment_preimage),
3831 on_to_local_output_csv: None,
3834 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3836 payment_preimage: Some(payment_preimage),
3838 htlc_value_satoshis: Some(amount_msat / 1000),
3842 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3843 if entry.height != height { return true; }
3845 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3846 *htlc_source != source
3851 let entry = OnchainEventEntry {
3853 transaction: Some(tx.clone()),
3855 block_hash: Some(*block_hash),
3856 event: OnchainEvent::HTLCUpdate {
3857 source, payment_hash,
3858 htlc_value_satoshis: Some(amount_msat / 1000),
3859 commitment_tx_output_idx: Some(input.previous_output.vout),
3862 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
3863 self.onchain_events_awaiting_threshold_conf.push(entry);
3869 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3870 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) where L::Target: Logger {
3871 let mut spendable_output = None;
3872 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3873 if i > ::core::u16::MAX as usize {
3874 // While it is possible that an output exists on chain which is greater than the
3875 // 2^16th output in a given transaction, this is only possible if the output is not
3876 // in a lightning transaction and was instead placed there by some third party who
3877 // wishes to give us money for no reason.
3878 // Namely, any lightning transactions which we pre-sign will never have anywhere
3879 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3880 // scripts are not longer than one byte in length and because they are inherently
3881 // non-standard due to their size.
3882 // Thus, it is completely safe to ignore such outputs, and while it may result in
3883 // us ignoring non-lightning fund to us, that is only possible if someone fills
3884 // nearly a full block with garbage just to hit this case.
3887 if outp.script_pubkey == self.destination_script {
3888 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3889 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3890 output: outp.clone(),
3894 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3895 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3896 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3897 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3898 per_commitment_point: broadcasted_holder_revokable_script.1,
3899 to_self_delay: self.on_holder_tx_csv,
3900 output: outp.clone(),
3901 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3902 channel_keys_id: self.channel_keys_id,
3903 channel_value_satoshis: self.channel_value_satoshis,
3908 if self.counterparty_payment_script == outp.script_pubkey {
3909 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3910 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3911 output: outp.clone(),
3912 channel_keys_id: self.channel_keys_id,
3913 channel_value_satoshis: self.channel_value_satoshis,
3917 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3918 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3919 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3920 output: outp.clone(),
3925 if let Some(spendable_output) = spendable_output {
3926 let entry = OnchainEventEntry {
3928 transaction: Some(tx.clone()),
3930 block_hash: Some(*block_hash),
3931 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3933 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3934 self.onchain_events_awaiting_threshold_conf.push(entry);
3939 impl<Signer: WriteableEcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3941 T::Target: BroadcasterInterface,
3942 F::Target: FeeEstimator,
3945 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3946 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3949 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3950 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3954 impl<Signer: WriteableEcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
3956 M: Deref<Target = ChannelMonitor<Signer>>,
3957 T::Target: BroadcasterInterface,
3958 F::Target: FeeEstimator,
3961 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3962 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3965 fn transaction_unconfirmed(&self, txid: &Txid) {
3966 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3969 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3970 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3973 fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
3974 self.0.get_relevant_txids()
3978 const MAX_ALLOC_SIZE: usize = 64*1024;
3980 impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
3981 for (BlockHash, ChannelMonitor<SP::Signer>) {
3982 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
3983 macro_rules! unwrap_obj {
3987 Err(_) => return Err(DecodeError::InvalidValue),
3992 let (entropy_source, signer_provider) = args;
3994 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3996 let latest_update_id: u64 = Readable::read(reader)?;
3997 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3999 let destination_script = Readable::read(reader)?;
4000 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4002 let revokable_address = Readable::read(reader)?;
4003 let per_commitment_point = Readable::read(reader)?;
4004 let revokable_script = Readable::read(reader)?;
4005 Some((revokable_address, per_commitment_point, revokable_script))
4008 _ => return Err(DecodeError::InvalidValue),
4010 let counterparty_payment_script = Readable::read(reader)?;
4011 let shutdown_script = {
4012 let script = <Script as Readable>::read(reader)?;
4013 if script.is_empty() { None } else { Some(script) }
4016 let channel_keys_id = Readable::read(reader)?;
4017 let holder_revocation_basepoint = Readable::read(reader)?;
4018 // Technically this can fail and serialize fail a round-trip, but only for serialization of
4019 // barely-init'd ChannelMonitors that we can't do anything with.
4020 let outpoint = OutPoint {
4021 txid: Readable::read(reader)?,
4022 index: Readable::read(reader)?,
4024 let funding_info = (outpoint, Readable::read(reader)?);
4025 let current_counterparty_commitment_txid = Readable::read(reader)?;
4026 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4028 let counterparty_commitment_params = Readable::read(reader)?;
4029 let funding_redeemscript = Readable::read(reader)?;
4030 let channel_value_satoshis = Readable::read(reader)?;
4032 let their_cur_per_commitment_points = {
4033 let first_idx = <U48 as Readable>::read(reader)?.0;
4037 let first_point = Readable::read(reader)?;
4038 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4039 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4040 Some((first_idx, first_point, None))
4042 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4047 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4049 let commitment_secrets = Readable::read(reader)?;
4051 macro_rules! read_htlc_in_commitment {
4054 let offered: bool = Readable::read(reader)?;
4055 let amount_msat: u64 = Readable::read(reader)?;
4056 let cltv_expiry: u32 = Readable::read(reader)?;
4057 let payment_hash: PaymentHash = Readable::read(reader)?;
4058 let transaction_output_index: Option<u32> = Readable::read(reader)?;
4060 HTLCOutputInCommitment {
4061 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4067 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4068 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4069 for _ in 0..counterparty_claimable_outpoints_len {
4070 let txid: Txid = Readable::read(reader)?;
4071 let htlcs_count: u64 = Readable::read(reader)?;
4072 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4073 for _ in 0..htlcs_count {
4074 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4076 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
4077 return Err(DecodeError::InvalidValue);
4081 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4082 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
4083 for _ in 0..counterparty_commitment_txn_on_chain_len {
4084 let txid: Txid = Readable::read(reader)?;
4085 let commitment_number = <U48 as Readable>::read(reader)?.0;
4086 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
4087 return Err(DecodeError::InvalidValue);
4091 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4092 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4093 for _ in 0..counterparty_hash_commitment_number_len {
4094 let payment_hash: PaymentHash = Readable::read(reader)?;
4095 let commitment_number = <U48 as Readable>::read(reader)?.0;
4096 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
4097 return Err(DecodeError::InvalidValue);
4101 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4102 match <u8 as Readable>::read(reader)? {
4105 Some(Readable::read(reader)?)
4107 _ => return Err(DecodeError::InvalidValue),
4109 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4111 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4112 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4114 let payment_preimages_len: u64 = Readable::read(reader)?;
4115 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4116 for _ in 0..payment_preimages_len {
4117 let preimage: PaymentPreimage = Readable::read(reader)?;
4118 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
4119 if let Some(_) = payment_preimages.insert(hash, preimage) {
4120 return Err(DecodeError::InvalidValue);
4124 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4125 let mut pending_monitor_events = Some(
4126 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4127 for _ in 0..pending_monitor_events_len {
4128 let ev = match <u8 as Readable>::read(reader)? {
4129 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4130 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
4131 _ => return Err(DecodeError::InvalidValue)
4133 pending_monitor_events.as_mut().unwrap().push(ev);
4136 let pending_events_len: u64 = Readable::read(reader)?;
4137 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4138 for _ in 0..pending_events_len {
4139 if let Some(event) = MaybeReadable::read(reader)? {
4140 pending_events.push(event);
4144 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4146 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4147 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4148 for _ in 0..waiting_threshold_conf_len {
4149 if let Some(val) = MaybeReadable::read(reader)? {
4150 onchain_events_awaiting_threshold_conf.push(val);
4154 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4155 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<Script>>())));
4156 for _ in 0..outputs_to_watch_len {
4157 let txid = Readable::read(reader)?;
4158 let outputs_len: u64 = Readable::read(reader)?;
4159 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
4160 for _ in 0..outputs_len {
4161 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
4163 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
4164 return Err(DecodeError::InvalidValue);
4167 let onchain_tx_handler: OnchainTxHandler<SP::Signer> = ReadableArgs::read(
4168 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
4171 let lockdown_from_offchain = Readable::read(reader)?;
4172 let holder_tx_signed = Readable::read(reader)?;
4174 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
4175 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
4176 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
4177 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
4178 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
4179 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
4180 return Err(DecodeError::InvalidValue);
4184 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
4185 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
4186 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
4187 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
4188 return Err(DecodeError::InvalidValue);
4191 let mut funding_spend_confirmed = None;
4192 let mut htlcs_resolved_on_chain = Some(Vec::new());
4193 let mut funding_spend_seen = Some(false);
4194 let mut counterparty_node_id = None;
4195 let mut confirmed_commitment_tx_counterparty_output = None;
4196 let mut spendable_txids_confirmed = Some(Vec::new());
4197 let mut counterparty_fulfilled_htlcs = Some(HashMap::new());
4198 read_tlv_fields!(reader, {
4199 (1, funding_spend_confirmed, option),
4200 (3, htlcs_resolved_on_chain, optional_vec),
4201 (5, pending_monitor_events, optional_vec),
4202 (7, funding_spend_seen, option),
4203 (9, counterparty_node_id, option),
4204 (11, confirmed_commitment_tx_counterparty_output, option),
4205 (13, spendable_txids_confirmed, optional_vec),
4206 (15, counterparty_fulfilled_htlcs, option),
4209 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
4211 commitment_transaction_number_obscure_factor,
4214 broadcasted_holder_revokable_script,
4215 counterparty_payment_script,
4219 holder_revocation_basepoint,
4221 current_counterparty_commitment_txid,
4222 prev_counterparty_commitment_txid,
4224 counterparty_commitment_params,
4225 funding_redeemscript,
4226 channel_value_satoshis,
4227 their_cur_per_commitment_points,
4232 counterparty_claimable_outpoints,
4233 counterparty_commitment_txn_on_chain,
4234 counterparty_hash_commitment_number,
4235 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
4237 prev_holder_signed_commitment_tx,
4238 current_holder_commitment_tx,
4239 current_counterparty_commitment_number,
4240 current_holder_commitment_number,
4243 pending_monitor_events: pending_monitor_events.unwrap(),
4245 is_processing_pending_events: false,
4247 onchain_events_awaiting_threshold_conf,
4252 lockdown_from_offchain,
4254 funding_spend_seen: funding_spend_seen.unwrap(),
4255 funding_spend_confirmed,
4256 confirmed_commitment_tx_counterparty_output,
4257 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
4258 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
4261 counterparty_node_id,
4268 use bitcoin::blockdata::script::{Script, Builder};
4269 use bitcoin::blockdata::opcodes;
4270 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
4271 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
4272 use bitcoin::util::sighash;
4273 use bitcoin::hashes::Hash;
4274 use bitcoin::hashes::sha256::Hash as Sha256;
4275 use bitcoin::hashes::hex::FromHex;
4276 use bitcoin::hash_types::{BlockHash, Txid};
4277 use bitcoin::network::constants::Network;
4278 use bitcoin::secp256k1::{SecretKey,PublicKey};
4279 use bitcoin::secp256k1::Secp256k1;
4283 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
4285 use super::ChannelMonitorUpdateStep;
4286 use crate::{check_added_monitors, check_closed_broadcast, check_closed_event, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
4287 use crate::chain::{BestBlock, Confirm};
4288 use crate::chain::channelmonitor::ChannelMonitor;
4289 use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
4290 use crate::chain::transaction::OutPoint;
4291 use crate::sign::InMemorySigner;
4292 use crate::events::ClosureReason;
4293 use crate::ln::{PaymentPreimage, PaymentHash};
4294 use crate::ln::chan_utils;
4295 use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
4296 use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
4297 use crate::ln::functional_test_utils::*;
4298 use crate::ln::script::ShutdownScript;
4299 use crate::util::errors::APIError;
4300 use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
4301 use crate::util::ser::{ReadableArgs, Writeable};
4302 use crate::sync::{Arc, Mutex};
4304 use bitcoin::{PackedLockTime, Sequence, Witness};
4305 use crate::ln::features::ChannelTypeFeatures;
4306 use crate::prelude::*;
4308 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
4309 // Previously, monitor updates were allowed freely even after a funding-spend transaction
4310 // confirmed. This would allow a race condition where we could receive a payment (including
4311 // the counterparty revoking their broadcasted state!) and accept it without recourse as
4312 // long as the ChannelMonitor receives the block first, the full commitment update dance
4313 // occurs after the block is connected, and before the ChannelManager receives the block.
4314 // Obviously this is an incredibly contrived race given the counterparty would be risking
4315 // their full channel balance for it, but its worth fixing nonetheless as it makes the
4316 // potential ChannelMonitor states simpler to reason about.
4318 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
4319 // updates is handled correctly in such conditions.
4320 let chanmon_cfgs = create_chanmon_cfgs(3);
4321 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4322 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4323 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4324 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
4325 create_announced_chan_between_nodes(&nodes, 1, 2);
4327 // Rebalance somewhat
4328 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
4330 // First route two payments for testing at the end
4331 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4332 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
4334 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
4335 assert_eq!(local_txn.len(), 1);
4336 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
4337 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
4338 check_spends!(remote_txn[1], remote_txn[0]);
4339 check_spends!(remote_txn[2], remote_txn[0]);
4340 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
4342 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
4343 // channel is now closed, but the ChannelManager doesn't know that yet.
4344 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
4345 let conf_height = nodes[0].best_block_info().1 + 1;
4346 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
4347 &[(0, broadcast_tx)], conf_height);
4349 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
4350 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
4351 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
4353 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
4354 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
4355 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
4356 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash,
4357 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4358 ), true, APIError::ChannelUnavailable { ref err },
4359 assert!(err.contains("ChannelMonitor storage failure")));
4360 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
4361 check_closed_broadcast!(nodes[1], true);
4362 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() },
4363 [nodes[0].node.get_our_node_id()], 100000);
4365 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
4366 // and provides the claim preimages for the two pending HTLCs. The first update generates
4367 // an error, but the point of this test is to ensure the later updates are still applied.
4368 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
4369 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
4370 assert_eq!(replay_update.updates.len(), 1);
4371 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
4372 } else { panic!(); }
4373 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
4374 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
4376 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
4378 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
4380 // Even though we error'd on the first update, we should still have generated an HTLC claim
4382 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4383 assert!(txn_broadcasted.len() >= 2);
4384 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
4385 assert_eq!(tx.input.len(), 1);
4386 tx.input[0].previous_output.txid == broadcast_tx.txid()
4387 }).collect::<Vec<_>>();
4388 assert_eq!(htlc_txn.len(), 2);
4389 check_spends!(htlc_txn[0], broadcast_tx);
4390 check_spends!(htlc_txn[1], broadcast_tx);
4393 fn test_funding_spend_refuses_updates() {
4394 do_test_funding_spend_refuses_updates(true);
4395 do_test_funding_spend_refuses_updates(false);
4399 fn test_prune_preimages() {
4400 let secp_ctx = Secp256k1::new();
4401 let logger = Arc::new(TestLogger::new());
4402 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
4403 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4405 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4407 let mut preimages = Vec::new();
4410 let preimage = PaymentPreimage([i; 32]);
4411 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
4412 preimages.push((preimage, hash));
4416 macro_rules! preimages_slice_to_htlcs {
4417 ($preimages_slice: expr) => {
4419 let mut res = Vec::new();
4420 for (idx, preimage) in $preimages_slice.iter().enumerate() {
4421 res.push((HTLCOutputInCommitment {
4425 payment_hash: preimage.1.clone(),
4426 transaction_output_index: Some(idx as u32),
4433 macro_rules! preimages_slice_to_htlc_outputs {
4434 ($preimages_slice: expr) => {
4435 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
4438 let dummy_sig = crate::util::crypto::sign(&secp_ctx,
4439 &bitcoin::secp256k1::Message::from_slice(&[42; 32]).unwrap(),
4440 &SecretKey::from_slice(&[42; 32]).unwrap());
4442 macro_rules! test_preimages_exist {
4443 ($preimages_slice: expr, $monitor: expr) => {
4444 for preimage in $preimages_slice {
4445 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
4450 let keys = InMemorySigner::new(
4452 SecretKey::from_slice(&[41; 32]).unwrap(),
4453 SecretKey::from_slice(&[41; 32]).unwrap(),
4454 SecretKey::from_slice(&[41; 32]).unwrap(),
4455 SecretKey::from_slice(&[41; 32]).unwrap(),
4456 SecretKey::from_slice(&[41; 32]).unwrap(),
4463 let counterparty_pubkeys = ChannelPublicKeys {
4464 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
4465 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
4466 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
4467 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
4468 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
4470 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
4471 let channel_parameters = ChannelTransactionParameters {
4472 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
4473 holder_selected_contest_delay: 66,
4474 is_outbound_from_holder: true,
4475 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
4476 pubkeys: counterparty_pubkeys,
4477 selected_contest_delay: 67,
4479 funding_outpoint: Some(funding_outpoint),
4480 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
4482 // Prune with one old state and a holder commitment tx holding a few overlaps with the
4484 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4485 let best_block = BestBlock::from_network(Network::Testnet);
4486 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
4487 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
4488 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
4489 &channel_parameters, Script::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
4490 best_block, dummy_key);
4492 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
4493 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4494 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
4495 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4496 monitor.provide_latest_counterparty_commitment_tx(Txid::from_inner(Sha256::hash(b"1").into_inner()),
4497 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
4498 monitor.provide_latest_counterparty_commitment_tx(Txid::from_inner(Sha256::hash(b"2").into_inner()),
4499 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
4500 for &(ref preimage, ref hash) in preimages.iter() {
4501 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
4502 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
4505 // Now provide a secret, pruning preimages 10-15
4506 let mut secret = [0; 32];
4507 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
4508 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
4509 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
4510 test_preimages_exist!(&preimages[0..10], monitor);
4511 test_preimages_exist!(&preimages[15..20], monitor);
4513 monitor.provide_latest_counterparty_commitment_tx(Txid::from_inner(Sha256::hash(b"3").into_inner()),
4514 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
4516 // Now provide a further secret, pruning preimages 15-17
4517 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
4518 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
4519 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
4520 test_preimages_exist!(&preimages[0..10], monitor);
4521 test_preimages_exist!(&preimages[17..20], monitor);
4523 monitor.provide_latest_counterparty_commitment_tx(Txid::from_inner(Sha256::hash(b"4").into_inner()),
4524 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
4526 // Now update holder commitment tx info, pruning only element 18 as we still care about the
4527 // previous commitment tx's preimages too
4528 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
4529 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4530 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
4531 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4532 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
4533 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
4534 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
4535 test_preimages_exist!(&preimages[0..10], monitor);
4536 test_preimages_exist!(&preimages[18..20], monitor);
4538 // But if we do it again, we'll prune 5-10
4539 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
4540 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
4541 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
4542 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap();
4543 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
4544 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
4545 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
4546 test_preimages_exist!(&preimages[0..5], monitor);
4550 fn test_claim_txn_weight_computation() {
4551 // We test Claim txn weight, knowing that we want expected weigth and
4552 // not actual case to avoid sigs and time-lock delays hell variances.
4554 let secp_ctx = Secp256k1::new();
4555 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
4556 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
4558 macro_rules! sign_input {
4559 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
4560 let htlc = HTLCOutputInCommitment {
4561 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
4563 cltv_expiry: 2 << 16,
4564 payment_hash: PaymentHash([1; 32]),
4565 transaction_output_index: Some($idx as u32),
4567 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &pubkey, &pubkey, &pubkey) };
4568 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
4569 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
4570 let mut ser_sig = sig.serialize_der().to_vec();
4571 ser_sig.push(EcdsaSighashType::All as u8);
4572 $sum_actual_sigs += ser_sig.len();
4573 let witness = $sighash_parts.witness_mut($idx).unwrap();
4574 witness.push(ser_sig);
4575 if *$weight == WEIGHT_REVOKED_OUTPUT {
4576 witness.push(vec!(1));
4577 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
4578 witness.push(pubkey.clone().serialize().to_vec());
4579 } else if *$weight == weight_received_htlc($opt_anchors) {
4580 witness.push(vec![0]);
4582 witness.push(PaymentPreimage([1; 32]).0.to_vec());
4584 witness.push(redeem_script.into_bytes());
4585 let witness = witness.to_vec();
4586 println!("witness[0] {}", witness[0].len());
4587 println!("witness[1] {}", witness[1].len());
4588 println!("witness[2] {}", witness[2].len());
4592 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
4593 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
4595 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
4596 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
4597 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4598 let mut sum_actual_sigs = 0;
4600 claim_tx.input.push(TxIn {
4601 previous_output: BitcoinOutPoint {
4605 script_sig: Script::new(),
4606 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4607 witness: Witness::new(),
4610 claim_tx.output.push(TxOut {
4611 script_pubkey: script_pubkey.clone(),
4614 let base_weight = claim_tx.weight();
4615 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(channel_type_features), weight_revoked_offered_htlc(channel_type_features), weight_revoked_received_htlc(channel_type_features)];
4616 let mut inputs_total_weight = 2; // count segwit flags
4618 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4619 for (idx, inp) in inputs_weight.iter().enumerate() {
4620 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
4621 inputs_total_weight += inp;
4624 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4627 // Claim tx with 1 offered HTLCs, 3 received HTLCs
4628 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
4629 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4630 let mut sum_actual_sigs = 0;
4632 claim_tx.input.push(TxIn {
4633 previous_output: BitcoinOutPoint {
4637 script_sig: Script::new(),
4638 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4639 witness: Witness::new(),
4642 claim_tx.output.push(TxOut {
4643 script_pubkey: script_pubkey.clone(),
4646 let base_weight = claim_tx.weight();
4647 let inputs_weight = vec![weight_offered_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features)];
4648 let mut inputs_total_weight = 2; // count segwit flags
4650 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4651 for (idx, inp) in inputs_weight.iter().enumerate() {
4652 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
4653 inputs_total_weight += inp;
4656 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4659 // Justice tx with 1 revoked HTLC-Success tx output
4660 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
4661 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4662 let mut sum_actual_sigs = 0;
4663 claim_tx.input.push(TxIn {
4664 previous_output: BitcoinOutPoint {
4668 script_sig: Script::new(),
4669 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4670 witness: Witness::new(),
4672 claim_tx.output.push(TxOut {
4673 script_pubkey: script_pubkey.clone(),
4676 let base_weight = claim_tx.weight();
4677 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
4678 let mut inputs_total_weight = 2; // count segwit flags
4680 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4681 for (idx, inp) in inputs_weight.iter().enumerate() {
4682 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, channel_type_features);
4683 inputs_total_weight += inp;
4686 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
4690 // Further testing is done in the ChannelManager integration tests.