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};
60 /// An update generated by the underlying Channel itself which contains some new information the
61 /// ChannelMonitor should be made aware of.
62 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
65 pub struct ChannelMonitorUpdate {
66 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
67 /// The sequence number of this update. Updates *must* be replayed in-order according to this
68 /// sequence number (and updates may panic if they are not). The update_id values are strictly
69 /// increasing and increase by one for each new update, with one exception specified below.
71 /// This sequence number is also used to track up to which points updates which returned
72 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
73 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
75 /// The only instance where update_id values are not strictly increasing is the case where we
76 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
77 /// its docs for more details.
82 /// (1) a channel has been force closed and
83 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
84 /// this channel's (the backward link's) broadcasted commitment transaction
85 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
86 /// with the update providing said payment preimage. No other update types are allowed after
88 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
90 impl Writeable for ChannelMonitorUpdate {
91 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
92 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
93 self.update_id.write(w)?;
94 (self.updates.len() as u64).write(w)?;
95 for update_step in self.updates.iter() {
96 update_step.write(w)?;
98 write_tlv_fields!(w, {});
102 impl Readable for ChannelMonitorUpdate {
103 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
104 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
105 let update_id: u64 = Readable::read(r)?;
106 let len: u64 = Readable::read(r)?;
107 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
109 if let Some(upd) = MaybeReadable::read(r)? {
113 read_tlv_fields!(r, {});
114 Ok(Self { update_id, updates })
118 /// An event to be processed by the ChannelManager.
119 #[derive(Clone, PartialEq)]
120 pub enum MonitorEvent {
121 /// A monitor event containing an HTLCUpdate.
122 HTLCEvent(HTLCUpdate),
124 /// A monitor event that the Channel's commitment transaction was confirmed.
125 CommitmentTxConfirmed(OutPoint),
127 /// Indicates a [`ChannelMonitor`] update has completed. See
128 /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
130 /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
132 /// The funding outpoint of the [`ChannelMonitor`] that was updated
133 funding_txo: OutPoint,
134 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
135 /// [`ChannelMonitor::get_latest_update_id`].
137 /// Note that this should only be set to a given update's ID if all previous updates for the
138 /// same [`ChannelMonitor`] have been applied and persisted.
139 monitor_update_id: u64,
142 /// Indicates a [`ChannelMonitor`] update has failed. See
143 /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
145 /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
146 UpdateFailed(OutPoint),
148 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
149 // Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
150 // generated only in ChainMonitor
151 (0, UpdateCompleted) => {
152 (0, funding_txo, required),
153 (2, monitor_update_id, required),
157 (4, CommitmentTxConfirmed),
161 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
162 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
163 /// preimage claim backward will lead to loss of funds.
164 #[derive(Clone, PartialEq)]
165 pub struct HTLCUpdate {
166 pub(crate) payment_hash: PaymentHash,
167 pub(crate) payment_preimage: Option<PaymentPreimage>,
168 pub(crate) source: HTLCSource,
169 pub(crate) htlc_value_satoshis: Option<u64>,
171 impl_writeable_tlv_based!(HTLCUpdate, {
172 (0, payment_hash, required),
173 (1, htlc_value_satoshis, option),
174 (2, source, required),
175 (4, payment_preimage, option),
178 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
179 /// instead claiming it in its own individual transaction.
180 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
181 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
182 /// HTLC-Success transaction.
183 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
184 /// transaction confirmed (and we use it in a few more, equivalent, places).
185 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
186 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
187 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
188 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
189 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
190 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
191 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
192 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
193 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
194 /// accurate block height.
195 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
196 /// with at worst this delay, so we are not only using this value as a mercy for them but also
197 /// us as a safeguard to delay with enough time.
198 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
199 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
200 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
203 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
204 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
205 /// by a [`ChannelMonitor`] may be incorrect.
206 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
207 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
208 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
209 // keep bumping another claim tx to solve the outpoint.
210 pub const ANTI_REORG_DELAY: u32 = 6;
211 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
212 /// refuse to accept a new HTLC.
214 /// This is used for a few separate purposes:
215 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
216 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
218 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
219 /// condition with the above), we will fail this HTLC without telling the user we received it,
221 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
222 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
224 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
225 /// in a race condition between the user connecting a block (which would fail it) and the user
226 /// providing us the preimage (which would claim it).
227 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
229 // TODO(devrandom) replace this with HolderCommitmentTransaction
230 #[derive(Clone, PartialEq)]
231 struct HolderSignedTx {
232 /// txid of the transaction in tx, just used to make comparison faster
234 revocation_key: PublicKey,
235 a_htlc_key: PublicKey,
236 b_htlc_key: PublicKey,
237 delayed_payment_key: PublicKey,
238 per_commitment_point: PublicKey,
239 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
240 to_self_value_sat: u64,
243 impl_writeable_tlv_based!(HolderSignedTx, {
245 // Note that this is filled in with data from OnchainTxHandler if it's missing.
246 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
247 (1, to_self_value_sat, (default_value, u64::max_value())),
248 (2, revocation_key, required),
249 (4, a_htlc_key, required),
250 (6, b_htlc_key, required),
251 (8, delayed_payment_key, required),
252 (10, per_commitment_point, required),
253 (12, feerate_per_kw, required),
254 (14, htlc_outputs, vec_type)
257 /// We use this to track static counterparty commitment transaction data and to generate any
258 /// justice or 2nd-stage preimage/timeout transactions.
260 struct CounterpartyCommitmentParameters {
261 counterparty_delayed_payment_base_key: PublicKey,
262 counterparty_htlc_base_key: PublicKey,
263 on_counterparty_tx_csv: u16,
266 impl Writeable for CounterpartyCommitmentParameters {
267 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
268 w.write_all(&byte_utils::be64_to_array(0))?;
269 write_tlv_fields!(w, {
270 (0, self.counterparty_delayed_payment_base_key, required),
271 (2, self.counterparty_htlc_base_key, required),
272 (4, self.on_counterparty_tx_csv, required),
277 impl Readable for CounterpartyCommitmentParameters {
278 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
279 let counterparty_commitment_transaction = {
280 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
281 // used. Read it for compatibility.
282 let per_htlc_len: u64 = Readable::read(r)?;
283 for _ in 0..per_htlc_len {
284 let _txid: Txid = Readable::read(r)?;
285 let htlcs_count: u64 = Readable::read(r)?;
286 for _ in 0..htlcs_count {
287 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
291 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
292 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
293 let mut on_counterparty_tx_csv: u16 = 0;
294 read_tlv_fields!(r, {
295 (0, counterparty_delayed_payment_base_key, required),
296 (2, counterparty_htlc_base_key, required),
297 (4, on_counterparty_tx_csv, required),
299 CounterpartyCommitmentParameters {
300 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
301 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
302 on_counterparty_tx_csv,
305 Ok(counterparty_commitment_transaction)
309 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
310 /// transaction causing it.
312 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
314 struct OnchainEventEntry {
320 impl OnchainEventEntry {
321 fn confirmation_threshold(&self) -> u32 {
322 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
324 OnchainEvent::MaturingOutput {
325 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
327 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
328 // it's broadcastable when we see the previous block.
329 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
331 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
332 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
333 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
334 // it's broadcastable when we see the previous block.
335 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
342 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
343 best_block.height() >= self.confirmation_threshold()
347 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
348 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
351 /// An outbound HTLC failing after a transaction is confirmed. Used
352 /// * when an outbound HTLC output is spent by us after the HTLC timed out
353 /// * an outbound HTLC which was not present in the commitment transaction which appeared
354 /// on-chain (either because it was not fully committed to or it was dust).
355 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
356 /// appearing only as an `HTLCSpendConfirmation`, below.
359 payment_hash: PaymentHash,
360 htlc_value_satoshis: Option<u64>,
361 /// None in the second case, above, ie when there is no relevant output in the commitment
362 /// transaction which appeared on chain.
363 commitment_tx_output_idx: Option<u32>,
366 descriptor: SpendableOutputDescriptor,
368 /// A spend of the funding output, either a commitment transaction or a cooperative closing
370 FundingSpendConfirmation {
371 /// The CSV delay for the output of the funding spend transaction (implying it is a local
372 /// commitment transaction, and this is the delay on the to_self output).
373 on_local_output_csv: Option<u16>,
375 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
376 /// is constructed. This is used when
377 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
378 /// immediately claim the HTLC on the inbound edge and track the resolution here,
379 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
380 /// * an inbound HTLC is claimed by us (with a preimage).
381 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
383 HTLCSpendConfirmation {
384 commitment_tx_output_idx: u32,
385 /// If the claim was made by either party with a preimage, this is filled in
386 preimage: Option<PaymentPreimage>,
387 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
388 /// we set this to the output CSV value which we will have to wait until to spend the
389 /// output (and generate a SpendableOutput event).
390 on_to_local_output_csv: Option<u16>,
394 impl Writeable for OnchainEventEntry {
395 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
396 write_tlv_fields!(writer, {
397 (0, self.txid, required),
398 (2, self.height, required),
399 (4, self.event, required),
405 impl MaybeReadable for OnchainEventEntry {
406 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
407 let mut txid = Default::default();
409 let mut event = None;
410 read_tlv_fields!(reader, {
412 (2, height, required),
413 (4, event, ignorable),
415 if let Some(ev) = event {
416 Ok(Some(Self { txid, height, event: ev }))
423 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
425 (0, source, required),
426 (1, htlc_value_satoshis, option),
427 (2, payment_hash, required),
428 (3, commitment_tx_output_idx, option),
430 (1, MaturingOutput) => {
431 (0, descriptor, required),
433 (3, FundingSpendConfirmation) => {
434 (0, on_local_output_csv, option),
436 (5, HTLCSpendConfirmation) => {
437 (0, commitment_tx_output_idx, required),
438 (2, preimage, option),
439 (4, on_to_local_output_csv, option),
444 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
446 pub(crate) enum ChannelMonitorUpdateStep {
447 LatestHolderCommitmentTXInfo {
448 commitment_tx: HolderCommitmentTransaction,
449 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
451 LatestCounterpartyCommitmentTXInfo {
452 commitment_txid: Txid,
453 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
454 commitment_number: u64,
455 their_per_commitment_point: PublicKey,
458 payment_preimage: PaymentPreimage,
464 /// Used to indicate that the no future updates will occur, and likely that the latest holder
465 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
467 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
468 /// think we've fallen behind!
469 should_broadcast: bool,
472 scriptpubkey: Script,
476 impl ChannelMonitorUpdateStep {
477 fn variant_name(&self) -> &'static str {
479 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
480 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
481 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
482 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
483 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
484 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
489 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
490 (0, LatestHolderCommitmentTXInfo) => {
491 (0, commitment_tx, required),
492 (2, htlc_outputs, vec_type),
494 (1, LatestCounterpartyCommitmentTXInfo) => {
495 (0, commitment_txid, required),
496 (2, commitment_number, required),
497 (4, their_per_commitment_point, required),
498 (6, htlc_outputs, vec_type),
500 (2, PaymentPreimage) => {
501 (0, payment_preimage, required),
503 (3, CommitmentSecret) => {
505 (2, secret, required),
507 (4, ChannelForceClosed) => {
508 (0, should_broadcast, required),
510 (5, ShutdownScript) => {
511 (0, scriptpubkey, required),
515 /// Details about the balance(s) available for spending once the channel appears on chain.
517 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
519 #[derive(Clone, Debug, PartialEq, Eq)]
520 #[cfg_attr(test, derive(PartialOrd, Ord))]
522 /// The channel is not yet closed (or the commitment or closing transaction has not yet
523 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
524 /// force-closed now.
525 ClaimableOnChannelClose {
526 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
527 /// required to do so.
528 claimable_amount_satoshis: u64,
530 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
531 /// we consider it spendable.
532 ClaimableAwaitingConfirmations {
533 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
534 /// were spent in broadcasting the transaction.
535 claimable_amount_satoshis: u64,
536 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
538 confirmation_height: u32,
540 /// The channel has been closed, and the given balance should be ours but awaiting spending
541 /// transaction confirmation. If the spending transaction does not confirm in time, it is
542 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
544 /// Once the spending transaction confirms, before it has reached enough confirmations to be
545 /// considered safe from chain reorganizations, the balance will instead be provided via
546 /// [`Balance::ClaimableAwaitingConfirmations`].
547 ContentiousClaimable {
548 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
549 /// required to do so.
550 claimable_amount_satoshis: u64,
551 /// The height at which the counterparty may be able to claim the balance if we have not
555 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
556 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
557 /// likely to be claimed by our counterparty before we do.
558 MaybeClaimableHTLCAwaitingTimeout {
559 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
560 /// required to do so.
561 claimable_amount_satoshis: u64,
562 /// The height at which we will be able to claim the balance if our counterparty has not
564 claimable_height: u32,
568 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
570 struct IrrevocablyResolvedHTLC {
571 commitment_tx_output_idx: u32,
572 /// Only set if the HTLC claim was ours using a payment preimage
573 payment_preimage: Option<PaymentPreimage>,
576 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
577 (0, commitment_tx_output_idx, required),
578 (2, payment_preimage, option),
581 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
582 /// on-chain transactions to ensure no loss of funds occurs.
584 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
585 /// information and are actively monitoring the chain.
587 /// Pending Events or updated HTLCs which have not yet been read out by
588 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
589 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
590 /// gotten are fully handled before re-serializing the new state.
592 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
593 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
594 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
595 /// returned block hash and the the current chain and then reconnecting blocks to get to the
596 /// best chain) upon deserializing the object!
597 pub struct ChannelMonitor<Signer: Sign> {
599 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
601 inner: Mutex<ChannelMonitorImpl<Signer>>,
604 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
605 latest_update_id: u64,
606 commitment_transaction_number_obscure_factor: u64,
608 destination_script: Script,
609 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
610 counterparty_payment_script: Script,
611 shutdown_script: Option<Script>,
613 channel_keys_id: [u8; 32],
614 holder_revocation_basepoint: PublicKey,
615 funding_info: (OutPoint, Script),
616 current_counterparty_commitment_txid: Option<Txid>,
617 prev_counterparty_commitment_txid: Option<Txid>,
619 counterparty_commitment_params: CounterpartyCommitmentParameters,
620 funding_redeemscript: Script,
621 channel_value_satoshis: u64,
622 // first is the idx of the first of the two per-commitment points
623 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
625 on_holder_tx_csv: u16,
627 commitment_secrets: CounterpartyCommitmentSecrets,
628 /// The set of outpoints in each counterparty commitment transaction. We always need at least
629 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
630 /// transaction broadcast as we need to be able to construct the witness script in all cases.
631 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
632 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
633 /// Nor can we figure out their commitment numbers without the commitment transaction they are
634 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
635 /// commitment transactions which we find on-chain, mapping them to the commitment number which
636 /// can be used to derive the revocation key and claim the transactions.
637 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
638 /// Cache used to make pruning of payment_preimages faster.
639 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
640 /// counterparty transactions (ie should remain pretty small).
641 /// Serialized to disk but should generally not be sent to Watchtowers.
642 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
644 // We store two holder commitment transactions to avoid any race conditions where we may update
645 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
646 // various monitors for one channel being out of sync, and us broadcasting a holder
647 // transaction for which we have deleted claim information on some watchtowers.
648 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
649 current_holder_commitment_tx: HolderSignedTx,
651 // Used just for ChannelManager to make sure it has the latest channel data during
653 current_counterparty_commitment_number: u64,
654 // Used just for ChannelManager to make sure it has the latest channel data during
656 current_holder_commitment_number: u64,
658 /// The set of payment hashes from inbound payments for which we know the preimage. Payment
659 /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
660 /// remote commitment transactions are automatically removed when commitment transactions are
662 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
664 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
665 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
666 // presumably user implementations thereof as well) where we update the in-memory channel
667 // object, then before the persistence finishes (as it's all under a read-lock), we return
668 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
669 // the pre-event state here, but have processed the event in the `ChannelManager`.
670 // Note that because the `event_lock` in `ChainMonitor` is only taken in
671 // block/transaction-connected events and *not* during block/transaction-disconnected events,
672 // we further MUST NOT generate events during block/transaction-disconnection.
673 pending_monitor_events: Vec<MonitorEvent>,
675 pending_events: Vec<Event>,
677 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
678 // which to take actions once they reach enough confirmations. Each entry includes the
679 // transaction's id and the height when the transaction was confirmed on chain.
680 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
682 // If we get serialized out and re-read, we need to make sure that the chain monitoring
683 // interface knows about the TXOs that we want to be notified of spends of. We could probably
684 // be smart and derive them from the above storage fields, but its much simpler and more
685 // Obviously Correct (tm) if we just keep track of them explicitly.
686 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
689 pub onchain_tx_handler: OnchainTxHandler<Signer>,
691 onchain_tx_handler: OnchainTxHandler<Signer>,
693 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
694 // channel has been force-closed. After this is set, no further holder commitment transaction
695 // updates may occur, and we panic!() if one is provided.
696 lockdown_from_offchain: bool,
698 // Set once we've signed a holder commitment transaction and handed it over to our
699 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
700 // may occur, and we fail any such monitor updates.
702 // In case of update rejection due to a locally already signed commitment transaction, we
703 // nevertheless store update content to track in case of concurrent broadcast by another
704 // remote monitor out-of-order with regards to the block view.
705 holder_tx_signed: bool,
707 // If a spend of the funding output is seen, we set this to true and reject any further
708 // updates. This prevents any further changes in the offchain state no matter the order
709 // of block connection between ChannelMonitors and the ChannelManager.
710 funding_spend_seen: bool,
712 funding_spend_confirmed: Option<Txid>,
713 /// The set of HTLCs which have been either claimed or failed on chain and have reached
714 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
715 /// spending CSV for revocable outputs).
716 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
718 // We simply modify best_block in Channel's block_connected so that serialization is
719 // consistent but hopefully the users' copy handles block_connected in a consistent way.
720 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
721 // their best_block from its state and not based on updated copies that didn't run through
722 // the full block_connected).
723 best_block: BestBlock,
725 /// The node_id of our counterparty
726 counterparty_node_id: Option<PublicKey>,
728 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
731 /// Transaction outputs to watch for on-chain spends.
732 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
734 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
735 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
737 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
738 fn eq(&self, other: &Self) -> bool {
739 let inner = self.inner.lock().unwrap();
740 let other = other.inner.lock().unwrap();
745 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
746 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
748 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
749 fn eq(&self, other: &Self) -> bool {
750 if self.latest_update_id != other.latest_update_id ||
751 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
752 self.destination_script != other.destination_script ||
753 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
754 self.counterparty_payment_script != other.counterparty_payment_script ||
755 self.channel_keys_id != other.channel_keys_id ||
756 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
757 self.funding_info != other.funding_info ||
758 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
759 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
760 self.counterparty_commitment_params != other.counterparty_commitment_params ||
761 self.funding_redeemscript != other.funding_redeemscript ||
762 self.channel_value_satoshis != other.channel_value_satoshis ||
763 self.their_cur_per_commitment_points != other.their_cur_per_commitment_points ||
764 self.on_holder_tx_csv != other.on_holder_tx_csv ||
765 self.commitment_secrets != other.commitment_secrets ||
766 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
767 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
768 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
769 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
770 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
771 self.current_holder_commitment_number != other.current_holder_commitment_number ||
772 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
773 self.payment_preimages != other.payment_preimages ||
774 self.pending_monitor_events != other.pending_monitor_events ||
775 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
776 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
777 self.outputs_to_watch != other.outputs_to_watch ||
778 self.lockdown_from_offchain != other.lockdown_from_offchain ||
779 self.holder_tx_signed != other.holder_tx_signed ||
780 self.funding_spend_seen != other.funding_spend_seen ||
781 self.funding_spend_confirmed != other.funding_spend_confirmed ||
782 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
791 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
792 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
793 self.inner.lock().unwrap().write(writer)
797 // These are also used for ChannelMonitorUpdate, above.
798 const SERIALIZATION_VERSION: u8 = 1;
799 const MIN_SERIALIZATION_VERSION: u8 = 1;
801 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
802 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
803 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
805 self.latest_update_id.write(writer)?;
807 // Set in initial Channel-object creation, so should always be set by now:
808 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
810 self.destination_script.write(writer)?;
811 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
812 writer.write_all(&[0; 1])?;
813 broadcasted_holder_revokable_script.0.write(writer)?;
814 broadcasted_holder_revokable_script.1.write(writer)?;
815 broadcasted_holder_revokable_script.2.write(writer)?;
817 writer.write_all(&[1; 1])?;
820 self.counterparty_payment_script.write(writer)?;
821 match &self.shutdown_script {
822 Some(script) => script.write(writer)?,
823 None => Script::new().write(writer)?,
826 self.channel_keys_id.write(writer)?;
827 self.holder_revocation_basepoint.write(writer)?;
828 writer.write_all(&self.funding_info.0.txid[..])?;
829 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
830 self.funding_info.1.write(writer)?;
831 self.current_counterparty_commitment_txid.write(writer)?;
832 self.prev_counterparty_commitment_txid.write(writer)?;
834 self.counterparty_commitment_params.write(writer)?;
835 self.funding_redeemscript.write(writer)?;
836 self.channel_value_satoshis.write(writer)?;
838 match self.their_cur_per_commitment_points {
839 Some((idx, pubkey, second_option)) => {
840 writer.write_all(&byte_utils::be48_to_array(idx))?;
841 writer.write_all(&pubkey.serialize())?;
842 match second_option {
843 Some(second_pubkey) => {
844 writer.write_all(&second_pubkey.serialize())?;
847 writer.write_all(&[0; 33])?;
852 writer.write_all(&byte_utils::be48_to_array(0))?;
856 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
858 self.commitment_secrets.write(writer)?;
860 macro_rules! serialize_htlc_in_commitment {
861 ($htlc_output: expr) => {
862 writer.write_all(&[$htlc_output.offered as u8; 1])?;
863 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
864 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
865 writer.write_all(&$htlc_output.payment_hash.0[..])?;
866 $htlc_output.transaction_output_index.write(writer)?;
870 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
871 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
872 writer.write_all(&txid[..])?;
873 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
874 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
875 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
876 || Some(**txid) == self.prev_counterparty_commitment_txid,
877 "HTLC Sources for all revoked commitment transactions should be none!");
878 serialize_htlc_in_commitment!(htlc_output);
879 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
883 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
884 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
885 writer.write_all(&txid[..])?;
886 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
889 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
890 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
891 writer.write_all(&payment_hash.0[..])?;
892 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
895 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
896 writer.write_all(&[1; 1])?;
897 prev_holder_tx.write(writer)?;
899 writer.write_all(&[0; 1])?;
902 self.current_holder_commitment_tx.write(writer)?;
904 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
905 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
907 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
908 for payment_preimage in self.payment_preimages.values() {
909 writer.write_all(&payment_preimage.0[..])?;
912 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
913 MonitorEvent::HTLCEvent(_) => true,
914 MonitorEvent::CommitmentTxConfirmed(_) => true,
916 }).count() as u64).to_be_bytes())?;
917 for event in self.pending_monitor_events.iter() {
919 MonitorEvent::HTLCEvent(upd) => {
923 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
924 _ => {}, // Covered in the TLV writes below
928 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
929 for event in self.pending_events.iter() {
930 event.write(writer)?;
933 self.best_block.block_hash().write(writer)?;
934 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
936 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
937 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
938 entry.write(writer)?;
941 (self.outputs_to_watch.len() as u64).write(writer)?;
942 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
944 (idx_scripts.len() as u64).write(writer)?;
945 for (idx, script) in idx_scripts.iter() {
947 script.write(writer)?;
950 self.onchain_tx_handler.write(writer)?;
952 self.lockdown_from_offchain.write(writer)?;
953 self.holder_tx_signed.write(writer)?;
955 write_tlv_fields!(writer, {
956 (1, self.funding_spend_confirmed, option),
957 (3, self.htlcs_resolved_on_chain, vec_type),
958 (5, self.pending_monitor_events, vec_type),
959 (7, self.funding_spend_seen, required),
960 (9, self.counterparty_node_id, option),
967 impl<Signer: Sign> ChannelMonitor<Signer> {
968 /// For lockorder enforcement purposes, we need to have a single site which constructs the
969 /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
970 /// PartialEq implementation) we may decide a lockorder violation has occurred.
971 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
972 ChannelMonitor { inner: Mutex::new(imp) }
975 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
976 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
977 channel_parameters: &ChannelTransactionParameters,
978 funding_redeemscript: Script, channel_value_satoshis: u64,
979 commitment_transaction_number_obscure_factor: u64,
980 initial_holder_commitment_tx: HolderCommitmentTransaction,
981 best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
983 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
984 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
985 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
987 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
988 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
989 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
990 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
992 let channel_keys_id = keys.channel_keys_id();
993 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
995 // block for Rust 1.34 compat
996 let (holder_commitment_tx, current_holder_commitment_number) = {
997 let trusted_tx = initial_holder_commitment_tx.trust();
998 let txid = trusted_tx.txid();
1000 let tx_keys = trusted_tx.keys();
1001 let holder_commitment_tx = HolderSignedTx {
1003 revocation_key: tx_keys.revocation_key,
1004 a_htlc_key: tx_keys.broadcaster_htlc_key,
1005 b_htlc_key: tx_keys.countersignatory_htlc_key,
1006 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1007 per_commitment_point: tx_keys.per_commitment_point,
1008 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1009 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1010 feerate_per_kw: trusted_tx.feerate_per_kw(),
1012 (holder_commitment_tx, trusted_tx.commitment_number())
1015 let onchain_tx_handler =
1016 OnchainTxHandler::new(destination_script.clone(), keys,
1017 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
1019 let mut outputs_to_watch = HashMap::new();
1020 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1022 Self::from_impl(ChannelMonitorImpl {
1023 latest_update_id: 0,
1024 commitment_transaction_number_obscure_factor,
1026 destination_script: destination_script.clone(),
1027 broadcasted_holder_revokable_script: None,
1028 counterparty_payment_script,
1032 holder_revocation_basepoint,
1034 current_counterparty_commitment_txid: None,
1035 prev_counterparty_commitment_txid: None,
1037 counterparty_commitment_params,
1038 funding_redeemscript,
1039 channel_value_satoshis,
1040 their_cur_per_commitment_points: None,
1042 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1044 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1045 counterparty_claimable_outpoints: HashMap::new(),
1046 counterparty_commitment_txn_on_chain: HashMap::new(),
1047 counterparty_hash_commitment_number: HashMap::new(),
1049 prev_holder_signed_commitment_tx: None,
1050 current_holder_commitment_tx: holder_commitment_tx,
1051 current_counterparty_commitment_number: 1 << 48,
1052 current_holder_commitment_number,
1054 payment_preimages: HashMap::new(),
1055 pending_monitor_events: Vec::new(),
1056 pending_events: Vec::new(),
1058 onchain_events_awaiting_threshold_conf: Vec::new(),
1063 lockdown_from_offchain: false,
1064 holder_tx_signed: false,
1065 funding_spend_seen: false,
1066 funding_spend_confirmed: None,
1067 htlcs_resolved_on_chain: Vec::new(),
1070 counterparty_node_id: Some(counterparty_node_id),
1077 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1078 self.inner.lock().unwrap().provide_secret(idx, secret)
1081 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1082 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1083 /// possibly future revocation/preimage information) to claim outputs where possible.
1084 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1085 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1088 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1089 commitment_number: u64,
1090 their_per_commitment_point: PublicKey,
1092 ) where L::Target: Logger {
1093 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1094 txid, htlc_outputs, commitment_number, their_per_commitment_point, logger)
1098 fn provide_latest_holder_commitment_tx(
1099 &self, holder_commitment_tx: HolderCommitmentTransaction,
1100 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1101 ) -> Result<(), ()> {
1102 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs).map_err(|_| ())
1105 /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1106 /// off-chain state with a new commitment transaction.
1107 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1109 payment_hash: &PaymentHash,
1110 payment_preimage: &PaymentPreimage,
1112 fee_estimator: &LowerBoundedFeeEstimator<F>,
1115 B::Target: BroadcasterInterface,
1116 F::Target: FeeEstimator,
1119 self.inner.lock().unwrap().provide_payment_preimage(
1120 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1123 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1128 B::Target: BroadcasterInterface,
1131 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1134 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1137 /// panics if the given update is not the next update by update_id.
1138 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1140 updates: &ChannelMonitorUpdate,
1146 B::Target: BroadcasterInterface,
1147 F::Target: FeeEstimator,
1150 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1153 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1155 pub fn get_latest_update_id(&self) -> u64 {
1156 self.inner.lock().unwrap().get_latest_update_id()
1159 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1160 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1161 self.inner.lock().unwrap().get_funding_txo().clone()
1164 /// Gets a list of txids, with their output scripts (in the order they appear in the
1165 /// transaction), which we must learn about spends of via block_connected().
1166 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1167 self.inner.lock().unwrap().get_outputs_to_watch()
1168 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1171 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1172 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1173 /// have been registered.
1174 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1175 let lock = self.inner.lock().unwrap();
1176 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1177 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1178 for (index, script_pubkey) in outputs.iter() {
1179 assert!(*index <= u16::max_value() as u32);
1180 filter.register_output(WatchedOutput {
1182 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1183 script_pubkey: script_pubkey.clone(),
1189 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1190 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1191 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1192 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1195 /// Gets the list of pending events which were generated by previous actions, clearing the list
1198 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1199 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1200 /// no internal locking in ChannelMonitors.
1201 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1202 self.inner.lock().unwrap().get_and_clear_pending_events()
1205 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1206 self.inner.lock().unwrap().get_min_seen_secret()
1209 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1210 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1213 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1214 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1217 pub(crate) fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1218 self.inner.lock().unwrap().counterparty_node_id
1221 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1222 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1223 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1224 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1225 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1226 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1227 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1228 /// out-of-band the other node operator to coordinate with him if option is available to you.
1229 /// In any-case, choice is up to the user.
1230 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1231 where L::Target: Logger {
1232 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1235 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1236 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1237 /// revoked commitment transaction.
1238 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1239 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1240 where L::Target: Logger {
1241 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1244 /// Processes transactions in a newly connected block, which may result in any of the following:
1245 /// - update the monitor's state against resolved HTLCs
1246 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1247 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1248 /// - detect settled outputs for later spending
1249 /// - schedule and bump any in-flight claims
1251 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1252 /// [`get_outputs_to_watch`].
1254 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1255 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1257 header: &BlockHeader,
1258 txdata: &TransactionData,
1263 ) -> Vec<TransactionOutputs>
1265 B::Target: BroadcasterInterface,
1266 F::Target: FeeEstimator,
1269 self.inner.lock().unwrap().block_connected(
1270 header, txdata, height, broadcaster, fee_estimator, logger)
1273 /// Determines if the disconnected block contained any transactions of interest and updates
1275 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1277 header: &BlockHeader,
1283 B::Target: BroadcasterInterface,
1284 F::Target: FeeEstimator,
1287 self.inner.lock().unwrap().block_disconnected(
1288 header, height, broadcaster, fee_estimator, logger)
1291 /// Processes transactions confirmed in a block with the given header and height, returning new
1292 /// outputs to watch. See [`block_connected`] for details.
1294 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1295 /// blocks. See [`chain::Confirm`] for calling expectations.
1297 /// [`block_connected`]: Self::block_connected
1298 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1300 header: &BlockHeader,
1301 txdata: &TransactionData,
1306 ) -> Vec<TransactionOutputs>
1308 B::Target: BroadcasterInterface,
1309 F::Target: FeeEstimator,
1312 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1313 self.inner.lock().unwrap().transactions_confirmed(
1314 header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
1317 /// Processes a transaction that was reorganized out of the chain.
1319 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1320 /// than blocks. See [`chain::Confirm`] for calling expectations.
1322 /// [`block_disconnected`]: Self::block_disconnected
1323 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1330 B::Target: BroadcasterInterface,
1331 F::Target: FeeEstimator,
1334 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1335 self.inner.lock().unwrap().transaction_unconfirmed(
1336 txid, broadcaster, &bounded_fee_estimator, logger);
1339 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1340 /// [`block_connected`] for details.
1342 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1343 /// blocks. See [`chain::Confirm`] for calling expectations.
1345 /// [`block_connected`]: Self::block_connected
1346 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1348 header: &BlockHeader,
1353 ) -> Vec<TransactionOutputs>
1355 B::Target: BroadcasterInterface,
1356 F::Target: FeeEstimator,
1359 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1360 self.inner.lock().unwrap().best_block_updated(
1361 header, height, broadcaster, &bounded_fee_estimator, logger)
1364 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1365 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1366 let inner = self.inner.lock().unwrap();
1367 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1369 .map(|entry| entry.txid)
1370 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1372 txids.sort_unstable();
1377 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1378 /// [`chain::Confirm`] interfaces.
1379 pub fn current_best_block(&self) -> BestBlock {
1380 self.inner.lock().unwrap().best_block.clone()
1383 /// Gets the balances in this channel which are either claimable by us if we were to
1384 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1387 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1388 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1389 /// balance, or until our counterparty has claimed the balance and accrued several
1390 /// confirmations on the claim transaction.
1392 /// Note that the balances available when you or your counterparty have broadcasted revoked
1393 /// state(s) may not be fully captured here.
1396 /// See [`Balance`] for additional details on the types of claimable balances which
1397 /// may be returned here and their meanings.
1398 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1399 let mut res = Vec::new();
1400 let us = self.inner.lock().unwrap();
1402 let mut confirmed_txid = us.funding_spend_confirmed;
1403 let mut pending_commitment_tx_conf_thresh = None;
1404 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1405 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1406 Some((event.txid, event.confirmation_threshold()))
1409 if let Some((txid, conf_thresh)) = funding_spend_pending {
1410 debug_assert!(us.funding_spend_confirmed.is_none(),
1411 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1412 confirmed_txid = Some(txid);
1413 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1416 macro_rules! walk_htlcs {
1417 ($holder_commitment: expr, $htlc_iter: expr) => {
1418 for htlc in $htlc_iter {
1419 if let Some(htlc_commitment_tx_output_idx) = htlc.transaction_output_index {
1420 if let Some(conf_thresh) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1421 if let OnchainEvent::MaturingOutput { descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) } = &event.event {
1422 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx { Some(event.confirmation_threshold()) } else { None }
1425 debug_assert!($holder_commitment);
1426 res.push(Balance::ClaimableAwaitingConfirmations {
1427 claimable_amount_satoshis: htlc.amount_msat / 1000,
1428 confirmation_height: conf_thresh,
1430 } else if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc_commitment_tx_output_idx) {
1431 // Funding transaction spends should be fully confirmed by the time any
1432 // HTLC transactions are resolved, unless we're talking about a holder
1433 // commitment tx, whose resolution is delayed until the CSV timeout is
1434 // reached, even though HTLCs may be resolved after only
1435 // ANTI_REORG_DELAY confirmations.
1436 debug_assert!($holder_commitment || us.funding_spend_confirmed.is_some());
1437 } else if htlc.offered == $holder_commitment {
1438 // If the payment was outbound, check if there's an HTLCUpdate
1439 // indicating we have spent this HTLC with a timeout, claiming it back
1440 // and awaiting confirmations on it.
1441 let htlc_update_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1442 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1443 if commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1444 Some(event.confirmation_threshold()) } else { None }
1447 if let Some(conf_thresh) = htlc_update_pending {
1448 res.push(Balance::ClaimableAwaitingConfirmations {
1449 claimable_amount_satoshis: htlc.amount_msat / 1000,
1450 confirmation_height: conf_thresh,
1453 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1454 claimable_amount_satoshis: htlc.amount_msat / 1000,
1455 claimable_height: htlc.cltv_expiry,
1458 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1459 // Otherwise (the payment was inbound), only expose it as claimable if
1460 // we know the preimage.
1461 // Note that if there is a pending claim, but it did not use the
1462 // preimage, we lost funds to our counterparty! We will then continue
1463 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1464 let htlc_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1465 if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } = event.event {
1466 if commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1467 Some((event.confirmation_threshold(), preimage.is_some()))
1471 if let Some((conf_thresh, true)) = htlc_spend_pending {
1472 res.push(Balance::ClaimableAwaitingConfirmations {
1473 claimable_amount_satoshis: htlc.amount_msat / 1000,
1474 confirmation_height: conf_thresh,
1477 res.push(Balance::ContentiousClaimable {
1478 claimable_amount_satoshis: htlc.amount_msat / 1000,
1479 timeout_height: htlc.cltv_expiry,
1488 if let Some(txid) = confirmed_txid {
1489 let mut found_commitment_tx = false;
1490 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1491 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1492 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1493 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1494 if let OnchainEvent::MaturingOutput {
1495 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1497 Some(descriptor.output.value)
1500 res.push(Balance::ClaimableAwaitingConfirmations {
1501 claimable_amount_satoshis: value,
1502 confirmation_height: conf_thresh,
1505 // If a counterparty commitment transaction is awaiting confirmation, we
1506 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1507 // confirmation with the same height or have never met our dust amount.
1510 found_commitment_tx = true;
1511 } else if txid == us.current_holder_commitment_tx.txid {
1512 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1513 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1514 res.push(Balance::ClaimableAwaitingConfirmations {
1515 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1516 confirmation_height: conf_thresh,
1519 found_commitment_tx = true;
1520 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1521 if txid == prev_commitment.txid {
1522 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1523 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1524 res.push(Balance::ClaimableAwaitingConfirmations {
1525 claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1526 confirmation_height: conf_thresh,
1529 found_commitment_tx = true;
1532 if !found_commitment_tx {
1533 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1534 // We blindly assume this is a cooperative close transaction here, and that
1535 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1536 // the amount we can claim as we'll punish a misbehaving counterparty.
1537 res.push(Balance::ClaimableAwaitingConfirmations {
1538 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1539 confirmation_height: conf_thresh,
1543 // TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1546 let mut claimable_inbound_htlc_value_sat = 0;
1547 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1548 if htlc.transaction_output_index.is_none() { continue; }
1550 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1551 claimable_amount_satoshis: htlc.amount_msat / 1000,
1552 claimable_height: htlc.cltv_expiry,
1554 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1555 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1558 res.push(Balance::ClaimableOnChannelClose {
1559 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1566 /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1567 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1568 pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1569 let mut res = HashMap::new();
1570 let us = self.inner.lock().unwrap();
1572 macro_rules! walk_htlcs {
1573 ($holder_commitment: expr, $htlc_iter: expr) => {
1574 for (htlc, source) in $htlc_iter {
1575 if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.commitment_tx_output_idx) == htlc.transaction_output_index) {
1576 // We should assert that funding_spend_confirmed is_some() here, but we
1577 // have some unit tests which violate HTLC transaction CSVs entirely and
1579 // TODO: Once tests all connect transactions at consensus-valid times, we
1580 // should assert here like we do in `get_claimable_balances`.
1581 } else if htlc.offered == $holder_commitment {
1582 // If the payment was outbound, check if there's an HTLCUpdate
1583 // indicating we have spent this HTLC with a timeout, claiming it back
1584 // and awaiting confirmations on it.
1585 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1586 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1587 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1588 // before considering it "no longer pending" - this matches when we
1589 // provide the ChannelManager an HTLC failure event.
1590 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
1591 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1592 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
1593 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1594 // immediately non-pending, matching when we provide ChannelManager
1596 Some(commitment_tx_output_idx) == htlc.transaction_output_index
1599 if !htlc_update_confd {
1600 res.insert(source.clone(), htlc.clone());
1607 // We're only concerned with the confirmation count of HTLC transactions, and don't
1608 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1609 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1610 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1611 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1612 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1617 if let Some(txid) = confirmed_txid {
1618 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1619 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1620 if let &Some(ref source) = b {
1621 Some((a, &**source))
1624 } else if txid == us.current_holder_commitment_tx.txid {
1625 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1626 if let Some(source) = c { Some((a, source)) } else { None }
1628 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1629 if txid == prev_commitment.txid {
1630 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1631 if let Some(source) = c { Some((a, source)) } else { None }
1636 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1637 // closed), just examine the available counterparty commitment transactions. See docs
1638 // on `fail_unbroadcast_htlcs`, below, for justification.
1639 macro_rules! walk_counterparty_commitment {
1641 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1642 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1643 if let &Some(ref source) = source_option {
1644 res.insert((**source).clone(), htlc.clone());
1650 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1651 walk_counterparty_commitment!(txid);
1653 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1654 walk_counterparty_commitment!(txid);
1661 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
1662 self.inner.lock().unwrap().payment_preimages.clone()
1666 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1667 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1668 /// after ANTI_REORG_DELAY blocks.
1670 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1671 /// are the commitment transactions which are generated by us. The off-chain state machine in
1672 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1673 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1674 /// included in a remote commitment transaction are failed back if they are not present in the
1675 /// broadcasted commitment transaction.
1677 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1678 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1679 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1680 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1681 macro_rules! fail_unbroadcast_htlcs {
1682 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr,
1683 $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1684 macro_rules! check_htlc_fails {
1685 ($txid: expr, $commitment_tx: expr) => {
1686 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1687 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1688 if let &Some(ref source) = source_option {
1689 // Check if the HTLC is present in the commitment transaction that was
1690 // broadcast, but not if it was below the dust limit, which we should
1691 // fail backwards immediately as there is no way for us to learn the
1692 // payment_preimage.
1693 // Note that if the dust limit were allowed to change between
1694 // commitment transactions we'd want to be check whether *any*
1695 // broadcastable commitment transaction has the HTLC in it, but it
1696 // cannot currently change after channel initialization, so we don't
1698 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1700 let mut matched_htlc = false;
1701 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1702 if broadcast_htlc.transaction_output_index.is_some() &&
1703 (Some(&**source) == *broadcast_source ||
1704 (broadcast_source.is_none() &&
1705 broadcast_htlc.payment_hash == htlc.payment_hash &&
1706 broadcast_htlc.amount_msat == htlc.amount_msat)) {
1707 matched_htlc = true;
1711 if matched_htlc { continue; }
1712 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1713 if entry.height != $commitment_tx_conf_height { return true; }
1715 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1716 *update_source != **source
1721 let entry = OnchainEventEntry {
1722 txid: $commitment_txid_confirmed,
1723 height: $commitment_tx_conf_height,
1724 event: OnchainEvent::HTLCUpdate {
1725 source: (**source).clone(),
1726 payment_hash: htlc.payment_hash.clone(),
1727 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
1728 commitment_tx_output_idx: None,
1731 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
1732 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type,
1733 $commitment_txid_confirmed, entry.confirmation_threshold());
1734 $self.onchain_events_awaiting_threshold_conf.push(entry);
1740 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1741 check_htlc_fails!(txid, "current");
1743 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1744 check_htlc_fails!(txid, "previous");
1749 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
1750 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
1751 // in-line tests later.
1754 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
1755 let mut ret = [opcodes::all::OP_NOP.into_u8(); 136];
1756 ret[131] = opcodes::all::OP_DROP.into_u8();
1757 ret[132] = opcodes::all::OP_DROP.into_u8();
1758 ret[133] = opcodes::all::OP_DROP.into_u8();
1759 ret[134] = opcodes::all::OP_DROP.into_u8();
1760 ret[135] = opcodes::OP_TRUE.into_u8();
1765 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
1766 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
1769 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1770 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1771 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1772 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1773 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1774 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1775 return Err("Previous secret did not match new one");
1778 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1779 // events for now-revoked/fulfilled HTLCs.
1780 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1781 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1786 if !self.payment_preimages.is_empty() {
1787 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1788 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1789 let min_idx = self.get_min_seen_secret();
1790 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1792 self.payment_preimages.retain(|&k, _| {
1793 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1794 if k == htlc.payment_hash {
1798 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1799 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1800 if k == htlc.payment_hash {
1805 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1812 counterparty_hash_commitment_number.remove(&k);
1821 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 {
1822 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1823 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1824 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1826 for &(ref htlc, _) in &htlc_outputs {
1827 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1830 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1831 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1832 self.current_counterparty_commitment_txid = Some(txid);
1833 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1834 self.current_counterparty_commitment_number = commitment_number;
1835 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1836 match self.their_cur_per_commitment_points {
1837 Some(old_points) => {
1838 if old_points.0 == commitment_number + 1 {
1839 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
1840 } else if old_points.0 == commitment_number + 2 {
1841 if let Some(old_second_point) = old_points.2 {
1842 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
1844 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1847 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1851 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
1854 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1855 for htlc in htlc_outputs {
1856 if htlc.0.transaction_output_index.is_some() {
1862 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1863 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1864 /// is important that any clones of this channel monitor (including remote clones) by kept
1865 /// up-to-date as our holder commitment transaction is updated.
1866 /// Panics if set_on_holder_tx_csv has never been called.
1867 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), &'static str> {
1868 // block for Rust 1.34 compat
1869 let mut new_holder_commitment_tx = {
1870 let trusted_tx = holder_commitment_tx.trust();
1871 let txid = trusted_tx.txid();
1872 let tx_keys = trusted_tx.keys();
1873 self.current_holder_commitment_number = trusted_tx.commitment_number();
1876 revocation_key: tx_keys.revocation_key,
1877 a_htlc_key: tx_keys.broadcaster_htlc_key,
1878 b_htlc_key: tx_keys.countersignatory_htlc_key,
1879 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1880 per_commitment_point: tx_keys.per_commitment_point,
1882 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1883 feerate_per_kw: trusted_tx.feerate_per_kw(),
1886 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1887 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1888 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1889 if self.holder_tx_signed {
1890 return Err("Latest holder commitment signed has already been signed, update is rejected");
1895 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1896 /// commitment_tx_infos which contain the payment hash have been revoked.
1897 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1898 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
1899 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
1900 where B::Target: BroadcasterInterface,
1901 F::Target: FeeEstimator,
1904 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1906 // If the channel is force closed, try to claim the output from this preimage.
1907 // First check if a counterparty commitment transaction has been broadcasted:
1908 macro_rules! claim_htlcs {
1909 ($commitment_number: expr, $txid: expr) => {
1910 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1911 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1914 if let Some(txid) = self.current_counterparty_commitment_txid {
1915 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1916 claim_htlcs!(*commitment_number, txid);
1920 if let Some(txid) = self.prev_counterparty_commitment_txid {
1921 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1922 claim_htlcs!(*commitment_number, txid);
1927 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1928 // claiming the HTLC output from each of the holder commitment transactions.
1929 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1930 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1931 // holder commitment transactions.
1932 if self.broadcasted_holder_revokable_script.is_some() {
1933 // Assume that the broadcasted commitment transaction confirmed in the current best
1934 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1936 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1937 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1938 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1939 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1940 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1945 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1946 where B::Target: BroadcasterInterface,
1949 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1950 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1951 broadcaster.broadcast_transaction(tx);
1953 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
1956 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
1957 where B::Target: BroadcasterInterface,
1958 F::Target: FeeEstimator,
1961 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} changes.",
1962 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
1963 // ChannelMonitor updates may be applied after force close if we receive a
1964 // preimage for a broadcasted commitment transaction HTLC output that we'd
1965 // like to claim on-chain. If this is the case, we no longer have guaranteed
1966 // access to the monitor's update ID, so we use a sentinel value instead.
1967 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1968 assert_eq!(updates.updates.len(), 1);
1969 match updates.updates[0] {
1970 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1972 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
1973 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
1976 } else if self.latest_update_id + 1 != updates.update_id {
1977 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1979 let mut ret = Ok(());
1980 for update in updates.updates.iter() {
1982 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1983 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1984 if self.lockdown_from_offchain { panic!(); }
1985 if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
1986 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
1987 log_error!(logger, " {}", e);
1991 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point } => {
1992 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1993 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
1995 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1996 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1997 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
1998 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2000 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2001 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2002 if let Err(e) = self.provide_secret(*idx, *secret) {
2003 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2004 log_error!(logger, " {}", e);
2008 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2009 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2010 self.lockdown_from_offchain = true;
2011 if *should_broadcast {
2012 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2013 } else if !self.holder_tx_signed {
2014 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");
2016 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2017 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2018 // shouldn't print the scary warning above.
2019 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2022 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2023 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2024 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2025 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2030 self.latest_update_id = updates.update_id;
2032 if ret.is_ok() && self.funding_spend_seen {
2033 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2038 pub fn get_latest_update_id(&self) -> u64 {
2039 self.latest_update_id
2042 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2046 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2047 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2048 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2049 // its trivial to do, double-check that here.
2050 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2051 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2053 &self.outputs_to_watch
2056 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2057 let mut ret = Vec::new();
2058 mem::swap(&mut ret, &mut self.pending_monitor_events);
2062 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
2063 let mut ret = Vec::new();
2064 mem::swap(&mut ret, &mut self.pending_events);
2068 /// Can only fail if idx is < get_min_seen_secret
2069 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2070 self.commitment_secrets.get_secret(idx)
2073 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2074 self.commitment_secrets.get_min_seen_secret()
2077 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2078 self.current_counterparty_commitment_number
2081 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2082 self.current_holder_commitment_number
2085 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2086 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2087 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2088 /// HTLC-Success/HTLC-Timeout transactions.
2089 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
2090 /// revoked counterparty commitment tx
2091 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
2092 // Most secp and related errors trying to create keys means we have no hope of constructing
2093 // a spend transaction...so we return no transactions to broadcast
2094 let mut claimable_outpoints = Vec::new();
2095 let mut watch_outputs = Vec::new();
2097 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2098 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2100 macro_rules! ignore_error {
2101 ( $thing : expr ) => {
2104 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
2109 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
2110 if commitment_number >= self.get_min_seen_secret() {
2111 let secret = self.get_secret(commitment_number).unwrap();
2112 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2113 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2114 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2115 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));
2117 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2118 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2120 // First, process non-htlc outputs (to_holder & to_counterparty)
2121 for (idx, outp) in tx.output.iter().enumerate() {
2122 if outp.script_pubkey == revokeable_p2wsh {
2123 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);
2124 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);
2125 claimable_outpoints.push(justice_package);
2129 // Then, try to find revoked htlc outputs
2130 if let Some(ref per_commitment_data) = per_commitment_option {
2131 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2132 if let Some(transaction_output_index) = htlc.transaction_output_index {
2133 if transaction_output_index as usize >= tx.output.len() ||
2134 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2135 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
2137 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());
2138 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2139 claimable_outpoints.push(justice_package);
2144 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2145 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2146 // We're definitely a counterparty commitment transaction!
2147 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2148 for (idx, outp) in tx.output.iter().enumerate() {
2149 watch_outputs.push((idx as u32, outp.clone()));
2151 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2153 if let Some(per_commitment_data) = per_commitment_option {
2154 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, height,
2155 per_commitment_data.iter().map(|(htlc, htlc_source)|
2156 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2159 debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2160 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, height,
2161 [].iter().map(|reference| *reference), logger);
2164 } else if let Some(per_commitment_data) = per_commitment_option {
2165 // While this isn't useful yet, there is a potential race where if a counterparty
2166 // revokes a state at the same time as the commitment transaction for that state is
2167 // confirmed, and the watchtower receives the block before the user, the user could
2168 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2169 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2170 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2172 for (idx, outp) in tx.output.iter().enumerate() {
2173 watch_outputs.push((idx as u32, outp.clone()));
2175 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2177 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2178 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, height,
2179 per_commitment_data.iter().map(|(htlc, htlc_source)|
2180 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2183 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
2184 for req in htlc_claim_reqs {
2185 claimable_outpoints.push(req);
2189 (claimable_outpoints, (commitment_txid, watch_outputs))
2192 fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
2193 let mut claimable_outpoints = Vec::new();
2194 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
2195 if let Some(per_commitment_points) = self.their_cur_per_commitment_points {
2196 let per_commitment_point_option =
2197 // If the counterparty commitment tx is the latest valid state, use their latest
2198 // per-commitment point
2199 if per_commitment_points.0 == commitment_number { Some(&per_commitment_points.1) }
2200 else if let Some(point) = per_commitment_points.2.as_ref() {
2201 // If counterparty commitment tx is the state previous to the latest valid state, use
2202 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2203 // them to temporarily have two valid commitment txns from our viewpoint)
2204 if per_commitment_points.0 == commitment_number + 1 { Some(point) } else { None }
2206 if let Some(per_commitment_point) = per_commitment_point_option {
2207 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2208 if let Some(transaction_output_index) = htlc.transaction_output_index {
2209 if let Some(transaction) = tx {
2210 if transaction_output_index as usize >= transaction.output.len() ||
2211 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2212 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
2215 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2216 if preimage.is_some() || !htlc.offered {
2217 let counterparty_htlc_outp = if htlc.offered {
2218 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2219 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2220 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2221 self.counterparty_commitment_params.counterparty_htlc_base_key,
2222 preimage.unwrap(), htlc.clone()))
2224 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2225 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2226 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2227 self.counterparty_commitment_params.counterparty_htlc_base_key,
2230 let aggregation = if !htlc.offered { false } else { true };
2231 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2232 claimable_outpoints.push(counterparty_package);
2242 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2243 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 {
2244 let htlc_txid = tx.txid();
2245 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2246 return (Vec::new(), None)
2249 macro_rules! ignore_error {
2250 ( $thing : expr ) => {
2253 Err(_) => return (Vec::new(), None)
2258 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2259 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2260 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2262 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2263 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);
2264 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);
2265 let claimable_outpoints = vec!(justice_package);
2266 let outputs = vec![(0, tx.output[0].clone())];
2267 (claimable_outpoints, Some((htlc_txid, outputs)))
2270 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2271 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2272 // script so we can detect whether a holder transaction has been seen on-chain.
2273 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2274 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2276 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2277 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2279 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2280 if let Some(transaction_output_index) = htlc.transaction_output_index {
2281 let htlc_output = if htlc.offered {
2282 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2284 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2287 // We can't build an HTLC-Success transaction without the preimage
2290 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2292 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2293 claim_requests.push(htlc_package);
2297 (claim_requests, broadcasted_holder_revokable_script)
2300 // Returns holder HTLC outputs to watch and react to in case of spending.
2301 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2302 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2303 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2304 if let Some(transaction_output_index) = htlc.transaction_output_index {
2305 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2311 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2312 /// revoked using data in holder_claimable_outpoints.
2313 /// Should not be used if check_spend_revoked_transaction succeeds.
2314 /// Returns None unless the transaction is definitely one of our commitment transactions.
2315 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2316 let commitment_txid = tx.txid();
2317 let mut claim_requests = Vec::new();
2318 let mut watch_outputs = Vec::new();
2320 macro_rules! append_onchain_update {
2321 ($updates: expr, $to_watch: expr) => {
2322 claim_requests = $updates.0;
2323 self.broadcasted_holder_revokable_script = $updates.1;
2324 watch_outputs.append(&mut $to_watch);
2328 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2329 let mut is_holder_tx = false;
2331 if self.current_holder_commitment_tx.txid == commitment_txid {
2332 is_holder_tx = true;
2333 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2334 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2335 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2336 append_onchain_update!(res, to_watch);
2337 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, height,
2338 self.current_holder_commitment_tx.htlc_outputs.iter()
2339 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2340 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2341 if holder_tx.txid == commitment_txid {
2342 is_holder_tx = true;
2343 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2344 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2345 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2346 append_onchain_update!(res, to_watch);
2347 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, height,
2348 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2354 Some((claim_requests, (commitment_txid, watch_outputs)))
2360 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2361 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2362 self.holder_tx_signed = true;
2363 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2364 let txid = commitment_tx.txid();
2365 let mut holder_transactions = vec![commitment_tx];
2366 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2367 if let Some(vout) = htlc.0.transaction_output_index {
2368 let preimage = if !htlc.0.offered {
2369 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2370 // We can't build an HTLC-Success transaction without the preimage
2373 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2374 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2375 // current locktime requirements on-chain. We will broadcast them in
2376 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2377 // Note that we add + 1 as transactions are broadcastable when they can be
2378 // confirmed in the next block.
2381 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2382 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2383 holder_transactions.push(htlc_tx);
2387 // 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.
2388 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2392 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2393 /// Note that this includes possibly-locktimed-in-the-future transactions!
2394 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2395 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2396 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2397 let txid = commitment_tx.txid();
2398 let mut holder_transactions = vec![commitment_tx];
2399 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2400 if let Some(vout) = htlc.0.transaction_output_index {
2401 let preimage = if !htlc.0.offered {
2402 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2403 // We can't build an HTLC-Success transaction without the preimage
2407 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2408 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2409 holder_transactions.push(htlc_tx);
2416 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>
2417 where B::Target: BroadcasterInterface,
2418 F::Target: FeeEstimator,
2421 let block_hash = header.block_hash();
2422 self.best_block = BestBlock::new(block_hash, height);
2424 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2425 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2428 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2430 header: &BlockHeader,
2433 fee_estimator: &LowerBoundedFeeEstimator<F>,
2435 ) -> Vec<TransactionOutputs>
2437 B::Target: BroadcasterInterface,
2438 F::Target: FeeEstimator,
2441 let block_hash = header.block_hash();
2443 if height > self.best_block.height() {
2444 self.best_block = BestBlock::new(block_hash, height);
2445 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2446 } else if block_hash != self.best_block.block_hash() {
2447 self.best_block = BestBlock::new(block_hash, height);
2448 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2449 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2451 } else { Vec::new() }
2454 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2456 header: &BlockHeader,
2457 txdata: &TransactionData,
2460 fee_estimator: &LowerBoundedFeeEstimator<F>,
2462 ) -> Vec<TransactionOutputs>
2464 B::Target: BroadcasterInterface,
2465 F::Target: FeeEstimator,
2468 let txn_matched = self.filter_block(txdata);
2469 for tx in &txn_matched {
2470 let mut output_val = 0;
2471 for out in tx.output.iter() {
2472 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2473 output_val += out.value;
2474 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2478 let block_hash = header.block_hash();
2480 let mut watch_outputs = Vec::new();
2481 let mut claimable_outpoints = Vec::new();
2482 for tx in &txn_matched {
2483 if tx.input.len() == 1 {
2484 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2485 // commitment transactions and HTLC transactions will all only ever have one input,
2486 // which is an easy way to filter out any potential non-matching txn for lazy
2488 let prevout = &tx.input[0].previous_output;
2489 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2490 let mut balance_spendable_csv = None;
2491 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2492 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2493 self.funding_spend_seen = true;
2494 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2495 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2496 if !new_outputs.1.is_empty() {
2497 watch_outputs.push(new_outputs);
2499 claimable_outpoints.append(&mut new_outpoints);
2500 if new_outpoints.is_empty() {
2501 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2502 if !new_outputs.1.is_empty() {
2503 watch_outputs.push(new_outputs);
2505 claimable_outpoints.append(&mut new_outpoints);
2506 balance_spendable_csv = Some(self.on_holder_tx_csv);
2510 let txid = tx.txid();
2511 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2514 event: OnchainEvent::FundingSpendConfirmation {
2515 on_local_output_csv: balance_spendable_csv,
2519 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2520 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2521 claimable_outpoints.append(&mut new_outpoints);
2522 if let Some(new_outputs) = new_outputs_option {
2523 watch_outputs.push(new_outputs);
2528 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2529 // can also be resolved in a few other ways which can have more than one output. Thus,
2530 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2531 self.is_resolving_htlc_output(&tx, height, &logger);
2533 self.is_paying_spendable_output(&tx, height, &logger);
2536 if height > self.best_block.height() {
2537 self.best_block = BestBlock::new(block_hash, height);
2540 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2543 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2544 /// `self.best_block` before calling if a new best blockchain tip is available. More
2545 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2546 /// complexity especially in `OnchainTx::update_claims_view`.
2548 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2549 /// confirmed at, even if it is not the current best height.
2550 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2553 txn_matched: Vec<&Transaction>,
2554 mut watch_outputs: Vec<TransactionOutputs>,
2555 mut claimable_outpoints: Vec<PackageTemplate>,
2557 fee_estimator: &LowerBoundedFeeEstimator<F>,
2559 ) -> Vec<TransactionOutputs>
2561 B::Target: BroadcasterInterface,
2562 F::Target: FeeEstimator,
2565 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2566 debug_assert!(self.best_block.height() >= conf_height);
2568 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2569 if should_broadcast {
2570 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2571 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());
2572 claimable_outpoints.push(commitment_package);
2573 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2574 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2575 self.holder_tx_signed = true;
2576 // Because we're broadcasting a commitment transaction, we should construct the package
2577 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2578 // "not yet confirmed" things as discardable, so we cannot do that here.
2579 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2580 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2581 if !new_outputs.is_empty() {
2582 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2584 claimable_outpoints.append(&mut new_outpoints);
2587 // Find which on-chain events have reached their confirmation threshold.
2588 let onchain_events_awaiting_threshold_conf =
2589 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2590 let mut onchain_events_reaching_threshold_conf = Vec::new();
2591 for entry in onchain_events_awaiting_threshold_conf {
2592 if entry.has_reached_confirmation_threshold(&self.best_block) {
2593 onchain_events_reaching_threshold_conf.push(entry);
2595 self.onchain_events_awaiting_threshold_conf.push(entry);
2599 // Used to check for duplicate HTLC resolutions.
2600 #[cfg(debug_assertions)]
2601 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2603 .filter_map(|entry| match &entry.event {
2604 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2608 #[cfg(debug_assertions)]
2609 let mut matured_htlcs = Vec::new();
2611 // Produce actionable events from on-chain events having reached their threshold.
2612 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2614 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2615 // Check for duplicate HTLC resolutions.
2616 #[cfg(debug_assertions)]
2619 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2620 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2621 call either transaction_unconfirmed for the conflicting transaction \
2622 or block_disconnected for a block containing it.");
2624 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2625 "A matured HTLC transaction conflicts with a maturing one; failed to \
2626 call either transaction_unconfirmed for the conflicting transaction \
2627 or block_disconnected for a block containing it.");
2628 matured_htlcs.push(source.clone());
2631 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2632 log_bytes!(payment_hash.0), entry.txid);
2633 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2635 payment_preimage: None,
2636 source: source.clone(),
2637 htlc_value_satoshis,
2639 if let Some(idx) = commitment_tx_output_idx {
2640 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx: idx, payment_preimage: None });
2643 OnchainEvent::MaturingOutput { descriptor } => {
2644 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2645 self.pending_events.push(Event::SpendableOutputs {
2646 outputs: vec![descriptor]
2649 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2650 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { commitment_tx_output_idx, payment_preimage: preimage });
2652 OnchainEvent::FundingSpendConfirmation { .. } => {
2653 self.funding_spend_confirmed = Some(entry.txid);
2658 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2660 // Determine new outputs to watch by comparing against previously known outputs to watch,
2661 // updating the latter in the process.
2662 watch_outputs.retain(|&(ref txid, ref txouts)| {
2663 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2664 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2668 // If we see a transaction for which we registered outputs previously,
2669 // make sure the registered scriptpubkey at the expected index match
2670 // the actual transaction output one. We failed this case before #653.
2671 for tx in &txn_matched {
2672 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2673 for idx_and_script in outputs.iter() {
2674 assert!((idx_and_script.0 as usize) < tx.output.len());
2675 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2683 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2684 where B::Target: BroadcasterInterface,
2685 F::Target: FeeEstimator,
2688 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2691 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2692 //- maturing spendable output has transaction paying us has been disconnected
2693 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2695 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2696 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2698 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2701 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2705 fee_estimator: &LowerBoundedFeeEstimator<F>,
2708 B::Target: BroadcasterInterface,
2709 F::Target: FeeEstimator,
2712 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2713 log_info!(logger, "Removing onchain event with txid {}", txid);
2716 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2719 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2720 /// transactions thereof.
2721 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2722 let mut matched_txn = HashSet::new();
2723 txdata.iter().filter(|&&(_, tx)| {
2724 let mut matches = self.spends_watched_output(tx);
2725 for input in tx.input.iter() {
2726 if matches { break; }
2727 if matched_txn.contains(&input.previous_output.txid) {
2732 matched_txn.insert(tx.txid());
2735 }).map(|(_, tx)| *tx).collect()
2738 /// Checks if a given transaction spends any watched outputs.
2739 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2740 for input in tx.input.iter() {
2741 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2742 for (idx, _script_pubkey) in outputs.iter() {
2743 if *idx == input.previous_output.vout {
2746 // If the expected script is a known type, check that the witness
2747 // appears to be spending the correct type (ie that the match would
2748 // actually succeed in BIP 158/159-style filters).
2749 if _script_pubkey.is_v0_p2wsh() {
2750 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
2751 // In at least one test we use a deliberately bogus witness
2752 // script which hit an old panic. Thus, we check for that here
2753 // and avoid the assert if its the expected bogus script.
2757 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2758 } else if _script_pubkey.is_v0_p2wpkh() {
2759 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2760 } else { panic!(); }
2771 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2772 // We need to consider all HTLCs which are:
2773 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2774 // transactions and we'd end up in a race, or
2775 // * are in our latest holder commitment transaction, as this is the thing we will
2776 // broadcast if we go on-chain.
2777 // Note that we consider HTLCs which were below dust threshold here - while they don't
2778 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2779 // to the source, and if we don't fail the channel we will have to ensure that the next
2780 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2781 // easier to just fail the channel as this case should be rare enough anyway.
2782 let height = self.best_block.height();
2783 macro_rules! scan_commitment {
2784 ($htlcs: expr, $holder_tx: expr) => {
2785 for ref htlc in $htlcs {
2786 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2787 // chain with enough room to claim the HTLC without our counterparty being able to
2788 // time out the HTLC first.
2789 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2790 // concern is being able to claim the corresponding inbound HTLC (on another
2791 // channel) before it expires. In fact, we don't even really care if our
2792 // counterparty here claims such an outbound HTLC after it expired as long as we
2793 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2794 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2795 // we give ourselves a few blocks of headroom after expiration before going
2796 // on-chain for an expired HTLC.
2797 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2798 // from us until we've reached the point where we go on-chain with the
2799 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2800 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2801 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2802 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2803 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2804 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2805 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2806 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2807 // The final, above, condition is checked for statically in channelmanager
2808 // with CHECK_CLTV_EXPIRY_SANITY_2.
2809 let htlc_outbound = $holder_tx == htlc.offered;
2810 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2811 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2812 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2819 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2821 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2822 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2823 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2826 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2827 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2828 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2835 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2836 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2837 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2838 'outer_loop: for input in &tx.input {
2839 let mut payment_data = None;
2840 let witness_items = input.witness.len();
2841 let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
2842 let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
2843 let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
2844 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
2845 let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
2846 && input.witness.second_to_last().unwrap().len() == 32;
2847 #[cfg(not(fuzzing))]
2848 let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2849 let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
2850 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
2852 #[cfg(not(fuzzing))]
2853 let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
2855 let mut payment_preimage = PaymentPreimage([0; 32]);
2856 if accepted_preimage_claim {
2857 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2858 } else if offered_preimage_claim {
2859 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
2862 macro_rules! log_claim {
2863 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2864 let outbound_htlc = $holder_tx == $htlc.offered;
2865 // HTLCs must either be claimed by a matching script type or through the
2867 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2868 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2869 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2870 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2871 // Further, only exactly one of the possible spend paths should have been
2872 // matched by any HTLC spend:
2873 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2874 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2875 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2876 revocation_sig_claim as u8, 1);
2877 if ($holder_tx && revocation_sig_claim) ||
2878 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2879 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2880 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2881 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2882 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2884 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2885 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2886 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2887 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2892 macro_rules! check_htlc_valid_counterparty {
2893 ($counterparty_txid: expr, $htlc_output: expr) => {
2894 if let Some(txid) = $counterparty_txid {
2895 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2896 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2897 if let &Some(ref source) = pending_source {
2898 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2899 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2908 macro_rules! scan_commitment {
2909 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2910 for (ref htlc_output, source_option) in $htlcs {
2911 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2912 if let Some(ref source) = source_option {
2913 log_claim!($tx_info, $holder_tx, htlc_output, true);
2914 // We have a resolution of an HTLC either from one of our latest
2915 // holder commitment transactions or an unrevoked counterparty commitment
2916 // transaction. This implies we either learned a preimage, the HTLC
2917 // has timed out, or we screwed up. In any case, we should now
2918 // resolve the source HTLC with the original sender.
2919 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2920 } else if !$holder_tx {
2921 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2922 if payment_data.is_none() {
2923 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2926 if payment_data.is_none() {
2927 log_claim!($tx_info, $holder_tx, htlc_output, false);
2928 let outbound_htlc = $holder_tx == htlc_output.offered;
2929 if !outbound_htlc || revocation_sig_claim {
2930 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2931 txid: tx.txid(), height,
2932 event: OnchainEvent::HTLCSpendConfirmation {
2933 commitment_tx_output_idx: input.previous_output.vout,
2934 preimage: if accepted_preimage_claim || offered_preimage_claim {
2935 Some(payment_preimage) } else { None },
2936 // If this is a payment to us (!outbound_htlc, above),
2937 // wait for the CSV delay before dropping the HTLC from
2938 // claimable balance if the claim was an HTLC-Success
2940 on_to_local_output_csv: if accepted_preimage_claim {
2941 Some(self.on_holder_tx_csv) } else { None },
2945 // Outbound claims should always have payment_data, unless
2946 // we've already failed the HTLC as the commitment transaction
2947 // which was broadcasted was revoked. In that case, we should
2948 // spend the HTLC output here immediately, and expose that fact
2949 // as a Balance, something which we do not yet do.
2950 // TODO: Track the above as claimable!
2952 continue 'outer_loop;
2959 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2960 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2961 "our latest holder commitment tx", true);
2963 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2964 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2965 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2966 "our previous holder commitment tx", true);
2969 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2970 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2971 "counterparty commitment tx", false);
2974 // Check that scan_commitment, above, decided there is some source worth relaying an
2975 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2976 if let Some((source, payment_hash, amount_msat)) = payment_data {
2977 if accepted_preimage_claim {
2978 if !self.pending_monitor_events.iter().any(
2979 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2980 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2983 event: OnchainEvent::HTLCSpendConfirmation {
2984 commitment_tx_output_idx: input.previous_output.vout,
2985 preimage: Some(payment_preimage),
2986 on_to_local_output_csv: None,
2989 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2991 payment_preimage: Some(payment_preimage),
2993 htlc_value_satoshis: Some(amount_msat / 1000),
2996 } else if offered_preimage_claim {
2997 if !self.pending_monitor_events.iter().any(
2998 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2999 upd.source == source
3001 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3004 event: OnchainEvent::HTLCSpendConfirmation {
3005 commitment_tx_output_idx: input.previous_output.vout,
3006 preimage: Some(payment_preimage),
3007 on_to_local_output_csv: None,
3010 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3012 payment_preimage: Some(payment_preimage),
3014 htlc_value_satoshis: Some(amount_msat / 1000),
3018 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3019 if entry.height != height { return true; }
3021 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3022 *htlc_source != source
3027 let entry = OnchainEventEntry {
3030 event: OnchainEvent::HTLCUpdate {
3031 source, payment_hash,
3032 htlc_value_satoshis: Some(amount_msat / 1000),
3033 commitment_tx_output_idx: Some(input.previous_output.vout),
3036 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());
3037 self.onchain_events_awaiting_threshold_conf.push(entry);
3043 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3044 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3045 let mut spendable_output = None;
3046 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3047 if i > ::core::u16::MAX as usize {
3048 // While it is possible that an output exists on chain which is greater than the
3049 // 2^16th output in a given transaction, this is only possible if the output is not
3050 // in a lightning transaction and was instead placed there by some third party who
3051 // wishes to give us money for no reason.
3052 // Namely, any lightning transactions which we pre-sign will never have anywhere
3053 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3054 // scripts are not longer than one byte in length and because they are inherently
3055 // non-standard due to their size.
3056 // Thus, it is completely safe to ignore such outputs, and while it may result in
3057 // us ignoring non-lightning fund to us, that is only possible if someone fills
3058 // nearly a full block with garbage just to hit this case.
3061 if outp.script_pubkey == self.destination_script {
3062 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3063 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3064 output: outp.clone(),
3068 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3069 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3070 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3071 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3072 per_commitment_point: broadcasted_holder_revokable_script.1,
3073 to_self_delay: self.on_holder_tx_csv,
3074 output: outp.clone(),
3075 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3076 channel_keys_id: self.channel_keys_id,
3077 channel_value_satoshis: self.channel_value_satoshis,
3082 if self.counterparty_payment_script == outp.script_pubkey {
3083 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3084 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3085 output: outp.clone(),
3086 channel_keys_id: self.channel_keys_id,
3087 channel_value_satoshis: self.channel_value_satoshis,
3091 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3092 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3093 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3094 output: outp.clone(),
3099 if let Some(spendable_output) = spendable_output {
3100 let entry = OnchainEventEntry {
3103 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3105 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3106 self.onchain_events_awaiting_threshold_conf.push(entry);
3111 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3113 T::Target: BroadcasterInterface,
3114 F::Target: FeeEstimator,
3117 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3118 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3121 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3122 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3126 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3128 T::Target: BroadcasterInterface,
3129 F::Target: FeeEstimator,
3132 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3133 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3136 fn transaction_unconfirmed(&self, txid: &Txid) {
3137 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3140 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3141 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3144 fn get_relevant_txids(&self) -> Vec<Txid> {
3145 self.0.get_relevant_txids()
3149 const MAX_ALLOC_SIZE: usize = 64*1024;
3151 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3152 for (BlockHash, ChannelMonitor<Signer>) {
3153 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3154 macro_rules! unwrap_obj {
3158 Err(_) => return Err(DecodeError::InvalidValue),
3163 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3165 let latest_update_id: u64 = Readable::read(reader)?;
3166 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3168 let destination_script = Readable::read(reader)?;
3169 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3171 let revokable_address = Readable::read(reader)?;
3172 let per_commitment_point = Readable::read(reader)?;
3173 let revokable_script = Readable::read(reader)?;
3174 Some((revokable_address, per_commitment_point, revokable_script))
3177 _ => return Err(DecodeError::InvalidValue),
3179 let counterparty_payment_script = Readable::read(reader)?;
3180 let shutdown_script = {
3181 let script = <Script as Readable>::read(reader)?;
3182 if script.is_empty() { None } else { Some(script) }
3185 let channel_keys_id = Readable::read(reader)?;
3186 let holder_revocation_basepoint = Readable::read(reader)?;
3187 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3188 // barely-init'd ChannelMonitors that we can't do anything with.
3189 let outpoint = OutPoint {
3190 txid: Readable::read(reader)?,
3191 index: Readable::read(reader)?,
3193 let funding_info = (outpoint, Readable::read(reader)?);
3194 let current_counterparty_commitment_txid = Readable::read(reader)?;
3195 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3197 let counterparty_commitment_params = Readable::read(reader)?;
3198 let funding_redeemscript = Readable::read(reader)?;
3199 let channel_value_satoshis = Readable::read(reader)?;
3201 let their_cur_per_commitment_points = {
3202 let first_idx = <U48 as Readable>::read(reader)?.0;
3206 let first_point = Readable::read(reader)?;
3207 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3208 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3209 Some((first_idx, first_point, None))
3211 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3216 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3218 let commitment_secrets = Readable::read(reader)?;
3220 macro_rules! read_htlc_in_commitment {
3223 let offered: bool = Readable::read(reader)?;
3224 let amount_msat: u64 = Readable::read(reader)?;
3225 let cltv_expiry: u32 = Readable::read(reader)?;
3226 let payment_hash: PaymentHash = Readable::read(reader)?;
3227 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3229 HTLCOutputInCommitment {
3230 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3236 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3237 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3238 for _ in 0..counterparty_claimable_outpoints_len {
3239 let txid: Txid = Readable::read(reader)?;
3240 let htlcs_count: u64 = Readable::read(reader)?;
3241 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3242 for _ in 0..htlcs_count {
3243 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3245 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3246 return Err(DecodeError::InvalidValue);
3250 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3251 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3252 for _ in 0..counterparty_commitment_txn_on_chain_len {
3253 let txid: Txid = Readable::read(reader)?;
3254 let commitment_number = <U48 as Readable>::read(reader)?.0;
3255 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3256 return Err(DecodeError::InvalidValue);
3260 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3261 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3262 for _ in 0..counterparty_hash_commitment_number_len {
3263 let payment_hash: PaymentHash = Readable::read(reader)?;
3264 let commitment_number = <U48 as Readable>::read(reader)?.0;
3265 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3266 return Err(DecodeError::InvalidValue);
3270 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3271 match <u8 as Readable>::read(reader)? {
3274 Some(Readable::read(reader)?)
3276 _ => return Err(DecodeError::InvalidValue),
3278 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3280 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3281 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3283 let payment_preimages_len: u64 = Readable::read(reader)?;
3284 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3285 for _ in 0..payment_preimages_len {
3286 let preimage: PaymentPreimage = Readable::read(reader)?;
3287 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3288 if let Some(_) = payment_preimages.insert(hash, preimage) {
3289 return Err(DecodeError::InvalidValue);
3293 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3294 let mut pending_monitor_events = Some(
3295 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3296 for _ in 0..pending_monitor_events_len {
3297 let ev = match <u8 as Readable>::read(reader)? {
3298 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3299 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3300 _ => return Err(DecodeError::InvalidValue)
3302 pending_monitor_events.as_mut().unwrap().push(ev);
3305 let pending_events_len: u64 = Readable::read(reader)?;
3306 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3307 for _ in 0..pending_events_len {
3308 if let Some(event) = MaybeReadable::read(reader)? {
3309 pending_events.push(event);
3313 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3315 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3316 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3317 for _ in 0..waiting_threshold_conf_len {
3318 if let Some(val) = MaybeReadable::read(reader)? {
3319 onchain_events_awaiting_threshold_conf.push(val);
3323 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3324 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>>())));
3325 for _ in 0..outputs_to_watch_len {
3326 let txid = Readable::read(reader)?;
3327 let outputs_len: u64 = Readable::read(reader)?;
3328 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3329 for _ in 0..outputs_len {
3330 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3332 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3333 return Err(DecodeError::InvalidValue);
3336 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3338 let lockdown_from_offchain = Readable::read(reader)?;
3339 let holder_tx_signed = Readable::read(reader)?;
3341 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3342 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3343 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3344 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3345 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3346 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3347 return Err(DecodeError::InvalidValue);
3351 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3352 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3353 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3354 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3355 return Err(DecodeError::InvalidValue);
3358 let mut funding_spend_confirmed = None;
3359 let mut htlcs_resolved_on_chain = Some(Vec::new());
3360 let mut funding_spend_seen = Some(false);
3361 let mut counterparty_node_id = None;
3362 read_tlv_fields!(reader, {
3363 (1, funding_spend_confirmed, option),
3364 (3, htlcs_resolved_on_chain, vec_type),
3365 (5, pending_monitor_events, vec_type),
3366 (7, funding_spend_seen, option),
3367 (9, counterparty_node_id, option),
3370 let mut secp_ctx = Secp256k1::new();
3371 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3373 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3375 commitment_transaction_number_obscure_factor,
3378 broadcasted_holder_revokable_script,
3379 counterparty_payment_script,
3383 holder_revocation_basepoint,
3385 current_counterparty_commitment_txid,
3386 prev_counterparty_commitment_txid,
3388 counterparty_commitment_params,
3389 funding_redeemscript,
3390 channel_value_satoshis,
3391 their_cur_per_commitment_points,
3396 counterparty_claimable_outpoints,
3397 counterparty_commitment_txn_on_chain,
3398 counterparty_hash_commitment_number,
3400 prev_holder_signed_commitment_tx,
3401 current_holder_commitment_tx,
3402 current_counterparty_commitment_number,
3403 current_holder_commitment_number,
3406 pending_monitor_events: pending_monitor_events.unwrap(),
3409 onchain_events_awaiting_threshold_conf,
3414 lockdown_from_offchain,
3416 funding_spend_seen: funding_spend_seen.unwrap(),
3417 funding_spend_confirmed,
3418 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3421 counterparty_node_id,
3430 use bitcoin::blockdata::block::BlockHeader;
3431 use bitcoin::blockdata::script::{Script, Builder};
3432 use bitcoin::blockdata::opcodes;
3433 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3434 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3435 use bitcoin::util::sighash;
3436 use bitcoin::hashes::Hash;
3437 use bitcoin::hashes::sha256::Hash as Sha256;
3438 use bitcoin::hashes::hex::FromHex;
3439 use bitcoin::hash_types::{BlockHash, Txid};
3440 use bitcoin::network::constants::Network;
3441 use bitcoin::secp256k1::{SecretKey,PublicKey};
3442 use bitcoin::secp256k1::Secp256k1;
3446 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3448 use super::ChannelMonitorUpdateStep;
3449 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};
3450 use chain::{BestBlock, Confirm};
3451 use chain::channelmonitor::ChannelMonitor;
3452 use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3453 use chain::transaction::OutPoint;
3454 use chain::keysinterface::InMemorySigner;
3455 use ln::{PaymentPreimage, PaymentHash};
3457 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3458 use ln::channelmanager::PaymentSendFailure;
3459 use ln::features::InitFeatures;
3460 use ln::functional_test_utils::*;
3461 use ln::script::ShutdownScript;
3462 use util::errors::APIError;
3463 use util::events::{ClosureReason, MessageSendEventsProvider};
3464 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3465 use util::ser::{ReadableArgs, Writeable};
3466 use sync::{Arc, Mutex};
3468 use bitcoin::Witness;
3471 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3472 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3473 // confirmed. This would allow a race condition where we could receive a payment (including
3474 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3475 // long as the ChannelMonitor receives the block first, the full commitment update dance
3476 // occurs after the block is connected, and before the ChannelManager receives the block.
3477 // Obviously this is an incredibly contrived race given the counterparty would be risking
3478 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3479 // potential ChannelMonitor states simpler to reason about.
3481 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3482 // updates is handled correctly in such conditions.
3483 let chanmon_cfgs = create_chanmon_cfgs(3);
3484 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3485 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3486 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3487 let channel = create_announced_chan_between_nodes(
3488 &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3489 create_announced_chan_between_nodes(
3490 &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3492 // Rebalance somewhat
3493 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3495 // First route two payments for testing at the end
3496 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3497 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3499 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3500 assert_eq!(local_txn.len(), 1);
3501 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3502 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3503 check_spends!(remote_txn[1], remote_txn[0]);
3504 check_spends!(remote_txn[2], remote_txn[0]);
3505 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3507 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3508 // channel is now closed, but the ChannelManager doesn't know that yet.
3509 let new_header = BlockHeader {
3510 version: 2, time: 0, bits: 0, nonce: 0,
3511 prev_blockhash: nodes[0].best_block_info().0,
3512 merkle_root: Default::default() };
3513 let conf_height = nodes[0].best_block_info().1 + 1;
3514 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3515 &[(0, broadcast_tx)], conf_height);
3517 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3518 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3519 &nodes[1].keys_manager.backing).unwrap();
3521 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3522 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3523 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3524 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3525 true, APIError::ChannelUnavailable { ref err },
3526 assert!(err.contains("ChannelMonitor storage failure")));
3527 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3528 check_closed_broadcast!(nodes[1], true);
3529 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3531 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3532 // and provides the claim preimages for the two pending HTLCs. The first update generates
3533 // an error, but the point of this test is to ensure the later updates are still applied.
3534 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3535 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3536 assert_eq!(replay_update.updates.len(), 1);
3537 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3538 } else { panic!(); }
3539 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3540 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3542 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3544 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3546 // Even though we error'd on the first update, we should still have generated an HTLC claim
3548 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3549 assert!(txn_broadcasted.len() >= 2);
3550 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3551 assert_eq!(tx.input.len(), 1);
3552 tx.input[0].previous_output.txid == broadcast_tx.txid()
3553 }).collect::<Vec<_>>();
3554 assert_eq!(htlc_txn.len(), 2);
3555 check_spends!(htlc_txn[0], broadcast_tx);
3556 check_spends!(htlc_txn[1], broadcast_tx);
3559 fn test_funding_spend_refuses_updates() {
3560 do_test_funding_spend_refuses_updates(true);
3561 do_test_funding_spend_refuses_updates(false);
3565 fn test_prune_preimages() {
3566 let secp_ctx = Secp256k1::new();
3567 let logger = Arc::new(TestLogger::new());
3568 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3569 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3571 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3572 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3574 let mut preimages = Vec::new();
3577 let preimage = PaymentPreimage([i; 32]);
3578 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3579 preimages.push((preimage, hash));
3583 macro_rules! preimages_slice_to_htlc_outputs {
3584 ($preimages_slice: expr) => {
3586 let mut res = Vec::new();
3587 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3588 res.push((HTLCOutputInCommitment {
3592 payment_hash: preimage.1.clone(),
3593 transaction_output_index: Some(idx as u32),
3600 macro_rules! preimages_to_holder_htlcs {
3601 ($preimages_slice: expr) => {
3603 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3604 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3610 macro_rules! test_preimages_exist {
3611 ($preimages_slice: expr, $monitor: expr) => {
3612 for preimage in $preimages_slice {
3613 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3618 let keys = InMemorySigner::new(
3620 SecretKey::from_slice(&[41; 32]).unwrap(),
3621 SecretKey::from_slice(&[41; 32]).unwrap(),
3622 SecretKey::from_slice(&[41; 32]).unwrap(),
3623 SecretKey::from_slice(&[41; 32]).unwrap(),
3624 SecretKey::from_slice(&[41; 32]).unwrap(),
3625 SecretKey::from_slice(&[41; 32]).unwrap(),
3631 let counterparty_pubkeys = ChannelPublicKeys {
3632 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3633 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3634 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3635 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3636 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3638 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
3639 let channel_parameters = ChannelTransactionParameters {
3640 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3641 holder_selected_contest_delay: 66,
3642 is_outbound_from_holder: true,
3643 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3644 pubkeys: counterparty_pubkeys,
3645 selected_contest_delay: 67,
3647 funding_outpoint: Some(funding_outpoint),
3650 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3652 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3653 let best_block = BestBlock::from_genesis(Network::Testnet);
3654 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3655 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3656 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3657 &channel_parameters,
3658 Script::new(), 46, 0,
3659 HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3661 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3662 let dummy_txid = dummy_tx.txid();
3663 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3664 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3665 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3666 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3667 for &(ref preimage, ref hash) in preimages.iter() {
3668 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3669 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3672 // Now provide a secret, pruning preimages 10-15
3673 let mut secret = [0; 32];
3674 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3675 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3676 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3677 test_preimages_exist!(&preimages[0..10], monitor);
3678 test_preimages_exist!(&preimages[15..20], monitor);
3680 // Now provide a further secret, pruning preimages 15-17
3681 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3682 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3683 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3684 test_preimages_exist!(&preimages[0..10], monitor);
3685 test_preimages_exist!(&preimages[17..20], monitor);
3687 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3688 // previous commitment tx's preimages too
3689 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3690 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3691 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3692 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3693 test_preimages_exist!(&preimages[0..10], monitor);
3694 test_preimages_exist!(&preimages[18..20], monitor);
3696 // But if we do it again, we'll prune 5-10
3697 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3698 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3699 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3700 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3701 test_preimages_exist!(&preimages[0..5], monitor);
3705 fn test_claim_txn_weight_computation() {
3706 // We test Claim txn weight, knowing that we want expected weigth and
3707 // not actual case to avoid sigs and time-lock delays hell variances.
3709 let secp_ctx = Secp256k1::new();
3710 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3711 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3713 macro_rules! sign_input {
3714 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3715 let htlc = HTLCOutputInCommitment {
3716 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3718 cltv_expiry: 2 << 16,
3719 payment_hash: PaymentHash([1; 32]),
3720 transaction_output_index: Some($idx as u32),
3722 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) };
3723 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3724 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3725 let mut ser_sig = sig.serialize_der().to_vec();
3726 ser_sig.push(EcdsaSighashType::All as u8);
3727 $sum_actual_sigs += ser_sig.len();
3728 let witness = $sighash_parts.witness_mut($idx).unwrap();
3729 witness.push(ser_sig);
3730 if *$weight == WEIGHT_REVOKED_OUTPUT {
3731 witness.push(vec!(1));
3732 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3733 witness.push(pubkey.clone().serialize().to_vec());
3734 } else if *$weight == weight_received_htlc($opt_anchors) {
3735 witness.push(vec![0]);
3737 witness.push(PaymentPreimage([1; 32]).0.to_vec());
3739 witness.push(redeem_script.into_bytes());
3740 let witness = witness.to_vec();
3741 println!("witness[0] {}", witness[0].len());
3742 println!("witness[1] {}", witness[1].len());
3743 println!("witness[2] {}", witness[2].len());
3747 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3748 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3750 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3751 for &opt_anchors in [false, true].iter() {
3752 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3753 let mut sum_actual_sigs = 0;
3755 claim_tx.input.push(TxIn {
3756 previous_output: BitcoinOutPoint {
3760 script_sig: Script::new(),
3761 sequence: 0xfffffffd,
3762 witness: Witness::new(),
3765 claim_tx.output.push(TxOut {
3766 script_pubkey: script_pubkey.clone(),
3769 let base_weight = claim_tx.weight();
3770 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)];
3771 let mut inputs_total_weight = 2; // count segwit flags
3773 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3774 for (idx, inp) in inputs_weight.iter().enumerate() {
3775 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3776 inputs_total_weight += inp;
3779 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3782 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3783 for &opt_anchors in [false, true].iter() {
3784 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3785 let mut sum_actual_sigs = 0;
3787 claim_tx.input.push(TxIn {
3788 previous_output: BitcoinOutPoint {
3792 script_sig: Script::new(),
3793 sequence: 0xfffffffd,
3794 witness: Witness::new(),
3797 claim_tx.output.push(TxOut {
3798 script_pubkey: script_pubkey.clone(),
3801 let base_weight = claim_tx.weight();
3802 let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
3803 let mut inputs_total_weight = 2; // count segwit flags
3805 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3806 for (idx, inp) in inputs_weight.iter().enumerate() {
3807 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3808 inputs_total_weight += inp;
3811 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3814 // Justice tx with 1 revoked HTLC-Success tx output
3815 for &opt_anchors in [false, true].iter() {
3816 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3817 let mut sum_actual_sigs = 0;
3818 claim_tx.input.push(TxIn {
3819 previous_output: BitcoinOutPoint {
3823 script_sig: Script::new(),
3824 sequence: 0xfffffffd,
3825 witness: Witness::new(),
3827 claim_tx.output.push(TxOut {
3828 script_pubkey: script_pubkey.clone(),
3831 let base_weight = claim_tx.weight();
3832 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3833 let mut inputs_total_weight = 2; // count segwit flags
3835 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
3836 for (idx, inp) in inputs_weight.iter().enumerate() {
3837 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
3838 inputs_total_weight += inp;
3841 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3845 // Further testing is done in the ChannelManager integration tests.