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::script::{Script, Builder};
26 use bitcoin::blockdata::opcodes;
28 use bitcoin::hashes::Hash;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
32 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
33 use bitcoin::secp256k1::{SecretKey, PublicKey};
34 use bitcoin::secp256k1;
36 use ln::{PaymentHash, PaymentPreimage};
37 use ln::msgs::DecodeError;
39 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
40 use ln::channelmanager::HTLCSource;
42 use chain::{BestBlock, WatchedOutput};
43 use chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
44 use chain::transaction::{OutPoint, TransactionData};
45 use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
46 use chain::onchaintx::OnchainTxHandler;
47 use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
49 use util::logger::Logger;
50 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
52 use util::events::Event;
56 use io::{self, Error};
57 use core::convert::TryInto;
61 /// An update generated by the underlying Channel itself which contains some new information the
62 /// ChannelMonitor should be made aware of.
63 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
66 pub struct ChannelMonitorUpdate {
67 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
68 /// The sequence number of this update. Updates *must* be replayed in-order according to this
69 /// sequence number (and updates may panic if they are not). The update_id values are strictly
70 /// increasing and increase by one for each new update, with one exception specified below.
72 /// This sequence number is also used to track up to which points updates which returned
73 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
74 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
76 /// The only instance where update_id values are not strictly increasing is the case where we
77 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
78 /// its docs for more details.
83 /// (1) a channel has been force closed and
84 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
85 /// this channel's (the backward link's) broadcasted commitment transaction
86 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
87 /// with the update providing said payment preimage. No other update types are allowed after
89 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
91 impl Writeable for ChannelMonitorUpdate {
92 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
93 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
94 self.update_id.write(w)?;
95 (self.updates.len() as u64).write(w)?;
96 for update_step in self.updates.iter() {
97 update_step.write(w)?;
99 write_tlv_fields!(w, {});
103 impl Readable for ChannelMonitorUpdate {
104 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
105 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
106 let update_id: u64 = Readable::read(r)?;
107 let len: u64 = Readable::read(r)?;
108 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
110 if let Some(upd) = MaybeReadable::read(r)? {
114 read_tlv_fields!(r, {});
115 Ok(Self { update_id, updates })
119 /// An event to be processed by the ChannelManager.
120 #[derive(Clone, PartialEq)]
121 pub enum MonitorEvent {
122 /// A monitor event containing an HTLCUpdate.
123 HTLCEvent(HTLCUpdate),
125 /// A monitor event that the Channel's commitment transaction was confirmed.
126 CommitmentTxConfirmed(OutPoint),
128 /// Indicates a [`ChannelMonitor`] update has completed. See
129 /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
131 /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
133 /// The funding outpoint of the [`ChannelMonitor`] that was updated
134 funding_txo: OutPoint,
135 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
136 /// [`ChannelMonitor::get_latest_update_id`].
138 /// Note that this should only be set to a given update's ID if all previous updates for the
139 /// same [`ChannelMonitor`] have been applied and persisted.
140 monitor_update_id: u64,
143 /// Indicates a [`ChannelMonitor`] update has failed. See
144 /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
146 /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
147 UpdateFailed(OutPoint),
149 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
150 // Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
151 // generated only in ChainMonitor
152 (0, UpdateCompleted) => {
153 (0, funding_txo, required),
154 (2, monitor_update_id, required),
158 (4, CommitmentTxConfirmed),
162 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
163 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
164 /// preimage claim backward will lead to loss of funds.
165 #[derive(Clone, PartialEq)]
166 pub struct HTLCUpdate {
167 pub(crate) payment_hash: PaymentHash,
168 pub(crate) payment_preimage: Option<PaymentPreimage>,
169 pub(crate) source: HTLCSource,
170 pub(crate) htlc_value_satoshis: Option<u64>,
172 impl_writeable_tlv_based!(HTLCUpdate, {
173 (0, payment_hash, required),
174 (1, htlc_value_satoshis, option),
175 (2, source, required),
176 (4, payment_preimage, option),
179 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
180 /// instead claiming it in its own individual transaction.
181 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
182 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
183 /// HTLC-Success transaction.
184 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
185 /// transaction confirmed (and we use it in a few more, equivalent, places).
186 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
187 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
188 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
189 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
190 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
191 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
192 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
193 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
194 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
195 /// accurate block height.
196 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
197 /// with at worst this delay, so we are not only using this value as a mercy for them but also
198 /// us as a safeguard to delay with enough time.
199 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
200 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
201 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
204 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
205 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
206 /// by a [`ChannelMonitor`] may be incorrect.
207 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
208 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
209 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
210 // keep bumping another claim tx to solve the outpoint.
211 pub const ANTI_REORG_DELAY: u32 = 6;
212 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
213 /// refuse to accept a new HTLC.
215 /// This is used for a few separate purposes:
216 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
217 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
219 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
220 /// condition with the above), we will fail this HTLC without telling the user we received it,
222 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
223 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
225 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
226 /// in a race condition between the user connecting a block (which would fail it) and the user
227 /// providing us the preimage (which would claim it).
228 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
230 // TODO(devrandom) replace this with HolderCommitmentTransaction
231 #[derive(Clone, PartialEq)]
232 struct HolderSignedTx {
233 /// txid of the transaction in tx, just used to make comparison faster
235 revocation_key: PublicKey,
236 a_htlc_key: PublicKey,
237 b_htlc_key: PublicKey,
238 delayed_payment_key: PublicKey,
239 per_commitment_point: PublicKey,
240 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
241 to_self_value_sat: u64,
244 impl_writeable_tlv_based!(HolderSignedTx, {
246 // Note that this is filled in with data from OnchainTxHandler if it's missing.
247 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
248 (1, to_self_value_sat, (default_value, u64::max_value())),
249 (2, revocation_key, required),
250 (4, a_htlc_key, required),
251 (6, b_htlc_key, required),
252 (8, delayed_payment_key, required),
253 (10, per_commitment_point, required),
254 (12, feerate_per_kw, required),
255 (14, htlc_outputs, vec_type)
258 /// We use this to track static counterparty commitment transaction data and to generate any
259 /// justice or 2nd-stage preimage/timeout transactions.
261 struct CounterpartyCommitmentParameters {
262 counterparty_delayed_payment_base_key: PublicKey,
263 counterparty_htlc_base_key: PublicKey,
264 on_counterparty_tx_csv: u16,
267 impl Writeable for CounterpartyCommitmentParameters {
268 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
269 w.write_all(&byte_utils::be64_to_array(0))?;
270 write_tlv_fields!(w, {
271 (0, self.counterparty_delayed_payment_base_key, required),
272 (2, self.counterparty_htlc_base_key, required),
273 (4, self.on_counterparty_tx_csv, required),
278 impl Readable for CounterpartyCommitmentParameters {
279 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
280 let counterparty_commitment_transaction = {
281 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
282 // used. Read it for compatibility.
283 let per_htlc_len: u64 = Readable::read(r)?;
284 for _ in 0..per_htlc_len {
285 let _txid: Txid = Readable::read(r)?;
286 let htlcs_count: u64 = Readable::read(r)?;
287 for _ in 0..htlcs_count {
288 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
292 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
293 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
294 let mut on_counterparty_tx_csv: u16 = 0;
295 read_tlv_fields!(r, {
296 (0, counterparty_delayed_payment_base_key, required),
297 (2, counterparty_htlc_base_key, required),
298 (4, on_counterparty_tx_csv, required),
300 CounterpartyCommitmentParameters {
301 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
302 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
303 on_counterparty_tx_csv,
306 Ok(counterparty_commitment_transaction)
310 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
311 /// transaction causing it.
313 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
315 struct OnchainEventEntry {
319 transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
322 impl OnchainEventEntry {
323 fn confirmation_threshold(&self) -> u32 {
324 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
326 OnchainEvent::MaturingOutput {
327 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
329 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
330 // it's broadcastable when we see the previous block.
331 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
333 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
334 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
335 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
336 // it's broadcastable when we see the previous block.
337 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
344 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
345 best_block.height() >= self.confirmation_threshold()
349 /// The (output index, sats value) for the counterparty's output in a commitment transaction.
351 /// This was added as an `Option` in 0.0.110.
352 type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>;
354 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
355 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
358 /// An outbound HTLC failing after a transaction is confirmed. Used
359 /// * when an outbound HTLC output is spent by us after the HTLC timed out
360 /// * an outbound HTLC which was not present in the commitment transaction which appeared
361 /// on-chain (either because it was not fully committed to or it was dust).
362 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
363 /// appearing only as an `HTLCSpendConfirmation`, below.
366 payment_hash: PaymentHash,
367 htlc_value_satoshis: Option<u64>,
368 /// None in the second case, above, ie when there is no relevant output in the commitment
369 /// transaction which appeared on chain.
370 commitment_tx_output_idx: Option<u32>,
373 descriptor: SpendableOutputDescriptor,
375 /// A spend of the funding output, either a commitment transaction or a cooperative closing
377 FundingSpendConfirmation {
378 /// The CSV delay for the output of the funding spend transaction (implying it is a local
379 /// commitment transaction, and this is the delay on the to_self output).
380 on_local_output_csv: Option<u16>,
381 /// If the funding spend transaction was a known remote commitment transaction, we track
382 /// the output index and amount of the counterparty's `to_self` output here.
383 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
385 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
386 /// is constructed. This is used when
387 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
388 /// immediately claim the HTLC on the inbound edge and track the resolution here,
389 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
390 /// * an inbound HTLC is claimed by us (with a preimage).
391 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
393 HTLCSpendConfirmation {
394 commitment_tx_output_idx: u32,
395 /// If the claim was made by either party with a preimage, this is filled in
396 preimage: Option<PaymentPreimage>,
397 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
398 /// we set this to the output CSV value which we will have to wait until to spend the
399 /// output (and generate a SpendableOutput event).
400 on_to_local_output_csv: Option<u16>,
404 impl Writeable for OnchainEventEntry {
405 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
406 write_tlv_fields!(writer, {
407 (0, self.txid, required),
408 (1, self.transaction, option),
409 (2, self.height, required),
410 (4, self.event, required),
416 impl MaybeReadable for OnchainEventEntry {
417 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
418 let mut txid = Txid::all_zeros();
419 let mut transaction = None;
421 let mut event = None;
422 read_tlv_fields!(reader, {
424 (1, transaction, option),
425 (2, height, required),
426 (4, event, ignorable),
428 if let Some(ev) = event {
429 Ok(Some(Self { txid, transaction, height, event: ev }))
436 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
438 (0, source, required),
439 (1, htlc_value_satoshis, option),
440 (2, payment_hash, required),
441 (3, commitment_tx_output_idx, option),
443 (1, MaturingOutput) => {
444 (0, descriptor, required),
446 (3, FundingSpendConfirmation) => {
447 (0, on_local_output_csv, option),
448 (1, commitment_tx_to_counterparty_output, option),
450 (5, HTLCSpendConfirmation) => {
451 (0, commitment_tx_output_idx, required),
452 (2, preimage, option),
453 (4, on_to_local_output_csv, option),
458 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
460 pub(crate) enum ChannelMonitorUpdateStep {
461 LatestHolderCommitmentTXInfo {
462 commitment_tx: HolderCommitmentTransaction,
463 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
465 LatestCounterpartyCommitmentTXInfo {
466 commitment_txid: Txid,
467 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
468 commitment_number: u64,
469 their_per_commitment_point: PublicKey,
472 payment_preimage: PaymentPreimage,
478 /// Used to indicate that the no future updates will occur, and likely that the latest holder
479 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
481 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
482 /// think we've fallen behind!
483 should_broadcast: bool,
486 scriptpubkey: Script,
490 impl ChannelMonitorUpdateStep {
491 fn variant_name(&self) -> &'static str {
493 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
494 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
495 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
496 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
497 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
498 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
503 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
504 (0, LatestHolderCommitmentTXInfo) => {
505 (0, commitment_tx, required),
506 (2, htlc_outputs, vec_type),
508 (1, LatestCounterpartyCommitmentTXInfo) => {
509 (0, commitment_txid, required),
510 (2, commitment_number, required),
511 (4, their_per_commitment_point, required),
512 (6, htlc_outputs, vec_type),
514 (2, PaymentPreimage) => {
515 (0, payment_preimage, required),
517 (3, CommitmentSecret) => {
519 (2, secret, required),
521 (4, ChannelForceClosed) => {
522 (0, should_broadcast, required),
524 (5, ShutdownScript) => {
525 (0, scriptpubkey, required),
529 /// Details about the balance(s) available for spending once the channel appears on chain.
531 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
533 #[derive(Clone, Debug, PartialEq, Eq)]
534 #[cfg_attr(test, derive(PartialOrd, Ord))]
536 /// The channel is not yet closed (or the commitment or closing transaction has not yet
537 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
538 /// force-closed now.
539 ClaimableOnChannelClose {
540 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
541 /// required to do so.
542 claimable_amount_satoshis: u64,
544 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
545 /// we consider it spendable.
546 ClaimableAwaitingConfirmations {
547 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
548 /// were spent in broadcasting the transaction.
549 claimable_amount_satoshis: u64,
550 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
552 confirmation_height: u32,
554 /// The channel has been closed, and the given balance should be ours but awaiting spending
555 /// transaction confirmation. If the spending transaction does not confirm in time, it is
556 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
558 /// Once the spending transaction confirms, before it has reached enough confirmations to be
559 /// considered safe from chain reorganizations, the balance will instead be provided via
560 /// [`Balance::ClaimableAwaitingConfirmations`].
561 ContentiousClaimable {
562 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
563 /// required to do so.
564 claimable_amount_satoshis: u64,
565 /// The height at which the counterparty may be able to claim the balance if we have not
569 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
570 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
571 /// likely to be claimed by our counterparty before we do.
572 MaybeClaimableHTLCAwaitingTimeout {
573 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
574 /// required to do so.
575 claimable_amount_satoshis: u64,
576 /// The height at which we will be able to claim the balance if our counterparty has not
578 claimable_height: u32,
582 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
584 struct IrrevocablyResolvedHTLC {
585 commitment_tx_output_idx: u32,
586 /// Only set if the HTLC claim was ours using a payment preimage
587 payment_preimage: Option<PaymentPreimage>,
590 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
591 (0, commitment_tx_output_idx, required),
592 (2, payment_preimage, option),
595 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
596 /// on-chain transactions to ensure no loss of funds occurs.
598 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
599 /// information and are actively monitoring the chain.
601 /// Pending Events or updated HTLCs which have not yet been read out by
602 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
603 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
604 /// gotten are fully handled before re-serializing the new state.
606 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
607 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
608 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
609 /// returned block hash and the the current chain and then reconnecting blocks to get to the
610 /// best chain) upon deserializing the object!
611 pub struct ChannelMonitor<Signer: Sign> {
613 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
615 inner: Mutex<ChannelMonitorImpl<Signer>>,
618 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
619 latest_update_id: u64,
620 commitment_transaction_number_obscure_factor: u64,
622 destination_script: Script,
623 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
624 counterparty_payment_script: Script,
625 shutdown_script: Option<Script>,
627 channel_keys_id: [u8; 32],
628 holder_revocation_basepoint: PublicKey,
629 funding_info: (OutPoint, Script),
630 current_counterparty_commitment_txid: Option<Txid>,
631 prev_counterparty_commitment_txid: Option<Txid>,
633 counterparty_commitment_params: CounterpartyCommitmentParameters,
634 funding_redeemscript: Script,
635 channel_value_satoshis: u64,
636 // first is the idx of the first of the two per-commitment points
637 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
639 on_holder_tx_csv: u16,
641 commitment_secrets: CounterpartyCommitmentSecrets,
642 /// The set of outpoints in each counterparty commitment transaction. We always need at least
643 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
644 /// transaction broadcast as we need to be able to construct the witness script in all cases.
645 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
646 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
647 /// Nor can we figure out their commitment numbers without the commitment transaction they are
648 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
649 /// commitment transactions which we find on-chain, mapping them to the commitment number which
650 /// can be used to derive the revocation key and claim the transactions.
651 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
652 /// Cache used to make pruning of payment_preimages faster.
653 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
654 /// counterparty transactions (ie should remain pretty small).
655 /// Serialized to disk but should generally not be sent to Watchtowers.
656 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
658 // We store two holder commitment transactions to avoid any race conditions where we may update
659 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
660 // various monitors for one channel being out of sync, and us broadcasting a holder
661 // transaction for which we have deleted claim information on some watchtowers.
662 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
663 current_holder_commitment_tx: HolderSignedTx,
665 // Used just for ChannelManager to make sure it has the latest channel data during
667 current_counterparty_commitment_number: u64,
668 // Used just for ChannelManager to make sure it has the latest channel data during
670 current_holder_commitment_number: u64,
672 /// The set of payment hashes from inbound payments for which we know the preimage. Payment
673 /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
674 /// remote commitment transactions are automatically removed when commitment transactions are
676 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
678 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
679 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
680 // presumably user implementations thereof as well) where we update the in-memory channel
681 // object, then before the persistence finishes (as it's all under a read-lock), we return
682 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
683 // the pre-event state here, but have processed the event in the `ChannelManager`.
684 // Note that because the `event_lock` in `ChainMonitor` is only taken in
685 // block/transaction-connected events and *not* during block/transaction-disconnected events,
686 // we further MUST NOT generate events during block/transaction-disconnection.
687 pending_monitor_events: Vec<MonitorEvent>,
689 pending_events: Vec<Event>,
691 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
692 // which to take actions once they reach enough confirmations. Each entry includes the
693 // transaction's id and the height when the transaction was confirmed on chain.
694 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
696 // If we get serialized out and re-read, we need to make sure that the chain monitoring
697 // interface knows about the TXOs that we want to be notified of spends of. We could probably
698 // be smart and derive them from the above storage fields, but its much simpler and more
699 // Obviously Correct (tm) if we just keep track of them explicitly.
700 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
703 pub onchain_tx_handler: OnchainTxHandler<Signer>,
705 onchain_tx_handler: OnchainTxHandler<Signer>,
707 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
708 // channel has been force-closed. After this is set, no further holder commitment transaction
709 // updates may occur, and we panic!() if one is provided.
710 lockdown_from_offchain: bool,
712 // Set once we've signed a holder commitment transaction and handed it over to our
713 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
714 // may occur, and we fail any such monitor updates.
716 // In case of update rejection due to a locally already signed commitment transaction, we
717 // nevertheless store update content to track in case of concurrent broadcast by another
718 // remote monitor out-of-order with regards to the block view.
719 holder_tx_signed: bool,
721 // If a spend of the funding output is seen, we set this to true and reject any further
722 // updates. This prevents any further changes in the offchain state no matter the order
723 // of block connection between ChannelMonitors and the ChannelManager.
724 funding_spend_seen: bool,
726 funding_spend_confirmed: Option<Txid>,
727 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
728 /// The set of HTLCs which have been either claimed or failed on chain and have reached
729 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
730 /// spending CSV for revocable outputs).
731 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
733 // We simply modify best_block in Channel's block_connected so that serialization is
734 // consistent but hopefully the users' copy handles block_connected in a consistent way.
735 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
736 // their best_block from its state and not based on updated copies that didn't run through
737 // the full block_connected).
738 best_block: BestBlock,
740 /// The node_id of our counterparty
741 counterparty_node_id: Option<PublicKey>,
743 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
746 /// Transaction outputs to watch for on-chain spends.
747 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
749 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
750 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
752 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
753 fn eq(&self, other: &Self) -> bool {
754 let inner = self.inner.lock().unwrap();
755 let other = other.inner.lock().unwrap();
760 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
761 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
763 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
764 fn eq(&self, other: &Self) -> bool {
765 if self.latest_update_id != other.latest_update_id ||
766 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
767 self.destination_script != other.destination_script ||
768 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
769 self.counterparty_payment_script != other.counterparty_payment_script ||
770 self.channel_keys_id != other.channel_keys_id ||
771 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
772 self.funding_info != other.funding_info ||
773 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
774 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
775 self.counterparty_commitment_params != other.counterparty_commitment_params ||
776 self.funding_redeemscript != other.funding_redeemscript ||
777 self.channel_value_satoshis != other.channel_value_satoshis ||
778 self.their_cur_per_commitment_points != other.their_cur_per_commitment_points ||
779 self.on_holder_tx_csv != other.on_holder_tx_csv ||
780 self.commitment_secrets != other.commitment_secrets ||
781 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
782 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
783 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
784 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
785 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
786 self.current_holder_commitment_number != other.current_holder_commitment_number ||
787 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
788 self.payment_preimages != other.payment_preimages ||
789 self.pending_monitor_events != other.pending_monitor_events ||
790 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
791 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
792 self.outputs_to_watch != other.outputs_to_watch ||
793 self.lockdown_from_offchain != other.lockdown_from_offchain ||
794 self.holder_tx_signed != other.holder_tx_signed ||
795 self.funding_spend_seen != other.funding_spend_seen ||
796 self.funding_spend_confirmed != other.funding_spend_confirmed ||
797 self.confirmed_commitment_tx_counterparty_output != other.confirmed_commitment_tx_counterparty_output ||
798 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
807 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
808 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
809 self.inner.lock().unwrap().write(writer)
813 // These are also used for ChannelMonitorUpdate, above.
814 const SERIALIZATION_VERSION: u8 = 1;
815 const MIN_SERIALIZATION_VERSION: u8 = 1;
817 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
818 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
819 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
821 self.latest_update_id.write(writer)?;
823 // Set in initial Channel-object creation, so should always be set by now:
824 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
826 self.destination_script.write(writer)?;
827 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
828 writer.write_all(&[0; 1])?;
829 broadcasted_holder_revokable_script.0.write(writer)?;
830 broadcasted_holder_revokable_script.1.write(writer)?;
831 broadcasted_holder_revokable_script.2.write(writer)?;
833 writer.write_all(&[1; 1])?;
836 self.counterparty_payment_script.write(writer)?;
837 match &self.shutdown_script {
838 Some(script) => script.write(writer)?,
839 None => Script::new().write(writer)?,
842 self.channel_keys_id.write(writer)?;
843 self.holder_revocation_basepoint.write(writer)?;
844 writer.write_all(&self.funding_info.0.txid[..])?;
845 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
846 self.funding_info.1.write(writer)?;
847 self.current_counterparty_commitment_txid.write(writer)?;
848 self.prev_counterparty_commitment_txid.write(writer)?;
850 self.counterparty_commitment_params.write(writer)?;
851 self.funding_redeemscript.write(writer)?;
852 self.channel_value_satoshis.write(writer)?;
854 match self.their_cur_per_commitment_points {
855 Some((idx, pubkey, second_option)) => {
856 writer.write_all(&byte_utils::be48_to_array(idx))?;
857 writer.write_all(&pubkey.serialize())?;
858 match second_option {
859 Some(second_pubkey) => {
860 writer.write_all(&second_pubkey.serialize())?;
863 writer.write_all(&[0; 33])?;
868 writer.write_all(&byte_utils::be48_to_array(0))?;
872 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
874 self.commitment_secrets.write(writer)?;
876 macro_rules! serialize_htlc_in_commitment {
877 ($htlc_output: expr) => {
878 writer.write_all(&[$htlc_output.offered as u8; 1])?;
879 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
880 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
881 writer.write_all(&$htlc_output.payment_hash.0[..])?;
882 $htlc_output.transaction_output_index.write(writer)?;
886 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
887 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
888 writer.write_all(&txid[..])?;
889 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
890 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
891 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
892 || Some(**txid) == self.prev_counterparty_commitment_txid,
893 "HTLC Sources for all revoked commitment transactions should be none!");
894 serialize_htlc_in_commitment!(htlc_output);
895 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
899 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
900 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
901 writer.write_all(&txid[..])?;
902 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
905 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
906 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
907 writer.write_all(&payment_hash.0[..])?;
908 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
911 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
912 writer.write_all(&[1; 1])?;
913 prev_holder_tx.write(writer)?;
915 writer.write_all(&[0; 1])?;
918 self.current_holder_commitment_tx.write(writer)?;
920 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
921 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
923 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
924 for payment_preimage in self.payment_preimages.values() {
925 writer.write_all(&payment_preimage.0[..])?;
928 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
929 MonitorEvent::HTLCEvent(_) => true,
930 MonitorEvent::CommitmentTxConfirmed(_) => true,
932 }).count() as u64).to_be_bytes())?;
933 for event in self.pending_monitor_events.iter() {
935 MonitorEvent::HTLCEvent(upd) => {
939 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
940 _ => {}, // Covered in the TLV writes below
944 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
945 for event in self.pending_events.iter() {
946 event.write(writer)?;
949 self.best_block.block_hash().write(writer)?;
950 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
952 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
953 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
954 entry.write(writer)?;
957 (self.outputs_to_watch.len() as u64).write(writer)?;
958 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
960 (idx_scripts.len() as u64).write(writer)?;
961 for (idx, script) in idx_scripts.iter() {
963 script.write(writer)?;
966 self.onchain_tx_handler.write(writer)?;
968 self.lockdown_from_offchain.write(writer)?;
969 self.holder_tx_signed.write(writer)?;
971 write_tlv_fields!(writer, {
972 (1, self.funding_spend_confirmed, option),
973 (3, self.htlcs_resolved_on_chain, vec_type),
974 (5, self.pending_monitor_events, vec_type),
975 (7, self.funding_spend_seen, required),
976 (9, self.counterparty_node_id, option),
977 (11, self.confirmed_commitment_tx_counterparty_output, option),
984 impl<Signer: Sign> ChannelMonitor<Signer> {
985 /// For lockorder enforcement purposes, we need to have a single site which constructs the
986 /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
987 /// PartialEq implementation) we may decide a lockorder violation has occurred.
988 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
989 ChannelMonitor { inner: Mutex::new(imp) }
992 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
993 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
994 channel_parameters: &ChannelTransactionParameters,
995 funding_redeemscript: Script, channel_value_satoshis: u64,
996 commitment_transaction_number_obscure_factor: u64,
997 initial_holder_commitment_tx: HolderCommitmentTransaction,
998 best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
1000 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1001 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1002 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1004 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1005 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1006 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1007 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1009 let channel_keys_id = keys.channel_keys_id();
1010 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1012 // block for Rust 1.34 compat
1013 let (holder_commitment_tx, current_holder_commitment_number) = {
1014 let trusted_tx = initial_holder_commitment_tx.trust();
1015 let txid = trusted_tx.txid();
1017 let tx_keys = trusted_tx.keys();
1018 let holder_commitment_tx = HolderSignedTx {
1020 revocation_key: tx_keys.revocation_key,
1021 a_htlc_key: tx_keys.broadcaster_htlc_key,
1022 b_htlc_key: tx_keys.countersignatory_htlc_key,
1023 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1024 per_commitment_point: tx_keys.per_commitment_point,
1025 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1026 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1027 feerate_per_kw: trusted_tx.feerate_per_kw(),
1029 (holder_commitment_tx, trusted_tx.commitment_number())
1032 let onchain_tx_handler =
1033 OnchainTxHandler::new(destination_script.clone(), keys,
1034 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
1036 let mut outputs_to_watch = HashMap::new();
1037 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1039 Self::from_impl(ChannelMonitorImpl {
1040 latest_update_id: 0,
1041 commitment_transaction_number_obscure_factor,
1043 destination_script: destination_script.clone(),
1044 broadcasted_holder_revokable_script: None,
1045 counterparty_payment_script,
1049 holder_revocation_basepoint,
1051 current_counterparty_commitment_txid: None,
1052 prev_counterparty_commitment_txid: None,
1054 counterparty_commitment_params,
1055 funding_redeemscript,
1056 channel_value_satoshis,
1057 their_cur_per_commitment_points: None,
1059 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1061 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1062 counterparty_claimable_outpoints: HashMap::new(),
1063 counterparty_commitment_txn_on_chain: HashMap::new(),
1064 counterparty_hash_commitment_number: HashMap::new(),
1066 prev_holder_signed_commitment_tx: None,
1067 current_holder_commitment_tx: holder_commitment_tx,
1068 current_counterparty_commitment_number: 1 << 48,
1069 current_holder_commitment_number,
1071 payment_preimages: HashMap::new(),
1072 pending_monitor_events: Vec::new(),
1073 pending_events: Vec::new(),
1075 onchain_events_awaiting_threshold_conf: Vec::new(),
1080 lockdown_from_offchain: false,
1081 holder_tx_signed: false,
1082 funding_spend_seen: false,
1083 funding_spend_confirmed: None,
1084 confirmed_commitment_tx_counterparty_output: None,
1085 htlcs_resolved_on_chain: Vec::new(),
1088 counterparty_node_id: Some(counterparty_node_id),
1095 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1096 self.inner.lock().unwrap().provide_secret(idx, secret)
1099 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1100 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1101 /// possibly future revocation/preimage information) to claim outputs where possible.
1102 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1103 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1106 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1107 commitment_number: u64,
1108 their_per_commitment_point: PublicKey,
1110 ) where L::Target: Logger {
1111 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1112 txid, htlc_outputs, commitment_number, their_per_commitment_point, logger)
1116 fn provide_latest_holder_commitment_tx(
1117 &self, holder_commitment_tx: HolderCommitmentTransaction,
1118 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1119 ) -> Result<(), ()> {
1120 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs).map_err(|_| ())
1123 /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1124 /// off-chain state with a new commitment transaction.
1125 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1127 payment_hash: &PaymentHash,
1128 payment_preimage: &PaymentPreimage,
1130 fee_estimator: &LowerBoundedFeeEstimator<F>,
1133 B::Target: BroadcasterInterface,
1134 F::Target: FeeEstimator,
1137 self.inner.lock().unwrap().provide_payment_preimage(
1138 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1141 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1146 B::Target: BroadcasterInterface,
1149 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1152 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1155 /// panics if the given update is not the next update by update_id.
1156 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1158 updates: &ChannelMonitorUpdate,
1164 B::Target: BroadcasterInterface,
1165 F::Target: FeeEstimator,
1168 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1171 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1173 pub fn get_latest_update_id(&self) -> u64 {
1174 self.inner.lock().unwrap().get_latest_update_id()
1177 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1178 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1179 self.inner.lock().unwrap().get_funding_txo().clone()
1182 /// Gets a list of txids, with their output scripts (in the order they appear in the
1183 /// transaction), which we must learn about spends of via block_connected().
1184 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1185 self.inner.lock().unwrap().get_outputs_to_watch()
1186 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1189 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1190 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1191 /// have been registered.
1192 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1193 let lock = self.inner.lock().unwrap();
1194 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1195 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1196 for (index, script_pubkey) in outputs.iter() {
1197 assert!(*index <= u16::max_value() as u32);
1198 filter.register_output(WatchedOutput {
1200 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1201 script_pubkey: script_pubkey.clone(),
1207 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1208 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1209 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1210 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1213 /// Gets the list of pending events which were generated by previous actions, clearing the list
1216 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1217 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1218 /// no internal locking in ChannelMonitors.
1219 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1220 self.inner.lock().unwrap().get_and_clear_pending_events()
1223 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1224 self.inner.lock().unwrap().get_min_seen_secret()
1227 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1228 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1231 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1232 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1235 /// Gets the `node_id` of the counterparty for this channel.
1237 /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1239 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1240 self.inner.lock().unwrap().counterparty_node_id
1243 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1244 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1245 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1246 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1247 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1248 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1249 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1250 /// out-of-band the other node operator to coordinate with him if option is available to you.
1251 /// In any-case, choice is up to the user.
1252 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1253 where L::Target: Logger {
1254 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1257 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1258 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1259 /// revoked commitment transaction.
1260 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1261 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1262 where L::Target: Logger {
1263 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1266 /// Processes transactions in a newly connected block, which may result in any of the following:
1267 /// - update the monitor's state against resolved HTLCs
1268 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1269 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1270 /// - detect settled outputs for later spending
1271 /// - schedule and bump any in-flight claims
1273 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1274 /// [`get_outputs_to_watch`].
1276 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1277 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1279 header: &BlockHeader,
1280 txdata: &TransactionData,
1285 ) -> Vec<TransactionOutputs>
1287 B::Target: BroadcasterInterface,
1288 F::Target: FeeEstimator,
1291 self.inner.lock().unwrap().block_connected(
1292 header, txdata, height, broadcaster, fee_estimator, logger)
1295 /// Determines if the disconnected block contained any transactions of interest and updates
1297 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1299 header: &BlockHeader,
1305 B::Target: BroadcasterInterface,
1306 F::Target: FeeEstimator,
1309 self.inner.lock().unwrap().block_disconnected(
1310 header, height, broadcaster, fee_estimator, logger)
1313 /// Processes transactions confirmed in a block with the given header and height, returning new
1314 /// outputs to watch. See [`block_connected`] for details.
1316 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1317 /// blocks. See [`chain::Confirm`] for calling expectations.
1319 /// [`block_connected`]: Self::block_connected
1320 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1322 header: &BlockHeader,
1323 txdata: &TransactionData,
1328 ) -> Vec<TransactionOutputs>
1330 B::Target: BroadcasterInterface,
1331 F::Target: FeeEstimator,
1334 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1335 self.inner.lock().unwrap().transactions_confirmed(
1336 header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
1339 /// Processes a transaction that was reorganized out of the chain.
1341 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1342 /// than blocks. See [`chain::Confirm`] for calling expectations.
1344 /// [`block_disconnected`]: Self::block_disconnected
1345 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1352 B::Target: BroadcasterInterface,
1353 F::Target: FeeEstimator,
1356 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1357 self.inner.lock().unwrap().transaction_unconfirmed(
1358 txid, broadcaster, &bounded_fee_estimator, logger);
1361 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1362 /// [`block_connected`] for details.
1364 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1365 /// blocks. See [`chain::Confirm`] for calling expectations.
1367 /// [`block_connected`]: Self::block_connected
1368 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1370 header: &BlockHeader,
1375 ) -> Vec<TransactionOutputs>
1377 B::Target: BroadcasterInterface,
1378 F::Target: FeeEstimator,
1381 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1382 self.inner.lock().unwrap().best_block_updated(
1383 header, height, broadcaster, &bounded_fee_estimator, logger)
1386 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1387 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1388 let inner = self.inner.lock().unwrap();
1389 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1391 .map(|entry| entry.txid)
1392 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1394 txids.sort_unstable();
1399 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1400 /// [`chain::Confirm`] interfaces.
1401 pub fn current_best_block(&self) -> BestBlock {
1402 self.inner.lock().unwrap().best_block.clone()
1405 /// Gets the balances in this channel which are either claimable by us if we were to
1406 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1409 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1410 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1411 /// balance, or until our counterparty has claimed the balance and accrued several
1412 /// confirmations on the claim transaction.
1414 /// Note that the balances available when you or your counterparty have broadcasted revoked
1415 /// state(s) may not be fully captured here.
1418 /// See [`Balance`] for additional details on the types of claimable balances which
1419 /// may be returned here and their meanings.
1420 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1421 let mut res = Vec::new();
1422 let us = self.inner.lock().unwrap();
1424 let mut confirmed_txid = us.funding_spend_confirmed;
1425 let mut pending_commitment_tx_conf_thresh = None;
1426 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1427 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1428 Some((event.txid, event.confirmation_threshold()))
1431 if let Some((txid, conf_thresh)) = funding_spend_pending {
1432 debug_assert!(us.funding_spend_confirmed.is_none(),
1433 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1434 confirmed_txid = Some(txid);
1435 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1438 macro_rules! walk_htlcs {
1439 ($holder_commitment: expr, $htlc_iter: expr) => {
1440 for htlc in $htlc_iter {
1441 if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1442 if let Some(conf_thresh) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1443 if let OnchainEvent::MaturingOutput { descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) } = &event.event {
1444 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx { Some(event.confirmation_threshold()) } else { None }
1447 debug_assert!($holder_commitment);
1448 res.push(Balance::ClaimableAwaitingConfirmations {
1449 claimable_amount_satoshis: htlc.amount_msat / 1000,
1450 confirmation_height: conf_thresh,
1452 } else if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx) {
1453 // Funding transaction spends should be fully confirmed by the time any
1454 // HTLC transactions are resolved, unless we're talking about a holder
1455 // commitment tx, whose resolution is delayed until the CSV timeout is
1456 // reached, even though HTLCs may be resolved after only
1457 // ANTI_REORG_DELAY confirmations.
1458 debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1459 } else if htlc.offered == $holder_commitment {
1460 // If the payment was outbound, check if there's an HTLCUpdate
1461 // indicating we have spent this HTLC with a timeout, claiming it back
1462 // and awaiting confirmations on it.
1463 let htlc_update_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1464 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1465 if commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1466 Some(event.confirmation_threshold()) } else { None }
1469 if let Some(conf_thresh) = htlc_update_pending {
1470 res.push(Balance::ClaimableAwaitingConfirmations {
1471 claimable_amount_satoshis: htlc.amount_msat / 1000,
1472 confirmation_height: conf_thresh,
1475 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1476 claimable_amount_satoshis: htlc.amount_msat / 1000,
1477 claimable_height: htlc.cltv_expiry,
1480 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1481 // Otherwise (the payment was inbound), only expose it as claimable if
1482 // we know the preimage.
1483 // Note that if there is a pending claim, but it did not use the
1484 // preimage, we lost funds to our counterparty! We will then continue
1485 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1486 let htlc_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1487 if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } = event.event {
1488 if commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1489 Some((event.confirmation_threshold(), preimage.is_some()))
1493 if let Some((conf_thresh, true)) = htlc_spend_pending {
1494 res.push(Balance::ClaimableAwaitingConfirmations {
1495 claimable_amount_satoshis: htlc.amount_msat / 1000,
1496 confirmation_height: conf_thresh,
1499 res.push(Balance::ContentiousClaimable {
1500 claimable_amount_satoshis: htlc.amount_msat / 1000,
1501 timeout_height: htlc.cltv_expiry,
1510 if let Some(txid) = confirmed_txid {
1511 let mut found_commitment_tx = false;
1512 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1513 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1514 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1515 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1516 if let OnchainEvent::MaturingOutput {
1517 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1519 Some(descriptor.output.value)
1522 res.push(Balance::ClaimableAwaitingConfirmations {
1523 claimable_amount_satoshis: value,
1524 confirmation_height: conf_thresh,
1527 // If a counterparty commitment transaction is awaiting confirmation, we
1528 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1529 // confirmation with the same height or have never met our dust amount.
1532 found_commitment_tx = true;
1533 } else if txid == us.current_holder_commitment_tx.txid {
1534 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1535 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1536 res.push(Balance::ClaimableAwaitingConfirmations {
1537 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1538 confirmation_height: conf_thresh,
1541 found_commitment_tx = true;
1542 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1543 if txid == prev_commitment.txid {
1544 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1545 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1546 res.push(Balance::ClaimableAwaitingConfirmations {
1547 claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1548 confirmation_height: conf_thresh,
1551 found_commitment_tx = true;
1554 if !found_commitment_tx {
1555 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1556 // We blindly assume this is a cooperative close transaction here, and that
1557 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1558 // the amount we can claim as we'll punish a misbehaving counterparty.
1559 res.push(Balance::ClaimableAwaitingConfirmations {
1560 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1561 confirmation_height: conf_thresh,
1565 // TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1568 let mut claimable_inbound_htlc_value_sat = 0;
1569 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1570 if htlc.transaction_output_index.is_none() { continue; }
1572 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1573 claimable_amount_satoshis: htlc.amount_msat / 1000,
1574 claimable_height: htlc.cltv_expiry,
1576 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1577 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1580 res.push(Balance::ClaimableOnChannelClose {
1581 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1588 /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1589 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1590 pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1591 let mut res = HashMap::new();
1592 let us = self.inner.lock().unwrap();
1594 macro_rules! walk_htlcs {
1595 ($holder_commitment: expr, $htlc_iter: expr) => {
1596 for (htlc, source) in $htlc_iter {
1597 if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.commitment_tx_output_idx) == htlc.transaction_output_index) {
1598 // We should assert that funding_spend_confirmed is_some() here, but we
1599 // have some unit tests which violate HTLC transaction CSVs entirely and
1601 // TODO: Once tests all connect transactions at consensus-valid times, we
1602 // should assert here like we do in `get_claimable_balances`.
1603 } else if htlc.offered == $holder_commitment {
1604 // If the payment was outbound, check if there's an HTLCUpdate
1605 // indicating we have spent this HTLC with a timeout, claiming it back
1606 // and awaiting confirmations on it.
1607 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1608 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1609 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1610 // before considering it "no longer pending" - this matches when we
1611 // provide the ChannelManager an HTLC failure event.
1612 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
1613 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1614 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
1615 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1616 // immediately non-pending, matching when we provide ChannelManager
1618 Some(commitment_tx_output_idx) == htlc.transaction_output_index
1621 if !htlc_update_confd {
1622 res.insert(source.clone(), htlc.clone());
1629 // We're only concerned with the confirmation count of HTLC transactions, and don't
1630 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1631 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1632 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1633 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1634 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1639 if let Some(txid) = confirmed_txid {
1640 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1641 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1642 if let &Some(ref source) = b {
1643 Some((a, &**source))
1646 } else if txid == us.current_holder_commitment_tx.txid {
1647 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1648 if let Some(source) = c { Some((a, source)) } else { None }
1650 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1651 if txid == prev_commitment.txid {
1652 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1653 if let Some(source) = c { Some((a, source)) } else { None }
1658 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1659 // closed), just examine the available counterparty commitment transactions. See docs
1660 // on `fail_unbroadcast_htlcs`, below, for justification.
1661 macro_rules! walk_counterparty_commitment {
1663 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1664 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1665 if let &Some(ref source) = source_option {
1666 res.insert((**source).clone(), htlc.clone());
1672 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1673 walk_counterparty_commitment!(txid);
1675 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1676 walk_counterparty_commitment!(txid);
1683 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
1684 self.inner.lock().unwrap().payment_preimages.clone()
1688 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1689 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1690 /// after ANTI_REORG_DELAY blocks.
1692 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1693 /// are the commitment transactions which are generated by us. The off-chain state machine in
1694 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1695 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1696 /// included in a remote commitment transaction are failed back if they are not present in the
1697 /// broadcasted commitment transaction.
1699 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1700 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1701 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1702 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1703 macro_rules! fail_unbroadcast_htlcs {
1704 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
1705 $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1706 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
1708 macro_rules! check_htlc_fails {
1709 ($txid: expr, $commitment_tx: expr) => {
1710 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1711 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1712 if let &Some(ref source) = source_option {
1713 // Check if the HTLC is present in the commitment transaction that was
1714 // broadcast, but not if it was below the dust limit, which we should
1715 // fail backwards immediately as there is no way for us to learn the
1716 // payment_preimage.
1717 // Note that if the dust limit were allowed to change between
1718 // commitment transactions we'd want to be check whether *any*
1719 // broadcastable commitment transaction has the HTLC in it, but it
1720 // cannot currently change after channel initialization, so we don't
1722 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1724 let mut matched_htlc = false;
1725 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1726 if broadcast_htlc.transaction_output_index.is_some() &&
1727 (Some(&**source) == *broadcast_source ||
1728 (broadcast_source.is_none() &&
1729 broadcast_htlc.payment_hash == htlc.payment_hash &&
1730 broadcast_htlc.amount_msat == htlc.amount_msat)) {
1731 matched_htlc = true;
1735 if matched_htlc { continue; }
1736 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1737 if entry.height != $commitment_tx_conf_height { return true; }
1739 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1740 *update_source != **source
1745 let entry = OnchainEventEntry {
1746 txid: $commitment_txid_confirmed,
1747 transaction: Some($commitment_tx_confirmed.clone()),
1748 height: $commitment_tx_conf_height,
1749 event: OnchainEvent::HTLCUpdate {
1750 source: (**source).clone(),
1751 payment_hash: htlc.payment_hash.clone(),
1752 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
1753 commitment_tx_output_idx: None,
1756 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
1757 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type,
1758 $commitment_txid_confirmed, entry.confirmation_threshold());
1759 $self.onchain_events_awaiting_threshold_conf.push(entry);
1765 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1766 check_htlc_fails!(txid, "current");
1768 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1769 check_htlc_fails!(txid, "previous");
1774 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
1775 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
1776 // in-line tests later.
1779 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
1780 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
1781 ret[131] = opcodes::all::OP_DROP.to_u8();
1782 ret[132] = opcodes::all::OP_DROP.to_u8();
1783 ret[133] = opcodes::all::OP_DROP.to_u8();
1784 ret[134] = opcodes::all::OP_DROP.to_u8();
1785 ret[135] = opcodes::OP_TRUE.to_u8();
1790 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
1791 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
1794 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1795 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1796 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1797 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1798 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1799 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1800 return Err("Previous secret did not match new one");
1803 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1804 // events for now-revoked/fulfilled HTLCs.
1805 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1806 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1811 if !self.payment_preimages.is_empty() {
1812 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1813 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1814 let min_idx = self.get_min_seen_secret();
1815 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1817 self.payment_preimages.retain(|&k, _| {
1818 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1819 if k == htlc.payment_hash {
1823 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1824 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1825 if k == htlc.payment_hash {
1830 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1837 counterparty_hash_commitment_number.remove(&k);
1846 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 {
1847 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1848 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1849 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1851 for &(ref htlc, _) in &htlc_outputs {
1852 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1855 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1856 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1857 self.current_counterparty_commitment_txid = Some(txid);
1858 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1859 self.current_counterparty_commitment_number = commitment_number;
1860 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1861 match self.their_cur_per_commitment_points {
1862 Some(old_points) => {
1863 if old_points.0 == commitment_number + 1 {
1864 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
1865 } else if old_points.0 == commitment_number + 2 {
1866 if let Some(old_second_point) = old_points.2 {
1867 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
1869 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1872 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1876 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1879 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1880 for htlc in htlc_outputs {
1881 if htlc.0.transaction_output_index.is_some() {
1887 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1888 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1889 /// is important that any clones of this channel monitor (including remote clones) by kept
1890 /// up-to-date as our holder commitment transaction is updated.
1891 /// Panics if set_on_holder_tx_csv has never been called.
1892 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), &'static str> {
1893 // block for Rust 1.34 compat
1894 let mut new_holder_commitment_tx = {
1895 let trusted_tx = holder_commitment_tx.trust();
1896 let txid = trusted_tx.txid();
1897 let tx_keys = trusted_tx.keys();
1898 self.current_holder_commitment_number = trusted_tx.commitment_number();
1901 revocation_key: tx_keys.revocation_key,
1902 a_htlc_key: tx_keys.broadcaster_htlc_key,
1903 b_htlc_key: tx_keys.countersignatory_htlc_key,
1904 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1905 per_commitment_point: tx_keys.per_commitment_point,
1907 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1908 feerate_per_kw: trusted_tx.feerate_per_kw(),
1911 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1912 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1913 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1914 if self.holder_tx_signed {
1915 return Err("Latest holder commitment signed has already been signed, update is rejected");
1920 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1921 /// commitment_tx_infos which contain the payment hash have been revoked.
1922 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1923 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
1924 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
1925 where B::Target: BroadcasterInterface,
1926 F::Target: FeeEstimator,
1929 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1931 // If the channel is force closed, try to claim the output from this preimage.
1932 // First check if a counterparty commitment transaction has been broadcasted:
1933 macro_rules! claim_htlcs {
1934 ($commitment_number: expr, $txid: expr) => {
1935 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
1936 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1939 if let Some(txid) = self.current_counterparty_commitment_txid {
1940 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1941 claim_htlcs!(*commitment_number, txid);
1945 if let Some(txid) = self.prev_counterparty_commitment_txid {
1946 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1947 claim_htlcs!(*commitment_number, txid);
1952 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1953 // claiming the HTLC output from each of the holder commitment transactions.
1954 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1955 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1956 // holder commitment transactions.
1957 if self.broadcasted_holder_revokable_script.is_some() {
1958 // Assume that the broadcasted commitment transaction confirmed in the current best
1959 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1961 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1962 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1963 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1964 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1965 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1970 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1971 where B::Target: BroadcasterInterface,
1974 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1975 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1976 broadcaster.broadcast_transaction(tx);
1978 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
1981 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
1982 where B::Target: BroadcasterInterface,
1983 F::Target: FeeEstimator,
1986 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} changes.",
1987 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
1988 // ChannelMonitor updates may be applied after force close if we receive a
1989 // preimage for a broadcasted commitment transaction HTLC output that we'd
1990 // like to claim on-chain. If this is the case, we no longer have guaranteed
1991 // access to the monitor's update ID, so we use a sentinel value instead.
1992 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1993 assert_eq!(updates.updates.len(), 1);
1994 match updates.updates[0] {
1995 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1997 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
1998 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2001 } else if self.latest_update_id + 1 != updates.update_id {
2002 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2004 let mut ret = Ok(());
2005 for update in updates.updates.iter() {
2007 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
2008 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2009 if self.lockdown_from_offchain { panic!(); }
2010 if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
2011 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2012 log_error!(logger, " {}", e);
2016 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point } => {
2017 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2018 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2020 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2021 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2022 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2023 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2025 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2026 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2027 if let Err(e) = self.provide_secret(*idx, *secret) {
2028 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2029 log_error!(logger, " {}", e);
2033 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2034 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2035 self.lockdown_from_offchain = true;
2036 if *should_broadcast {
2037 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2038 } else if !self.holder_tx_signed {
2039 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");
2041 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2042 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2043 // shouldn't print the scary warning above.
2044 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2047 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2048 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2049 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2050 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2055 self.latest_update_id = updates.update_id;
2057 if ret.is_ok() && self.funding_spend_seen {
2058 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2063 pub fn get_latest_update_id(&self) -> u64 {
2064 self.latest_update_id
2067 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2071 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2072 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2073 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2074 // its trivial to do, double-check that here.
2075 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2076 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2078 &self.outputs_to_watch
2081 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2082 let mut ret = Vec::new();
2083 mem::swap(&mut ret, &mut self.pending_monitor_events);
2087 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
2088 let mut ret = Vec::new();
2089 mem::swap(&mut ret, &mut self.pending_events);
2093 /// Can only fail if idx is < get_min_seen_secret
2094 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2095 self.commitment_secrets.get_secret(idx)
2098 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2099 self.commitment_secrets.get_min_seen_secret()
2102 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2103 self.current_counterparty_commitment_number
2106 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2107 self.current_holder_commitment_number
2110 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2111 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2112 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2113 /// HTLC-Success/HTLC-Timeout transactions.
2115 /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
2116 /// general information about the output that is to the counterparty in the commitment
2118 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L)
2119 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
2120 where L::Target: Logger {
2121 // Most secp and related errors trying to create keys means we have no hope of constructing
2122 // a spend transaction...so we return no transactions to broadcast
2123 let mut claimable_outpoints = Vec::new();
2124 let mut watch_outputs = Vec::new();
2125 let mut to_counterparty_output_info = None;
2127 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2128 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2130 macro_rules! ignore_error {
2131 ( $thing : expr ) => {
2134 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2139 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);
2140 if commitment_number >= self.get_min_seen_secret() {
2141 let secret = self.get_secret(commitment_number).unwrap();
2142 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2143 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2144 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2145 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));
2147 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2148 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2150 // First, process non-htlc outputs (to_holder & to_counterparty)
2151 for (idx, outp) in tx.output.iter().enumerate() {
2152 if outp.script_pubkey == revokeable_p2wsh {
2153 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);
2154 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);
2155 claimable_outpoints.push(justice_package);
2156 to_counterparty_output_info =
2157 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
2161 // Then, try to find revoked htlc outputs
2162 if let Some(ref per_commitment_data) = per_commitment_option {
2163 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2164 if let Some(transaction_output_index) = htlc.transaction_output_index {
2165 if transaction_output_index as usize >= tx.output.len() ||
2166 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2167 // per_commitment_data is corrupt or our commitment signing key leaked!
2168 return (claimable_outpoints, (commitment_txid, watch_outputs),
2169 to_counterparty_output_info);
2171 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());
2172 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2173 claimable_outpoints.push(justice_package);
2178 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2179 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2180 // We're definitely a counterparty commitment transaction!
2181 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2182 for (idx, outp) in tx.output.iter().enumerate() {
2183 watch_outputs.push((idx as u32, outp.clone()));
2185 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2187 if let Some(per_commitment_data) = per_commitment_option {
2188 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
2189 per_commitment_data.iter().map(|(htlc, htlc_source)|
2190 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2193 debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2194 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
2195 [].iter().map(|reference| *reference), logger);
2198 } else if let Some(per_commitment_data) = per_commitment_option {
2199 // While this isn't useful yet, there is a potential race where if a counterparty
2200 // revokes a state at the same time as the commitment transaction for that state is
2201 // confirmed, and the watchtower receives the block before the user, the user could
2202 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2203 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2204 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2206 for (idx, outp) in tx.output.iter().enumerate() {
2207 watch_outputs.push((idx as u32, outp.clone()));
2209 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2211 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2212 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height,
2213 per_commitment_data.iter().map(|(htlc, htlc_source)|
2214 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2217 let (htlc_claim_reqs, counterparty_output_info) =
2218 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
2219 to_counterparty_output_info = counterparty_output_info;
2220 for req in htlc_claim_reqs {
2221 claimable_outpoints.push(req);
2225 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2228 /// Returns the HTLC claim package templates and the counterparty output info
2229 fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
2230 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
2231 let mut claimable_outpoints = Vec::new();
2232 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
2233 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
2234 if let Some(per_commitment_points) = self.their_cur_per_commitment_points {
2235 let per_commitment_point_option =
2236 // If the counterparty commitment tx is the latest valid state, use their latest
2237 // per-commitment point
2238 if per_commitment_points.0 == commitment_number { Some(&per_commitment_points.1) }
2239 else if let Some(point) = per_commitment_points.2.as_ref() {
2240 // If counterparty commitment tx is the state previous to the latest valid state, use
2241 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2242 // them to temporarily have two valid commitment txns from our viewpoint)
2243 if per_commitment_points.0 == commitment_number + 1 { Some(point) } else { None }
2245 if let Some(per_commitment_point) = per_commitment_point_option {
2246 if let Some(transaction) = tx {
2247 let revokeable_p2wsh_opt =
2248 if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
2249 &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
2251 if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
2252 &per_commitment_point,
2253 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
2255 Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2256 self.counterparty_commitment_params.on_counterparty_tx_csv,
2257 &delayed_key).to_v0_p2wsh())
2259 debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
2263 debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
2266 if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
2267 for (idx, outp) in transaction.output.iter().enumerate() {
2268 if outp.script_pubkey == revokeable_p2wsh {
2269 to_counterparty_output_info =
2270 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2276 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2277 if let Some(transaction_output_index) = htlc.transaction_output_index {
2278 if let Some(transaction) = tx {
2279 if transaction_output_index as usize >= transaction.output.len() ||
2280 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2281 // per_commitment_data is corrupt or our commitment signing key leaked!
2282 return (claimable_outpoints, to_counterparty_output_info);
2285 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2286 if preimage.is_some() || !htlc.offered {
2287 let counterparty_htlc_outp = if htlc.offered {
2288 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2289 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2290 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2291 self.counterparty_commitment_params.counterparty_htlc_base_key,
2292 preimage.unwrap(), htlc.clone()))
2294 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2295 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2296 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2297 self.counterparty_commitment_params.counterparty_htlc_base_key,
2300 let aggregation = if !htlc.offered { false } else { true };
2301 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2302 claimable_outpoints.push(counterparty_package);
2309 (claimable_outpoints, to_counterparty_output_info)
2312 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2313 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 {
2314 let htlc_txid = tx.txid();
2315 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2316 return (Vec::new(), None)
2319 macro_rules! ignore_error {
2320 ( $thing : expr ) => {
2323 Err(_) => return (Vec::new(), None)
2328 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2329 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2330 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2332 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2333 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);
2334 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);
2335 let claimable_outpoints = vec!(justice_package);
2336 let outputs = vec![(0, tx.output[0].clone())];
2337 (claimable_outpoints, Some((htlc_txid, outputs)))
2340 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2341 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2342 // script so we can detect whether a holder transaction has been seen on-chain.
2343 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2344 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2346 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2347 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2349 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2350 if let Some(transaction_output_index) = htlc.transaction_output_index {
2351 let htlc_output = if htlc.offered {
2352 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2354 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2357 // We can't build an HTLC-Success transaction without the preimage
2360 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2362 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2363 claim_requests.push(htlc_package);
2367 (claim_requests, broadcasted_holder_revokable_script)
2370 // Returns holder HTLC outputs to watch and react to in case of spending.
2371 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2372 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2373 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2374 if let Some(transaction_output_index) = htlc.transaction_output_index {
2375 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2381 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2382 /// revoked using data in holder_claimable_outpoints.
2383 /// Should not be used if check_spend_revoked_transaction succeeds.
2384 /// Returns None unless the transaction is definitely one of our commitment transactions.
2385 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2386 let commitment_txid = tx.txid();
2387 let mut claim_requests = Vec::new();
2388 let mut watch_outputs = Vec::new();
2390 macro_rules! append_onchain_update {
2391 ($updates: expr, $to_watch: expr) => {
2392 claim_requests = $updates.0;
2393 self.broadcasted_holder_revokable_script = $updates.1;
2394 watch_outputs.append(&mut $to_watch);
2398 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2399 let mut is_holder_tx = false;
2401 if self.current_holder_commitment_tx.txid == commitment_txid {
2402 is_holder_tx = true;
2403 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2404 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2405 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2406 append_onchain_update!(res, to_watch);
2407 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
2408 self.current_holder_commitment_tx.htlc_outputs.iter()
2409 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2410 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2411 if holder_tx.txid == commitment_txid {
2412 is_holder_tx = true;
2413 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2414 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2415 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2416 append_onchain_update!(res, to_watch);
2417 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height,
2418 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2424 Some((claim_requests, (commitment_txid, watch_outputs)))
2430 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2431 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2432 self.holder_tx_signed = true;
2433 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2434 let txid = commitment_tx.txid();
2435 let mut holder_transactions = vec![commitment_tx];
2436 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2437 if let Some(vout) = htlc.0.transaction_output_index {
2438 let preimage = if !htlc.0.offered {
2439 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2440 // We can't build an HTLC-Success transaction without the preimage
2443 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2444 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2445 // current locktime requirements on-chain. We will broadcast them in
2446 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2447 // Note that we add + 1 as transactions are broadcastable when they can be
2448 // confirmed in the next block.
2451 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2452 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2453 holder_transactions.push(htlc_tx);
2457 // 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.
2458 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2462 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2463 /// Note that this includes possibly-locktimed-in-the-future transactions!
2464 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2465 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2466 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2467 let txid = commitment_tx.txid();
2468 let mut holder_transactions = vec![commitment_tx];
2469 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2470 if let Some(vout) = htlc.0.transaction_output_index {
2471 let preimage = if !htlc.0.offered {
2472 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2473 // We can't build an HTLC-Success transaction without the preimage
2477 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2478 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2479 holder_transactions.push(htlc_tx);
2486 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>
2487 where B::Target: BroadcasterInterface,
2488 F::Target: FeeEstimator,
2491 let block_hash = header.block_hash();
2492 self.best_block = BestBlock::new(block_hash, height);
2494 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2495 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2498 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2500 header: &BlockHeader,
2503 fee_estimator: &LowerBoundedFeeEstimator<F>,
2505 ) -> Vec<TransactionOutputs>
2507 B::Target: BroadcasterInterface,
2508 F::Target: FeeEstimator,
2511 let block_hash = header.block_hash();
2513 if height > self.best_block.height() {
2514 self.best_block = BestBlock::new(block_hash, height);
2515 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2516 } else if block_hash != self.best_block.block_hash() {
2517 self.best_block = BestBlock::new(block_hash, height);
2518 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2519 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2521 } else { Vec::new() }
2524 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2526 header: &BlockHeader,
2527 txdata: &TransactionData,
2530 fee_estimator: &LowerBoundedFeeEstimator<F>,
2532 ) -> Vec<TransactionOutputs>
2534 B::Target: BroadcasterInterface,
2535 F::Target: FeeEstimator,
2538 let txn_matched = self.filter_block(txdata);
2539 for tx in &txn_matched {
2540 let mut output_val = 0;
2541 for out in tx.output.iter() {
2542 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2543 output_val += out.value;
2544 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2548 let block_hash = header.block_hash();
2550 let mut watch_outputs = Vec::new();
2551 let mut claimable_outpoints = Vec::new();
2552 for tx in &txn_matched {
2553 if tx.input.len() == 1 {
2554 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2555 // commitment transactions and HTLC transactions will all only ever have one input,
2556 // which is an easy way to filter out any potential non-matching txn for lazy
2558 let prevout = &tx.input[0].previous_output;
2559 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2560 let mut balance_spendable_csv = None;
2561 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2562 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2563 self.funding_spend_seen = true;
2564 let mut commitment_tx_to_counterparty_output = None;
2565 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
2566 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
2567 self.check_spend_counterparty_transaction(&tx, height, &logger);
2568 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
2569 if !new_outputs.1.is_empty() {
2570 watch_outputs.push(new_outputs);
2572 claimable_outpoints.append(&mut new_outpoints);
2573 if new_outpoints.is_empty() {
2574 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2575 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
2576 "A commitment transaction matched as both a counterparty and local commitment tx?");
2577 if !new_outputs.1.is_empty() {
2578 watch_outputs.push(new_outputs);
2580 claimable_outpoints.append(&mut new_outpoints);
2581 balance_spendable_csv = Some(self.on_holder_tx_csv);
2585 let txid = tx.txid();
2586 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2588 transaction: Some((*tx).clone()),
2590 event: OnchainEvent::FundingSpendConfirmation {
2591 on_local_output_csv: balance_spendable_csv,
2592 commitment_tx_to_counterparty_output,
2596 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2597 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2598 claimable_outpoints.append(&mut new_outpoints);
2599 if let Some(new_outputs) = new_outputs_option {
2600 watch_outputs.push(new_outputs);
2605 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2606 // can also be resolved in a few other ways which can have more than one output. Thus,
2607 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2608 self.is_resolving_htlc_output(&tx, height, &logger);
2610 self.is_paying_spendable_output(&tx, height, &logger);
2613 if height > self.best_block.height() {
2614 self.best_block = BestBlock::new(block_hash, height);
2617 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2620 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2621 /// `self.best_block` before calling if a new best blockchain tip is available. More
2622 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2623 /// complexity especially in `OnchainTx::update_claims_view`.
2625 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2626 /// confirmed at, even if it is not the current best height.
2627 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2630 txn_matched: Vec<&Transaction>,
2631 mut watch_outputs: Vec<TransactionOutputs>,
2632 mut claimable_outpoints: Vec<PackageTemplate>,
2634 fee_estimator: &LowerBoundedFeeEstimator<F>,
2636 ) -> Vec<TransactionOutputs>
2638 B::Target: BroadcasterInterface,
2639 F::Target: FeeEstimator,
2642 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2643 debug_assert!(self.best_block.height() >= conf_height);
2645 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2646 if should_broadcast {
2647 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2648 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());
2649 claimable_outpoints.push(commitment_package);
2650 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2651 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2652 self.holder_tx_signed = true;
2653 // Because we're broadcasting a commitment transaction, we should construct the package
2654 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2655 // "not yet confirmed" things as discardable, so we cannot do that here.
2656 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2657 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2658 if !new_outputs.is_empty() {
2659 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2661 claimable_outpoints.append(&mut new_outpoints);
2664 // Find which on-chain events have reached their confirmation threshold.
2665 let onchain_events_awaiting_threshold_conf =
2666 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2667 let mut onchain_events_reaching_threshold_conf = Vec::new();
2668 for entry in onchain_events_awaiting_threshold_conf {
2669 if entry.has_reached_confirmation_threshold(&self.best_block) {
2670 onchain_events_reaching_threshold_conf.push(entry);
2672 self.onchain_events_awaiting_threshold_conf.push(entry);
2676 // Used to check for duplicate HTLC resolutions.
2677 #[cfg(debug_assertions)]
2678 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2680 .filter_map(|entry| match &entry.event {
2681 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2685 #[cfg(debug_assertions)]
2686 let mut matured_htlcs = Vec::new();
2688 // Produce actionable events from on-chain events having reached their threshold.
2689 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2691 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2692 // Check for duplicate HTLC resolutions.
2693 #[cfg(debug_assertions)]
2696 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2697 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2698 call either transaction_unconfirmed for the conflicting transaction \
2699 or block_disconnected for a block containing it.");
2701 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2702 "A matured HTLC transaction conflicts with a maturing one; failed to \
2703 call either transaction_unconfirmed for the conflicting transaction \
2704 or block_disconnected for a block containing it.");
2705 matured_htlcs.push(source.clone());
2708 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2709 log_bytes!(payment_hash.0), entry.txid);
2710 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2712 payment_preimage: None,
2713 source: source.clone(),
2714 htlc_value_satoshis,
2716 if let Some(idx) = commitment_tx_output_idx {
2717 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx: idx, payment_preimage: None });
2720 OnchainEvent::MaturingOutput { descriptor } => {
2721 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2722 self.pending_events.push(Event::SpendableOutputs {
2723 outputs: vec![descriptor]
2726 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2727 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx, payment_preimage: preimage });
2729 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
2730 self.funding_spend_confirmed = Some(entry.txid);
2731 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
2736 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2738 // Determine new outputs to watch by comparing against previously known outputs to watch,
2739 // updating the latter in the process.
2740 watch_outputs.retain(|&(ref txid, ref txouts)| {
2741 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2742 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2746 // If we see a transaction for which we registered outputs previously,
2747 // make sure the registered scriptpubkey at the expected index match
2748 // the actual transaction output one. We failed this case before #653.
2749 for tx in &txn_matched {
2750 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2751 for idx_and_script in outputs.iter() {
2752 assert!((idx_and_script.0 as usize) < tx.output.len());
2753 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2761 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2762 where B::Target: BroadcasterInterface,
2763 F::Target: FeeEstimator,
2766 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2769 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2770 //- maturing spendable output has transaction paying us has been disconnected
2771 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2773 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2774 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2776 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2779 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2783 fee_estimator: &LowerBoundedFeeEstimator<F>,
2786 B::Target: BroadcasterInterface,
2787 F::Target: FeeEstimator,
2790 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2791 log_info!(logger, "Removing onchain event with txid {}", txid);
2794 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2797 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2798 /// transactions thereof.
2799 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2800 let mut matched_txn = HashSet::new();
2801 txdata.iter().filter(|&&(_, tx)| {
2802 let mut matches = self.spends_watched_output(tx);
2803 for input in tx.input.iter() {
2804 if matches { break; }
2805 if matched_txn.contains(&input.previous_output.txid) {
2810 matched_txn.insert(tx.txid());
2813 }).map(|(_, tx)| *tx).collect()
2816 /// Checks if a given transaction spends any watched outputs.
2817 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2818 for input in tx.input.iter() {
2819 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2820 for (idx, _script_pubkey) in outputs.iter() {
2821 if *idx == input.previous_output.vout {
2824 // If the expected script is a known type, check that the witness
2825 // appears to be spending the correct type (ie that the match would
2826 // actually succeed in BIP 158/159-style filters).
2827 if _script_pubkey.is_v0_p2wsh() {
2828 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
2829 // In at least one test we use a deliberately bogus witness
2830 // script which hit an old panic. Thus, we check for that here
2831 // and avoid the assert if its the expected bogus script.
2835 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2836 } else if _script_pubkey.is_v0_p2wpkh() {
2837 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2838 } else { panic!(); }
2849 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2850 // We need to consider all HTLCs which are:
2851 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2852 // transactions and we'd end up in a race, or
2853 // * are in our latest holder commitment transaction, as this is the thing we will
2854 // broadcast if we go on-chain.
2855 // Note that we consider HTLCs which were below dust threshold here - while they don't
2856 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2857 // to the source, and if we don't fail the channel we will have to ensure that the next
2858 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2859 // easier to just fail the channel as this case should be rare enough anyway.
2860 let height = self.best_block.height();
2861 macro_rules! scan_commitment {
2862 ($htlcs: expr, $holder_tx: expr) => {
2863 for ref htlc in $htlcs {
2864 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2865 // chain with enough room to claim the HTLC without our counterparty being able to
2866 // time out the HTLC first.
2867 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2868 // concern is being able to claim the corresponding inbound HTLC (on another
2869 // channel) before it expires. In fact, we don't even really care if our
2870 // counterparty here claims such an outbound HTLC after it expired as long as we
2871 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2872 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2873 // we give ourselves a few blocks of headroom after expiration before going
2874 // on-chain for an expired HTLC.
2875 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2876 // from us until we've reached the point where we go on-chain with the
2877 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2878 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2879 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2880 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2881 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2882 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2883 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2884 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2885 // The final, above, condition is checked for statically in channelmanager
2886 // with CHECK_CLTV_EXPIRY_SANITY_2.
2887 let htlc_outbound = $holder_tx == htlc.offered;
2888 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2889 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2890 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2897 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2899 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2900 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2901 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2904 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2905 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2906 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2913 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2914 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2915 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2916 'outer_loop: for input in &tx.input {
2917 let mut payment_data = None;
2918 let witness_items = input.witness.len();
2919 let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
2920 let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
2921 let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
2922 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
2923 let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
2924 && input.witness.second_to_last().unwrap().len() == 32;
2925 #[cfg(not(fuzzing))]
2926 let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2927 let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
2928 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
2930 #[cfg(not(fuzzing))]
2931 let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
2933 let mut payment_preimage = PaymentPreimage([0; 32]);
2934 if accepted_preimage_claim {
2935 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2936 } else if offered_preimage_claim {
2937 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2940 macro_rules! log_claim {
2941 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2942 let outbound_htlc = $holder_tx == $htlc.offered;
2943 // HTLCs must either be claimed by a matching script type or through the
2945 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2946 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2947 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2948 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2949 // Further, only exactly one of the possible spend paths should have been
2950 // matched by any HTLC spend:
2951 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2952 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2953 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2954 revocation_sig_claim as u8, 1);
2955 if ($holder_tx && revocation_sig_claim) ||
2956 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2957 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2958 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2959 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2960 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2962 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2963 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2964 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2965 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2970 macro_rules! check_htlc_valid_counterparty {
2971 ($counterparty_txid: expr, $htlc_output: expr) => {
2972 if let Some(txid) = $counterparty_txid {
2973 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2974 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2975 if let &Some(ref source) = pending_source {
2976 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2977 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2986 macro_rules! scan_commitment {
2987 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2988 for (ref htlc_output, source_option) in $htlcs {
2989 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2990 if let Some(ref source) = source_option {
2991 log_claim!($tx_info, $holder_tx, htlc_output, true);
2992 // We have a resolution of an HTLC either from one of our latest
2993 // holder commitment transactions or an unrevoked counterparty commitment
2994 // transaction. This implies we either learned a preimage, the HTLC
2995 // has timed out, or we screwed up. In any case, we should now
2996 // resolve the source HTLC with the original sender.
2997 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2998 } else if !$holder_tx {
2999 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3000 if payment_data.is_none() {
3001 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3004 if payment_data.is_none() {
3005 log_claim!($tx_info, $holder_tx, htlc_output, false);
3006 let outbound_htlc = $holder_tx == htlc_output.offered;
3007 if !outbound_htlc || revocation_sig_claim {
3008 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3009 txid: tx.txid(), height, transaction: Some(tx.clone()),
3010 event: OnchainEvent::HTLCSpendConfirmation {
3011 commitment_tx_output_idx: input.previous_output.vout,
3012 preimage: if accepted_preimage_claim || offered_preimage_claim {
3013 Some(payment_preimage) } else { None },
3014 // If this is a payment to us (!outbound_htlc, above),
3015 // wait for the CSV delay before dropping the HTLC from
3016 // claimable balance if the claim was an HTLC-Success
3018 on_to_local_output_csv: if accepted_preimage_claim {
3019 Some(self.on_holder_tx_csv) } else { None },
3023 // Outbound claims should always have payment_data, unless
3024 // we've already failed the HTLC as the commitment transaction
3025 // which was broadcasted was revoked. In that case, we should
3026 // spend the HTLC output here immediately, and expose that fact
3027 // as a Balance, something which we do not yet do.
3028 // TODO: Track the above as claimable!
3030 continue 'outer_loop;
3037 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3038 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3039 "our latest holder commitment tx", true);
3041 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3042 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3043 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3044 "our previous holder commitment tx", true);
3047 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3048 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3049 "counterparty commitment tx", false);
3052 // Check that scan_commitment, above, decided there is some source worth relaying an
3053 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3054 if let Some((source, payment_hash, amount_msat)) = payment_data {
3055 if accepted_preimage_claim {
3056 if !self.pending_monitor_events.iter().any(
3057 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3058 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3061 transaction: Some(tx.clone()),
3062 event: OnchainEvent::HTLCSpendConfirmation {
3063 commitment_tx_output_idx: input.previous_output.vout,
3064 preimage: Some(payment_preimage),
3065 on_to_local_output_csv: None,
3068 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3070 payment_preimage: Some(payment_preimage),
3072 htlc_value_satoshis: Some(amount_msat / 1000),
3075 } else if offered_preimage_claim {
3076 if !self.pending_monitor_events.iter().any(
3077 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3078 upd.source == source
3080 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3082 transaction: Some(tx.clone()),
3084 event: OnchainEvent::HTLCSpendConfirmation {
3085 commitment_tx_output_idx: input.previous_output.vout,
3086 preimage: Some(payment_preimage),
3087 on_to_local_output_csv: None,
3090 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3092 payment_preimage: Some(payment_preimage),
3094 htlc_value_satoshis: Some(amount_msat / 1000),
3098 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3099 if entry.height != height { return true; }
3101 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3102 *htlc_source != source
3107 let entry = OnchainEventEntry {
3109 transaction: Some(tx.clone()),
3111 event: OnchainEvent::HTLCUpdate {
3112 source, payment_hash,
3113 htlc_value_satoshis: Some(amount_msat / 1000),
3114 commitment_tx_output_idx: Some(input.previous_output.vout),
3117 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());
3118 self.onchain_events_awaiting_threshold_conf.push(entry);
3124 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3125 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3126 let mut spendable_output = None;
3127 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3128 if i > ::core::u16::MAX as usize {
3129 // While it is possible that an output exists on chain which is greater than the
3130 // 2^16th output in a given transaction, this is only possible if the output is not
3131 // in a lightning transaction and was instead placed there by some third party who
3132 // wishes to give us money for no reason.
3133 // Namely, any lightning transactions which we pre-sign will never have anywhere
3134 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3135 // scripts are not longer than one byte in length and because they are inherently
3136 // non-standard due to their size.
3137 // Thus, it is completely safe to ignore such outputs, and while it may result in
3138 // us ignoring non-lightning fund to us, that is only possible if someone fills
3139 // nearly a full block with garbage just to hit this case.
3142 if outp.script_pubkey == self.destination_script {
3143 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3144 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3145 output: outp.clone(),
3149 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3150 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3151 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3152 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3153 per_commitment_point: broadcasted_holder_revokable_script.1,
3154 to_self_delay: self.on_holder_tx_csv,
3155 output: outp.clone(),
3156 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3157 channel_keys_id: self.channel_keys_id,
3158 channel_value_satoshis: self.channel_value_satoshis,
3163 if self.counterparty_payment_script == outp.script_pubkey {
3164 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3165 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3166 output: outp.clone(),
3167 channel_keys_id: self.channel_keys_id,
3168 channel_value_satoshis: self.channel_value_satoshis,
3172 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3173 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3174 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3175 output: outp.clone(),
3180 if let Some(spendable_output) = spendable_output {
3181 let entry = OnchainEventEntry {
3183 transaction: Some(tx.clone()),
3185 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3187 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3188 self.onchain_events_awaiting_threshold_conf.push(entry);
3193 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3195 T::Target: BroadcasterInterface,
3196 F::Target: FeeEstimator,
3199 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3200 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3203 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3204 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3208 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3210 T::Target: BroadcasterInterface,
3211 F::Target: FeeEstimator,
3214 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3215 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3218 fn transaction_unconfirmed(&self, txid: &Txid) {
3219 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3222 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3223 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3226 fn get_relevant_txids(&self) -> Vec<Txid> {
3227 self.0.get_relevant_txids()
3231 const MAX_ALLOC_SIZE: usize = 64*1024;
3233 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3234 for (BlockHash, ChannelMonitor<Signer>) {
3235 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3236 macro_rules! unwrap_obj {
3240 Err(_) => return Err(DecodeError::InvalidValue),
3245 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3247 let latest_update_id: u64 = Readable::read(reader)?;
3248 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3250 let destination_script = Readable::read(reader)?;
3251 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3253 let revokable_address = Readable::read(reader)?;
3254 let per_commitment_point = Readable::read(reader)?;
3255 let revokable_script = Readable::read(reader)?;
3256 Some((revokable_address, per_commitment_point, revokable_script))
3259 _ => return Err(DecodeError::InvalidValue),
3261 let counterparty_payment_script = Readable::read(reader)?;
3262 let shutdown_script = {
3263 let script = <Script as Readable>::read(reader)?;
3264 if script.is_empty() { None } else { Some(script) }
3267 let channel_keys_id = Readable::read(reader)?;
3268 let holder_revocation_basepoint = Readable::read(reader)?;
3269 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3270 // barely-init'd ChannelMonitors that we can't do anything with.
3271 let outpoint = OutPoint {
3272 txid: Readable::read(reader)?,
3273 index: Readable::read(reader)?,
3275 let funding_info = (outpoint, Readable::read(reader)?);
3276 let current_counterparty_commitment_txid = Readable::read(reader)?;
3277 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3279 let counterparty_commitment_params = Readable::read(reader)?;
3280 let funding_redeemscript = Readable::read(reader)?;
3281 let channel_value_satoshis = Readable::read(reader)?;
3283 let their_cur_per_commitment_points = {
3284 let first_idx = <U48 as Readable>::read(reader)?.0;
3288 let first_point = Readable::read(reader)?;
3289 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3290 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3291 Some((first_idx, first_point, None))
3293 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3298 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3300 let commitment_secrets = Readable::read(reader)?;
3302 macro_rules! read_htlc_in_commitment {
3305 let offered: bool = Readable::read(reader)?;
3306 let amount_msat: u64 = Readable::read(reader)?;
3307 let cltv_expiry: u32 = Readable::read(reader)?;
3308 let payment_hash: PaymentHash = Readable::read(reader)?;
3309 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3311 HTLCOutputInCommitment {
3312 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3318 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3319 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3320 for _ in 0..counterparty_claimable_outpoints_len {
3321 let txid: Txid = Readable::read(reader)?;
3322 let htlcs_count: u64 = Readable::read(reader)?;
3323 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3324 for _ in 0..htlcs_count {
3325 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3327 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3328 return Err(DecodeError::InvalidValue);
3332 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3333 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3334 for _ in 0..counterparty_commitment_txn_on_chain_len {
3335 let txid: Txid = Readable::read(reader)?;
3336 let commitment_number = <U48 as Readable>::read(reader)?.0;
3337 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3338 return Err(DecodeError::InvalidValue);
3342 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3343 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3344 for _ in 0..counterparty_hash_commitment_number_len {
3345 let payment_hash: PaymentHash = Readable::read(reader)?;
3346 let commitment_number = <U48 as Readable>::read(reader)?.0;
3347 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3348 return Err(DecodeError::InvalidValue);
3352 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3353 match <u8 as Readable>::read(reader)? {
3356 Some(Readable::read(reader)?)
3358 _ => return Err(DecodeError::InvalidValue),
3360 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3362 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3363 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3365 let payment_preimages_len: u64 = Readable::read(reader)?;
3366 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3367 for _ in 0..payment_preimages_len {
3368 let preimage: PaymentPreimage = Readable::read(reader)?;
3369 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3370 if let Some(_) = payment_preimages.insert(hash, preimage) {
3371 return Err(DecodeError::InvalidValue);
3375 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3376 let mut pending_monitor_events = Some(
3377 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3378 for _ in 0..pending_monitor_events_len {
3379 let ev = match <u8 as Readable>::read(reader)? {
3380 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3381 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3382 _ => return Err(DecodeError::InvalidValue)
3384 pending_monitor_events.as_mut().unwrap().push(ev);
3387 let pending_events_len: u64 = Readable::read(reader)?;
3388 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3389 for _ in 0..pending_events_len {
3390 if let Some(event) = MaybeReadable::read(reader)? {
3391 pending_events.push(event);
3395 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3397 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3398 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3399 for _ in 0..waiting_threshold_conf_len {
3400 if let Some(val) = MaybeReadable::read(reader)? {
3401 onchain_events_awaiting_threshold_conf.push(val);
3405 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3406 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>>())));
3407 for _ in 0..outputs_to_watch_len {
3408 let txid = Readable::read(reader)?;
3409 let outputs_len: u64 = Readable::read(reader)?;
3410 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3411 for _ in 0..outputs_len {
3412 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3414 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3415 return Err(DecodeError::InvalidValue);
3418 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3420 let lockdown_from_offchain = Readable::read(reader)?;
3421 let holder_tx_signed = Readable::read(reader)?;
3423 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3424 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3425 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3426 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3427 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3428 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3429 return Err(DecodeError::InvalidValue);
3433 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3434 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3435 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3436 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3437 return Err(DecodeError::InvalidValue);
3440 let mut funding_spend_confirmed = None;
3441 let mut htlcs_resolved_on_chain = Some(Vec::new());
3442 let mut funding_spend_seen = Some(false);
3443 let mut counterparty_node_id = None;
3444 let mut confirmed_commitment_tx_counterparty_output = None;
3445 read_tlv_fields!(reader, {
3446 (1, funding_spend_confirmed, option),
3447 (3, htlcs_resolved_on_chain, vec_type),
3448 (5, pending_monitor_events, vec_type),
3449 (7, funding_spend_seen, option),
3450 (9, counterparty_node_id, option),
3451 (11, confirmed_commitment_tx_counterparty_output, option),
3454 let mut secp_ctx = Secp256k1::new();
3455 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3457 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3459 commitment_transaction_number_obscure_factor,
3462 broadcasted_holder_revokable_script,
3463 counterparty_payment_script,
3467 holder_revocation_basepoint,
3469 current_counterparty_commitment_txid,
3470 prev_counterparty_commitment_txid,
3472 counterparty_commitment_params,
3473 funding_redeemscript,
3474 channel_value_satoshis,
3475 their_cur_per_commitment_points,
3480 counterparty_claimable_outpoints,
3481 counterparty_commitment_txn_on_chain,
3482 counterparty_hash_commitment_number,
3484 prev_holder_signed_commitment_tx,
3485 current_holder_commitment_tx,
3486 current_counterparty_commitment_number,
3487 current_holder_commitment_number,
3490 pending_monitor_events: pending_monitor_events.unwrap(),
3493 onchain_events_awaiting_threshold_conf,
3498 lockdown_from_offchain,
3500 funding_spend_seen: funding_spend_seen.unwrap(),
3501 funding_spend_confirmed,
3502 confirmed_commitment_tx_counterparty_output,
3503 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3506 counterparty_node_id,
3515 use bitcoin::blockdata::block::BlockHeader;
3516 use bitcoin::blockdata::script::{Script, Builder};
3517 use bitcoin::blockdata::opcodes;
3518 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3519 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3520 use bitcoin::util::sighash;
3521 use bitcoin::hashes::Hash;
3522 use bitcoin::hashes::sha256::Hash as Sha256;
3523 use bitcoin::hashes::hex::FromHex;
3524 use bitcoin::hash_types::{BlockHash, Txid};
3525 use bitcoin::network::constants::Network;
3526 use bitcoin::secp256k1::{SecretKey,PublicKey};
3527 use bitcoin::secp256k1::Secp256k1;
3531 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3533 use super::ChannelMonitorUpdateStep;
3534 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};
3535 use chain::{BestBlock, Confirm};
3536 use chain::channelmonitor::ChannelMonitor;
3537 use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3538 use chain::transaction::OutPoint;
3539 use chain::keysinterface::InMemorySigner;
3540 use ln::{PaymentPreimage, PaymentHash};
3542 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3543 use ln::channelmanager::PaymentSendFailure;
3544 use ln::features::InitFeatures;
3545 use ln::functional_test_utils::*;
3546 use ln::script::ShutdownScript;
3547 use util::errors::APIError;
3548 use util::events::{ClosureReason, MessageSendEventsProvider};
3549 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3550 use util::ser::{ReadableArgs, Writeable};
3551 use sync::{Arc, Mutex};
3553 use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
3556 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3557 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3558 // confirmed. This would allow a race condition where we could receive a payment (including
3559 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3560 // long as the ChannelMonitor receives the block first, the full commitment update dance
3561 // occurs after the block is connected, and before the ChannelManager receives the block.
3562 // Obviously this is an incredibly contrived race given the counterparty would be risking
3563 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3564 // potential ChannelMonitor states simpler to reason about.
3566 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3567 // updates is handled correctly in such conditions.
3568 let chanmon_cfgs = create_chanmon_cfgs(3);
3569 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3570 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3571 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3572 let channel = create_announced_chan_between_nodes(
3573 &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3574 create_announced_chan_between_nodes(
3575 &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3577 // Rebalance somewhat
3578 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3580 // First route two payments for testing at the end
3581 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3582 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3584 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3585 assert_eq!(local_txn.len(), 1);
3586 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3587 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3588 check_spends!(remote_txn[1], remote_txn[0]);
3589 check_spends!(remote_txn[2], remote_txn[0]);
3590 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3592 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3593 // channel is now closed, but the ChannelManager doesn't know that yet.
3594 let new_header = BlockHeader {
3595 version: 2, time: 0, bits: 0, nonce: 0,
3596 prev_blockhash: nodes[0].best_block_info().0,
3597 merkle_root: TxMerkleNode::all_zeros() };
3598 let conf_height = nodes[0].best_block_info().1 + 1;
3599 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3600 &[(0, broadcast_tx)], conf_height);
3602 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3603 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3604 &nodes[1].keys_manager.backing).unwrap();
3606 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3607 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3608 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3609 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3610 true, APIError::ChannelUnavailable { ref err },
3611 assert!(err.contains("ChannelMonitor storage failure")));
3612 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3613 check_closed_broadcast!(nodes[1], true);
3614 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3616 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3617 // and provides the claim preimages for the two pending HTLCs. The first update generates
3618 // an error, but the point of this test is to ensure the later updates are still applied.
3619 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3620 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3621 assert_eq!(replay_update.updates.len(), 1);
3622 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3623 } else { panic!(); }
3624 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3625 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3627 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3629 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3631 // Even though we error'd on the first update, we should still have generated an HTLC claim
3633 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3634 assert!(txn_broadcasted.len() >= 2);
3635 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3636 assert_eq!(tx.input.len(), 1);
3637 tx.input[0].previous_output.txid == broadcast_tx.txid()
3638 }).collect::<Vec<_>>();
3639 assert_eq!(htlc_txn.len(), 2);
3640 check_spends!(htlc_txn[0], broadcast_tx);
3641 check_spends!(htlc_txn[1], broadcast_tx);
3644 fn test_funding_spend_refuses_updates() {
3645 do_test_funding_spend_refuses_updates(true);
3646 do_test_funding_spend_refuses_updates(false);
3650 fn test_prune_preimages() {
3651 let secp_ctx = Secp256k1::new();
3652 let logger = Arc::new(TestLogger::new());
3653 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3654 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3656 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3657 let dummy_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3659 let mut preimages = Vec::new();
3662 let preimage = PaymentPreimage([i; 32]);
3663 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3664 preimages.push((preimage, hash));
3668 macro_rules! preimages_slice_to_htlc_outputs {
3669 ($preimages_slice: expr) => {
3671 let mut res = Vec::new();
3672 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3673 res.push((HTLCOutputInCommitment {
3677 payment_hash: preimage.1.clone(),
3678 transaction_output_index: Some(idx as u32),
3685 macro_rules! preimages_to_holder_htlcs {
3686 ($preimages_slice: expr) => {
3688 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3689 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3695 macro_rules! test_preimages_exist {
3696 ($preimages_slice: expr, $monitor: expr) => {
3697 for preimage in $preimages_slice {
3698 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3703 let keys = InMemorySigner::new(
3705 SecretKey::from_slice(&[41; 32]).unwrap(),
3706 SecretKey::from_slice(&[41; 32]).unwrap(),
3707 SecretKey::from_slice(&[41; 32]).unwrap(),
3708 SecretKey::from_slice(&[41; 32]).unwrap(),
3709 SecretKey::from_slice(&[41; 32]).unwrap(),
3710 SecretKey::from_slice(&[41; 32]).unwrap(),
3716 let counterparty_pubkeys = ChannelPublicKeys {
3717 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3718 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3719 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3720 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3721 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3723 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
3724 let channel_parameters = ChannelTransactionParameters {
3725 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3726 holder_selected_contest_delay: 66,
3727 is_outbound_from_holder: true,
3728 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3729 pubkeys: counterparty_pubkeys,
3730 selected_contest_delay: 67,
3732 funding_outpoint: Some(funding_outpoint),
3735 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3737 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3738 let best_block = BestBlock::from_genesis(Network::Testnet);
3739 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3740 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3741 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3742 &channel_parameters,
3743 Script::new(), 46, 0,
3744 HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3746 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3747 let dummy_txid = dummy_tx.txid();
3748 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3749 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3750 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3751 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3752 for &(ref preimage, ref hash) in preimages.iter() {
3753 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3754 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3757 // Now provide a secret, pruning preimages 10-15
3758 let mut secret = [0; 32];
3759 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3760 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3761 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3762 test_preimages_exist!(&preimages[0..10], monitor);
3763 test_preimages_exist!(&preimages[15..20], monitor);
3765 // Now provide a further secret, pruning preimages 15-17
3766 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3767 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3768 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3769 test_preimages_exist!(&preimages[0..10], monitor);
3770 test_preimages_exist!(&preimages[17..20], monitor);
3772 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3773 // previous commitment tx's preimages too
3774 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3775 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3776 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3777 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3778 test_preimages_exist!(&preimages[0..10], monitor);
3779 test_preimages_exist!(&preimages[18..20], monitor);
3781 // But if we do it again, we'll prune 5-10
3782 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3783 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3784 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3785 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3786 test_preimages_exist!(&preimages[0..5], monitor);
3790 fn test_claim_txn_weight_computation() {
3791 // We test Claim txn weight, knowing that we want expected weigth and
3792 // not actual case to avoid sigs and time-lock delays hell variances.
3794 let secp_ctx = Secp256k1::new();
3795 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3796 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3798 macro_rules! sign_input {
3799 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3800 let htlc = HTLCOutputInCommitment {
3801 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3803 cltv_expiry: 2 << 16,
3804 payment_hash: PaymentHash([1; 32]),
3805 transaction_output_index: Some($idx as u32),
3807 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) };
3808 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3809 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3810 let mut ser_sig = sig.serialize_der().to_vec();
3811 ser_sig.push(EcdsaSighashType::All as u8);
3812 $sum_actual_sigs += ser_sig.len();
3813 let witness = $sighash_parts.witness_mut($idx).unwrap();
3814 witness.push(ser_sig);
3815 if *$weight == WEIGHT_REVOKED_OUTPUT {
3816 witness.push(vec!(1));
3817 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3818 witness.push(pubkey.clone().serialize().to_vec());
3819 } else if *$weight == weight_received_htlc($opt_anchors) {
3820 witness.push(vec![0]);
3822 witness.push(PaymentPreimage([1; 32]).0.to_vec());
3824 witness.push(redeem_script.into_bytes());
3825 let witness = witness.to_vec();
3826 println!("witness[0] {}", witness[0].len());
3827 println!("witness[1] {}", witness[1].len());
3828 println!("witness[2] {}", witness[2].len());
3832 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3833 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3835 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3836 for &opt_anchors in [false, true].iter() {
3837 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3838 let mut sum_actual_sigs = 0;
3840 claim_tx.input.push(TxIn {
3841 previous_output: BitcoinOutPoint {
3845 script_sig: Script::new(),
3846 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3847 witness: Witness::new(),
3850 claim_tx.output.push(TxOut {
3851 script_pubkey: script_pubkey.clone(),
3854 let base_weight = claim_tx.weight();
3855 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)];
3856 let mut inputs_total_weight = 2; // count segwit flags
3858 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3859 for (idx, inp) in inputs_weight.iter().enumerate() {
3860 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3861 inputs_total_weight += inp;
3864 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3867 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3868 for &opt_anchors in [false, true].iter() {
3869 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3870 let mut sum_actual_sigs = 0;
3872 claim_tx.input.push(TxIn {
3873 previous_output: BitcoinOutPoint {
3877 script_sig: Script::new(),
3878 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3879 witness: Witness::new(),
3882 claim_tx.output.push(TxOut {
3883 script_pubkey: script_pubkey.clone(),
3886 let base_weight = claim_tx.weight();
3887 let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
3888 let mut inputs_total_weight = 2; // count segwit flags
3890 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3891 for (idx, inp) in inputs_weight.iter().enumerate() {
3892 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3893 inputs_total_weight += inp;
3896 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3899 // Justice tx with 1 revoked HTLC-Success tx output
3900 for &opt_anchors in [false, true].iter() {
3901 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3902 let mut sum_actual_sigs = 0;
3903 claim_tx.input.push(TxIn {
3904 previous_output: BitcoinOutPoint {
3908 script_sig: Script::new(),
3909 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
3910 witness: Witness::new(),
3912 claim_tx.output.push(TxOut {
3913 script_pubkey: script_pubkey.clone(),
3916 let base_weight = claim_tx.weight();
3917 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3918 let mut inputs_total_weight = 2; // count segwit flags
3920 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3921 for (idx, inp) in inputs_weight.iter().enumerate() {
3922 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3923 inputs_total_weight += inp;
3926 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3930 // Further testing is done in the ChannelManager integration tests.