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::{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,Signature};
33 use bitcoin::secp256k1::key::{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};
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, feature = "fuzztarget", 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 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
119 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
120 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
122 /// Contains a developer-readable error message.
123 #[derive(Clone, Debug)]
124 pub struct MonitorUpdateError(pub &'static str);
126 /// An event to be processed by the ChannelManager.
127 #[derive(Clone, PartialEq)]
128 pub enum MonitorEvent {
129 /// A monitor event containing an HTLCUpdate.
130 HTLCEvent(HTLCUpdate),
132 /// A monitor event that the Channel's commitment transaction was confirmed.
133 CommitmentTxConfirmed(OutPoint),
135 /// Indicates a [`ChannelMonitor`] update has completed. See
136 /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
138 /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
140 /// The funding outpoint of the [`ChannelMonitor`] that was updated
141 funding_txo: OutPoint,
142 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
143 /// [`ChannelMonitor::get_latest_update_id`].
145 /// Note that this should only be set to a given update's ID if all previous updates for the
146 /// same [`ChannelMonitor`] have been applied and persisted.
147 monitor_update_id: u64,
150 /// Indicates a [`ChannelMonitor`] update has failed. See
151 /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
153 /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
154 UpdateFailed(OutPoint),
156 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
157 // Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
158 // generated only in ChainMonitor
159 (0, UpdateCompleted) => {
160 (0, funding_txo, required),
161 (2, monitor_update_id, required),
165 (4, CommitmentTxConfirmed),
169 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
170 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
171 /// preimage claim backward will lead to loss of funds.
172 #[derive(Clone, PartialEq)]
173 pub struct HTLCUpdate {
174 pub(crate) payment_hash: PaymentHash,
175 pub(crate) payment_preimage: Option<PaymentPreimage>,
176 pub(crate) source: HTLCSource,
177 pub(crate) onchain_value_satoshis: Option<u64>,
179 impl_writeable_tlv_based!(HTLCUpdate, {
180 (0, payment_hash, required),
181 (1, onchain_value_satoshis, option),
182 (2, source, required),
183 (4, payment_preimage, option),
186 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
187 /// instead claiming it in its own individual transaction.
188 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
189 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
190 /// HTLC-Success transaction.
191 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
192 /// transaction confirmed (and we use it in a few more, equivalent, places).
193 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
194 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
195 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
196 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
197 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
198 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
199 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
200 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
201 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
202 /// accurate block height.
203 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
204 /// with at worst this delay, so we are not only using this value as a mercy for them but also
205 /// us as a safeguard to delay with enough time.
206 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
207 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
208 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
211 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
212 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
213 /// by a [`ChannelMonitor`] may be incorrect.
214 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
215 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
216 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
217 // keep bumping another claim tx to solve the outpoint.
218 pub const ANTI_REORG_DELAY: u32 = 6;
219 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
220 /// refuse to accept a new HTLC.
222 /// This is used for a few separate purposes:
223 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
224 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
226 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
227 /// condition with the above), we will fail this HTLC without telling the user we received it,
229 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
230 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
232 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
233 /// in a race condition between the user connecting a block (which would fail it) and the user
234 /// providing us the preimage (which would claim it).
235 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
237 // TODO(devrandom) replace this with HolderCommitmentTransaction
238 #[derive(Clone, PartialEq)]
239 struct HolderSignedTx {
240 /// txid of the transaction in tx, just used to make comparison faster
242 revocation_key: PublicKey,
243 a_htlc_key: PublicKey,
244 b_htlc_key: PublicKey,
245 delayed_payment_key: PublicKey,
246 per_commitment_point: PublicKey,
247 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
248 to_self_value_sat: u64,
251 impl_writeable_tlv_based!(HolderSignedTx, {
253 // Note that this is filled in with data from OnchainTxHandler if it's missing.
254 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
255 (1, to_self_value_sat, (default_value, u64::max_value())),
256 (2, revocation_key, required),
257 (4, a_htlc_key, required),
258 (6, b_htlc_key, required),
259 (8, delayed_payment_key, required),
260 (10, per_commitment_point, required),
261 (12, feerate_per_kw, required),
262 (14, htlc_outputs, vec_type)
265 /// We use this to track static counterparty commitment transaction data and to generate any
266 /// justice or 2nd-stage preimage/timeout transactions.
268 struct CounterpartyCommitmentParameters {
269 counterparty_delayed_payment_base_key: PublicKey,
270 counterparty_htlc_base_key: PublicKey,
271 on_counterparty_tx_csv: u16,
274 impl Writeable for CounterpartyCommitmentParameters {
275 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
276 w.write_all(&byte_utils::be64_to_array(0))?;
277 write_tlv_fields!(w, {
278 (0, self.counterparty_delayed_payment_base_key, required),
279 (2, self.counterparty_htlc_base_key, required),
280 (4, self.on_counterparty_tx_csv, required),
285 impl Readable for CounterpartyCommitmentParameters {
286 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
287 let counterparty_commitment_transaction = {
288 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
289 // used. Read it for compatibility.
290 let per_htlc_len: u64 = Readable::read(r)?;
291 for _ in 0..per_htlc_len {
292 let _txid: Txid = Readable::read(r)?;
293 let htlcs_count: u64 = Readable::read(r)?;
294 for _ in 0..htlcs_count {
295 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
299 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
300 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
301 let mut on_counterparty_tx_csv: u16 = 0;
302 read_tlv_fields!(r, {
303 (0, counterparty_delayed_payment_base_key, required),
304 (2, counterparty_htlc_base_key, required),
305 (4, on_counterparty_tx_csv, required),
307 CounterpartyCommitmentParameters {
308 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
309 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
310 on_counterparty_tx_csv,
313 Ok(counterparty_commitment_transaction)
317 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
318 /// transaction causing it.
320 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
322 struct OnchainEventEntry {
328 impl OnchainEventEntry {
329 fn confirmation_threshold(&self) -> u32 {
330 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
332 OnchainEvent::MaturingOutput {
333 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
335 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
336 // it's broadcastable when we see the previous block.
337 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
339 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
340 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
341 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
342 // it's broadcastable when we see the previous block.
343 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
350 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
351 best_block.height() >= self.confirmation_threshold()
355 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
356 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
359 /// An outbound HTLC failing after a transaction is confirmed. Used
360 /// * when an outbound HTLC output is spent by us after the HTLC timed out
361 /// * an outbound HTLC which was not present in the commitment transaction which appeared
362 /// on-chain (either because it was not fully committed to or it was dust).
363 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
364 /// appearing only as an `HTLCSpendConfirmation`, below.
367 payment_hash: PaymentHash,
368 onchain_value_satoshis: Option<u64>,
369 /// None in the second case, above, ie when there is no relevant output in the commitment
370 /// transaction which appeared on chain.
371 input_idx: Option<u32>,
374 descriptor: SpendableOutputDescriptor,
376 /// A spend of the funding output, either a commitment transaction or a cooperative closing
378 FundingSpendConfirmation {
379 /// The CSV delay for the output of the funding spend transaction (implying it is a local
380 /// commitment transaction, and this is the delay on the to_self output).
381 on_local_output_csv: Option<u16>,
383 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
384 /// is constructed. This is used when
385 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
386 /// immediately claim the HTLC on the inbound edge and track the resolution here,
387 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
388 /// * an inbound HTLC is claimed by us (with a preimage).
389 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
391 HTLCSpendConfirmation {
393 /// If the claim was made by either party with a preimage, this is filled in
394 preimage: Option<PaymentPreimage>,
395 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
396 /// we set this to the output CSV value which we will have to wait until to spend the
397 /// output (and generate a SpendableOutput event).
398 on_to_local_output_csv: Option<u16>,
402 impl Writeable for OnchainEventEntry {
403 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
404 write_tlv_fields!(writer, {
405 (0, self.txid, required),
406 (2, self.height, required),
407 (4, self.event, required),
413 impl MaybeReadable for OnchainEventEntry {
414 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
415 let mut txid = Default::default();
417 let mut event = None;
418 read_tlv_fields!(reader, {
420 (2, height, required),
421 (4, event, ignorable),
423 if let Some(ev) = event {
424 Ok(Some(Self { txid, height, event: ev }))
431 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
433 (0, source, required),
434 (1, onchain_value_satoshis, option),
435 (2, payment_hash, required),
436 (3, input_idx, option),
438 (1, MaturingOutput) => {
439 (0, descriptor, required),
441 (3, FundingSpendConfirmation) => {
442 (0, on_local_output_csv, option),
444 (5, HTLCSpendConfirmation) => {
445 (0, input_idx, required),
446 (2, preimage, option),
447 (4, on_to_local_output_csv, option),
452 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
454 pub(crate) enum ChannelMonitorUpdateStep {
455 LatestHolderCommitmentTXInfo {
456 commitment_tx: HolderCommitmentTransaction,
457 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
459 LatestCounterpartyCommitmentTXInfo {
460 commitment_txid: Txid,
461 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
462 commitment_number: u64,
463 their_revocation_point: PublicKey,
466 payment_preimage: PaymentPreimage,
472 /// Used to indicate that the no future updates will occur, and likely that the latest holder
473 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
475 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
476 /// think we've fallen behind!
477 should_broadcast: bool,
480 scriptpubkey: Script,
484 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
485 (0, LatestHolderCommitmentTXInfo) => {
486 (0, commitment_tx, required),
487 (2, htlc_outputs, vec_type),
489 (1, LatestCounterpartyCommitmentTXInfo) => {
490 (0, commitment_txid, required),
491 (2, commitment_number, required),
492 (4, their_revocation_point, required),
493 (6, htlc_outputs, vec_type),
495 (2, PaymentPreimage) => {
496 (0, payment_preimage, required),
498 (3, CommitmentSecret) => {
500 (2, secret, required),
502 (4, ChannelForceClosed) => {
503 (0, should_broadcast, required),
505 (5, ShutdownScript) => {
506 (0, scriptpubkey, required),
510 /// Details about the balance(s) available for spending once the channel appears on chain.
512 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
514 #[derive(Clone, Debug, PartialEq, Eq)]
515 #[cfg_attr(test, derive(PartialOrd, Ord))]
517 /// The channel is not yet closed (or the commitment or closing transaction has not yet
518 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
519 /// force-closed now.
520 ClaimableOnChannelClose {
521 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
522 /// required to do so.
523 claimable_amount_satoshis: u64,
525 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
526 /// we consider it spendable.
527 ClaimableAwaitingConfirmations {
528 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
529 /// were spent in broadcasting the transaction.
530 claimable_amount_satoshis: u64,
531 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
533 confirmation_height: u32,
535 /// The channel has been closed, and the given balance should be ours but awaiting spending
536 /// transaction confirmation. If the spending transaction does not confirm in time, it is
537 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
539 /// Once the spending transaction confirms, before it has reached enough confirmations to be
540 /// considered safe from chain reorganizations, the balance will instead be provided via
541 /// [`Balance::ClaimableAwaitingConfirmations`].
542 ContentiousClaimable {
543 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
544 /// required to do so.
545 claimable_amount_satoshis: u64,
546 /// The height at which the counterparty may be able to claim the balance if we have not
550 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
551 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
552 /// likely to be claimed by our counterparty before we do.
553 MaybeClaimableHTLCAwaitingTimeout {
554 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
555 /// required to do so.
556 claimable_amount_satoshis: u64,
557 /// The height at which we will be able to claim the balance if our counterparty has not
559 claimable_height: u32,
563 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
565 struct IrrevocablyResolvedHTLC {
567 /// Only set if the HTLC claim was ours using a payment preimage
568 payment_preimage: Option<PaymentPreimage>,
571 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
572 (0, input_idx, required),
573 (2, payment_preimage, option),
576 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
577 /// on-chain transactions to ensure no loss of funds occurs.
579 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
580 /// information and are actively monitoring the chain.
582 /// Pending Events or updated HTLCs which have not yet been read out by
583 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
584 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
585 /// gotten are fully handled before re-serializing the new state.
587 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
588 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
589 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
590 /// returned block hash and the the current chain and then reconnecting blocks to get to the
591 /// best chain) upon deserializing the object!
592 pub struct ChannelMonitor<Signer: Sign> {
594 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
596 inner: Mutex<ChannelMonitorImpl<Signer>>,
599 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
600 latest_update_id: u64,
601 commitment_transaction_number_obscure_factor: u64,
603 destination_script: Script,
604 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
605 counterparty_payment_script: Script,
606 shutdown_script: Option<Script>,
608 channel_keys_id: [u8; 32],
609 holder_revocation_basepoint: PublicKey,
610 funding_info: (OutPoint, Script),
611 current_counterparty_commitment_txid: Option<Txid>,
612 prev_counterparty_commitment_txid: Option<Txid>,
614 counterparty_commitment_params: CounterpartyCommitmentParameters,
615 funding_redeemscript: Script,
616 channel_value_satoshis: u64,
617 // first is the idx of the first of the two revocation points
618 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
620 on_holder_tx_csv: u16,
622 commitment_secrets: CounterpartyCommitmentSecrets,
623 /// The set of outpoints in each counterparty commitment transaction. We always need at least
624 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
625 /// transaction broadcast as we need to be able to construct the witness script in all cases.
626 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
627 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
628 /// Nor can we figure out their commitment numbers without the commitment transaction they are
629 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
630 /// commitment transactions which we find on-chain, mapping them to the commitment number which
631 /// can be used to derive the revocation key and claim the transactions.
632 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
633 /// Cache used to make pruning of payment_preimages faster.
634 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
635 /// counterparty transactions (ie should remain pretty small).
636 /// Serialized to disk but should generally not be sent to Watchtowers.
637 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
639 // We store two holder commitment transactions to avoid any race conditions where we may update
640 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
641 // various monitors for one channel being out of sync, and us broadcasting a holder
642 // transaction for which we have deleted claim information on some watchtowers.
643 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
644 current_holder_commitment_tx: HolderSignedTx,
646 // Used just for ChannelManager to make sure it has the latest channel data during
648 current_counterparty_commitment_number: u64,
649 // Used just for ChannelManager to make sure it has the latest channel data during
651 current_holder_commitment_number: u64,
653 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
655 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
656 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
657 // presumably user implementations thereof as well) where we update the in-memory channel
658 // object, then before the persistence finishes (as it's all under a read-lock), we return
659 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
660 // the pre-event state here, but have processed the event in the `ChannelManager`.
661 // Note that because the `event_lock` in `ChainMonitor` is only taken in
662 // block/transaction-connected events and *not* during block/transaction-disconnected events,
663 // we further MUST NOT generate events during block/transaction-disconnection.
664 pending_monitor_events: Vec<MonitorEvent>,
666 pending_events: Vec<Event>,
668 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
669 // which to take actions once they reach enough confirmations. Each entry includes the
670 // transaction's id and the height when the transaction was confirmed on chain.
671 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
673 // If we get serialized out and re-read, we need to make sure that the chain monitoring
674 // interface knows about the TXOs that we want to be notified of spends of. We could probably
675 // be smart and derive them from the above storage fields, but its much simpler and more
676 // Obviously Correct (tm) if we just keep track of them explicitly.
677 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
680 pub onchain_tx_handler: OnchainTxHandler<Signer>,
682 onchain_tx_handler: OnchainTxHandler<Signer>,
684 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
685 // channel has been force-closed. After this is set, no further holder commitment transaction
686 // updates may occur, and we panic!() if one is provided.
687 lockdown_from_offchain: bool,
689 // Set once we've signed a holder commitment transaction and handed it over to our
690 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
691 // may occur, and we fail any such monitor updates.
693 // In case of update rejection due to a locally already signed commitment transaction, we
694 // nevertheless store update content to track in case of concurrent broadcast by another
695 // remote monitor out-of-order with regards to the block view.
696 holder_tx_signed: bool,
698 funding_spend_confirmed: Option<Txid>,
699 /// The set of HTLCs which have been either claimed or failed on chain and have reached
700 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
701 /// spending CSV for revocable outputs).
702 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
704 // We simply modify best_block in Channel's block_connected so that serialization is
705 // consistent but hopefully the users' copy handles block_connected in a consistent way.
706 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
707 // their best_block from its state and not based on updated copies that didn't run through
708 // the full block_connected).
709 best_block: BestBlock,
711 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
714 /// Transaction outputs to watch for on-chain spends.
715 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
717 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
718 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
719 /// underlying object
720 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
721 fn eq(&self, other: &Self) -> bool {
722 let inner = self.inner.lock().unwrap();
723 let other = other.inner.lock().unwrap();
728 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
729 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
730 /// underlying object
731 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
732 fn eq(&self, other: &Self) -> bool {
733 if self.latest_update_id != other.latest_update_id ||
734 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
735 self.destination_script != other.destination_script ||
736 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
737 self.counterparty_payment_script != other.counterparty_payment_script ||
738 self.channel_keys_id != other.channel_keys_id ||
739 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
740 self.funding_info != other.funding_info ||
741 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
742 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
743 self.counterparty_commitment_params != other.counterparty_commitment_params ||
744 self.funding_redeemscript != other.funding_redeemscript ||
745 self.channel_value_satoshis != other.channel_value_satoshis ||
746 self.their_cur_revocation_points != other.their_cur_revocation_points ||
747 self.on_holder_tx_csv != other.on_holder_tx_csv ||
748 self.commitment_secrets != other.commitment_secrets ||
749 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
750 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
751 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
752 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
753 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
754 self.current_holder_commitment_number != other.current_holder_commitment_number ||
755 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
756 self.payment_preimages != other.payment_preimages ||
757 self.pending_monitor_events != other.pending_monitor_events ||
758 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
759 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
760 self.outputs_to_watch != other.outputs_to_watch ||
761 self.lockdown_from_offchain != other.lockdown_from_offchain ||
762 self.holder_tx_signed != other.holder_tx_signed ||
763 self.funding_spend_confirmed != other.funding_spend_confirmed ||
764 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
773 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
774 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
775 self.inner.lock().unwrap().write(writer)
779 // These are also used for ChannelMonitorUpdate, above.
780 const SERIALIZATION_VERSION: u8 = 1;
781 const MIN_SERIALIZATION_VERSION: u8 = 1;
783 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
784 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
785 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
787 self.latest_update_id.write(writer)?;
789 // Set in initial Channel-object creation, so should always be set by now:
790 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
792 self.destination_script.write(writer)?;
793 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
794 writer.write_all(&[0; 1])?;
795 broadcasted_holder_revokable_script.0.write(writer)?;
796 broadcasted_holder_revokable_script.1.write(writer)?;
797 broadcasted_holder_revokable_script.2.write(writer)?;
799 writer.write_all(&[1; 1])?;
802 self.counterparty_payment_script.write(writer)?;
803 match &self.shutdown_script {
804 Some(script) => script.write(writer)?,
805 None => Script::new().write(writer)?,
808 self.channel_keys_id.write(writer)?;
809 self.holder_revocation_basepoint.write(writer)?;
810 writer.write_all(&self.funding_info.0.txid[..])?;
811 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
812 self.funding_info.1.write(writer)?;
813 self.current_counterparty_commitment_txid.write(writer)?;
814 self.prev_counterparty_commitment_txid.write(writer)?;
816 self.counterparty_commitment_params.write(writer)?;
817 self.funding_redeemscript.write(writer)?;
818 self.channel_value_satoshis.write(writer)?;
820 match self.their_cur_revocation_points {
821 Some((idx, pubkey, second_option)) => {
822 writer.write_all(&byte_utils::be48_to_array(idx))?;
823 writer.write_all(&pubkey.serialize())?;
824 match second_option {
825 Some(second_pubkey) => {
826 writer.write_all(&second_pubkey.serialize())?;
829 writer.write_all(&[0; 33])?;
834 writer.write_all(&byte_utils::be48_to_array(0))?;
838 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
840 self.commitment_secrets.write(writer)?;
842 macro_rules! serialize_htlc_in_commitment {
843 ($htlc_output: expr) => {
844 writer.write_all(&[$htlc_output.offered as u8; 1])?;
845 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
846 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
847 writer.write_all(&$htlc_output.payment_hash.0[..])?;
848 $htlc_output.transaction_output_index.write(writer)?;
852 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
853 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
854 writer.write_all(&txid[..])?;
855 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
856 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
857 serialize_htlc_in_commitment!(htlc_output);
858 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
862 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
863 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
864 writer.write_all(&txid[..])?;
865 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
868 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
869 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
870 writer.write_all(&payment_hash.0[..])?;
871 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
874 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
875 writer.write_all(&[1; 1])?;
876 prev_holder_tx.write(writer)?;
878 writer.write_all(&[0; 1])?;
881 self.current_holder_commitment_tx.write(writer)?;
883 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
884 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
886 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
887 for payment_preimage in self.payment_preimages.values() {
888 writer.write_all(&payment_preimage.0[..])?;
891 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
892 MonitorEvent::HTLCEvent(_) => true,
893 MonitorEvent::CommitmentTxConfirmed(_) => true,
895 }).count() as u64).to_be_bytes())?;
896 for event in self.pending_monitor_events.iter() {
898 MonitorEvent::HTLCEvent(upd) => {
902 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
903 _ => {}, // Covered in the TLV writes below
907 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
908 for event in self.pending_events.iter() {
909 event.write(writer)?;
912 self.best_block.block_hash().write(writer)?;
913 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
915 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
916 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
917 entry.write(writer)?;
920 (self.outputs_to_watch.len() as u64).write(writer)?;
921 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
923 (idx_scripts.len() as u64).write(writer)?;
924 for (idx, script) in idx_scripts.iter() {
926 script.write(writer)?;
929 self.onchain_tx_handler.write(writer)?;
931 self.lockdown_from_offchain.write(writer)?;
932 self.holder_tx_signed.write(writer)?;
934 write_tlv_fields!(writer, {
935 (1, self.funding_spend_confirmed, option),
936 (3, self.htlcs_resolved_on_chain, vec_type),
937 (5, self.pending_monitor_events, vec_type),
944 impl<Signer: Sign> ChannelMonitor<Signer> {
945 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
946 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
947 channel_parameters: &ChannelTransactionParameters,
948 funding_redeemscript: Script, channel_value_satoshis: u64,
949 commitment_transaction_number_obscure_factor: u64,
950 initial_holder_commitment_tx: HolderCommitmentTransaction,
951 best_block: BestBlock) -> ChannelMonitor<Signer> {
953 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
954 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
955 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
957 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
958 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
959 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
960 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
962 let channel_keys_id = keys.channel_keys_id();
963 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
965 // block for Rust 1.34 compat
966 let (holder_commitment_tx, current_holder_commitment_number) = {
967 let trusted_tx = initial_holder_commitment_tx.trust();
968 let txid = trusted_tx.txid();
970 let tx_keys = trusted_tx.keys();
971 let holder_commitment_tx = HolderSignedTx {
973 revocation_key: tx_keys.revocation_key,
974 a_htlc_key: tx_keys.broadcaster_htlc_key,
975 b_htlc_key: tx_keys.countersignatory_htlc_key,
976 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
977 per_commitment_point: tx_keys.per_commitment_point,
978 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
979 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
980 feerate_per_kw: trusted_tx.feerate_per_kw(),
982 (holder_commitment_tx, trusted_tx.commitment_number())
985 let onchain_tx_handler =
986 OnchainTxHandler::new(destination_script.clone(), keys,
987 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
989 let mut outputs_to_watch = HashMap::new();
990 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
993 inner: Mutex::new(ChannelMonitorImpl {
995 commitment_transaction_number_obscure_factor,
997 destination_script: destination_script.clone(),
998 broadcasted_holder_revokable_script: None,
999 counterparty_payment_script,
1003 holder_revocation_basepoint,
1005 current_counterparty_commitment_txid: None,
1006 prev_counterparty_commitment_txid: None,
1008 counterparty_commitment_params,
1009 funding_redeemscript,
1010 channel_value_satoshis,
1011 their_cur_revocation_points: None,
1013 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1015 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1016 counterparty_claimable_outpoints: HashMap::new(),
1017 counterparty_commitment_txn_on_chain: HashMap::new(),
1018 counterparty_hash_commitment_number: HashMap::new(),
1020 prev_holder_signed_commitment_tx: None,
1021 current_holder_commitment_tx: holder_commitment_tx,
1022 current_counterparty_commitment_number: 1 << 48,
1023 current_holder_commitment_number,
1025 payment_preimages: HashMap::new(),
1026 pending_monitor_events: Vec::new(),
1027 pending_events: Vec::new(),
1029 onchain_events_awaiting_threshold_conf: Vec::new(),
1034 lockdown_from_offchain: false,
1035 holder_tx_signed: false,
1036 funding_spend_confirmed: None,
1037 htlcs_resolved_on_chain: Vec::new(),
1047 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1048 self.inner.lock().unwrap().provide_secret(idx, secret)
1051 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1052 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1053 /// possibly future revocation/preimage information) to claim outputs where possible.
1054 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1055 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1058 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1059 commitment_number: u64,
1060 their_revocation_point: PublicKey,
1062 ) where L::Target: Logger {
1063 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1064 txid, htlc_outputs, commitment_number, their_revocation_point, logger)
1068 fn provide_latest_holder_commitment_tx(
1070 holder_commitment_tx: HolderCommitmentTransaction,
1071 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1072 ) -> Result<(), MonitorUpdateError> {
1073 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
1074 holder_commitment_tx, htlc_outputs)
1078 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1080 payment_hash: &PaymentHash,
1081 payment_preimage: &PaymentPreimage,
1086 B::Target: BroadcasterInterface,
1087 F::Target: FeeEstimator,
1090 self.inner.lock().unwrap().provide_payment_preimage(
1091 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1094 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1099 B::Target: BroadcasterInterface,
1102 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1105 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1108 /// panics if the given update is not the next update by update_id.
1109 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1111 updates: &ChannelMonitorUpdate,
1115 ) -> Result<(), MonitorUpdateError>
1117 B::Target: BroadcasterInterface,
1118 F::Target: FeeEstimator,
1121 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1124 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1126 pub fn get_latest_update_id(&self) -> u64 {
1127 self.inner.lock().unwrap().get_latest_update_id()
1130 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1131 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1132 self.inner.lock().unwrap().get_funding_txo().clone()
1135 /// Gets a list of txids, with their output scripts (in the order they appear in the
1136 /// transaction), which we must learn about spends of via block_connected().
1137 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1138 self.inner.lock().unwrap().get_outputs_to_watch()
1139 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1142 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1143 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1144 /// have been registered.
1145 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1146 let lock = self.inner.lock().unwrap();
1147 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1148 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1149 for (index, script_pubkey) in outputs.iter() {
1150 assert!(*index <= u16::max_value() as u32);
1151 filter.register_output(WatchedOutput {
1153 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1154 script_pubkey: script_pubkey.clone(),
1160 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1161 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1162 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1163 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1166 /// Gets the list of pending events which were generated by previous actions, clearing the list
1169 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1170 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1171 /// no internal locking in ChannelMonitors.
1172 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1173 self.inner.lock().unwrap().get_and_clear_pending_events()
1176 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1177 self.inner.lock().unwrap().get_min_seen_secret()
1180 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1181 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1184 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1185 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1188 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1189 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1190 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1191 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1192 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1193 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1194 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1195 /// out-of-band the other node operator to coordinate with him if option is available to you.
1196 /// In any-case, choice is up to the user.
1197 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1198 where L::Target: Logger {
1199 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1202 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1203 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1204 /// revoked commitment transaction.
1205 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1206 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1207 where L::Target: Logger {
1208 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1211 /// Processes transactions in a newly connected block, which may result in any of the following:
1212 /// - update the monitor's state against resolved HTLCs
1213 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1214 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1215 /// - detect settled outputs for later spending
1216 /// - schedule and bump any in-flight claims
1218 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1219 /// [`get_outputs_to_watch`].
1221 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1222 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1224 header: &BlockHeader,
1225 txdata: &TransactionData,
1230 ) -> Vec<TransactionOutputs>
1232 B::Target: BroadcasterInterface,
1233 F::Target: FeeEstimator,
1236 self.inner.lock().unwrap().block_connected(
1237 header, txdata, height, broadcaster, fee_estimator, logger)
1240 /// Determines if the disconnected block contained any transactions of interest and updates
1242 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1244 header: &BlockHeader,
1250 B::Target: BroadcasterInterface,
1251 F::Target: FeeEstimator,
1254 self.inner.lock().unwrap().block_disconnected(
1255 header, height, broadcaster, fee_estimator, logger)
1258 /// Processes transactions confirmed in a block with the given header and height, returning new
1259 /// outputs to watch. See [`block_connected`] for details.
1261 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1262 /// blocks. See [`chain::Confirm`] for calling expectations.
1264 /// [`block_connected`]: Self::block_connected
1265 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1267 header: &BlockHeader,
1268 txdata: &TransactionData,
1273 ) -> Vec<TransactionOutputs>
1275 B::Target: BroadcasterInterface,
1276 F::Target: FeeEstimator,
1279 self.inner.lock().unwrap().transactions_confirmed(
1280 header, txdata, height, broadcaster, fee_estimator, logger)
1283 /// Processes a transaction that was reorganized out of the chain.
1285 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1286 /// than blocks. See [`chain::Confirm`] for calling expectations.
1288 /// [`block_disconnected`]: Self::block_disconnected
1289 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1296 B::Target: BroadcasterInterface,
1297 F::Target: FeeEstimator,
1300 self.inner.lock().unwrap().transaction_unconfirmed(
1301 txid, broadcaster, fee_estimator, logger);
1304 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1305 /// [`block_connected`] for details.
1307 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1308 /// blocks. See [`chain::Confirm`] for calling expectations.
1310 /// [`block_connected`]: Self::block_connected
1311 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1313 header: &BlockHeader,
1318 ) -> Vec<TransactionOutputs>
1320 B::Target: BroadcasterInterface,
1321 F::Target: FeeEstimator,
1324 self.inner.lock().unwrap().best_block_updated(
1325 header, height, broadcaster, fee_estimator, logger)
1328 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1329 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1330 let inner = self.inner.lock().unwrap();
1331 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1333 .map(|entry| entry.txid)
1334 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1336 txids.sort_unstable();
1341 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1342 /// [`chain::Confirm`] interfaces.
1343 pub fn current_best_block(&self) -> BestBlock {
1344 self.inner.lock().unwrap().best_block.clone()
1347 /// Gets the balances in this channel which are either claimable by us if we were to
1348 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1351 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1352 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1353 /// balance, or until our counterparty has claimed the balance and accrued several
1354 /// confirmations on the claim transaction.
1356 /// Note that the balances available when you or your counterparty have broadcasted revoked
1357 /// state(s) may not be fully captured here.
1360 /// See [`Balance`] for additional details on the types of claimable balances which
1361 /// may be returned here and their meanings.
1362 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1363 let mut res = Vec::new();
1364 let us = self.inner.lock().unwrap();
1366 let mut confirmed_txid = us.funding_spend_confirmed;
1367 let mut pending_commitment_tx_conf_thresh = None;
1368 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1369 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1370 Some((event.txid, event.confirmation_threshold()))
1373 if let Some((txid, conf_thresh)) = funding_spend_pending {
1374 debug_assert!(us.funding_spend_confirmed.is_none(),
1375 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1376 confirmed_txid = Some(txid);
1377 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1380 macro_rules! walk_htlcs {
1381 ($holder_commitment: expr, $htlc_iter: expr) => {
1382 for htlc in $htlc_iter {
1383 if let Some(htlc_input_idx) = htlc.transaction_output_index {
1384 if us.htlcs_resolved_on_chain.iter().any(|v| v.input_idx == htlc_input_idx) {
1385 assert!(us.funding_spend_confirmed.is_some());
1386 } else if htlc.offered == $holder_commitment {
1387 // If the payment was outbound, check if there's an HTLCUpdate
1388 // indicating we have spent this HTLC with a timeout, claiming it back
1389 // and awaiting confirmations on it.
1390 let htlc_update_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1391 if let OnchainEvent::HTLCUpdate { input_idx: Some(input_idx), .. } = event.event {
1392 if input_idx == htlc_input_idx { Some(event.confirmation_threshold()) } else { None }
1395 if let Some(conf_thresh) = htlc_update_pending {
1396 res.push(Balance::ClaimableAwaitingConfirmations {
1397 claimable_amount_satoshis: htlc.amount_msat / 1000,
1398 confirmation_height: conf_thresh,
1401 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1402 claimable_amount_satoshis: htlc.amount_msat / 1000,
1403 claimable_height: htlc.cltv_expiry,
1406 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1407 // Otherwise (the payment was inbound), only expose it as claimable if
1408 // we know the preimage.
1409 // Note that if there is a pending claim, but it did not use the
1410 // preimage, we lost funds to our counterparty! We will then continue
1411 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1412 let htlc_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1413 if let OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } = event.event {
1414 if input_idx == htlc_input_idx {
1415 Some((event.confirmation_threshold(), preimage.is_some()))
1419 if let Some((conf_thresh, true)) = htlc_spend_pending {
1420 res.push(Balance::ClaimableAwaitingConfirmations {
1421 claimable_amount_satoshis: htlc.amount_msat / 1000,
1422 confirmation_height: conf_thresh,
1425 res.push(Balance::ContentiousClaimable {
1426 claimable_amount_satoshis: htlc.amount_msat / 1000,
1427 timeout_height: htlc.cltv_expiry,
1436 if let Some(txid) = confirmed_txid {
1437 let mut found_commitment_tx = false;
1438 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1439 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().map(|(a, _)| a));
1440 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1441 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1442 if let OnchainEvent::MaturingOutput {
1443 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1445 Some(descriptor.output.value)
1448 res.push(Balance::ClaimableAwaitingConfirmations {
1449 claimable_amount_satoshis: value,
1450 confirmation_height: conf_thresh,
1453 // If a counterparty commitment transaction is awaiting confirmation, we
1454 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1455 // confirmation with the same height or have never met our dust amount.
1458 found_commitment_tx = true;
1459 } else if txid == us.current_holder_commitment_tx.txid {
1460 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1461 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1462 res.push(Balance::ClaimableAwaitingConfirmations {
1463 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1464 confirmation_height: conf_thresh,
1467 found_commitment_tx = true;
1468 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1469 if txid == prev_commitment.txid {
1470 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1471 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1472 res.push(Balance::ClaimableAwaitingConfirmations {
1473 claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1474 confirmation_height: conf_thresh,
1477 found_commitment_tx = true;
1480 if !found_commitment_tx {
1481 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1482 // We blindly assume this is a cooperative close transaction here, and that
1483 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1484 // the amount we can claim as we'll punish a misbehaving counterparty.
1485 res.push(Balance::ClaimableAwaitingConfirmations {
1486 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1487 confirmation_height: conf_thresh,
1491 // TODO: Add logic to provide claimable balances for counterparty broadcasting revoked
1494 let mut claimable_inbound_htlc_value_sat = 0;
1495 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1496 if htlc.transaction_output_index.is_none() { continue; }
1498 res.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
1499 claimable_amount_satoshis: htlc.amount_msat / 1000,
1500 claimable_height: htlc.cltv_expiry,
1502 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1503 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1506 res.push(Balance::ClaimableOnChannelClose {
1507 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1514 /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1515 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1516 pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1517 let mut res = HashMap::new();
1518 let us = self.inner.lock().unwrap();
1520 macro_rules! walk_htlcs {
1521 ($holder_commitment: expr, $htlc_iter: expr) => {
1522 for (htlc, source) in $htlc_iter {
1523 if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.input_idx) == htlc.transaction_output_index) {
1524 // We should assert that funding_spend_confirmed is_some() here, but we
1525 // have some unit tests which violate HTLC transaction CSVs entirely and
1527 // TODO: Once tests all connect transactions at consensus-valid times, we
1528 // should assert here like we do in `get_claimable_balances`.
1529 } else if htlc.offered == $holder_commitment {
1530 // If the payment was outbound, check if there's an HTLCUpdate
1531 // indicating we have spent this HTLC with a timeout, claiming it back
1532 // and awaiting confirmations on it.
1533 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1534 if let OnchainEvent::HTLCUpdate { input_idx: Some(input_idx), .. } = event.event {
1535 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1536 // before considering it "no longer pending" - this matches when we
1537 // provide the ChannelManager an HTLC failure event.
1538 Some(input_idx) == htlc.transaction_output_index &&
1539 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1540 } else if let OnchainEvent::HTLCSpendConfirmation { input_idx, .. } = event.event {
1541 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1542 // immediately non-pending, matching when we provide ChannelManager
1544 Some(input_idx) == htlc.transaction_output_index
1547 if !htlc_update_confd {
1548 res.insert(source.clone(), htlc.clone());
1555 // We're only concerned with the confirmation count of HTLC transactions, and don't
1556 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1557 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1558 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1559 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1560 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1565 if let Some(txid) = confirmed_txid {
1566 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1567 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1568 if let &Some(ref source) = b {
1569 Some((a, &**source))
1572 } else if txid == us.current_holder_commitment_tx.txid {
1573 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1574 if let Some(source) = c { Some((a, source)) } else { None }
1576 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1577 if txid == prev_commitment.txid {
1578 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1579 if let Some(source) = c { Some((a, source)) } else { None }
1584 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1585 // closed), just examine the available counterparty commitment transactions. See docs
1586 // on `fail_unbroadcast_htlcs`, below, for justification.
1587 macro_rules! walk_counterparty_commitment {
1589 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1590 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1591 if let &Some(ref source) = source_option {
1592 res.insert((**source).clone(), htlc.clone());
1598 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1599 walk_counterparty_commitment!(txid);
1601 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1602 walk_counterparty_commitment!(txid);
1610 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1611 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1612 /// after ANTI_REORG_DELAY blocks.
1614 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1615 /// are the commitment transactions which are generated by us. The off-chain state machine in
1616 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1617 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1618 /// included in a remote commitment transaction are failed back if they are not present in the
1619 /// broadcasted commitment transaction.
1621 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1622 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1623 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1624 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1625 macro_rules! fail_unbroadcast_htlcs {
1626 ($self: expr, $commitment_tx_type: expr, $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1627 macro_rules! check_htlc_fails {
1628 ($txid: expr, $commitment_tx: expr) => {
1629 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1630 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1631 if let &Some(ref source) = source_option {
1632 // Check if the HTLC is present in the commitment transaction that was
1633 // broadcast, but not if it was below the dust limit, which we should
1634 // fail backwards immediately as there is no way for us to learn the
1635 // payment_preimage.
1636 // Note that if the dust limit were allowed to change between
1637 // commitment transactions we'd want to be check whether *any*
1638 // broadcastable commitment transaction has the HTLC in it, but it
1639 // cannot currently change after channel initialization, so we don't
1641 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1642 let mut matched_htlc = false;
1643 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1644 if broadcast_htlc.transaction_output_index.is_some() && Some(&**source) == *broadcast_source {
1645 matched_htlc = true;
1649 if matched_htlc { continue; }
1650 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1651 if entry.height != $commitment_tx_conf_height { return true; }
1653 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1654 *update_source != **source
1659 let entry = OnchainEventEntry {
1661 height: $commitment_tx_conf_height,
1662 event: OnchainEvent::HTLCUpdate {
1663 source: (**source).clone(),
1664 payment_hash: htlc.payment_hash.clone(),
1665 onchain_value_satoshis: Some(htlc.amount_msat / 1000),
1669 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction, waiting for confirmation (at height {})",
1670 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type, entry.confirmation_threshold());
1671 $self.onchain_events_awaiting_threshold_conf.push(entry);
1677 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1678 check_htlc_fails!(txid, "current");
1680 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1681 check_htlc_fails!(txid, "previous");
1686 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1687 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1688 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1689 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1690 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1691 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1692 return Err(MonitorUpdateError("Previous secret did not match new one"));
1695 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1696 // events for now-revoked/fulfilled HTLCs.
1697 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1698 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1703 if !self.payment_preimages.is_empty() {
1704 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1705 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1706 let min_idx = self.get_min_seen_secret();
1707 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1709 self.payment_preimages.retain(|&k, _| {
1710 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1711 if k == htlc.payment_hash {
1715 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1716 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1717 if k == htlc.payment_hash {
1722 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1729 counterparty_hash_commitment_number.remove(&k);
1738 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_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
1739 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1740 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1741 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1743 for &(ref htlc, _) in &htlc_outputs {
1744 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1747 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1748 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1749 self.current_counterparty_commitment_txid = Some(txid);
1750 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1751 self.current_counterparty_commitment_number = commitment_number;
1752 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1753 match self.their_cur_revocation_points {
1754 Some(old_points) => {
1755 if old_points.0 == commitment_number + 1 {
1756 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1757 } else if old_points.0 == commitment_number + 2 {
1758 if let Some(old_second_point) = old_points.2 {
1759 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1761 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1764 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1768 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1771 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1772 for htlc in htlc_outputs {
1773 if htlc.0.transaction_output_index.is_some() {
1779 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1780 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1781 /// is important that any clones of this channel monitor (including remote clones) by kept
1782 /// up-to-date as our holder commitment transaction is updated.
1783 /// Panics if set_on_holder_tx_csv has never been called.
1784 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1785 // block for Rust 1.34 compat
1786 let mut new_holder_commitment_tx = {
1787 let trusted_tx = holder_commitment_tx.trust();
1788 let txid = trusted_tx.txid();
1789 let tx_keys = trusted_tx.keys();
1790 self.current_holder_commitment_number = trusted_tx.commitment_number();
1793 revocation_key: tx_keys.revocation_key,
1794 a_htlc_key: tx_keys.broadcaster_htlc_key,
1795 b_htlc_key: tx_keys.countersignatory_htlc_key,
1796 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1797 per_commitment_point: tx_keys.per_commitment_point,
1799 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1800 feerate_per_kw: trusted_tx.feerate_per_kw(),
1803 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1804 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1805 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1806 if self.holder_tx_signed {
1807 return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1812 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1813 /// commitment_tx_infos which contain the payment hash have been revoked.
1814 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &F, logger: &L)
1815 where B::Target: BroadcasterInterface,
1816 F::Target: FeeEstimator,
1819 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1821 // If the channel is force closed, try to claim the output from this preimage.
1822 // First check if a counterparty commitment transaction has been broadcasted:
1823 macro_rules! claim_htlcs {
1824 ($commitment_number: expr, $txid: expr) => {
1825 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1826 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1829 if let Some(txid) = self.current_counterparty_commitment_txid {
1830 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1831 claim_htlcs!(*commitment_number, txid);
1835 if let Some(txid) = self.prev_counterparty_commitment_txid {
1836 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1837 claim_htlcs!(*commitment_number, txid);
1842 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1843 // claiming the HTLC output from each of the holder commitment transactions.
1844 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1845 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1846 // holder commitment transactions.
1847 if self.broadcasted_holder_revokable_script.is_some() {
1848 // Assume that the broadcasted commitment transaction confirmed in the current best
1849 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1851 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1852 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1853 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1854 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1855 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1860 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1861 where B::Target: BroadcasterInterface,
1864 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1865 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1866 broadcaster.broadcast_transaction(tx);
1868 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
1871 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
1872 where B::Target: BroadcasterInterface,
1873 F::Target: FeeEstimator,
1876 // ChannelMonitor updates may be applied after force close if we receive a
1877 // preimage for a broadcasted commitment transaction HTLC output that we'd
1878 // like to claim on-chain. If this is the case, we no longer have guaranteed
1879 // access to the monitor's update ID, so we use a sentinel value instead.
1880 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1881 match updates.updates[0] {
1882 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1883 _ => panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage"),
1885 assert_eq!(updates.updates.len(), 1);
1886 } else if self.latest_update_id + 1 != updates.update_id {
1887 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1889 for update in updates.updates.iter() {
1891 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1892 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1893 if self.lockdown_from_offchain { panic!(); }
1894 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
1896 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1897 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1898 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1900 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1901 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1902 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1904 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1905 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1906 self.provide_secret(*idx, *secret)?
1908 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1909 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1910 self.lockdown_from_offchain = true;
1911 if *should_broadcast {
1912 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1913 } else if !self.holder_tx_signed {
1914 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");
1916 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
1917 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1918 // shouldn't print the scary warning above.
1919 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1922 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
1923 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
1924 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
1925 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
1930 self.latest_update_id = updates.update_id;
1934 pub fn get_latest_update_id(&self) -> u64 {
1935 self.latest_update_id
1938 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1942 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1943 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1944 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1945 // its trivial to do, double-check that here.
1946 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1947 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1949 &self.outputs_to_watch
1952 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1953 let mut ret = Vec::new();
1954 mem::swap(&mut ret, &mut self.pending_monitor_events);
1958 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1959 let mut ret = Vec::new();
1960 mem::swap(&mut ret, &mut self.pending_events);
1964 /// Can only fail if idx is < get_min_seen_secret
1965 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1966 self.commitment_secrets.get_secret(idx)
1969 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1970 self.commitment_secrets.get_min_seen_secret()
1973 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1974 self.current_counterparty_commitment_number
1977 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1978 self.current_holder_commitment_number
1981 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1982 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1983 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1984 /// HTLC-Success/HTLC-Timeout transactions.
1985 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1986 /// revoked counterparty commitment tx
1987 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1988 // Most secp and related errors trying to create keys means we have no hope of constructing
1989 // a spend transaction...so we return no transactions to broadcast
1990 let mut claimable_outpoints = Vec::new();
1991 let mut watch_outputs = Vec::new();
1993 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1994 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1996 macro_rules! ignore_error {
1997 ( $thing : expr ) => {
2000 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
2005 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);
2006 if commitment_number >= self.get_min_seen_secret() {
2007 let secret = self.get_secret(commitment_number).unwrap();
2008 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2009 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2010 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2011 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));
2013 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2014 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2016 // First, process non-htlc outputs (to_holder & to_counterparty)
2017 for (idx, outp) in tx.output.iter().enumerate() {
2018 if outp.script_pubkey == revokeable_p2wsh {
2019 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);
2020 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);
2021 claimable_outpoints.push(justice_package);
2025 // Then, try to find revoked htlc outputs
2026 if let Some(ref per_commitment_data) = per_commitment_option {
2027 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2028 if let Some(transaction_output_index) = htlc.transaction_output_index {
2029 if transaction_output_index as usize >= tx.output.len() ||
2030 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2031 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
2033 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());
2034 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2035 claimable_outpoints.push(justice_package);
2040 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2041 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2042 // We're definitely a counterparty commitment transaction!
2043 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2044 for (idx, outp) in tx.output.iter().enumerate() {
2045 watch_outputs.push((idx as u32, outp.clone()));
2047 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2049 fail_unbroadcast_htlcs!(self, "revoked counterparty", height, [].iter().map(|a| *a), logger);
2051 } else if let Some(per_commitment_data) = per_commitment_option {
2052 // While this isn't useful yet, there is a potential race where if a counterparty
2053 // revokes a state at the same time as the commitment transaction for that state is
2054 // confirmed, and the watchtower receives the block before the user, the user could
2055 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2056 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2057 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2059 for (idx, outp) in tx.output.iter().enumerate() {
2060 watch_outputs.push((idx as u32, outp.clone()));
2062 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2064 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2065 fail_unbroadcast_htlcs!(self, "counterparty", height, per_commitment_data.iter().map(|(a, b)| (a, b.as_ref().map(|b| b.as_ref()))), logger);
2067 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
2068 for req in htlc_claim_reqs {
2069 claimable_outpoints.push(req);
2073 (claimable_outpoints, (commitment_txid, watch_outputs))
2076 fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
2077 let mut claimable_outpoints = Vec::new();
2078 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
2079 if let Some(revocation_points) = self.their_cur_revocation_points {
2080 let revocation_point_option =
2081 // If the counterparty commitment tx is the latest valid state, use their latest
2082 // per-commitment point
2083 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
2084 else if let Some(point) = revocation_points.2.as_ref() {
2085 // If counterparty commitment tx is the state previous to the latest valid state, use
2086 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2087 // them to temporarily have two valid commitment txns from our viewpoint)
2088 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
2090 if let Some(revocation_point) = revocation_point_option {
2091 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2092 if let Some(transaction_output_index) = htlc.transaction_output_index {
2093 if let Some(transaction) = tx {
2094 if transaction_output_index as usize >= transaction.output.len() ||
2095 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2096 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
2099 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2100 if preimage.is_some() || !htlc.offered {
2101 let counterparty_htlc_outp = if htlc.offered { PackageSolvingData::CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput::build(*revocation_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, preimage.unwrap(), htlc.clone())) } else { PackageSolvingData::CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput::build(*revocation_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, htlc.clone())) };
2102 let aggregation = if !htlc.offered { false } else { true };
2103 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2104 claimable_outpoints.push(counterparty_package);
2114 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2115 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 {
2116 let htlc_txid = tx.txid();
2117 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2118 return (Vec::new(), None)
2121 macro_rules! ignore_error {
2122 ( $thing : expr ) => {
2125 Err(_) => return (Vec::new(), None)
2130 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2131 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2132 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2134 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2135 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);
2136 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);
2137 let claimable_outpoints = vec!(justice_package);
2138 let outputs = vec![(0, tx.output[0].clone())];
2139 (claimable_outpoints, Some((htlc_txid, outputs)))
2142 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2143 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2144 // script so we can detect whether a holder transaction has been seen on-chain.
2145 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2146 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2148 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2149 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2151 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2152 if let Some(transaction_output_index) = htlc.transaction_output_index {
2153 let htlc_output = if htlc.offered {
2154 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2156 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2159 // We can't build an HTLC-Success transaction without the preimage
2162 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2164 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2165 claim_requests.push(htlc_package);
2169 (claim_requests, broadcasted_holder_revokable_script)
2172 // Returns holder HTLC outputs to watch and react to in case of spending.
2173 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2174 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2175 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2176 if let Some(transaction_output_index) = htlc.transaction_output_index {
2177 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2183 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2184 /// revoked using data in holder_claimable_outpoints.
2185 /// Should not be used if check_spend_revoked_transaction succeeds.
2186 /// Returns None unless the transaction is definitely one of our commitment transactions.
2187 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2188 let commitment_txid = tx.txid();
2189 let mut claim_requests = Vec::new();
2190 let mut watch_outputs = Vec::new();
2192 macro_rules! append_onchain_update {
2193 ($updates: expr, $to_watch: expr) => {
2194 claim_requests = $updates.0;
2195 self.broadcasted_holder_revokable_script = $updates.1;
2196 watch_outputs.append(&mut $to_watch);
2200 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2201 let mut is_holder_tx = false;
2203 if self.current_holder_commitment_tx.txid == commitment_txid {
2204 is_holder_tx = true;
2205 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2206 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2207 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2208 append_onchain_update!(res, to_watch);
2209 fail_unbroadcast_htlcs!(self, "latest holder", height, self.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2210 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2211 if holder_tx.txid == commitment_txid {
2212 is_holder_tx = true;
2213 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2214 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2215 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2216 append_onchain_update!(res, to_watch);
2217 fail_unbroadcast_htlcs!(self, "previous holder", height, holder_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
2222 Some((claim_requests, (commitment_txid, watch_outputs)))
2228 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2229 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2230 self.holder_tx_signed = true;
2231 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2232 let txid = commitment_tx.txid();
2233 let mut holder_transactions = vec![commitment_tx];
2234 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2235 if let Some(vout) = htlc.0.transaction_output_index {
2236 let preimage = if !htlc.0.offered {
2237 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2238 // We can't build an HTLC-Success transaction without the preimage
2241 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2242 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2243 // current locktime requirements on-chain. We will broadcast them in
2244 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2245 // Note that we add + 1 as transactions are broadcastable when they can be
2246 // confirmed in the next block.
2249 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2250 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2251 holder_transactions.push(htlc_tx);
2255 // 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.
2256 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2260 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2261 /// Note that this includes possibly-locktimed-in-the-future transactions!
2262 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2263 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2264 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2265 let txid = commitment_tx.txid();
2266 let mut holder_transactions = vec![commitment_tx];
2267 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2268 if let Some(vout) = htlc.0.transaction_output_index {
2269 let preimage = if !htlc.0.offered {
2270 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2271 // We can't build an HTLC-Success transaction without the preimage
2275 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2276 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2277 holder_transactions.push(htlc_tx);
2284 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>
2285 where B::Target: BroadcasterInterface,
2286 F::Target: FeeEstimator,
2289 let block_hash = header.block_hash();
2290 self.best_block = BestBlock::new(block_hash, height);
2292 self.transactions_confirmed(header, txdata, height, broadcaster, fee_estimator, logger)
2295 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2297 header: &BlockHeader,
2302 ) -> Vec<TransactionOutputs>
2304 B::Target: BroadcasterInterface,
2305 F::Target: FeeEstimator,
2308 let block_hash = header.block_hash();
2310 if height > self.best_block.height() {
2311 self.best_block = BestBlock::new(block_hash, height);
2312 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2313 } else if block_hash != self.best_block.block_hash() {
2314 self.best_block = BestBlock::new(block_hash, height);
2315 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2316 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2318 } else { Vec::new() }
2321 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2323 header: &BlockHeader,
2324 txdata: &TransactionData,
2329 ) -> Vec<TransactionOutputs>
2331 B::Target: BroadcasterInterface,
2332 F::Target: FeeEstimator,
2335 let txn_matched = self.filter_block(txdata);
2336 for tx in &txn_matched {
2337 let mut output_val = 0;
2338 for out in tx.output.iter() {
2339 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2340 output_val += out.value;
2341 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2345 let block_hash = header.block_hash();
2347 let mut watch_outputs = Vec::new();
2348 let mut claimable_outpoints = Vec::new();
2349 for tx in &txn_matched {
2350 if tx.input.len() == 1 {
2351 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2352 // commitment transactions and HTLC transactions will all only ever have one input,
2353 // which is an easy way to filter out any potential non-matching txn for lazy
2355 let prevout = &tx.input[0].previous_output;
2356 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2357 let mut balance_spendable_csv = None;
2358 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2359 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2360 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2361 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2362 if !new_outputs.1.is_empty() {
2363 watch_outputs.push(new_outputs);
2365 claimable_outpoints.append(&mut new_outpoints);
2366 if new_outpoints.is_empty() {
2367 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2368 if !new_outputs.1.is_empty() {
2369 watch_outputs.push(new_outputs);
2371 claimable_outpoints.append(&mut new_outpoints);
2372 balance_spendable_csv = Some(self.on_holder_tx_csv);
2376 let txid = tx.txid();
2377 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2380 event: OnchainEvent::FundingSpendConfirmation {
2381 on_local_output_csv: balance_spendable_csv,
2385 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2386 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2387 claimable_outpoints.append(&mut new_outpoints);
2388 if let Some(new_outputs) = new_outputs_option {
2389 watch_outputs.push(new_outputs);
2394 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2395 // can also be resolved in a few other ways which can have more than one output. Thus,
2396 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2397 self.is_resolving_htlc_output(&tx, height, &logger);
2399 self.is_paying_spendable_output(&tx, height, &logger);
2402 if height > self.best_block.height() {
2403 self.best_block = BestBlock::new(block_hash, height);
2406 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2409 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2410 /// `self.best_block` before calling if a new best blockchain tip is available. More
2411 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2412 /// complexity especially in `OnchainTx::update_claims_view`.
2414 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2415 /// confirmed at, even if it is not the current best height.
2416 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2419 txn_matched: Vec<&Transaction>,
2420 mut watch_outputs: Vec<TransactionOutputs>,
2421 mut claimable_outpoints: Vec<PackageTemplate>,
2425 ) -> Vec<TransactionOutputs>
2427 B::Target: BroadcasterInterface,
2428 F::Target: FeeEstimator,
2431 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2432 debug_assert!(self.best_block.height() >= conf_height);
2434 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2435 if should_broadcast {
2436 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2437 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());
2438 claimable_outpoints.push(commitment_package);
2439 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2440 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2441 self.holder_tx_signed = true;
2442 // Because we're broadcasting a commitment transaction, we should construct the package
2443 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2444 // "not yet confirmed" things as discardable, so we cannot do that here.
2445 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2446 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2447 if !new_outputs.is_empty() {
2448 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2450 claimable_outpoints.append(&mut new_outpoints);
2453 // Find which on-chain events have reached their confirmation threshold.
2454 let onchain_events_awaiting_threshold_conf =
2455 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2456 let mut onchain_events_reaching_threshold_conf = Vec::new();
2457 for entry in onchain_events_awaiting_threshold_conf {
2458 if entry.has_reached_confirmation_threshold(&self.best_block) {
2459 onchain_events_reaching_threshold_conf.push(entry);
2461 self.onchain_events_awaiting_threshold_conf.push(entry);
2465 // Used to check for duplicate HTLC resolutions.
2466 #[cfg(debug_assertions)]
2467 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2469 .filter_map(|entry| match &entry.event {
2470 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2474 #[cfg(debug_assertions)]
2475 let mut matured_htlcs = Vec::new();
2477 // Produce actionable events from on-chain events having reached their threshold.
2478 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2480 OnchainEvent::HTLCUpdate { ref source, payment_hash, onchain_value_satoshis, input_idx } => {
2481 // Check for duplicate HTLC resolutions.
2482 #[cfg(debug_assertions)]
2485 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2486 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2487 call either transaction_unconfirmed for the conflicting transaction \
2488 or block_disconnected for a block containing it.");
2490 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2491 "A matured HTLC transaction conflicts with a maturing one; failed to \
2492 call either transaction_unconfirmed for the conflicting transaction \
2493 or block_disconnected for a block containing it.");
2494 matured_htlcs.push(source.clone());
2497 log_debug!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!(payment_hash.0));
2498 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2500 payment_preimage: None,
2501 source: source.clone(),
2502 onchain_value_satoshis,
2504 if let Some(idx) = input_idx {
2505 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx: idx, payment_preimage: None });
2508 OnchainEvent::MaturingOutput { descriptor } => {
2509 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2510 self.pending_events.push(Event::SpendableOutputs {
2511 outputs: vec![descriptor]
2514 OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } => {
2515 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx, payment_preimage: preimage });
2517 OnchainEvent::FundingSpendConfirmation { .. } => {
2518 self.funding_spend_confirmed = Some(entry.txid);
2523 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2525 // Determine new outputs to watch by comparing against previously known outputs to watch,
2526 // updating the latter in the process.
2527 watch_outputs.retain(|&(ref txid, ref txouts)| {
2528 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2529 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2533 // If we see a transaction for which we registered outputs previously,
2534 // make sure the registered scriptpubkey at the expected index match
2535 // the actual transaction output one. We failed this case before #653.
2536 for tx in &txn_matched {
2537 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2538 for idx_and_script in outputs.iter() {
2539 assert!((idx_and_script.0 as usize) < tx.output.len());
2540 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2548 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2549 where B::Target: BroadcasterInterface,
2550 F::Target: FeeEstimator,
2553 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2556 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2557 //- maturing spendable output has transaction paying us has been disconnected
2558 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2560 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2562 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2565 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2572 B::Target: BroadcasterInterface,
2573 F::Target: FeeEstimator,
2576 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.txid != *txid);
2577 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2580 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2581 /// transactions thereof.
2582 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2583 let mut matched_txn = HashSet::new();
2584 txdata.iter().filter(|&&(_, tx)| {
2585 let mut matches = self.spends_watched_output(tx);
2586 for input in tx.input.iter() {
2587 if matches { break; }
2588 if matched_txn.contains(&input.previous_output.txid) {
2593 matched_txn.insert(tx.txid());
2596 }).map(|(_, tx)| *tx).collect()
2599 /// Checks if a given transaction spends any watched outputs.
2600 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2601 for input in tx.input.iter() {
2602 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2603 for (idx, _script_pubkey) in outputs.iter() {
2604 if *idx == input.previous_output.vout {
2607 // If the expected script is a known type, check that the witness
2608 // appears to be spending the correct type (ie that the match would
2609 // actually succeed in BIP 158/159-style filters).
2610 if _script_pubkey.is_v0_p2wsh() {
2611 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2612 } else if _script_pubkey.is_v0_p2wpkh() {
2613 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2614 } else { panic!(); }
2625 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2626 // We need to consider all HTLCs which are:
2627 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2628 // transactions and we'd end up in a race, or
2629 // * are in our latest holder commitment transaction, as this is the thing we will
2630 // broadcast if we go on-chain.
2631 // Note that we consider HTLCs which were below dust threshold here - while they don't
2632 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2633 // to the source, and if we don't fail the channel we will have to ensure that the next
2634 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2635 // easier to just fail the channel as this case should be rare enough anyway.
2636 let height = self.best_block.height();
2637 macro_rules! scan_commitment {
2638 ($htlcs: expr, $holder_tx: expr) => {
2639 for ref htlc in $htlcs {
2640 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2641 // chain with enough room to claim the HTLC without our counterparty being able to
2642 // time out the HTLC first.
2643 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2644 // concern is being able to claim the corresponding inbound HTLC (on another
2645 // channel) before it expires. In fact, we don't even really care if our
2646 // counterparty here claims such an outbound HTLC after it expired as long as we
2647 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2648 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2649 // we give ourselves a few blocks of headroom after expiration before going
2650 // on-chain for an expired HTLC.
2651 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2652 // from us until we've reached the point where we go on-chain with the
2653 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2654 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2655 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2656 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2657 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2658 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2659 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2660 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2661 // The final, above, condition is checked for statically in channelmanager
2662 // with CHECK_CLTV_EXPIRY_SANITY_2.
2663 let htlc_outbound = $holder_tx == htlc.offered;
2664 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2665 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2666 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2673 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2675 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2676 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2677 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2680 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2681 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2682 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2689 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2690 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2691 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2692 'outer_loop: for input in &tx.input {
2693 let mut payment_data = None;
2694 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2695 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2696 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2697 #[cfg(not(fuzzing))]
2698 let accepted_timeout_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2699 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && !revocation_sig_claim;
2700 #[cfg(not(fuzzing))]
2701 let offered_timeout_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::OfferedHTLC);
2703 let mut payment_preimage = PaymentPreimage([0; 32]);
2704 if accepted_preimage_claim {
2705 payment_preimage.0.copy_from_slice(&input.witness[3]);
2706 } else if offered_preimage_claim {
2707 payment_preimage.0.copy_from_slice(&input.witness[1]);
2710 macro_rules! log_claim {
2711 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2712 let outbound_htlc = $holder_tx == $htlc.offered;
2713 // HTLCs must either be claimed by a matching script type or through the
2715 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2716 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2717 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2718 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2719 // Further, only exactly one of the possible spend paths should have been
2720 // matched by any HTLC spend:
2721 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2722 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2723 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2724 revocation_sig_claim as u8, 1);
2725 if ($holder_tx && revocation_sig_claim) ||
2726 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2727 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2728 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2729 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2730 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2732 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2733 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2734 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2735 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2740 macro_rules! check_htlc_valid_counterparty {
2741 ($counterparty_txid: expr, $htlc_output: expr) => {
2742 if let Some(txid) = $counterparty_txid {
2743 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2744 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2745 if let &Some(ref source) = pending_source {
2746 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2747 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2756 macro_rules! scan_commitment {
2757 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2758 for (ref htlc_output, source_option) in $htlcs {
2759 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2760 if let Some(ref source) = source_option {
2761 log_claim!($tx_info, $holder_tx, htlc_output, true);
2762 // We have a resolution of an HTLC either from one of our latest
2763 // holder commitment transactions or an unrevoked counterparty commitment
2764 // transaction. This implies we either learned a preimage, the HTLC
2765 // has timed out, or we screwed up. In any case, we should now
2766 // resolve the source HTLC with the original sender.
2767 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2768 } else if !$holder_tx {
2769 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2770 if payment_data.is_none() {
2771 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2774 if payment_data.is_none() {
2775 log_claim!($tx_info, $holder_tx, htlc_output, false);
2776 let outbound_htlc = $holder_tx == htlc_output.offered;
2777 if !outbound_htlc || revocation_sig_claim {
2778 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2779 txid: tx.txid(), height,
2780 event: OnchainEvent::HTLCSpendConfirmation {
2781 input_idx: input.previous_output.vout,
2782 preimage: if accepted_preimage_claim || offered_preimage_claim {
2783 Some(payment_preimage) } else { None },
2784 // If this is a payment to us (!outbound_htlc, above),
2785 // wait for the CSV delay before dropping the HTLC from
2786 // claimable balance if the claim was an HTLC-Success
2788 on_to_local_output_csv: if accepted_preimage_claim {
2789 Some(self.on_holder_tx_csv) } else { None },
2793 // Outbound claims should always have payment_data, unless
2794 // we've already failed the HTLC as the commitment transaction
2795 // which was broadcasted was revoked. In that case, we should
2796 // spend the HTLC output here immediately, and expose that fact
2797 // as a Balance, something which we do not yet do.
2798 // TODO: Track the above as claimable!
2800 continue 'outer_loop;
2807 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2808 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2809 "our latest holder commitment tx", true);
2811 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2812 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2813 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2814 "our previous holder commitment tx", true);
2817 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2818 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2819 "counterparty commitment tx", false);
2822 // Check that scan_commitment, above, decided there is some source worth relaying an
2823 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2824 if let Some((source, payment_hash, amount_msat)) = payment_data {
2825 if accepted_preimage_claim {
2826 if !self.pending_monitor_events.iter().any(
2827 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2828 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2831 event: OnchainEvent::HTLCSpendConfirmation {
2832 input_idx: input.previous_output.vout,
2833 preimage: Some(payment_preimage),
2834 on_to_local_output_csv: None,
2837 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2839 payment_preimage: Some(payment_preimage),
2841 onchain_value_satoshis: Some(amount_msat / 1000),
2844 } else if offered_preimage_claim {
2845 if !self.pending_monitor_events.iter().any(
2846 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2847 upd.source == source
2849 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2852 event: OnchainEvent::HTLCSpendConfirmation {
2853 input_idx: input.previous_output.vout,
2854 preimage: Some(payment_preimage),
2855 on_to_local_output_csv: None,
2858 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2860 payment_preimage: Some(payment_preimage),
2862 onchain_value_satoshis: Some(amount_msat / 1000),
2866 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2867 if entry.height != height { return true; }
2869 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
2870 *htlc_source != source
2875 let entry = OnchainEventEntry {
2878 event: OnchainEvent::HTLCUpdate {
2879 source, payment_hash,
2880 onchain_value_satoshis: Some(amount_msat / 1000),
2881 input_idx: Some(input.previous_output.vout),
2884 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());
2885 self.onchain_events_awaiting_threshold_conf.push(entry);
2891 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2892 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2893 let mut spendable_output = None;
2894 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2895 if i > ::core::u16::MAX as usize {
2896 // While it is possible that an output exists on chain which is greater than the
2897 // 2^16th output in a given transaction, this is only possible if the output is not
2898 // in a lightning transaction and was instead placed there by some third party who
2899 // wishes to give us money for no reason.
2900 // Namely, any lightning transactions which we pre-sign will never have anywhere
2901 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2902 // scripts are not longer than one byte in length and because they are inherently
2903 // non-standard due to their size.
2904 // Thus, it is completely safe to ignore such outputs, and while it may result in
2905 // us ignoring non-lightning fund to us, that is only possible if someone fills
2906 // nearly a full block with garbage just to hit this case.
2909 if outp.script_pubkey == self.destination_script {
2910 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2911 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2912 output: outp.clone(),
2916 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2917 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2918 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2919 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2920 per_commitment_point: broadcasted_holder_revokable_script.1,
2921 to_self_delay: self.on_holder_tx_csv,
2922 output: outp.clone(),
2923 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2924 channel_keys_id: self.channel_keys_id,
2925 channel_value_satoshis: self.channel_value_satoshis,
2930 if self.counterparty_payment_script == outp.script_pubkey {
2931 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2932 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2933 output: outp.clone(),
2934 channel_keys_id: self.channel_keys_id,
2935 channel_value_satoshis: self.channel_value_satoshis,
2939 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
2940 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2941 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2942 output: outp.clone(),
2947 if let Some(spendable_output) = spendable_output {
2948 let entry = OnchainEventEntry {
2951 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2953 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2954 self.onchain_events_awaiting_threshold_conf.push(entry);
2959 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2961 T::Target: BroadcasterInterface,
2962 F::Target: FeeEstimator,
2965 fn block_connected(&self, block: &Block, height: u32) {
2966 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2967 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2970 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2971 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2975 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
2977 T::Target: BroadcasterInterface,
2978 F::Target: FeeEstimator,
2981 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
2982 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
2985 fn transaction_unconfirmed(&self, txid: &Txid) {
2986 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
2989 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
2990 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
2993 fn get_relevant_txids(&self) -> Vec<Txid> {
2994 self.0.get_relevant_txids()
2998 const MAX_ALLOC_SIZE: usize = 64*1024;
3000 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3001 for (BlockHash, ChannelMonitor<Signer>) {
3002 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3003 macro_rules! unwrap_obj {
3007 Err(_) => return Err(DecodeError::InvalidValue),
3012 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3014 let latest_update_id: u64 = Readable::read(reader)?;
3015 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3017 let destination_script = Readable::read(reader)?;
3018 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3020 let revokable_address = Readable::read(reader)?;
3021 let per_commitment_point = Readable::read(reader)?;
3022 let revokable_script = Readable::read(reader)?;
3023 Some((revokable_address, per_commitment_point, revokable_script))
3026 _ => return Err(DecodeError::InvalidValue),
3028 let counterparty_payment_script = Readable::read(reader)?;
3029 let shutdown_script = {
3030 let script = <Script as Readable>::read(reader)?;
3031 if script.is_empty() { None } else { Some(script) }
3034 let channel_keys_id = Readable::read(reader)?;
3035 let holder_revocation_basepoint = Readable::read(reader)?;
3036 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3037 // barely-init'd ChannelMonitors that we can't do anything with.
3038 let outpoint = OutPoint {
3039 txid: Readable::read(reader)?,
3040 index: Readable::read(reader)?,
3042 let funding_info = (outpoint, Readable::read(reader)?);
3043 let current_counterparty_commitment_txid = Readable::read(reader)?;
3044 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3046 let counterparty_commitment_params = Readable::read(reader)?;
3047 let funding_redeemscript = Readable::read(reader)?;
3048 let channel_value_satoshis = Readable::read(reader)?;
3050 let their_cur_revocation_points = {
3051 let first_idx = <U48 as Readable>::read(reader)?.0;
3055 let first_point = Readable::read(reader)?;
3056 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3057 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3058 Some((first_idx, first_point, None))
3060 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3065 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3067 let commitment_secrets = Readable::read(reader)?;
3069 macro_rules! read_htlc_in_commitment {
3072 let offered: bool = Readable::read(reader)?;
3073 let amount_msat: u64 = Readable::read(reader)?;
3074 let cltv_expiry: u32 = Readable::read(reader)?;
3075 let payment_hash: PaymentHash = Readable::read(reader)?;
3076 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3078 HTLCOutputInCommitment {
3079 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3085 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3086 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3087 for _ in 0..counterparty_claimable_outpoints_len {
3088 let txid: Txid = Readable::read(reader)?;
3089 let htlcs_count: u64 = Readable::read(reader)?;
3090 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3091 for _ in 0..htlcs_count {
3092 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3094 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3095 return Err(DecodeError::InvalidValue);
3099 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3100 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3101 for _ in 0..counterparty_commitment_txn_on_chain_len {
3102 let txid: Txid = Readable::read(reader)?;
3103 let commitment_number = <U48 as Readable>::read(reader)?.0;
3104 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3105 return Err(DecodeError::InvalidValue);
3109 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3110 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3111 for _ in 0..counterparty_hash_commitment_number_len {
3112 let payment_hash: PaymentHash = Readable::read(reader)?;
3113 let commitment_number = <U48 as Readable>::read(reader)?.0;
3114 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3115 return Err(DecodeError::InvalidValue);
3119 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3120 match <u8 as Readable>::read(reader)? {
3123 Some(Readable::read(reader)?)
3125 _ => return Err(DecodeError::InvalidValue),
3127 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3129 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3130 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3132 let payment_preimages_len: u64 = Readable::read(reader)?;
3133 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3134 for _ in 0..payment_preimages_len {
3135 let preimage: PaymentPreimage = Readable::read(reader)?;
3136 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3137 if let Some(_) = payment_preimages.insert(hash, preimage) {
3138 return Err(DecodeError::InvalidValue);
3142 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3143 let mut pending_monitor_events = Some(
3144 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3145 for _ in 0..pending_monitor_events_len {
3146 let ev = match <u8 as Readable>::read(reader)? {
3147 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3148 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3149 _ => return Err(DecodeError::InvalidValue)
3151 pending_monitor_events.as_mut().unwrap().push(ev);
3154 let pending_events_len: u64 = Readable::read(reader)?;
3155 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3156 for _ in 0..pending_events_len {
3157 if let Some(event) = MaybeReadable::read(reader)? {
3158 pending_events.push(event);
3162 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3164 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3165 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3166 for _ in 0..waiting_threshold_conf_len {
3167 if let Some(val) = MaybeReadable::read(reader)? {
3168 onchain_events_awaiting_threshold_conf.push(val);
3172 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3173 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>>())));
3174 for _ in 0..outputs_to_watch_len {
3175 let txid = Readable::read(reader)?;
3176 let outputs_len: u64 = Readable::read(reader)?;
3177 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3178 for _ in 0..outputs_len {
3179 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3181 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3182 return Err(DecodeError::InvalidValue);
3185 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3187 let lockdown_from_offchain = Readable::read(reader)?;
3188 let holder_tx_signed = Readable::read(reader)?;
3190 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3191 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3192 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3193 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3194 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3195 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3196 return Err(DecodeError::InvalidValue);
3200 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3201 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3202 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3203 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3204 return Err(DecodeError::InvalidValue);
3207 let mut funding_spend_confirmed = None;
3208 let mut htlcs_resolved_on_chain = Some(Vec::new());
3209 read_tlv_fields!(reader, {
3210 (1, funding_spend_confirmed, option),
3211 (3, htlcs_resolved_on_chain, vec_type),
3212 (5, pending_monitor_events, vec_type),
3215 let mut secp_ctx = Secp256k1::new();
3216 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3218 Ok((best_block.block_hash(), ChannelMonitor {
3219 inner: Mutex::new(ChannelMonitorImpl {
3221 commitment_transaction_number_obscure_factor,
3224 broadcasted_holder_revokable_script,
3225 counterparty_payment_script,
3229 holder_revocation_basepoint,
3231 current_counterparty_commitment_txid,
3232 prev_counterparty_commitment_txid,
3234 counterparty_commitment_params,
3235 funding_redeemscript,
3236 channel_value_satoshis,
3237 their_cur_revocation_points,
3242 counterparty_claimable_outpoints,
3243 counterparty_commitment_txn_on_chain,
3244 counterparty_hash_commitment_number,
3246 prev_holder_signed_commitment_tx,
3247 current_holder_commitment_tx,
3248 current_counterparty_commitment_number,
3249 current_holder_commitment_number,
3252 pending_monitor_events: pending_monitor_events.unwrap(),
3255 onchain_events_awaiting_threshold_conf,
3260 lockdown_from_offchain,
3262 funding_spend_confirmed,
3263 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3275 use bitcoin::blockdata::script::{Script, Builder};
3276 use bitcoin::blockdata::opcodes;
3277 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3278 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3279 use bitcoin::util::bip143;
3280 use bitcoin::hashes::Hash;
3281 use bitcoin::hashes::sha256::Hash as Sha256;
3282 use bitcoin::hashes::hex::FromHex;
3283 use bitcoin::hash_types::Txid;
3284 use bitcoin::network::constants::Network;
3286 use chain::BestBlock;
3287 use chain::channelmonitor::ChannelMonitor;
3288 use chain::package::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
3289 use chain::transaction::OutPoint;
3290 use ln::{PaymentPreimage, PaymentHash};
3292 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3293 use ln::script::ShutdownScript;
3294 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3295 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
3296 use bitcoin::secp256k1::Secp256k1;
3297 use sync::{Arc, Mutex};
3298 use chain::keysinterface::InMemorySigner;
3302 fn test_prune_preimages() {
3303 let secp_ctx = Secp256k1::new();
3304 let logger = Arc::new(TestLogger::new());
3305 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3306 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: Mutex::new(253) });
3308 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3309 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3311 let mut preimages = Vec::new();
3314 let preimage = PaymentPreimage([i; 32]);
3315 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3316 preimages.push((preimage, hash));
3320 macro_rules! preimages_slice_to_htlc_outputs {
3321 ($preimages_slice: expr) => {
3323 let mut res = Vec::new();
3324 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3325 res.push((HTLCOutputInCommitment {
3329 payment_hash: preimage.1.clone(),
3330 transaction_output_index: Some(idx as u32),
3337 macro_rules! preimages_to_holder_htlcs {
3338 ($preimages_slice: expr) => {
3340 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3341 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3347 macro_rules! test_preimages_exist {
3348 ($preimages_slice: expr, $monitor: expr) => {
3349 for preimage in $preimages_slice {
3350 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3355 let keys = InMemorySigner::new(
3357 SecretKey::from_slice(&[41; 32]).unwrap(),
3358 SecretKey::from_slice(&[41; 32]).unwrap(),
3359 SecretKey::from_slice(&[41; 32]).unwrap(),
3360 SecretKey::from_slice(&[41; 32]).unwrap(),
3361 SecretKey::from_slice(&[41; 32]).unwrap(),
3367 let counterparty_pubkeys = ChannelPublicKeys {
3368 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3369 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3370 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3371 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3372 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3374 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
3375 let channel_parameters = ChannelTransactionParameters {
3376 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3377 holder_selected_contest_delay: 66,
3378 is_outbound_from_holder: true,
3379 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3380 pubkeys: counterparty_pubkeys,
3381 selected_contest_delay: 67,
3383 funding_outpoint: Some(funding_outpoint),
3386 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3388 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3389 let best_block = BestBlock::from_genesis(Network::Testnet);
3390 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3391 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3392 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3393 &channel_parameters,
3394 Script::new(), 46, 0,
3395 HolderCommitmentTransaction::dummy(), best_block);
3397 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3398 let dummy_txid = dummy_tx.txid();
3399 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3400 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3401 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3402 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3403 for &(ref preimage, ref hash) in preimages.iter() {
3404 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
3407 // Now provide a secret, pruning preimages 10-15
3408 let mut secret = [0; 32];
3409 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3410 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3411 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3412 test_preimages_exist!(&preimages[0..10], monitor);
3413 test_preimages_exist!(&preimages[15..20], monitor);
3415 // Now provide a further secret, pruning preimages 15-17
3416 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3417 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3418 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3419 test_preimages_exist!(&preimages[0..10], monitor);
3420 test_preimages_exist!(&preimages[17..20], monitor);
3422 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3423 // previous commitment tx's preimages too
3424 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3425 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3426 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3427 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3428 test_preimages_exist!(&preimages[0..10], monitor);
3429 test_preimages_exist!(&preimages[18..20], monitor);
3431 // But if we do it again, we'll prune 5-10
3432 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3433 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3434 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3435 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3436 test_preimages_exist!(&preimages[0..5], monitor);
3440 fn test_claim_txn_weight_computation() {
3441 // We test Claim txn weight, knowing that we want expected weigth and
3442 // not actual case to avoid sigs and time-lock delays hell variances.
3444 let secp_ctx = Secp256k1::new();
3445 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3446 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3447 let mut sum_actual_sigs = 0;
3449 macro_rules! sign_input {
3450 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3451 let htlc = HTLCOutputInCommitment {
3452 offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
3454 cltv_expiry: 2 << 16,
3455 payment_hash: PaymentHash([1; 32]),
3456 transaction_output_index: Some($idx as u32),
3458 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) };
3459 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3460 let sig = secp_ctx.sign(&sighash, &privkey);
3461 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3462 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3463 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3464 if *$weight == WEIGHT_REVOKED_OUTPUT {
3465 $sighash_parts.access_witness($idx).push(vec!(1));
3466 } else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
3467 $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3468 } else if *$weight == WEIGHT_RECEIVED_HTLC {
3469 $sighash_parts.access_witness($idx).push(vec![0]);
3471 $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3473 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3474 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3475 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3476 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3480 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3481 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3483 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3484 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3486 claim_tx.input.push(TxIn {
3487 previous_output: BitcoinOutPoint {
3491 script_sig: Script::new(),
3492 sequence: 0xfffffffd,
3493 witness: Vec::new(),
3496 claim_tx.output.push(TxOut {
3497 script_pubkey: script_pubkey.clone(),
3500 let base_weight = claim_tx.get_weight();
3501 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3502 let mut inputs_total_weight = 2; // count segwit flags
3504 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3505 for (idx, inp) in inputs_weight.iter().enumerate() {
3506 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3507 inputs_total_weight += inp;
3510 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3512 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3513 claim_tx.input.clear();
3514 sum_actual_sigs = 0;
3516 claim_tx.input.push(TxIn {
3517 previous_output: BitcoinOutPoint {
3521 script_sig: Script::new(),
3522 sequence: 0xfffffffd,
3523 witness: Vec::new(),
3526 let base_weight = claim_tx.get_weight();
3527 let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3528 let mut inputs_total_weight = 2; // count segwit flags
3530 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3531 for (idx, inp) in inputs_weight.iter().enumerate() {
3532 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3533 inputs_total_weight += inp;
3536 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3538 // Justice tx with 1 revoked HTLC-Success tx output
3539 claim_tx.input.clear();
3540 sum_actual_sigs = 0;
3541 claim_tx.input.push(TxIn {
3542 previous_output: BitcoinOutPoint {
3546 script_sig: Script::new(),
3547 sequence: 0xfffffffd,
3548 witness: Vec::new(),
3550 let base_weight = claim_tx.get_weight();
3551 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3552 let mut inputs_total_weight = 2; // count segwit flags
3554 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3555 for (idx, inp) in inputs_weight.iter().enumerate() {
3556 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, false);
3557 inputs_total_weight += inp;
3560 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3563 // Further testing is done in the ChannelManager integration tests.