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::{TxOut,Transaction};
25 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
26 use bitcoin::blockdata::script::{Script, Builder};
27 use bitcoin::blockdata::opcodes;
29 use bitcoin::hashes::Hash;
30 use bitcoin::hashes::sha256::Hash as Sha256;
31 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
33 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
34 use bitcoin::secp256k1::{SecretKey, PublicKey};
35 use bitcoin::secp256k1;
37 use ln::{PaymentHash, PaymentPreimage};
38 use ln::msgs::DecodeError;
40 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
41 use ln::channelmanager::HTLCSource;
43 use chain::{BestBlock, WatchedOutput};
44 use chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
45 use chain::transaction::{OutPoint, TransactionData};
46 use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
47 use chain::onchaintx::OnchainTxHandler;
48 use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
50 use util::logger::Logger;
51 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
53 use util::events::Event;
57 use io::{self, Error};
58 use core::convert::TryInto;
62 /// An update generated by the underlying Channel itself which contains some new information the
63 /// ChannelMonitor should be made aware of.
64 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
67 pub struct ChannelMonitorUpdate {
68 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
69 /// The sequence number of this update. Updates *must* be replayed in-order according to this
70 /// sequence number (and updates may panic if they are not). The update_id values are strictly
71 /// increasing and increase by one for each new update, with one exception specified below.
73 /// This sequence number is also used to track up to which points updates which returned
74 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
75 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
77 /// The only instance where update_id values are not strictly increasing is the case where we
78 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
79 /// its docs for more details.
84 /// (1) a channel has been force closed and
85 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
86 /// this channel's (the backward link's) broadcasted commitment transaction
87 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
88 /// with the update providing said payment preimage. No other update types are allowed after
90 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
92 impl Writeable for ChannelMonitorUpdate {
93 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
94 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
95 self.update_id.write(w)?;
96 (self.updates.len() as u64).write(w)?;
97 for update_step in self.updates.iter() {
98 update_step.write(w)?;
100 write_tlv_fields!(w, {});
104 impl Readable for ChannelMonitorUpdate {
105 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
106 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
107 let update_id: u64 = Readable::read(r)?;
108 let len: u64 = Readable::read(r)?;
109 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
111 if let Some(upd) = MaybeReadable::read(r)? {
115 read_tlv_fields!(r, {});
116 Ok(Self { update_id, updates })
120 /// An event to be processed by the ChannelManager.
121 #[derive(Clone, PartialEq)]
122 pub enum MonitorEvent {
123 /// A monitor event containing an HTLCUpdate.
124 HTLCEvent(HTLCUpdate),
126 /// A monitor event that the Channel's commitment transaction was confirmed.
127 CommitmentTxConfirmed(OutPoint),
129 /// Indicates a [`ChannelMonitor`] update has completed. See
130 /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
132 /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
134 /// The funding outpoint of the [`ChannelMonitor`] that was updated
135 funding_txo: OutPoint,
136 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
137 /// [`ChannelMonitor::get_latest_update_id`].
139 /// Note that this should only be set to a given update's ID if all previous updates for the
140 /// same [`ChannelMonitor`] have been applied and persisted.
141 monitor_update_id: u64,
144 /// Indicates a [`ChannelMonitor`] update has failed. See
145 /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
147 /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
148 UpdateFailed(OutPoint),
150 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
151 // Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
152 // generated only in ChainMonitor
153 (0, UpdateCompleted) => {
154 (0, funding_txo, required),
155 (2, monitor_update_id, required),
159 (4, CommitmentTxConfirmed),
163 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
164 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
165 /// preimage claim backward will lead to loss of funds.
166 #[derive(Clone, PartialEq)]
167 pub struct HTLCUpdate {
168 pub(crate) payment_hash: PaymentHash,
169 pub(crate) payment_preimage: Option<PaymentPreimage>,
170 pub(crate) source: HTLCSource,
171 pub(crate) htlc_value_satoshis: Option<u64>,
173 impl_writeable_tlv_based!(HTLCUpdate, {
174 (0, payment_hash, required),
175 (1, htlc_value_satoshis, option),
176 (2, source, required),
177 (4, payment_preimage, option),
180 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
181 /// instead claiming it in its own individual transaction.
182 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
183 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
184 /// HTLC-Success transaction.
185 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
186 /// transaction confirmed (and we use it in a few more, equivalent, places).
187 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
188 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
189 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
190 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
191 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
192 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
193 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
194 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
195 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
196 /// accurate block height.
197 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
198 /// with at worst this delay, so we are not only using this value as a mercy for them but also
199 /// us as a safeguard to delay with enough time.
200 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
201 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
202 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
205 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
206 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
207 /// by a [`ChannelMonitor`] may be incorrect.
208 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
209 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
210 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
211 // keep bumping another claim tx to solve the outpoint.
212 pub const ANTI_REORG_DELAY: u32 = 6;
213 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
214 /// refuse to accept a new HTLC.
216 /// This is used for a few separate purposes:
217 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
218 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
220 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
221 /// condition with the above), we will fail this HTLC without telling the user we received it,
223 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
224 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
226 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
227 /// in a race condition between the user connecting a block (which would fail it) and the user
228 /// providing us the preimage (which would claim it).
229 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
231 // TODO(devrandom) replace this with HolderCommitmentTransaction
232 #[derive(Clone, PartialEq)]
233 struct HolderSignedTx {
234 /// txid of the transaction in tx, just used to make comparison faster
236 revocation_key: PublicKey,
237 a_htlc_key: PublicKey,
238 b_htlc_key: PublicKey,
239 delayed_payment_key: PublicKey,
240 per_commitment_point: PublicKey,
241 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
242 to_self_value_sat: u64,
245 impl_writeable_tlv_based!(HolderSignedTx, {
247 // Note that this is filled in with data from OnchainTxHandler if it's missing.
248 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
249 (1, to_self_value_sat, (default_value, u64::max_value())),
250 (2, revocation_key, required),
251 (4, a_htlc_key, required),
252 (6, b_htlc_key, required),
253 (8, delayed_payment_key, required),
254 (10, per_commitment_point, required),
255 (12, feerate_per_kw, required),
256 (14, htlc_outputs, vec_type)
259 /// We use this to track static counterparty commitment transaction data and to generate any
260 /// justice or 2nd-stage preimage/timeout transactions.
262 struct CounterpartyCommitmentParameters {
263 counterparty_delayed_payment_base_key: PublicKey,
264 counterparty_htlc_base_key: PublicKey,
265 on_counterparty_tx_csv: u16,
268 impl Writeable for CounterpartyCommitmentParameters {
269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
270 w.write_all(&byte_utils::be64_to_array(0))?;
271 write_tlv_fields!(w, {
272 (0, self.counterparty_delayed_payment_base_key, required),
273 (2, self.counterparty_htlc_base_key, required),
274 (4, self.on_counterparty_tx_csv, required),
279 impl Readable for CounterpartyCommitmentParameters {
280 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
281 let counterparty_commitment_transaction = {
282 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
283 // used. Read it for compatibility.
284 let per_htlc_len: u64 = Readable::read(r)?;
285 for _ in 0..per_htlc_len {
286 let _txid: Txid = Readable::read(r)?;
287 let htlcs_count: u64 = Readable::read(r)?;
288 for _ in 0..htlcs_count {
289 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
293 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
294 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
295 let mut on_counterparty_tx_csv: u16 = 0;
296 read_tlv_fields!(r, {
297 (0, counterparty_delayed_payment_base_key, required),
298 (2, counterparty_htlc_base_key, required),
299 (4, on_counterparty_tx_csv, required),
301 CounterpartyCommitmentParameters {
302 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
303 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
304 on_counterparty_tx_csv,
307 Ok(counterparty_commitment_transaction)
311 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
312 /// transaction causing it.
314 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
316 struct OnchainEventEntry {
320 transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
323 impl OnchainEventEntry {
324 fn confirmation_threshold(&self) -> u32 {
325 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
327 OnchainEvent::MaturingOutput {
328 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
330 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
331 // it's broadcastable when we see the previous block.
332 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
334 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
335 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
336 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
337 // it's broadcastable when we see the previous block.
338 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
345 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
346 best_block.height() >= self.confirmation_threshold()
350 /// The (output index, sats value) for the counterparty's output in a commitment transaction.
352 /// This was added as an `Option` in 0.0.110.
353 type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>;
355 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
356 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
359 /// An outbound HTLC failing after a transaction is confirmed. Used
360 /// * when an outbound HTLC output is spent by us after the HTLC timed out
361 /// * an outbound HTLC which was not present in the commitment transaction which appeared
362 /// on-chain (either because it was not fully committed to or it was dust).
363 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
364 /// appearing only as an `HTLCSpendConfirmation`, below.
367 payment_hash: PaymentHash,
368 htlc_value_satoshis: Option<u64>,
369 /// None in the second case, above, ie when there is no relevant output in the commitment
370 /// transaction which appeared on chain.
371 commitment_tx_output_idx: Option<u32>,
373 /// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the
374 /// [`SpendableOutputDescriptor`].
376 descriptor: SpendableOutputDescriptor,
378 /// A spend of the funding output, either a commitment transaction or a cooperative closing
380 FundingSpendConfirmation {
381 /// The CSV delay for the output of the funding spend transaction (implying it is a local
382 /// commitment transaction, and this is the delay on the to_self output).
383 on_local_output_csv: Option<u16>,
384 /// If the funding spend transaction was a known remote commitment transaction, we track
385 /// the output index and amount of the counterparty's `to_self` output here.
387 /// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
388 /// counterparty output.
389 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
391 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
392 /// is constructed. This is used when
393 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
394 /// immediately claim the HTLC on the inbound edge and track the resolution here,
395 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
396 /// * an inbound HTLC is claimed by us (with a preimage).
397 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
399 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by an
400 /// HTLC-Success/HTLC-Failure transaction (and is still claimable with a revocation
402 HTLCSpendConfirmation {
403 commitment_tx_output_idx: u32,
404 /// If the claim was made by either party with a preimage, this is filled in
405 preimage: Option<PaymentPreimage>,
406 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
407 /// we set this to the output CSV value which we will have to wait until to spend the
408 /// output (and generate a SpendableOutput event).
409 on_to_local_output_csv: Option<u16>,
413 impl Writeable for OnchainEventEntry {
414 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
415 write_tlv_fields!(writer, {
416 (0, self.txid, required),
417 (1, self.transaction, option),
418 (2, self.height, required),
419 (4, self.event, required),
425 impl MaybeReadable for OnchainEventEntry {
426 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
427 let mut txid = Txid::all_zeros();
428 let mut transaction = None;
430 let mut event = None;
431 read_tlv_fields!(reader, {
433 (1, transaction, option),
434 (2, height, required),
435 (4, event, ignorable),
437 if let Some(ev) = event {
438 Ok(Some(Self { txid, transaction, height, event: ev }))
445 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
447 (0, source, required),
448 (1, htlc_value_satoshis, option),
449 (2, payment_hash, required),
450 (3, commitment_tx_output_idx, option),
452 (1, MaturingOutput) => {
453 (0, descriptor, required),
455 (3, FundingSpendConfirmation) => {
456 (0, on_local_output_csv, option),
457 (1, commitment_tx_to_counterparty_output, option),
459 (5, HTLCSpendConfirmation) => {
460 (0, commitment_tx_output_idx, required),
461 (2, preimage, option),
462 (4, on_to_local_output_csv, option),
467 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
469 pub(crate) enum ChannelMonitorUpdateStep {
470 LatestHolderCommitmentTXInfo {
471 commitment_tx: HolderCommitmentTransaction,
472 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
474 LatestCounterpartyCommitmentTXInfo {
475 commitment_txid: Txid,
476 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
477 commitment_number: u64,
478 their_per_commitment_point: PublicKey,
481 payment_preimage: PaymentPreimage,
487 /// Used to indicate that the no future updates will occur, and likely that the latest holder
488 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
490 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
491 /// think we've fallen behind!
492 should_broadcast: bool,
495 scriptpubkey: Script,
499 impl ChannelMonitorUpdateStep {
500 fn variant_name(&self) -> &'static str {
502 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
503 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
504 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
505 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
506 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
507 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
512 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
513 (0, LatestHolderCommitmentTXInfo) => {
514 (0, commitment_tx, required),
515 (2, htlc_outputs, vec_type),
517 (1, LatestCounterpartyCommitmentTXInfo) => {
518 (0, commitment_txid, required),
519 (2, commitment_number, required),
520 (4, their_per_commitment_point, required),
521 (6, htlc_outputs, vec_type),
523 (2, PaymentPreimage) => {
524 (0, payment_preimage, required),
526 (3, CommitmentSecret) => {
528 (2, secret, required),
530 (4, ChannelForceClosed) => {
531 (0, should_broadcast, required),
533 (5, ShutdownScript) => {
534 (0, scriptpubkey, required),
538 /// Details about the balance(s) available for spending once the channel appears on chain.
540 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
542 #[derive(Clone, Debug, PartialEq, Eq)]
543 #[cfg_attr(test, derive(PartialOrd, Ord))]
545 /// The channel is not yet closed (or the commitment or closing transaction has not yet
546 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
547 /// force-closed now.
548 ClaimableOnChannelClose {
549 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
550 /// required to do so.
551 claimable_amount_satoshis: u64,
553 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
554 /// we consider it spendable.
555 ClaimableAwaitingConfirmations {
556 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
557 /// were spent in broadcasting the transaction.
558 claimable_amount_satoshis: u64,
559 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
561 confirmation_height: u32,
563 /// The channel has been closed, and the given balance should be ours but awaiting spending
564 /// transaction confirmation. If the spending transaction does not confirm in time, it is
565 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
567 /// Once the spending transaction confirms, before it has reached enough confirmations to be
568 /// considered safe from chain reorganizations, the balance will instead be provided via
569 /// [`Balance::ClaimableAwaitingConfirmations`].
570 ContentiousClaimable {
571 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
572 /// required to do so.
573 claimable_amount_satoshis: u64,
574 /// The height at which the counterparty may be able to claim the balance if we have not
578 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
579 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
580 /// likely to be claimed by our counterparty before we do.
581 MaybeClaimableHTLCAwaitingTimeout {
582 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
583 /// required to do so.
584 claimable_amount_satoshis: u64,
585 /// The height at which we will be able to claim the balance if our counterparty has not
587 claimable_height: u32,
589 /// The channel has been closed, and our counterparty broadcasted a revoked commitment
592 /// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
593 /// following amount.
594 CounterpartyRevokedOutputClaimable {
595 /// The amount, in satoshis, of the output which we can claim.
597 /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
598 /// were already spent.
599 claimable_amount_satoshis: u64,
603 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
605 struct IrrevocablyResolvedHTLC {
606 commitment_tx_output_idx: u32,
607 /// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC
608 /// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
610 resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
611 /// Only set if the HTLC claim was ours using a payment preimage
612 payment_preimage: Option<PaymentPreimage>,
615 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
616 (0, commitment_tx_output_idx, required),
617 (1, resolving_txid, option),
618 (2, payment_preimage, option),
621 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
622 /// on-chain transactions to ensure no loss of funds occurs.
624 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
625 /// information and are actively monitoring the chain.
627 /// Pending Events or updated HTLCs which have not yet been read out by
628 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
629 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
630 /// gotten are fully handled before re-serializing the new state.
632 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
633 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
634 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
635 /// returned block hash and the the current chain and then reconnecting blocks to get to the
636 /// best chain) upon deserializing the object!
637 pub struct ChannelMonitor<Signer: Sign> {
639 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
641 inner: Mutex<ChannelMonitorImpl<Signer>>,
644 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
645 latest_update_id: u64,
646 commitment_transaction_number_obscure_factor: u64,
648 destination_script: Script,
649 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
650 counterparty_payment_script: Script,
651 shutdown_script: Option<Script>,
653 channel_keys_id: [u8; 32],
654 holder_revocation_basepoint: PublicKey,
655 funding_info: (OutPoint, Script),
656 current_counterparty_commitment_txid: Option<Txid>,
657 prev_counterparty_commitment_txid: Option<Txid>,
659 counterparty_commitment_params: CounterpartyCommitmentParameters,
660 funding_redeemscript: Script,
661 channel_value_satoshis: u64,
662 // first is the idx of the first of the two per-commitment points
663 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
665 on_holder_tx_csv: u16,
667 commitment_secrets: CounterpartyCommitmentSecrets,
668 /// The set of outpoints in each counterparty commitment transaction. We always need at least
669 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
670 /// transaction broadcast as we need to be able to construct the witness script in all cases.
671 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
672 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
673 /// Nor can we figure out their commitment numbers without the commitment transaction they are
674 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
675 /// commitment transactions which we find on-chain, mapping them to the commitment number which
676 /// can be used to derive the revocation key and claim the transactions.
677 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
678 /// Cache used to make pruning of payment_preimages faster.
679 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
680 /// counterparty transactions (ie should remain pretty small).
681 /// Serialized to disk but should generally not be sent to Watchtowers.
682 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
684 // We store two holder commitment transactions to avoid any race conditions where we may update
685 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
686 // various monitors for one channel being out of sync, and us broadcasting a holder
687 // transaction for which we have deleted claim information on some watchtowers.
688 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
689 current_holder_commitment_tx: HolderSignedTx,
691 // Used just for ChannelManager to make sure it has the latest channel data during
693 current_counterparty_commitment_number: u64,
694 // Used just for ChannelManager to make sure it has the latest channel data during
696 current_holder_commitment_number: u64,
698 /// The set of payment hashes from inbound payments for which we know the preimage. Payment
699 /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
700 /// remote commitment transactions are automatically removed when commitment transactions are
702 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
704 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
705 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
706 // presumably user implementations thereof as well) where we update the in-memory channel
707 // object, then before the persistence finishes (as it's all under a read-lock), we return
708 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
709 // the pre-event state here, but have processed the event in the `ChannelManager`.
710 // Note that because the `event_lock` in `ChainMonitor` is only taken in
711 // block/transaction-connected events and *not* during block/transaction-disconnected events,
712 // we further MUST NOT generate events during block/transaction-disconnection.
713 pending_monitor_events: Vec<MonitorEvent>,
715 pending_events: Vec<Event>,
717 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
718 // which to take actions once they reach enough confirmations. Each entry includes the
719 // transaction's id and the height when the transaction was confirmed on chain.
720 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
722 // If we get serialized out and re-read, we need to make sure that the chain monitoring
723 // interface knows about the TXOs that we want to be notified of spends of. We could probably
724 // be smart and derive them from the above storage fields, but its much simpler and more
725 // Obviously Correct (tm) if we just keep track of them explicitly.
726 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
729 pub onchain_tx_handler: OnchainTxHandler<Signer>,
731 onchain_tx_handler: OnchainTxHandler<Signer>,
733 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
734 // channel has been force-closed. After this is set, no further holder commitment transaction
735 // updates may occur, and we panic!() if one is provided.
736 lockdown_from_offchain: bool,
738 // Set once we've signed a holder commitment transaction and handed it over to our
739 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
740 // may occur, and we fail any such monitor updates.
742 // In case of update rejection due to a locally already signed commitment transaction, we
743 // nevertheless store update content to track in case of concurrent broadcast by another
744 // remote monitor out-of-order with regards to the block view.
745 holder_tx_signed: bool,
747 // If a spend of the funding output is seen, we set this to true and reject any further
748 // updates. This prevents any further changes in the offchain state no matter the order
749 // of block connection between ChannelMonitors and the ChannelManager.
750 funding_spend_seen: bool,
752 funding_spend_confirmed: Option<Txid>,
753 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
754 /// The set of HTLCs which have been either claimed or failed on chain and have reached
755 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
756 /// spending CSV for revocable outputs).
757 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
759 // We simply modify best_block in Channel's block_connected so that serialization is
760 // consistent but hopefully the users' copy handles block_connected in a consistent way.
761 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
762 // their best_block from its state and not based on updated copies that didn't run through
763 // the full block_connected).
764 best_block: BestBlock,
766 /// The node_id of our counterparty
767 counterparty_node_id: Option<PublicKey>,
769 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
772 /// Transaction outputs to watch for on-chain spends.
773 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
775 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
776 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
778 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
779 fn eq(&self, other: &Self) -> bool {
780 let inner = self.inner.lock().unwrap();
781 let other = other.inner.lock().unwrap();
786 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
787 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
789 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
790 fn eq(&self, other: &Self) -> bool {
791 if self.latest_update_id != other.latest_update_id ||
792 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
793 self.destination_script != other.destination_script ||
794 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
795 self.counterparty_payment_script != other.counterparty_payment_script ||
796 self.channel_keys_id != other.channel_keys_id ||
797 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
798 self.funding_info != other.funding_info ||
799 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
800 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
801 self.counterparty_commitment_params != other.counterparty_commitment_params ||
802 self.funding_redeemscript != other.funding_redeemscript ||
803 self.channel_value_satoshis != other.channel_value_satoshis ||
804 self.their_cur_per_commitment_points != other.their_cur_per_commitment_points ||
805 self.on_holder_tx_csv != other.on_holder_tx_csv ||
806 self.commitment_secrets != other.commitment_secrets ||
807 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
808 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
809 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
810 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
811 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
812 self.current_holder_commitment_number != other.current_holder_commitment_number ||
813 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
814 self.payment_preimages != other.payment_preimages ||
815 self.pending_monitor_events != other.pending_monitor_events ||
816 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
817 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
818 self.outputs_to_watch != other.outputs_to_watch ||
819 self.lockdown_from_offchain != other.lockdown_from_offchain ||
820 self.holder_tx_signed != other.holder_tx_signed ||
821 self.funding_spend_seen != other.funding_spend_seen ||
822 self.funding_spend_confirmed != other.funding_spend_confirmed ||
823 self.confirmed_commitment_tx_counterparty_output != other.confirmed_commitment_tx_counterparty_output ||
824 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
833 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
834 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
835 self.inner.lock().unwrap().write(writer)
839 // These are also used for ChannelMonitorUpdate, above.
840 const SERIALIZATION_VERSION: u8 = 1;
841 const MIN_SERIALIZATION_VERSION: u8 = 1;
843 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
844 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
845 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
847 self.latest_update_id.write(writer)?;
849 // Set in initial Channel-object creation, so should always be set by now:
850 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
852 self.destination_script.write(writer)?;
853 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
854 writer.write_all(&[0; 1])?;
855 broadcasted_holder_revokable_script.0.write(writer)?;
856 broadcasted_holder_revokable_script.1.write(writer)?;
857 broadcasted_holder_revokable_script.2.write(writer)?;
859 writer.write_all(&[1; 1])?;
862 self.counterparty_payment_script.write(writer)?;
863 match &self.shutdown_script {
864 Some(script) => script.write(writer)?,
865 None => Script::new().write(writer)?,
868 self.channel_keys_id.write(writer)?;
869 self.holder_revocation_basepoint.write(writer)?;
870 writer.write_all(&self.funding_info.0.txid[..])?;
871 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
872 self.funding_info.1.write(writer)?;
873 self.current_counterparty_commitment_txid.write(writer)?;
874 self.prev_counterparty_commitment_txid.write(writer)?;
876 self.counterparty_commitment_params.write(writer)?;
877 self.funding_redeemscript.write(writer)?;
878 self.channel_value_satoshis.write(writer)?;
880 match self.their_cur_per_commitment_points {
881 Some((idx, pubkey, second_option)) => {
882 writer.write_all(&byte_utils::be48_to_array(idx))?;
883 writer.write_all(&pubkey.serialize())?;
884 match second_option {
885 Some(second_pubkey) => {
886 writer.write_all(&second_pubkey.serialize())?;
889 writer.write_all(&[0; 33])?;
894 writer.write_all(&byte_utils::be48_to_array(0))?;
898 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
900 self.commitment_secrets.write(writer)?;
902 macro_rules! serialize_htlc_in_commitment {
903 ($htlc_output: expr) => {
904 writer.write_all(&[$htlc_output.offered as u8; 1])?;
905 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
906 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
907 writer.write_all(&$htlc_output.payment_hash.0[..])?;
908 $htlc_output.transaction_output_index.write(writer)?;
912 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
913 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
914 writer.write_all(&txid[..])?;
915 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
916 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
917 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
918 || Some(**txid) == self.prev_counterparty_commitment_txid,
919 "HTLC Sources for all revoked commitment transactions should be none!");
920 serialize_htlc_in_commitment!(htlc_output);
921 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
925 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
926 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
927 writer.write_all(&txid[..])?;
928 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
931 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
932 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
933 writer.write_all(&payment_hash.0[..])?;
934 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
937 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
938 writer.write_all(&[1; 1])?;
939 prev_holder_tx.write(writer)?;
941 writer.write_all(&[0; 1])?;
944 self.current_holder_commitment_tx.write(writer)?;
946 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
947 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
949 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
950 for payment_preimage in self.payment_preimages.values() {
951 writer.write_all(&payment_preimage.0[..])?;
954 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
955 MonitorEvent::HTLCEvent(_) => true,
956 MonitorEvent::CommitmentTxConfirmed(_) => true,
958 }).count() as u64).to_be_bytes())?;
959 for event in self.pending_monitor_events.iter() {
961 MonitorEvent::HTLCEvent(upd) => {
965 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
966 _ => {}, // Covered in the TLV writes below
970 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
971 for event in self.pending_events.iter() {
972 event.write(writer)?;
975 self.best_block.block_hash().write(writer)?;
976 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
978 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
979 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
980 entry.write(writer)?;
983 (self.outputs_to_watch.len() as u64).write(writer)?;
984 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
986 (idx_scripts.len() as u64).write(writer)?;
987 for (idx, script) in idx_scripts.iter() {
989 script.write(writer)?;
992 self.onchain_tx_handler.write(writer)?;
994 self.lockdown_from_offchain.write(writer)?;
995 self.holder_tx_signed.write(writer)?;
997 write_tlv_fields!(writer, {
998 (1, self.funding_spend_confirmed, option),
999 (3, self.htlcs_resolved_on_chain, vec_type),
1000 (5, self.pending_monitor_events, vec_type),
1001 (7, self.funding_spend_seen, required),
1002 (9, self.counterparty_node_id, option),
1003 (11, self.confirmed_commitment_tx_counterparty_output, option),
1010 impl<Signer: Sign> ChannelMonitor<Signer> {
1011 /// For lockorder enforcement purposes, we need to have a single site which constructs the
1012 /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1013 /// PartialEq implementation) we may decide a lockorder violation has occurred.
1014 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1015 ChannelMonitor { inner: Mutex::new(imp) }
1018 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
1019 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1020 channel_parameters: &ChannelTransactionParameters,
1021 funding_redeemscript: Script, channel_value_satoshis: u64,
1022 commitment_transaction_number_obscure_factor: u64,
1023 initial_holder_commitment_tx: HolderCommitmentTransaction,
1024 best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
1026 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1027 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1028 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1030 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1031 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1032 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1033 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1035 let channel_keys_id = keys.channel_keys_id();
1036 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1038 // block for Rust 1.34 compat
1039 let (holder_commitment_tx, current_holder_commitment_number) = {
1040 let trusted_tx = initial_holder_commitment_tx.trust();
1041 let txid = trusted_tx.txid();
1043 let tx_keys = trusted_tx.keys();
1044 let holder_commitment_tx = HolderSignedTx {
1046 revocation_key: tx_keys.revocation_key,
1047 a_htlc_key: tx_keys.broadcaster_htlc_key,
1048 b_htlc_key: tx_keys.countersignatory_htlc_key,
1049 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1050 per_commitment_point: tx_keys.per_commitment_point,
1051 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1052 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1053 feerate_per_kw: trusted_tx.feerate_per_kw(),
1055 (holder_commitment_tx, trusted_tx.commitment_number())
1058 let onchain_tx_handler =
1059 OnchainTxHandler::new(destination_script.clone(), keys,
1060 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
1062 let mut outputs_to_watch = HashMap::new();
1063 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1065 Self::from_impl(ChannelMonitorImpl {
1066 latest_update_id: 0,
1067 commitment_transaction_number_obscure_factor,
1069 destination_script: destination_script.clone(),
1070 broadcasted_holder_revokable_script: None,
1071 counterparty_payment_script,
1075 holder_revocation_basepoint,
1077 current_counterparty_commitment_txid: None,
1078 prev_counterparty_commitment_txid: None,
1080 counterparty_commitment_params,
1081 funding_redeemscript,
1082 channel_value_satoshis,
1083 their_cur_per_commitment_points: None,
1085 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1087 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1088 counterparty_claimable_outpoints: HashMap::new(),
1089 counterparty_commitment_txn_on_chain: HashMap::new(),
1090 counterparty_hash_commitment_number: HashMap::new(),
1092 prev_holder_signed_commitment_tx: None,
1093 current_holder_commitment_tx: holder_commitment_tx,
1094 current_counterparty_commitment_number: 1 << 48,
1095 current_holder_commitment_number,
1097 payment_preimages: HashMap::new(),
1098 pending_monitor_events: Vec::new(),
1099 pending_events: Vec::new(),
1101 onchain_events_awaiting_threshold_conf: Vec::new(),
1106 lockdown_from_offchain: false,
1107 holder_tx_signed: false,
1108 funding_spend_seen: false,
1109 funding_spend_confirmed: None,
1110 confirmed_commitment_tx_counterparty_output: None,
1111 htlcs_resolved_on_chain: Vec::new(),
1114 counterparty_node_id: Some(counterparty_node_id),
1121 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1122 self.inner.lock().unwrap().provide_secret(idx, secret)
1125 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1126 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1127 /// possibly future revocation/preimage information) to claim outputs where possible.
1128 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1129 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1132 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1133 commitment_number: u64,
1134 their_per_commitment_point: PublicKey,
1136 ) where L::Target: Logger {
1137 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1138 txid, htlc_outputs, commitment_number, their_per_commitment_point, logger)
1142 fn provide_latest_holder_commitment_tx(
1143 &self, holder_commitment_tx: HolderCommitmentTransaction,
1144 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1145 ) -> Result<(), ()> {
1146 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs).map_err(|_| ())
1149 /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1150 /// off-chain state with a new commitment transaction.
1151 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1153 payment_hash: &PaymentHash,
1154 payment_preimage: &PaymentPreimage,
1156 fee_estimator: &LowerBoundedFeeEstimator<F>,
1159 B::Target: BroadcasterInterface,
1160 F::Target: FeeEstimator,
1163 self.inner.lock().unwrap().provide_payment_preimage(
1164 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1167 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1172 B::Target: BroadcasterInterface,
1175 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1178 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1181 /// panics if the given update is not the next update by update_id.
1182 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1184 updates: &ChannelMonitorUpdate,
1190 B::Target: BroadcasterInterface,
1191 F::Target: FeeEstimator,
1194 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1197 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1199 pub fn get_latest_update_id(&self) -> u64 {
1200 self.inner.lock().unwrap().get_latest_update_id()
1203 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1204 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1205 self.inner.lock().unwrap().get_funding_txo().clone()
1208 /// Gets a list of txids, with their output scripts (in the order they appear in the
1209 /// transaction), which we must learn about spends of via block_connected().
1210 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1211 self.inner.lock().unwrap().get_outputs_to_watch()
1212 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1215 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1216 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1217 /// have been registered.
1218 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1219 let lock = self.inner.lock().unwrap();
1220 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1221 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1222 for (index, script_pubkey) in outputs.iter() {
1223 assert!(*index <= u16::max_value() as u32);
1224 filter.register_output(WatchedOutput {
1226 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1227 script_pubkey: script_pubkey.clone(),
1233 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1234 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1235 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1236 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1239 /// Gets the list of pending events which were generated by previous actions, clearing the list
1242 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1243 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1244 /// no internal locking in ChannelMonitors.
1245 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1246 self.inner.lock().unwrap().get_and_clear_pending_events()
1249 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1250 self.inner.lock().unwrap().get_min_seen_secret()
1253 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1254 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1257 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1258 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1261 /// Gets the `node_id` of the counterparty for this channel.
1263 /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1265 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1266 self.inner.lock().unwrap().counterparty_node_id
1269 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1270 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1271 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1272 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1273 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1274 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1275 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1276 /// out-of-band the other node operator to coordinate with him if option is available to you.
1277 /// In any-case, choice is up to the user.
1278 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1279 where L::Target: Logger {
1280 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1283 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1284 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1285 /// revoked commitment transaction.
1286 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1287 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1288 where L::Target: Logger {
1289 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1292 /// Processes transactions in a newly connected block, which may result in any of the following:
1293 /// - update the monitor's state against resolved HTLCs
1294 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1295 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1296 /// - detect settled outputs for later spending
1297 /// - schedule and bump any in-flight claims
1299 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1300 /// [`get_outputs_to_watch`].
1302 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1303 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1305 header: &BlockHeader,
1306 txdata: &TransactionData,
1311 ) -> Vec<TransactionOutputs>
1313 B::Target: BroadcasterInterface,
1314 F::Target: FeeEstimator,
1317 self.inner.lock().unwrap().block_connected(
1318 header, txdata, height, broadcaster, fee_estimator, logger)
1321 /// Determines if the disconnected block contained any transactions of interest and updates
1323 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1325 header: &BlockHeader,
1331 B::Target: BroadcasterInterface,
1332 F::Target: FeeEstimator,
1335 self.inner.lock().unwrap().block_disconnected(
1336 header, height, broadcaster, fee_estimator, logger)
1339 /// Processes transactions confirmed in a block with the given header and height, returning new
1340 /// outputs to watch. See [`block_connected`] for details.
1342 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1343 /// blocks. See [`chain::Confirm`] for calling expectations.
1345 /// [`block_connected`]: Self::block_connected
1346 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1348 header: &BlockHeader,
1349 txdata: &TransactionData,
1354 ) -> Vec<TransactionOutputs>
1356 B::Target: BroadcasterInterface,
1357 F::Target: FeeEstimator,
1360 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1361 self.inner.lock().unwrap().transactions_confirmed(
1362 header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
1365 /// Processes a transaction that was reorganized out of the chain.
1367 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1368 /// than blocks. See [`chain::Confirm`] for calling expectations.
1370 /// [`block_disconnected`]: Self::block_disconnected
1371 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1378 B::Target: BroadcasterInterface,
1379 F::Target: FeeEstimator,
1382 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1383 self.inner.lock().unwrap().transaction_unconfirmed(
1384 txid, broadcaster, &bounded_fee_estimator, logger);
1387 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1388 /// [`block_connected`] for details.
1390 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1391 /// blocks. See [`chain::Confirm`] for calling expectations.
1393 /// [`block_connected`]: Self::block_connected
1394 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1396 header: &BlockHeader,
1401 ) -> Vec<TransactionOutputs>
1403 B::Target: BroadcasterInterface,
1404 F::Target: FeeEstimator,
1407 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1408 self.inner.lock().unwrap().best_block_updated(
1409 header, height, broadcaster, &bounded_fee_estimator, logger)
1412 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1413 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1414 let inner = self.inner.lock().unwrap();
1415 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1417 .map(|entry| entry.txid)
1418 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1420 txids.sort_unstable();
1425 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1426 /// [`chain::Confirm`] interfaces.
1427 pub fn current_best_block(&self) -> BestBlock {
1428 self.inner.lock().unwrap().best_block.clone()
1432 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1433 /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1434 /// to one `Balance` for the HTLC.
1435 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1436 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1437 -> Option<Balance> {
1438 let htlc_commitment_tx_output_idx =
1439 if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1441 let mut htlc_spend_txid_opt = None;
1442 let mut holder_timeout_spend_pending = None;
1443 let mut htlc_spend_pending = None;
1444 let mut holder_delayed_output_pending = None;
1445 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1447 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1448 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1449 debug_assert!(htlc_spend_txid_opt.is_none());
1450 htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1451 debug_assert!(holder_timeout_spend_pending.is_none());
1452 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1453 holder_timeout_spend_pending = Some(event.confirmation_threshold());
1455 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1456 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1457 debug_assert!(htlc_spend_txid_opt.is_none());
1458 htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1459 debug_assert!(htlc_spend_pending.is_none());
1460 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1462 OnchainEvent::MaturingOutput {
1463 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1464 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx => {
1465 debug_assert!(holder_delayed_output_pending.is_none());
1466 holder_delayed_output_pending = Some(event.confirmation_threshold());
1471 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1472 .find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1473 debug_assert!(htlc_spend_txid_opt.is_none());
1474 htlc_spend_txid_opt = v.resolving_txid;
1477 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1479 let htlc_output_to_spend =
1480 if let Some(txid) = htlc_spend_txid_opt {
1482 self.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1483 "This code needs updating for anchors");
1484 BitcoinOutPoint::new(txid, 0)
1486 BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1488 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1490 if let Some(conf_thresh) = holder_delayed_output_pending {
1491 debug_assert!(holder_commitment);
1492 return Some(Balance::ClaimableAwaitingConfirmations {
1493 claimable_amount_satoshis: htlc.amount_msat / 1000,
1494 confirmation_height: conf_thresh,
1496 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
1497 // Funding transaction spends should be fully confirmed by the time any
1498 // HTLC transactions are resolved, unless we're talking about a holder
1499 // commitment tx, whose resolution is delayed until the CSV timeout is
1500 // reached, even though HTLCs may be resolved after only
1501 // ANTI_REORG_DELAY confirmations.
1502 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
1503 } else if counterparty_revoked_commitment {
1504 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1505 if let OnchainEvent::MaturingOutput {
1506 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1508 if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1509 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1510 Some(tx.txid()) == htlc_spend_txid_opt ||
1511 inp.previous_output.txid == htlc_spend_txid
1513 Some(inp.previous_output.txid) == confirmed_txid &&
1514 inp.previous_output.vout == htlc_commitment_tx_output_idx
1516 })).unwrap_or(false) {
1521 if htlc_output_claim_pending.is_some() {
1522 // We already push `Balance`s onto the `res` list for every
1523 // `StaticOutput` in a `MaturingOutput` in the revoked
1524 // counterparty commitment transaction case generally, so don't
1525 // need to do so again here.
1527 debug_assert!(holder_timeout_spend_pending.is_none(),
1528 "HTLCUpdate OnchainEvents should never appear for preimage claims");
1529 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1530 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1531 return Some(Balance::CounterpartyRevokedOutputClaimable {
1532 claimable_amount_satoshis: htlc.amount_msat / 1000,
1535 } else if htlc.offered == holder_commitment {
1536 // If the payment was outbound, check if there's an HTLCUpdate
1537 // indicating we have spent this HTLC with a timeout, claiming it back
1538 // and awaiting confirmations on it.
1539 if let Some(conf_thresh) = holder_timeout_spend_pending {
1540 return Some(Balance::ClaimableAwaitingConfirmations {
1541 claimable_amount_satoshis: htlc.amount_msat / 1000,
1542 confirmation_height: conf_thresh,
1545 return Some(Balance::MaybeClaimableHTLCAwaitingTimeout {
1546 claimable_amount_satoshis: htlc.amount_msat / 1000,
1547 claimable_height: htlc.cltv_expiry,
1550 } else if self.payment_preimages.get(&htlc.payment_hash).is_some() {
1551 // Otherwise (the payment was inbound), only expose it as claimable if
1552 // we know the preimage.
1553 // Note that if there is a pending claim, but it did not use the
1554 // preimage, we lost funds to our counterparty! We will then continue
1555 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1556 debug_assert!(holder_timeout_spend_pending.is_none());
1557 if let Some((conf_thresh, true)) = htlc_spend_pending {
1558 return Some(Balance::ClaimableAwaitingConfirmations {
1559 claimable_amount_satoshis: htlc.amount_msat / 1000,
1560 confirmation_height: conf_thresh,
1563 return Some(Balance::ContentiousClaimable {
1564 claimable_amount_satoshis: htlc.amount_msat / 1000,
1565 timeout_height: htlc.cltv_expiry,
1573 impl<Signer: Sign> ChannelMonitor<Signer> {
1574 /// Gets the balances in this channel which are either claimable by us if we were to
1575 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1578 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1579 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1580 /// balance, or until our counterparty has claimed the balance and accrued several
1581 /// confirmations on the claim transaction.
1583 /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1584 /// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1585 /// a revoked state.
1587 /// See [`Balance`] for additional details on the types of claimable balances which
1588 /// may be returned here and their meanings.
1589 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1590 let mut res = Vec::new();
1591 let us = self.inner.lock().unwrap();
1593 let mut confirmed_txid = us.funding_spend_confirmed;
1594 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
1595 let mut pending_commitment_tx_conf_thresh = None;
1596 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1597 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1600 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
1601 Some((event.txid, event.confirmation_threshold()))
1604 if let Some((txid, conf_thresh)) = funding_spend_pending {
1605 debug_assert!(us.funding_spend_confirmed.is_none(),
1606 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1607 confirmed_txid = Some(txid);
1608 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1611 macro_rules! walk_htlcs {
1612 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
1613 for htlc in $htlc_iter {
1614 if htlc.transaction_output_index.is_some() {
1616 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
1624 if let Some(txid) = confirmed_txid {
1625 let mut found_commitment_tx = false;
1626 if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1627 // First look for the to_remote output back to us.
1628 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1629 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1630 if let OnchainEvent::MaturingOutput {
1631 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1633 Some(descriptor.output.value)
1636 res.push(Balance::ClaimableAwaitingConfirmations {
1637 claimable_amount_satoshis: value,
1638 confirmation_height: conf_thresh,
1641 // If a counterparty commitment transaction is awaiting confirmation, we
1642 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1643 // confirmation with the same height or have never met our dust amount.
1646 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1647 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1649 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1650 // The counterparty broadcasted a revoked state!
1651 // Look for any StaticOutputs first, generating claimable balances for those.
1652 // If any match the confirmed counterparty revoked to_self output, skip
1653 // generating a CounterpartyRevokedOutputClaimable.
1654 let mut spent_counterparty_output = false;
1655 for event in us.onchain_events_awaiting_threshold_conf.iter() {
1656 if let OnchainEvent::MaturingOutput {
1657 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1659 res.push(Balance::ClaimableAwaitingConfirmations {
1660 claimable_amount_satoshis: output.value,
1661 confirmation_height: event.confirmation_threshold(),
1663 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1664 if event.transaction.as_ref().map(|tx|
1665 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1666 ).unwrap_or(false) {
1667 spent_counterparty_output = true;
1673 if spent_counterparty_output {
1674 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1675 let output_spendable = us.onchain_tx_handler
1676 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1677 if output_spendable {
1678 res.push(Balance::CounterpartyRevokedOutputClaimable {
1679 claimable_amount_satoshis: amt,
1683 // Counterparty output is missing, either it was broadcasted on a
1684 // previous version of LDK or the counterparty hadn't met dust.
1687 found_commitment_tx = true;
1688 } else if txid == us.current_holder_commitment_tx.txid {
1689 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1690 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1691 res.push(Balance::ClaimableAwaitingConfirmations {
1692 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1693 confirmation_height: conf_thresh,
1696 found_commitment_tx = true;
1697 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1698 if txid == prev_commitment.txid {
1699 walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1700 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1701 res.push(Balance::ClaimableAwaitingConfirmations {
1702 claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1703 confirmation_height: conf_thresh,
1706 found_commitment_tx = true;
1709 if !found_commitment_tx {
1710 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1711 // We blindly assume this is a cooperative close transaction here, and that
1712 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1713 // the amount we can claim as we'll punish a misbehaving counterparty.
1714 res.push(Balance::ClaimableAwaitingConfirmations {
1715 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1716 confirmation_height: conf_thresh,
1721 let mut claimable_inbound_htlc_value_sat = 0;
1722 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1723 if htlc.transaction_output_index.is_none() { continue; }
1725 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1726 claimable_amount_satoshis: htlc.amount_msat / 1000,
1727 claimable_height: htlc.cltv_expiry,
1729 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1730 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1733 res.push(Balance::ClaimableOnChannelClose {
1734 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1741 /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1742 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1743 pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1744 let mut res = HashMap::new();
1745 let us = self.inner.lock().unwrap();
1747 macro_rules! walk_htlcs {
1748 ($holder_commitment: expr, $htlc_iter: expr) => {
1749 for (htlc, source) in $htlc_iter {
1750 if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.commitment_tx_output_idx) == htlc.transaction_output_index) {
1751 // We should assert that funding_spend_confirmed is_some() here, but we
1752 // have some unit tests which violate HTLC transaction CSVs entirely and
1754 // TODO: Once tests all connect transactions at consensus-valid times, we
1755 // should assert here like we do in `get_claimable_balances`.
1756 } else if htlc.offered == $holder_commitment {
1757 // If the payment was outbound, check if there's an HTLCUpdate
1758 // indicating we have spent this HTLC with a timeout, claiming it back
1759 // and awaiting confirmations on it.
1760 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1761 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1762 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1763 // before considering it "no longer pending" - this matches when we
1764 // provide the ChannelManager an HTLC failure event.
1765 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
1766 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1767 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
1768 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1769 // immediately non-pending, matching when we provide ChannelManager
1771 Some(commitment_tx_output_idx) == htlc.transaction_output_index
1774 if !htlc_update_confd {
1775 res.insert(source.clone(), htlc.clone());
1782 // We're only concerned with the confirmation count of HTLC transactions, and don't
1783 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1784 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1785 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1786 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1787 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1792 if let Some(txid) = confirmed_txid {
1793 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1794 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1795 if let &Some(ref source) = b {
1796 Some((a, &**source))
1799 } else if txid == us.current_holder_commitment_tx.txid {
1800 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1801 if let Some(source) = c { Some((a, source)) } else { None }
1803 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1804 if txid == prev_commitment.txid {
1805 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1806 if let Some(source) = c { Some((a, source)) } else { None }
1811 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1812 // closed), just examine the available counterparty commitment transactions. See docs
1813 // on `fail_unbroadcast_htlcs`, below, for justification.
1814 macro_rules! walk_counterparty_commitment {
1816 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1817 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1818 if let &Some(ref source) = source_option {
1819 res.insert((**source).clone(), htlc.clone());
1825 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1826 walk_counterparty_commitment!(txid);
1828 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1829 walk_counterparty_commitment!(txid);
1836 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
1837 self.inner.lock().unwrap().payment_preimages.clone()
1841 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1842 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1843 /// after ANTI_REORG_DELAY blocks.
1845 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1846 /// are the commitment transactions which are generated by us. The off-chain state machine in
1847 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1848 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1849 /// included in a remote commitment transaction are failed back if they are not present in the
1850 /// broadcasted commitment transaction.
1852 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1853 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1854 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1855 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1856 macro_rules! fail_unbroadcast_htlcs {
1857 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
1858 $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1859 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
1861 macro_rules! check_htlc_fails {
1862 ($txid: expr, $commitment_tx: expr) => {
1863 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1864 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1865 if let &Some(ref source) = source_option {
1866 // Check if the HTLC is present in the commitment transaction that was
1867 // broadcast, but not if it was below the dust limit, which we should
1868 // fail backwards immediately as there is no way for us to learn the
1869 // payment_preimage.
1870 // Note that if the dust limit were allowed to change between
1871 // commitment transactions we'd want to be check whether *any*
1872 // broadcastable commitment transaction has the HTLC in it, but it
1873 // cannot currently change after channel initialization, so we don't
1875 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1877 let mut matched_htlc = false;
1878 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1879 if broadcast_htlc.transaction_output_index.is_some() &&
1880 (Some(&**source) == *broadcast_source ||
1881 (broadcast_source.is_none() &&
1882 broadcast_htlc.payment_hash == htlc.payment_hash &&
1883 broadcast_htlc.amount_msat == htlc.amount_msat)) {
1884 matched_htlc = true;
1888 if matched_htlc { continue; }
1889 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1890 if entry.height != $commitment_tx_conf_height { return true; }
1892 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1893 *update_source != **source
1898 let entry = OnchainEventEntry {
1899 txid: $commitment_txid_confirmed,
1900 transaction: Some($commitment_tx_confirmed.clone()),
1901 height: $commitment_tx_conf_height,
1902 event: OnchainEvent::HTLCUpdate {
1903 source: (**source).clone(),
1904 payment_hash: htlc.payment_hash.clone(),
1905 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
1906 commitment_tx_output_idx: None,
1909 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
1910 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type,
1911 $commitment_txid_confirmed, entry.confirmation_threshold());
1912 $self.onchain_events_awaiting_threshold_conf.push(entry);
1918 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1919 check_htlc_fails!(txid, "current");
1921 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1922 check_htlc_fails!(txid, "previous");
1927 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
1928 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
1929 // in-line tests later.
1932 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
1933 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
1934 ret[131] = opcodes::all::OP_DROP.to_u8();
1935 ret[132] = opcodes::all::OP_DROP.to_u8();
1936 ret[133] = opcodes::all::OP_DROP.to_u8();
1937 ret[134] = opcodes::all::OP_DROP.to_u8();
1938 ret[135] = opcodes::OP_TRUE.to_u8();
1943 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
1944 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
1947 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1948 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1949 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1950 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1951 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1952 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1953 return Err("Previous secret did not match new one");
1956 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1957 // events for now-revoked/fulfilled HTLCs.
1958 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1959 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1964 if !self.payment_preimages.is_empty() {
1965 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1966 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1967 let min_idx = self.get_min_seen_secret();
1968 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1970 self.payment_preimages.retain(|&k, _| {
1971 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1972 if k == htlc.payment_hash {
1976 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1977 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1978 if k == htlc.payment_hash {
1983 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1990 counterparty_hash_commitment_number.remove(&k);
1999 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 {
2000 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2001 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2002 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2004 for &(ref htlc, _) in &htlc_outputs {
2005 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2008 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2009 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2010 self.current_counterparty_commitment_txid = Some(txid);
2011 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2012 self.current_counterparty_commitment_number = commitment_number;
2013 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2014 match self.their_cur_per_commitment_points {
2015 Some(old_points) => {
2016 if old_points.0 == commitment_number + 1 {
2017 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2018 } else if old_points.0 == commitment_number + 2 {
2019 if let Some(old_second_point) = old_points.2 {
2020 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2022 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2025 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2029 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2032 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2033 for htlc in htlc_outputs {
2034 if htlc.0.transaction_output_index.is_some() {
2040 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2041 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2042 /// is important that any clones of this channel monitor (including remote clones) by kept
2043 /// up-to-date as our holder commitment transaction is updated.
2044 /// Panics if set_on_holder_tx_csv has never been called.
2045 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), &'static str> {
2046 // block for Rust 1.34 compat
2047 let mut new_holder_commitment_tx = {
2048 let trusted_tx = holder_commitment_tx.trust();
2049 let txid = trusted_tx.txid();
2050 let tx_keys = trusted_tx.keys();
2051 self.current_holder_commitment_number = trusted_tx.commitment_number();
2054 revocation_key: tx_keys.revocation_key,
2055 a_htlc_key: tx_keys.broadcaster_htlc_key,
2056 b_htlc_key: tx_keys.countersignatory_htlc_key,
2057 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2058 per_commitment_point: tx_keys.per_commitment_point,
2060 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2061 feerate_per_kw: trusted_tx.feerate_per_kw(),
2064 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2065 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2066 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2067 if self.holder_tx_signed {
2068 return Err("Latest holder commitment signed has already been signed, update is rejected");
2073 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2074 /// commitment_tx_infos which contain the payment hash have been revoked.
2075 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2076 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2077 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
2078 where B::Target: BroadcasterInterface,
2079 F::Target: FeeEstimator,
2082 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2084 // If the channel is force closed, try to claim the output from this preimage.
2085 // First check if a counterparty commitment transaction has been broadcasted:
2086 macro_rules! claim_htlcs {
2087 ($commitment_number: expr, $txid: expr) => {
2088 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2089 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2092 if let Some(txid) = self.current_counterparty_commitment_txid {
2093 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2094 claim_htlcs!(*commitment_number, txid);
2098 if let Some(txid) = self.prev_counterparty_commitment_txid {
2099 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2100 claim_htlcs!(*commitment_number, txid);
2105 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2106 // claiming the HTLC output from each of the holder commitment transactions.
2107 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2108 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2109 // holder commitment transactions.
2110 if self.broadcasted_holder_revokable_script.is_some() {
2111 // Assume that the broadcasted commitment transaction confirmed in the current best
2112 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2114 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2115 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2116 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
2117 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
2118 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2123 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
2124 where B::Target: BroadcasterInterface,
2127 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
2128 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
2129 broadcaster.broadcast_transaction(tx);
2131 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2134 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
2135 where B::Target: BroadcasterInterface,
2136 F::Target: FeeEstimator,
2139 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} changes.",
2140 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2141 // ChannelMonitor updates may be applied after force close if we receive a
2142 // preimage for a broadcasted commitment transaction HTLC output that we'd
2143 // like to claim on-chain. If this is the case, we no longer have guaranteed
2144 // access to the monitor's update ID, so we use a sentinel value instead.
2145 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2146 assert_eq!(updates.updates.len(), 1);
2147 match updates.updates[0] {
2148 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
2150 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2151 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2154 } else if self.latest_update_id + 1 != updates.update_id {
2155 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2157 let mut ret = Ok(());
2158 for update in updates.updates.iter() {
2160 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
2161 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2162 if self.lockdown_from_offchain { panic!(); }
2163 if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
2164 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2165 log_error!(logger, " {}", e);
2169 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point } => {
2170 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2171 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2173 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2174 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2175 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2176 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2178 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2179 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2180 if let Err(e) = self.provide_secret(*idx, *secret) {
2181 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2182 log_error!(logger, " {}", e);
2186 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2187 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2188 self.lockdown_from_offchain = true;
2189 if *should_broadcast {
2190 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2191 } else if !self.holder_tx_signed {
2192 log_error!(logger, "You have a toxic holder commitment transaction avaible in channel monitor, read comment in ChannelMonitor::get_latest_holder_commitment_txn to be informed of manual action to take");
2194 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2195 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2196 // shouldn't print the scary warning above.
2197 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2200 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2201 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2202 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2203 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2208 self.latest_update_id = updates.update_id;
2210 if ret.is_ok() && self.funding_spend_seen {
2211 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2216 pub fn get_latest_update_id(&self) -> u64 {
2217 self.latest_update_id
2220 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2224 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2225 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2226 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2227 // its trivial to do, double-check that here.
2228 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2229 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2231 &self.outputs_to_watch
2234 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2235 let mut ret = Vec::new();
2236 mem::swap(&mut ret, &mut self.pending_monitor_events);
2240 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
2241 let mut ret = Vec::new();
2242 mem::swap(&mut ret, &mut self.pending_events);
2246 /// Can only fail if idx is < get_min_seen_secret
2247 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2248 self.commitment_secrets.get_secret(idx)
2251 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2252 self.commitment_secrets.get_min_seen_secret()
2255 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2256 self.current_counterparty_commitment_number
2259 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2260 self.current_holder_commitment_number
2263 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2264 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2265 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2266 /// HTLC-Success/HTLC-Timeout transactions.
2268 /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
2269 /// general information about the output that is to the counterparty in the commitment
2271 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L)
2272 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
2273 where L::Target: Logger {
2274 // Most secp and related errors trying to create keys means we have no hope of constructing
2275 // a spend transaction...so we return no transactions to broadcast
2276 let mut claimable_outpoints = Vec::new();
2277 let mut watch_outputs = Vec::new();
2278 let mut to_counterparty_output_info = None;
2280 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2281 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2283 macro_rules! ignore_error {
2284 ( $thing : expr ) => {
2287 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2292 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);
2293 if commitment_number >= self.get_min_seen_secret() {
2294 let secret = self.get_secret(commitment_number).unwrap();
2295 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2296 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2297 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2298 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key));
2300 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2301 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2303 // First, process non-htlc outputs (to_holder & to_counterparty)
2304 for (idx, outp) in tx.output.iter().enumerate() {
2305 if outp.script_pubkey == revokeable_p2wsh {
2306 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);
2307 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, true, height);
2308 claimable_outpoints.push(justice_package);
2309 to_counterparty_output_info =
2310 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
2314 // Then, try to find revoked htlc outputs
2315 if let Some(ref per_commitment_data) = per_commitment_option {
2316 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2317 if let Some(transaction_output_index) = htlc.transaction_output_index {
2318 if transaction_output_index as usize >= tx.output.len() ||
2319 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2320 // per_commitment_data is corrupt or our commitment signing key leaked!
2321 return (claimable_outpoints, (commitment_txid, watch_outputs),
2322 to_counterparty_output_info);
2324 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.opt_anchors.is_some());
2325 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2326 claimable_outpoints.push(justice_package);
2331 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2332 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2333 // We're definitely a counterparty commitment transaction!
2334 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2335 for (idx, outp) in tx.output.iter().enumerate() {
2336 watch_outputs.push((idx as u32, outp.clone()));
2338 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2340 if let Some(per_commitment_data) = per_commitment_option {
2341 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
2342 per_commitment_data.iter().map(|(htlc, htlc_source)|
2343 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2346 debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2347 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
2348 [].iter().map(|reference| *reference), logger);
2351 } else if let Some(per_commitment_data) = per_commitment_option {
2352 // While this isn't useful yet, there is a potential race where if a counterparty
2353 // revokes a state at the same time as the commitment transaction for that state is
2354 // confirmed, and the watchtower receives the block before the user, the user could
2355 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2356 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2357 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2359 for (idx, outp) in tx.output.iter().enumerate() {
2360 watch_outputs.push((idx as u32, outp.clone()));
2362 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2364 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2365 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height,
2366 per_commitment_data.iter().map(|(htlc, htlc_source)|
2367 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2370 let (htlc_claim_reqs, counterparty_output_info) =
2371 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
2372 to_counterparty_output_info = counterparty_output_info;
2373 for req in htlc_claim_reqs {
2374 claimable_outpoints.push(req);
2378 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2381 /// Returns the HTLC claim package templates and the counterparty output info
2382 fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
2383 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
2384 let mut claimable_outpoints = Vec::new();
2385 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
2387 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
2388 Some(outputs) => outputs,
2389 None => return (claimable_outpoints, to_counterparty_output_info),
2391 let per_commitment_points = match self.their_cur_per_commitment_points {
2392 Some(points) => points,
2393 None => return (claimable_outpoints, to_counterparty_output_info),
2396 let per_commitment_point =
2397 // If the counterparty commitment tx is the latest valid state, use their latest
2398 // per-commitment point
2399 if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
2400 else if let Some(point) = per_commitment_points.2.as_ref() {
2401 // If counterparty commitment tx is the state previous to the latest valid state, use
2402 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2403 // them to temporarily have two valid commitment txns from our viewpoint)
2404 if per_commitment_points.0 == commitment_number + 1 {
2406 } else { return (claimable_outpoints, to_counterparty_output_info); }
2407 } else { return (claimable_outpoints, to_counterparty_output_info); };
2409 if let Some(transaction) = tx {
2410 let revokeable_p2wsh_opt =
2411 if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
2412 &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
2414 if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
2415 &per_commitment_point,
2416 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
2418 Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2419 self.counterparty_commitment_params.on_counterparty_tx_csv,
2420 &delayed_key).to_v0_p2wsh())
2422 debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
2426 debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
2429 if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
2430 for (idx, outp) in transaction.output.iter().enumerate() {
2431 if outp.script_pubkey == revokeable_p2wsh {
2432 to_counterparty_output_info =
2433 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2439 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2440 if let Some(transaction_output_index) = htlc.transaction_output_index {
2441 if let Some(transaction) = tx {
2442 if transaction_output_index as usize >= transaction.output.len() ||
2443 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2444 // per_commitment_data is corrupt or our commitment signing key leaked!
2445 return (claimable_outpoints, to_counterparty_output_info);
2448 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2449 if preimage.is_some() || !htlc.offered {
2450 let counterparty_htlc_outp = if htlc.offered {
2451 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2452 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2453 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2454 self.counterparty_commitment_params.counterparty_htlc_base_key,
2455 preimage.unwrap(), htlc.clone()))
2457 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2458 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2459 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2460 self.counterparty_commitment_params.counterparty_htlc_base_key,
2463 let aggregation = if !htlc.offered { false } else { true };
2464 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2465 claimable_outpoints.push(counterparty_package);
2470 (claimable_outpoints, to_counterparty_output_info)
2473 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2474 fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
2475 let htlc_txid = tx.txid();
2476 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2477 return (Vec::new(), None)
2480 macro_rules! ignore_error {
2481 ( $thing : expr ) => {
2484 Err(_) => return (Vec::new(), None)
2489 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2490 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2491 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2493 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2494 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, tx.output[0].value, self.counterparty_commitment_params.on_counterparty_tx_csv);
2495 let justice_package = PackageTemplate::build_package(htlc_txid, 0, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
2496 let claimable_outpoints = vec!(justice_package);
2497 let outputs = vec![(0, tx.output[0].clone())];
2498 (claimable_outpoints, Some((htlc_txid, outputs)))
2501 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2502 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2503 // script so we can detect whether a holder transaction has been seen on-chain.
2504 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2505 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2507 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2508 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2510 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2511 if let Some(transaction_output_index) = htlc.transaction_output_index {
2512 let htlc_output = if htlc.offered {
2513 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2515 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2518 // We can't build an HTLC-Success transaction without the preimage
2521 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2523 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2524 claim_requests.push(htlc_package);
2528 (claim_requests, broadcasted_holder_revokable_script)
2531 // Returns holder HTLC outputs to watch and react to in case of spending.
2532 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2533 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2534 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2535 if let Some(transaction_output_index) = htlc.transaction_output_index {
2536 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2542 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2543 /// revoked using data in holder_claimable_outpoints.
2544 /// Should not be used if check_spend_revoked_transaction succeeds.
2545 /// Returns None unless the transaction is definitely one of our commitment transactions.
2546 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2547 let commitment_txid = tx.txid();
2548 let mut claim_requests = Vec::new();
2549 let mut watch_outputs = Vec::new();
2551 macro_rules! append_onchain_update {
2552 ($updates: expr, $to_watch: expr) => {
2553 claim_requests = $updates.0;
2554 self.broadcasted_holder_revokable_script = $updates.1;
2555 watch_outputs.append(&mut $to_watch);
2559 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2560 let mut is_holder_tx = false;
2562 if self.current_holder_commitment_tx.txid == commitment_txid {
2563 is_holder_tx = true;
2564 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2565 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2566 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2567 append_onchain_update!(res, to_watch);
2568 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
2569 self.current_holder_commitment_tx.htlc_outputs.iter()
2570 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2571 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2572 if holder_tx.txid == commitment_txid {
2573 is_holder_tx = true;
2574 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2575 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2576 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2577 append_onchain_update!(res, to_watch);
2578 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height,
2579 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2585 Some((claim_requests, (commitment_txid, watch_outputs)))
2591 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2592 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2593 self.holder_tx_signed = true;
2594 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2595 let txid = commitment_tx.txid();
2596 let mut holder_transactions = vec![commitment_tx];
2597 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2598 if let Some(vout) = htlc.0.transaction_output_index {
2599 let preimage = if !htlc.0.offered {
2600 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2601 // We can't build an HTLC-Success transaction without the preimage
2604 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2605 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2606 // current locktime requirements on-chain. We will broadcast them in
2607 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2608 // Note that we add + 1 as transactions are broadcastable when they can be
2609 // confirmed in the next block.
2612 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2613 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2614 holder_transactions.push(htlc_tx);
2618 // 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.
2619 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2623 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2624 /// Note that this includes possibly-locktimed-in-the-future transactions!
2625 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2626 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2627 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2628 let txid = commitment_tx.txid();
2629 let mut holder_transactions = vec![commitment_tx];
2630 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2631 if let Some(vout) = htlc.0.transaction_output_index {
2632 let preimage = if !htlc.0.offered {
2633 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2634 // We can't build an HTLC-Success transaction without the preimage
2638 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2639 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2640 holder_transactions.push(htlc_tx);
2647 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>
2648 where B::Target: BroadcasterInterface,
2649 F::Target: FeeEstimator,
2652 let block_hash = header.block_hash();
2653 self.best_block = BestBlock::new(block_hash, height);
2655 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2656 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2659 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2661 header: &BlockHeader,
2664 fee_estimator: &LowerBoundedFeeEstimator<F>,
2666 ) -> Vec<TransactionOutputs>
2668 B::Target: BroadcasterInterface,
2669 F::Target: FeeEstimator,
2672 let block_hash = header.block_hash();
2674 if height > self.best_block.height() {
2675 self.best_block = BestBlock::new(block_hash, height);
2676 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2677 } else if block_hash != self.best_block.block_hash() {
2678 self.best_block = BestBlock::new(block_hash, height);
2679 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2680 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2682 } else { Vec::new() }
2685 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2687 header: &BlockHeader,
2688 txdata: &TransactionData,
2691 fee_estimator: &LowerBoundedFeeEstimator<F>,
2693 ) -> Vec<TransactionOutputs>
2695 B::Target: BroadcasterInterface,
2696 F::Target: FeeEstimator,
2699 let txn_matched = self.filter_block(txdata);
2700 for tx in &txn_matched {
2701 let mut output_val = 0;
2702 for out in tx.output.iter() {
2703 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2704 output_val += out.value;
2705 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2709 let block_hash = header.block_hash();
2711 let mut watch_outputs = Vec::new();
2712 let mut claimable_outpoints = Vec::new();
2713 for tx in &txn_matched {
2714 if tx.input.len() == 1 {
2715 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2716 // commitment transactions and HTLC transactions will all only ever have one input,
2717 // which is an easy way to filter out any potential non-matching txn for lazy
2719 let prevout = &tx.input[0].previous_output;
2720 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2721 let mut balance_spendable_csv = None;
2722 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2723 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2724 self.funding_spend_seen = true;
2725 let mut commitment_tx_to_counterparty_output = None;
2726 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
2727 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
2728 self.check_spend_counterparty_transaction(&tx, height, &logger);
2729 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
2730 if !new_outputs.1.is_empty() {
2731 watch_outputs.push(new_outputs);
2733 claimable_outpoints.append(&mut new_outpoints);
2734 if new_outpoints.is_empty() {
2735 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2736 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
2737 "A commitment transaction matched as both a counterparty and local commitment tx?");
2738 if !new_outputs.1.is_empty() {
2739 watch_outputs.push(new_outputs);
2741 claimable_outpoints.append(&mut new_outpoints);
2742 balance_spendable_csv = Some(self.on_holder_tx_csv);
2746 let txid = tx.txid();
2747 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2749 transaction: Some((*tx).clone()),
2751 event: OnchainEvent::FundingSpendConfirmation {
2752 on_local_output_csv: balance_spendable_csv,
2753 commitment_tx_to_counterparty_output,
2757 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2758 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2759 claimable_outpoints.append(&mut new_outpoints);
2760 if let Some(new_outputs) = new_outputs_option {
2761 watch_outputs.push(new_outputs);
2766 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2767 // can also be resolved in a few other ways which can have more than one output. Thus,
2768 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2769 self.is_resolving_htlc_output(&tx, height, &logger);
2771 self.is_paying_spendable_output(&tx, height, &logger);
2774 if height > self.best_block.height() {
2775 self.best_block = BestBlock::new(block_hash, height);
2778 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2781 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2782 /// `self.best_block` before calling if a new best blockchain tip is available. More
2783 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2784 /// complexity especially in `OnchainTx::update_claims_view`.
2786 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2787 /// confirmed at, even if it is not the current best height.
2788 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2791 txn_matched: Vec<&Transaction>,
2792 mut watch_outputs: Vec<TransactionOutputs>,
2793 mut claimable_outpoints: Vec<PackageTemplate>,
2795 fee_estimator: &LowerBoundedFeeEstimator<F>,
2797 ) -> Vec<TransactionOutputs>
2799 B::Target: BroadcasterInterface,
2800 F::Target: FeeEstimator,
2803 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2804 debug_assert!(self.best_block.height() >= conf_height);
2806 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2807 if should_broadcast {
2808 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2809 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(), false, self.best_block.height());
2810 claimable_outpoints.push(commitment_package);
2811 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2812 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2813 self.holder_tx_signed = true;
2814 // Because we're broadcasting a commitment transaction, we should construct the package
2815 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2816 // "not yet confirmed" things as discardable, so we cannot do that here.
2817 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2818 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2819 if !new_outputs.is_empty() {
2820 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2822 claimable_outpoints.append(&mut new_outpoints);
2825 // Find which on-chain events have reached their confirmation threshold.
2826 let onchain_events_awaiting_threshold_conf =
2827 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2828 let mut onchain_events_reaching_threshold_conf = Vec::new();
2829 for entry in onchain_events_awaiting_threshold_conf {
2830 if entry.has_reached_confirmation_threshold(&self.best_block) {
2831 onchain_events_reaching_threshold_conf.push(entry);
2833 self.onchain_events_awaiting_threshold_conf.push(entry);
2837 // Used to check for duplicate HTLC resolutions.
2838 #[cfg(debug_assertions)]
2839 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2841 .filter_map(|entry| match &entry.event {
2842 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2846 #[cfg(debug_assertions)]
2847 let mut matured_htlcs = Vec::new();
2849 // Produce actionable events from on-chain events having reached their threshold.
2850 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2852 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2853 // Check for duplicate HTLC resolutions.
2854 #[cfg(debug_assertions)]
2857 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2858 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2859 call either transaction_unconfirmed for the conflicting transaction \
2860 or block_disconnected for a block containing it.");
2862 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2863 "A matured HTLC transaction conflicts with a maturing one; failed to \
2864 call either transaction_unconfirmed for the conflicting transaction \
2865 or block_disconnected for a block containing it.");
2866 matured_htlcs.push(source.clone());
2869 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2870 log_bytes!(payment_hash.0), entry.txid);
2871 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2873 payment_preimage: None,
2874 source: source.clone(),
2875 htlc_value_satoshis,
2877 if let Some(idx) = commitment_tx_output_idx {
2878 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2879 commitment_tx_output_idx: idx, resolving_txid: Some(entry.txid),
2880 payment_preimage: None,
2884 OnchainEvent::MaturingOutput { descriptor } => {
2885 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2886 self.pending_events.push(Event::SpendableOutputs {
2887 outputs: vec![descriptor]
2890 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2891 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2892 commitment_tx_output_idx, resolving_txid: Some(entry.txid),
2893 payment_preimage: preimage,
2896 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
2897 self.funding_spend_confirmed = Some(entry.txid);
2898 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
2903 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2905 // Determine new outputs to watch by comparing against previously known outputs to watch,
2906 // updating the latter in the process.
2907 watch_outputs.retain(|&(ref txid, ref txouts)| {
2908 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2909 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2913 // If we see a transaction for which we registered outputs previously,
2914 // make sure the registered scriptpubkey at the expected index match
2915 // the actual transaction output one. We failed this case before #653.
2916 for tx in &txn_matched {
2917 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2918 for idx_and_script in outputs.iter() {
2919 assert!((idx_and_script.0 as usize) < tx.output.len());
2920 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2928 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2929 where B::Target: BroadcasterInterface,
2930 F::Target: FeeEstimator,
2933 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2936 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2937 //- maturing spendable output has transaction paying us has been disconnected
2938 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2940 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2941 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2943 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2946 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2950 fee_estimator: &LowerBoundedFeeEstimator<F>,
2953 B::Target: BroadcasterInterface,
2954 F::Target: FeeEstimator,
2957 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2958 log_info!(logger, "Removing onchain event with txid {}", txid);
2961 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2964 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2965 /// transactions thereof.
2966 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2967 let mut matched_txn = HashSet::new();
2968 txdata.iter().filter(|&&(_, tx)| {
2969 let mut matches = self.spends_watched_output(tx);
2970 for input in tx.input.iter() {
2971 if matches { break; }
2972 if matched_txn.contains(&input.previous_output.txid) {
2977 matched_txn.insert(tx.txid());
2980 }).map(|(_, tx)| *tx).collect()
2983 /// Checks if a given transaction spends any watched outputs.
2984 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2985 for input in tx.input.iter() {
2986 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2987 for (idx, _script_pubkey) in outputs.iter() {
2988 if *idx == input.previous_output.vout {
2991 // If the expected script is a known type, check that the witness
2992 // appears to be spending the correct type (ie that the match would
2993 // actually succeed in BIP 158/159-style filters).
2994 if _script_pubkey.is_v0_p2wsh() {
2995 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
2996 // In at least one test we use a deliberately bogus witness
2997 // script which hit an old panic. Thus, we check for that here
2998 // and avoid the assert if its the expected bogus script.
3002 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
3003 } else if _script_pubkey.is_v0_p2wpkh() {
3004 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
3005 } else { panic!(); }
3016 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
3017 // We need to consider all HTLCs which are:
3018 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
3019 // transactions and we'd end up in a race, or
3020 // * are in our latest holder commitment transaction, as this is the thing we will
3021 // broadcast if we go on-chain.
3022 // Note that we consider HTLCs which were below dust threshold here - while they don't
3023 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
3024 // to the source, and if we don't fail the channel we will have to ensure that the next
3025 // updates that peer sends us are update_fails, failing the channel if not. It's probably
3026 // easier to just fail the channel as this case should be rare enough anyway.
3027 let height = self.best_block.height();
3028 macro_rules! scan_commitment {
3029 ($htlcs: expr, $holder_tx: expr) => {
3030 for ref htlc in $htlcs {
3031 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
3032 // chain with enough room to claim the HTLC without our counterparty being able to
3033 // time out the HTLC first.
3034 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
3035 // concern is being able to claim the corresponding inbound HTLC (on another
3036 // channel) before it expires. In fact, we don't even really care if our
3037 // counterparty here claims such an outbound HTLC after it expired as long as we
3038 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
3039 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
3040 // we give ourselves a few blocks of headroom after expiration before going
3041 // on-chain for an expired HTLC.
3042 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
3043 // from us until we've reached the point where we go on-chain with the
3044 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
3045 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
3046 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
3047 // inbound_cltv == height + CLTV_CLAIM_BUFFER
3048 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
3049 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
3050 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
3051 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
3052 // The final, above, condition is checked for statically in channelmanager
3053 // with CHECK_CLTV_EXPIRY_SANITY_2.
3054 let htlc_outbound = $holder_tx == htlc.offered;
3055 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
3056 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
3057 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
3064 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
3066 if let Some(ref txid) = self.current_counterparty_commitment_txid {
3067 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3068 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3071 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
3072 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3073 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3080 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
3081 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
3082 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3083 'outer_loop: for input in &tx.input {
3084 let mut payment_data = None;
3085 let witness_items = input.witness.len();
3086 let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
3087 let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
3088 let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
3089 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
3090 let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
3091 && input.witness.second_to_last().unwrap().len() == 32;
3092 #[cfg(not(fuzzing))]
3093 let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
3094 let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
3095 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
3097 #[cfg(not(fuzzing))]
3098 let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
3100 let mut payment_preimage = PaymentPreimage([0; 32]);
3101 if accepted_preimage_claim {
3102 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3103 } else if offered_preimage_claim {
3104 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3107 macro_rules! log_claim {
3108 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
3109 let outbound_htlc = $holder_tx == $htlc.offered;
3110 // HTLCs must either be claimed by a matching script type or through the
3112 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3113 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
3114 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3115 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
3116 // Further, only exactly one of the possible spend paths should have been
3117 // matched by any HTLC spend:
3118 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3119 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
3120 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
3121 revocation_sig_claim as u8, 1);
3122 if ($holder_tx && revocation_sig_claim) ||
3123 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
3124 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
3125 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3126 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3127 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" });
3129 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
3130 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3131 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3132 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
3137 macro_rules! check_htlc_valid_counterparty {
3138 ($counterparty_txid: expr, $htlc_output: expr) => {
3139 if let Some(txid) = $counterparty_txid {
3140 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
3141 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
3142 if let &Some(ref source) = pending_source {
3143 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
3144 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
3153 macro_rules! scan_commitment {
3154 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
3155 for (ref htlc_output, source_option) in $htlcs {
3156 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
3157 if let Some(ref source) = source_option {
3158 log_claim!($tx_info, $holder_tx, htlc_output, true);
3159 // We have a resolution of an HTLC either from one of our latest
3160 // holder commitment transactions or an unrevoked counterparty commitment
3161 // transaction. This implies we either learned a preimage, the HTLC
3162 // has timed out, or we screwed up. In any case, we should now
3163 // resolve the source HTLC with the original sender.
3164 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
3165 } else if !$holder_tx {
3166 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3167 if payment_data.is_none() {
3168 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3171 if payment_data.is_none() {
3172 log_claim!($tx_info, $holder_tx, htlc_output, false);
3173 let outbound_htlc = $holder_tx == htlc_output.offered;
3174 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3175 txid: tx.txid(), height, transaction: Some(tx.clone()),
3176 event: OnchainEvent::HTLCSpendConfirmation {
3177 commitment_tx_output_idx: input.previous_output.vout,
3178 preimage: if accepted_preimage_claim || offered_preimage_claim {
3179 Some(payment_preimage) } else { None },
3180 // If this is a payment to us (ie !outbound_htlc), wait for
3181 // the CSV delay before dropping the HTLC from claimable
3182 // balance if the claim was an HTLC-Success transaction (ie
3183 // accepted_preimage_claim).
3184 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
3185 Some(self.on_holder_tx_csv) } else { None },
3188 continue 'outer_loop;
3195 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3196 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3197 "our latest holder commitment tx", true);
3199 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3200 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3201 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3202 "our previous holder commitment tx", true);
3205 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3206 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3207 "counterparty commitment tx", false);
3210 // Check that scan_commitment, above, decided there is some source worth relaying an
3211 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3212 if let Some((source, payment_hash, amount_msat)) = payment_data {
3213 if accepted_preimage_claim {
3214 if !self.pending_monitor_events.iter().any(
3215 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3216 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3219 transaction: Some(tx.clone()),
3220 event: OnchainEvent::HTLCSpendConfirmation {
3221 commitment_tx_output_idx: input.previous_output.vout,
3222 preimage: Some(payment_preimage),
3223 on_to_local_output_csv: None,
3226 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3228 payment_preimage: Some(payment_preimage),
3230 htlc_value_satoshis: Some(amount_msat / 1000),
3233 } else if offered_preimage_claim {
3234 if !self.pending_monitor_events.iter().any(
3235 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3236 upd.source == source
3238 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3240 transaction: Some(tx.clone()),
3242 event: OnchainEvent::HTLCSpendConfirmation {
3243 commitment_tx_output_idx: input.previous_output.vout,
3244 preimage: Some(payment_preimage),
3245 on_to_local_output_csv: None,
3248 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3250 payment_preimage: Some(payment_preimage),
3252 htlc_value_satoshis: Some(amount_msat / 1000),
3256 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3257 if entry.height != height { return true; }
3259 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3260 *htlc_source != source
3265 let entry = OnchainEventEntry {
3267 transaction: Some(tx.clone()),
3269 event: OnchainEvent::HTLCUpdate {
3270 source, payment_hash,
3271 htlc_value_satoshis: Some(amount_msat / 1000),
3272 commitment_tx_output_idx: Some(input.previous_output.vout),
3275 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", log_bytes!(payment_hash.0), entry.confirmation_threshold());
3276 self.onchain_events_awaiting_threshold_conf.push(entry);
3282 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3283 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3284 let mut spendable_output = None;
3285 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3286 if i > ::core::u16::MAX as usize {
3287 // While it is possible that an output exists on chain which is greater than the
3288 // 2^16th output in a given transaction, this is only possible if the output is not
3289 // in a lightning transaction and was instead placed there by some third party who
3290 // wishes to give us money for no reason.
3291 // Namely, any lightning transactions which we pre-sign will never have anywhere
3292 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3293 // scripts are not longer than one byte in length and because they are inherently
3294 // non-standard due to their size.
3295 // Thus, it is completely safe to ignore such outputs, and while it may result in
3296 // us ignoring non-lightning fund to us, that is only possible if someone fills
3297 // nearly a full block with garbage just to hit this case.
3300 if outp.script_pubkey == self.destination_script {
3301 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3302 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3303 output: outp.clone(),
3307 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3308 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3309 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3310 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3311 per_commitment_point: broadcasted_holder_revokable_script.1,
3312 to_self_delay: self.on_holder_tx_csv,
3313 output: outp.clone(),
3314 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3315 channel_keys_id: self.channel_keys_id,
3316 channel_value_satoshis: self.channel_value_satoshis,
3321 if self.counterparty_payment_script == outp.script_pubkey {
3322 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3323 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3324 output: outp.clone(),
3325 channel_keys_id: self.channel_keys_id,
3326 channel_value_satoshis: self.channel_value_satoshis,
3330 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3331 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3332 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3333 output: outp.clone(),
3338 if let Some(spendable_output) = spendable_output {
3339 let entry = OnchainEventEntry {
3341 transaction: Some(tx.clone()),
3343 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3345 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3346 self.onchain_events_awaiting_threshold_conf.push(entry);
3351 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3353 T::Target: BroadcasterInterface,
3354 F::Target: FeeEstimator,
3357 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3358 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3361 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3362 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3366 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3368 T::Target: BroadcasterInterface,
3369 F::Target: FeeEstimator,
3372 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3373 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3376 fn transaction_unconfirmed(&self, txid: &Txid) {
3377 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3380 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3381 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3384 fn get_relevant_txids(&self) -> Vec<Txid> {
3385 self.0.get_relevant_txids()
3389 const MAX_ALLOC_SIZE: usize = 64*1024;
3391 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3392 for (BlockHash, ChannelMonitor<Signer>) {
3393 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3394 macro_rules! unwrap_obj {
3398 Err(_) => return Err(DecodeError::InvalidValue),
3403 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3405 let latest_update_id: u64 = Readable::read(reader)?;
3406 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3408 let destination_script = Readable::read(reader)?;
3409 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3411 let revokable_address = Readable::read(reader)?;
3412 let per_commitment_point = Readable::read(reader)?;
3413 let revokable_script = Readable::read(reader)?;
3414 Some((revokable_address, per_commitment_point, revokable_script))
3417 _ => return Err(DecodeError::InvalidValue),
3419 let counterparty_payment_script = Readable::read(reader)?;
3420 let shutdown_script = {
3421 let script = <Script as Readable>::read(reader)?;
3422 if script.is_empty() { None } else { Some(script) }
3425 let channel_keys_id = Readable::read(reader)?;
3426 let holder_revocation_basepoint = Readable::read(reader)?;
3427 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3428 // barely-init'd ChannelMonitors that we can't do anything with.
3429 let outpoint = OutPoint {
3430 txid: Readable::read(reader)?,
3431 index: Readable::read(reader)?,
3433 let funding_info = (outpoint, Readable::read(reader)?);
3434 let current_counterparty_commitment_txid = Readable::read(reader)?;
3435 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3437 let counterparty_commitment_params = Readable::read(reader)?;
3438 let funding_redeemscript = Readable::read(reader)?;
3439 let channel_value_satoshis = Readable::read(reader)?;
3441 let their_cur_per_commitment_points = {
3442 let first_idx = <U48 as Readable>::read(reader)?.0;
3446 let first_point = Readable::read(reader)?;
3447 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3448 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3449 Some((first_idx, first_point, None))
3451 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3456 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3458 let commitment_secrets = Readable::read(reader)?;
3460 macro_rules! read_htlc_in_commitment {
3463 let offered: bool = Readable::read(reader)?;
3464 let amount_msat: u64 = Readable::read(reader)?;
3465 let cltv_expiry: u32 = Readable::read(reader)?;
3466 let payment_hash: PaymentHash = Readable::read(reader)?;
3467 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3469 HTLCOutputInCommitment {
3470 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3476 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3477 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3478 for _ in 0..counterparty_claimable_outpoints_len {
3479 let txid: Txid = Readable::read(reader)?;
3480 let htlcs_count: u64 = Readable::read(reader)?;
3481 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3482 for _ in 0..htlcs_count {
3483 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3485 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3486 return Err(DecodeError::InvalidValue);
3490 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3491 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3492 for _ in 0..counterparty_commitment_txn_on_chain_len {
3493 let txid: Txid = Readable::read(reader)?;
3494 let commitment_number = <U48 as Readable>::read(reader)?.0;
3495 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3496 return Err(DecodeError::InvalidValue);
3500 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3501 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3502 for _ in 0..counterparty_hash_commitment_number_len {
3503 let payment_hash: PaymentHash = Readable::read(reader)?;
3504 let commitment_number = <U48 as Readable>::read(reader)?.0;
3505 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3506 return Err(DecodeError::InvalidValue);
3510 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3511 match <u8 as Readable>::read(reader)? {
3514 Some(Readable::read(reader)?)
3516 _ => return Err(DecodeError::InvalidValue),
3518 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3520 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3521 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3523 let payment_preimages_len: u64 = Readable::read(reader)?;
3524 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3525 for _ in 0..payment_preimages_len {
3526 let preimage: PaymentPreimage = Readable::read(reader)?;
3527 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3528 if let Some(_) = payment_preimages.insert(hash, preimage) {
3529 return Err(DecodeError::InvalidValue);
3533 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3534 let mut pending_monitor_events = Some(
3535 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3536 for _ in 0..pending_monitor_events_len {
3537 let ev = match <u8 as Readable>::read(reader)? {
3538 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3539 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3540 _ => return Err(DecodeError::InvalidValue)
3542 pending_monitor_events.as_mut().unwrap().push(ev);
3545 let pending_events_len: u64 = Readable::read(reader)?;
3546 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3547 for _ in 0..pending_events_len {
3548 if let Some(event) = MaybeReadable::read(reader)? {
3549 pending_events.push(event);
3553 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3555 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3556 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3557 for _ in 0..waiting_threshold_conf_len {
3558 if let Some(val) = MaybeReadable::read(reader)? {
3559 onchain_events_awaiting_threshold_conf.push(val);
3563 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3564 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>>())));
3565 for _ in 0..outputs_to_watch_len {
3566 let txid = Readable::read(reader)?;
3567 let outputs_len: u64 = Readable::read(reader)?;
3568 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3569 for _ in 0..outputs_len {
3570 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3572 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3573 return Err(DecodeError::InvalidValue);
3576 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3578 let lockdown_from_offchain = Readable::read(reader)?;
3579 let holder_tx_signed = Readable::read(reader)?;
3581 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3582 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3583 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3584 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3585 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3586 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3587 return Err(DecodeError::InvalidValue);
3591 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3592 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3593 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3594 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3595 return Err(DecodeError::InvalidValue);
3598 let mut funding_spend_confirmed = None;
3599 let mut htlcs_resolved_on_chain = Some(Vec::new());
3600 let mut funding_spend_seen = Some(false);
3601 let mut counterparty_node_id = None;
3602 let mut confirmed_commitment_tx_counterparty_output = None;
3603 read_tlv_fields!(reader, {
3604 (1, funding_spend_confirmed, option),
3605 (3, htlcs_resolved_on_chain, vec_type),
3606 (5, pending_monitor_events, vec_type),
3607 (7, funding_spend_seen, option),
3608 (9, counterparty_node_id, option),
3609 (11, confirmed_commitment_tx_counterparty_output, option),
3612 let mut secp_ctx = Secp256k1::new();
3613 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3615 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3617 commitment_transaction_number_obscure_factor,
3620 broadcasted_holder_revokable_script,
3621 counterparty_payment_script,
3625 holder_revocation_basepoint,
3627 current_counterparty_commitment_txid,
3628 prev_counterparty_commitment_txid,
3630 counterparty_commitment_params,
3631 funding_redeemscript,
3632 channel_value_satoshis,
3633 their_cur_per_commitment_points,
3638 counterparty_claimable_outpoints,
3639 counterparty_commitment_txn_on_chain,
3640 counterparty_hash_commitment_number,
3642 prev_holder_signed_commitment_tx,
3643 current_holder_commitment_tx,
3644 current_counterparty_commitment_number,
3645 current_holder_commitment_number,
3648 pending_monitor_events: pending_monitor_events.unwrap(),
3651 onchain_events_awaiting_threshold_conf,
3656 lockdown_from_offchain,
3658 funding_spend_seen: funding_spend_seen.unwrap(),
3659 funding_spend_confirmed,
3660 confirmed_commitment_tx_counterparty_output,
3661 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3664 counterparty_node_id,
3673 use bitcoin::blockdata::block::BlockHeader;
3674 use bitcoin::blockdata::script::{Script, Builder};
3675 use bitcoin::blockdata::opcodes;
3676 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3677 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3678 use bitcoin::util::sighash;
3679 use bitcoin::hashes::Hash;
3680 use bitcoin::hashes::sha256::Hash as Sha256;
3681 use bitcoin::hashes::hex::FromHex;
3682 use bitcoin::hash_types::{BlockHash, Txid};
3683 use bitcoin::network::constants::Network;
3684 use bitcoin::secp256k1::{SecretKey,PublicKey};
3685 use bitcoin::secp256k1::Secp256k1;
3689 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3691 use super::ChannelMonitorUpdateStep;
3692 use ::{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};
3693 use chain::{BestBlock, Confirm};
3694 use chain::channelmonitor::ChannelMonitor;
3695 use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3696 use chain::transaction::OutPoint;
3697 use chain::keysinterface::InMemorySigner;
3698 use ln::{PaymentPreimage, PaymentHash};
3700 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3701 use ln::channelmanager::PaymentSendFailure;
3702 use ln::features::InitFeatures;
3703 use ln::functional_test_utils::*;
3704 use ln::script::ShutdownScript;
3705 use util::errors::APIError;
3706 use util::events::{ClosureReason, MessageSendEventsProvider};
3707 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3708 use util::ser::{ReadableArgs, Writeable};
3709 use sync::{Arc, Mutex};
3711 use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
3714 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3715 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3716 // confirmed. This would allow a race condition where we could receive a payment (including
3717 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3718 // long as the ChannelMonitor receives the block first, the full commitment update dance
3719 // occurs after the block is connected, and before the ChannelManager receives the block.
3720 // Obviously this is an incredibly contrived race given the counterparty would be risking
3721 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3722 // potential ChannelMonitor states simpler to reason about.
3724 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3725 // updates is handled correctly in such conditions.
3726 let chanmon_cfgs = create_chanmon_cfgs(3);
3727 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3728 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3729 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3730 let channel = create_announced_chan_between_nodes(
3731 &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3732 create_announced_chan_between_nodes(
3733 &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3735 // Rebalance somewhat
3736 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3738 // First route two payments for testing at the end
3739 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3740 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3742 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3743 assert_eq!(local_txn.len(), 1);
3744 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3745 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3746 check_spends!(remote_txn[1], remote_txn[0]);
3747 check_spends!(remote_txn[2], remote_txn[0]);
3748 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3750 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3751 // channel is now closed, but the ChannelManager doesn't know that yet.
3752 let new_header = BlockHeader {
3753 version: 2, time: 0, bits: 0, nonce: 0,
3754 prev_blockhash: nodes[0].best_block_info().0,
3755 merkle_root: TxMerkleNode::all_zeros() };
3756 let conf_height = nodes[0].best_block_info().1 + 1;
3757 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3758 &[(0, broadcast_tx)], conf_height);
3760 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3761 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3762 &nodes[1].keys_manager.backing).unwrap();
3764 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3765 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3766 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3767 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3768 true, APIError::ChannelUnavailable { ref err },
3769 assert!(err.contains("ChannelMonitor storage failure")));
3770 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3771 check_closed_broadcast!(nodes[1], true);
3772 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3774 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3775 // and provides the claim preimages for the two pending HTLCs. The first update generates
3776 // an error, but the point of this test is to ensure the later updates are still applied.
3777 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3778 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3779 assert_eq!(replay_update.updates.len(), 1);
3780 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3781 } else { panic!(); }
3782 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3783 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3785 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3787 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3789 // Even though we error'd on the first update, we should still have generated an HTLC claim
3791 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3792 assert!(txn_broadcasted.len() >= 2);
3793 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3794 assert_eq!(tx.input.len(), 1);
3795 tx.input[0].previous_output.txid == broadcast_tx.txid()
3796 }).collect::<Vec<_>>();
3797 assert_eq!(htlc_txn.len(), 2);
3798 check_spends!(htlc_txn[0], broadcast_tx);
3799 check_spends!(htlc_txn[1], broadcast_tx);
3802 fn test_funding_spend_refuses_updates() {
3803 do_test_funding_spend_refuses_updates(true);
3804 do_test_funding_spend_refuses_updates(false);
3808 fn test_prune_preimages() {
3809 let secp_ctx = Secp256k1::new();
3810 let logger = Arc::new(TestLogger::new());
3811 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3812 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3814 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3815 let dummy_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3817 let mut preimages = Vec::new();
3820 let preimage = PaymentPreimage([i; 32]);
3821 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3822 preimages.push((preimage, hash));
3826 macro_rules! preimages_slice_to_htlc_outputs {
3827 ($preimages_slice: expr) => {
3829 let mut res = Vec::new();
3830 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3831 res.push((HTLCOutputInCommitment {
3835 payment_hash: preimage.1.clone(),
3836 transaction_output_index: Some(idx as u32),
3843 macro_rules! preimages_to_holder_htlcs {
3844 ($preimages_slice: expr) => {
3846 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3847 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3853 macro_rules! test_preimages_exist {
3854 ($preimages_slice: expr, $monitor: expr) => {
3855 for preimage in $preimages_slice {
3856 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3861 let keys = InMemorySigner::new(
3863 SecretKey::from_slice(&[41; 32]).unwrap(),
3864 SecretKey::from_slice(&[41; 32]).unwrap(),
3865 SecretKey::from_slice(&[41; 32]).unwrap(),
3866 SecretKey::from_slice(&[41; 32]).unwrap(),
3867 SecretKey::from_slice(&[41; 32]).unwrap(),
3868 SecretKey::from_slice(&[41; 32]).unwrap(),
3874 let counterparty_pubkeys = ChannelPublicKeys {
3875 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3876 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3877 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3878 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3879 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3881 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
3882 let channel_parameters = ChannelTransactionParameters {
3883 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3884 holder_selected_contest_delay: 66,
3885 is_outbound_from_holder: true,
3886 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3887 pubkeys: counterparty_pubkeys,
3888 selected_contest_delay: 67,
3890 funding_outpoint: Some(funding_outpoint),
3893 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3895 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3896 let best_block = BestBlock::from_genesis(Network::Testnet);
3897 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3898 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3899 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3900 &channel_parameters,
3901 Script::new(), 46, 0,
3902 HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3904 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3905 let dummy_txid = dummy_tx.txid();
3906 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3907 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3908 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3909 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3910 for &(ref preimage, ref hash) in preimages.iter() {
3911 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3912 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3915 // Now provide a secret, pruning preimages 10-15
3916 let mut secret = [0; 32];
3917 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3918 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3919 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3920 test_preimages_exist!(&preimages[0..10], monitor);
3921 test_preimages_exist!(&preimages[15..20], monitor);
3923 // Now provide a further secret, pruning preimages 15-17
3924 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3925 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3926 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3927 test_preimages_exist!(&preimages[0..10], monitor);
3928 test_preimages_exist!(&preimages[17..20], monitor);
3930 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3931 // previous commitment tx's preimages too
3932 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3933 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3934 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3935 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3936 test_preimages_exist!(&preimages[0..10], monitor);
3937 test_preimages_exist!(&preimages[18..20], monitor);
3939 // But if we do it again, we'll prune 5-10
3940 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3941 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3942 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3943 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3944 test_preimages_exist!(&preimages[0..5], monitor);
3948 fn test_claim_txn_weight_computation() {
3949 // We test Claim txn weight, knowing that we want expected weigth and
3950 // not actual case to avoid sigs and time-lock delays hell variances.
3952 let secp_ctx = Secp256k1::new();
3953 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3954 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3956 macro_rules! sign_input {
3957 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3958 let htlc = HTLCOutputInCommitment {
3959 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3961 cltv_expiry: 2 << 16,
3962 payment_hash: PaymentHash([1; 32]),
3963 transaction_output_index: Some($idx as u32),
3965 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) };
3966 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3967 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3968 let mut ser_sig = sig.serialize_der().to_vec();
3969 ser_sig.push(EcdsaSighashType::All as u8);
3970 $sum_actual_sigs += ser_sig.len();
3971 let witness = $sighash_parts.witness_mut($idx).unwrap();
3972 witness.push(ser_sig);
3973 if *$weight == WEIGHT_REVOKED_OUTPUT {
3974 witness.push(vec!(1));
3975 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3976 witness.push(pubkey.clone().serialize().to_vec());
3977 } else if *$weight == weight_received_htlc($opt_anchors) {
3978 witness.push(vec![0]);
3980 witness.push(PaymentPreimage([1; 32]).0.to_vec());
3982 witness.push(redeem_script.into_bytes());
3983 let witness = witness.to_vec();
3984 println!("witness[0] {}", witness[0].len());
3985 println!("witness[1] {}", witness[1].len());
3986 println!("witness[2] {}", witness[2].len());
3990 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3991 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3993 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3994 for &opt_anchors in [false, true].iter() {
3995 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3996 let mut sum_actual_sigs = 0;
3998 claim_tx.input.push(TxIn {
3999 previous_output: BitcoinOutPoint {
4003 script_sig: Script::new(),
4004 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4005 witness: Witness::new(),
4008 claim_tx.output.push(TxOut {
4009 script_pubkey: script_pubkey.clone(),
4012 let base_weight = claim_tx.weight();
4013 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(opt_anchors), weight_revoked_offered_htlc(opt_anchors), weight_revoked_received_htlc(opt_anchors)];
4014 let mut inputs_total_weight = 2; // count segwit flags
4016 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4017 for (idx, inp) in inputs_weight.iter().enumerate() {
4018 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4019 inputs_total_weight += inp;
4022 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4025 // Claim tx with 1 offered HTLCs, 3 received HTLCs
4026 for &opt_anchors in [false, true].iter() {
4027 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4028 let mut sum_actual_sigs = 0;
4030 claim_tx.input.push(TxIn {
4031 previous_output: BitcoinOutPoint {
4035 script_sig: Script::new(),
4036 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4037 witness: Witness::new(),
4040 claim_tx.output.push(TxOut {
4041 script_pubkey: script_pubkey.clone(),
4044 let base_weight = claim_tx.weight();
4045 let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
4046 let mut inputs_total_weight = 2; // count segwit flags
4048 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4049 for (idx, inp) in inputs_weight.iter().enumerate() {
4050 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4051 inputs_total_weight += inp;
4054 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4057 // Justice tx with 1 revoked HTLC-Success tx output
4058 for &opt_anchors in [false, true].iter() {
4059 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4060 let mut sum_actual_sigs = 0;
4061 claim_tx.input.push(TxIn {
4062 previous_output: BitcoinOutPoint {
4066 script_sig: Script::new(),
4067 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4068 witness: Witness::new(),
4070 claim_tx.output.push(TxOut {
4071 script_pubkey: script_pubkey.clone(),
4074 let base_weight = claim_tx.weight();
4075 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
4076 let mut inputs_total_weight = 2; // count segwit flags
4078 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4079 for (idx, inp) in inputs_weight.iter().enumerate() {
4080 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4081 inputs_total_weight += inp;
4084 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
4088 // Further testing is done in the ChannelManager integration tests.