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 /// An error enum representing a failure to persist a channel monitor update.
119 #[derive(Clone, Copy, Debug, PartialEq)]
120 pub enum ChannelMonitorUpdateErr {
121 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
122 /// our state failed, but is expected to succeed at some point in the future).
124 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
125 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
126 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
127 /// restore the channel to an operational state.
129 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
130 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
131 /// writing out the latest ChannelManager state.
133 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
134 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
135 /// to claim it on this channel) and those updates must be applied wherever they can be. At
136 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
137 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
138 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
141 /// Note that even if updates made after TemporaryFailure succeed you must still call
142 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
145 /// Note that the update being processed here will not be replayed for you when you call
146 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
147 /// with the persisted ChannelMonitor on your own local disk prior to returning a
148 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
149 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
152 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
153 /// remote location (with local copies persisted immediately), it is anticipated that all
154 /// updates will return TemporaryFailure until the remote copies could be updated.
156 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
157 /// different watchtower and cannot update with all watchtowers that were previously informed
158 /// of this channel).
160 /// At reception of this error, ChannelManager will force-close the channel and return at
161 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
162 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
163 /// update must be rejected.
165 /// This failure may also signal a failure to update the local persisted copy of one of
166 /// the channel monitor instance.
168 /// Note that even when you fail a holder commitment transaction update, you must store the
169 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
170 /// broadcasts it (e.g distributed channel-monitor deployment)
172 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
173 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
174 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
175 /// lagging behind on block processing.
179 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
180 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
181 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
183 /// Contains a developer-readable error message.
184 #[derive(Clone, Debug)]
185 pub struct MonitorUpdateError(pub &'static str);
187 /// An event to be processed by the ChannelManager.
188 #[derive(Clone, PartialEq)]
189 pub enum MonitorEvent {
190 /// A monitor event containing an HTLCUpdate.
191 HTLCEvent(HTLCUpdate),
193 /// A monitor event that the Channel's commitment transaction was broadcasted.
194 CommitmentTxBroadcasted(OutPoint),
197 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
198 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
199 /// preimage claim backward will lead to loss of funds.
200 #[derive(Clone, PartialEq)]
201 pub struct HTLCUpdate {
202 pub(crate) payment_hash: PaymentHash,
203 pub(crate) payment_preimage: Option<PaymentPreimage>,
204 pub(crate) source: HTLCSource,
205 pub(crate) onchain_value_satoshis: Option<u64>,
207 impl_writeable_tlv_based!(HTLCUpdate, {
208 (0, payment_hash, required),
209 (1, onchain_value_satoshis, option),
210 (2, source, required),
211 (4, payment_preimage, option),
214 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
215 /// instead claiming it in its own individual transaction.
216 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
217 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
218 /// HTLC-Success transaction.
219 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
220 /// transaction confirmed (and we use it in a few more, equivalent, places).
221 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
222 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
223 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
224 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
225 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
226 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
227 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
228 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
229 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
230 /// accurate block height.
231 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
232 /// with at worst this delay, so we are not only using this value as a mercy for them but also
233 /// us as a safeguard to delay with enough time.
234 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
235 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
236 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
237 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
238 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
239 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
240 // keep bumping another claim tx to solve the outpoint.
241 pub const ANTI_REORG_DELAY: u32 = 6;
242 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
243 /// refuse to accept a new HTLC.
245 /// This is used for a few separate purposes:
246 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
247 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
249 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
250 /// condition with the above), we will fail this HTLC without telling the user we received it,
251 /// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
252 /// that HTLC expires within this many blocks, we will simply fail the HTLC instead.
254 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
255 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
257 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
258 /// in a race condition between the user connecting a block (which would fail it) and the user
259 /// providing us the preimage (which would claim it).
261 /// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
262 /// end up force-closing the channel on us to claim it.
263 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
265 // TODO(devrandom) replace this with HolderCommitmentTransaction
266 #[derive(Clone, PartialEq)]
267 struct HolderSignedTx {
268 /// txid of the transaction in tx, just used to make comparison faster
270 revocation_key: PublicKey,
271 a_htlc_key: PublicKey,
272 b_htlc_key: PublicKey,
273 delayed_payment_key: PublicKey,
274 per_commitment_point: PublicKey,
275 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
276 to_self_value_sat: u64,
279 impl_writeable_tlv_based!(HolderSignedTx, {
281 // Note that this is filled in with data from OnchainTxHandler if it's missing.
282 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
283 (1, to_self_value_sat, (default_value, u64::max_value())),
284 (2, revocation_key, required),
285 (4, a_htlc_key, required),
286 (6, b_htlc_key, required),
287 (8, delayed_payment_key, required),
288 (10, per_commitment_point, required),
289 (12, feerate_per_kw, required),
290 (14, htlc_outputs, vec_type)
293 /// We use this to track static counterparty commitment transaction data and to generate any
294 /// justice or 2nd-stage preimage/timeout transactions.
296 struct CounterpartyCommitmentParameters {
297 counterparty_delayed_payment_base_key: PublicKey,
298 counterparty_htlc_base_key: PublicKey,
299 on_counterparty_tx_csv: u16,
302 impl Writeable for CounterpartyCommitmentParameters {
303 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
304 w.write_all(&byte_utils::be64_to_array(0))?;
305 write_tlv_fields!(w, {
306 (0, self.counterparty_delayed_payment_base_key, required),
307 (2, self.counterparty_htlc_base_key, required),
308 (4, self.on_counterparty_tx_csv, required),
313 impl Readable for CounterpartyCommitmentParameters {
314 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
315 let counterparty_commitment_transaction = {
316 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
317 // used. Read it for compatibility.
318 let per_htlc_len: u64 = Readable::read(r)?;
319 for _ in 0..per_htlc_len {
320 let _txid: Txid = Readable::read(r)?;
321 let htlcs_count: u64 = Readable::read(r)?;
322 for _ in 0..htlcs_count {
323 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
327 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
328 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
329 let mut on_counterparty_tx_csv: u16 = 0;
330 read_tlv_fields!(r, {
331 (0, counterparty_delayed_payment_base_key, required),
332 (2, counterparty_htlc_base_key, required),
333 (4, on_counterparty_tx_csv, required),
335 CounterpartyCommitmentParameters {
336 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
337 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
338 on_counterparty_tx_csv,
341 Ok(counterparty_commitment_transaction)
345 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
346 /// transaction causing it.
348 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
350 struct OnchainEventEntry {
356 impl OnchainEventEntry {
357 fn confirmation_threshold(&self) -> u32 {
358 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
360 OnchainEvent::MaturingOutput {
361 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
363 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
364 // it's broadcastable when we see the previous block.
365 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
367 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
368 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
369 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
370 // it's broadcastable when we see the previous block.
371 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
378 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
379 best_block.height() >= self.confirmation_threshold()
383 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
384 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
387 /// An outbound HTLC failing after a transaction is confirmed. Used
388 /// * when an outbound HTLC output is spent by us after the HTLC timed out
389 /// * an outbound HTLC which was not present in the commitment transaction which appeared
390 /// on-chain (either because it was not fully committed to or it was dust).
391 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
392 /// appearing only as an `HTLCSpendConfirmation`, below.
395 payment_hash: PaymentHash,
396 onchain_value_satoshis: Option<u64>,
397 /// None in the second case, above, ie when there is no relevant output in the commitment
398 /// transaction which appeared on chain.
399 input_idx: Option<u32>,
402 descriptor: SpendableOutputDescriptor,
404 /// A spend of the funding output, either a commitment transaction or a cooperative closing
406 FundingSpendConfirmation {
407 /// The CSV delay for the output of the funding spend transaction (implying it is a local
408 /// commitment transaction, and this is the delay on the to_self output).
409 on_local_output_csv: Option<u16>,
411 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
412 /// is constructed. This is used when
413 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
414 /// immediately claim the HTLC on the inbound edge and track the resolution here,
415 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
416 /// * an inbound HTLC is claimed by us (with a preimage).
417 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
419 HTLCSpendConfirmation {
421 /// If the claim was made by either party with a preimage, this is filled in
422 preimage: Option<PaymentPreimage>,
423 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
424 /// we set this to the output CSV value which we will have to wait until to spend the
425 /// output (and generate a SpendableOutput event).
426 on_to_local_output_csv: Option<u16>,
430 impl Writeable for OnchainEventEntry {
431 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
432 write_tlv_fields!(writer, {
433 (0, self.txid, required),
434 (2, self.height, required),
435 (4, self.event, required),
441 impl MaybeReadable for OnchainEventEntry {
442 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
443 let mut txid = Default::default();
445 let mut event = None;
446 read_tlv_fields!(reader, {
448 (2, height, required),
449 (4, event, ignorable),
451 if let Some(ev) = event {
452 Ok(Some(Self { txid, height, event: ev }))
459 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
461 (0, source, required),
462 (1, onchain_value_satoshis, option),
463 (2, payment_hash, required),
464 (3, input_idx, option),
466 (1, MaturingOutput) => {
467 (0, descriptor, required),
469 (3, FundingSpendConfirmation) => {
470 (0, on_local_output_csv, option),
472 (5, HTLCSpendConfirmation) => {
473 (0, input_idx, required),
474 (2, preimage, option),
475 (4, on_to_local_output_csv, option),
480 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
482 pub(crate) enum ChannelMonitorUpdateStep {
483 LatestHolderCommitmentTXInfo {
484 commitment_tx: HolderCommitmentTransaction,
485 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
487 LatestCounterpartyCommitmentTXInfo {
488 commitment_txid: Txid,
489 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
490 commitment_number: u64,
491 their_revocation_point: PublicKey,
494 payment_preimage: PaymentPreimage,
500 /// Used to indicate that the no future updates will occur, and likely that the latest holder
501 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
503 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
504 /// think we've fallen behind!
505 should_broadcast: bool,
508 scriptpubkey: Script,
512 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
513 (0, LatestHolderCommitmentTXInfo) => {
514 (0, commitment_tx, required),
515 (2, htlc_outputs, vec_type),
517 (1, LatestCounterpartyCommitmentTXInfo) => {
518 (0, commitment_txid, required),
519 (2, commitment_number, required),
520 (4, their_revocation_point, required),
521 (6, htlc_outputs, vec_type),
523 (2, PaymentPreimage) => {
524 (0, payment_preimage, required),
526 (3, CommitmentSecret) => {
528 (2, secret, required),
530 (4, ChannelForceClosed) => {
531 (0, should_broadcast, required),
533 (5, ShutdownScript) => {
534 (0, scriptpubkey, required),
538 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
540 struct IrrevocablyResolvedHTLC {
542 /// Only set if the HTLC claim was ours using a payment preimage
543 payment_preimage: Option<PaymentPreimage>,
546 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
547 (0, input_idx, required),
548 (2, payment_preimage, option),
551 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
552 /// on-chain transactions to ensure no loss of funds occurs.
554 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
555 /// information and are actively monitoring the chain.
557 /// Pending Events or updated HTLCs which have not yet been read out by
558 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
559 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
560 /// gotten are fully handled before re-serializing the new state.
562 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
563 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
564 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
565 /// returned block hash and the the current chain and then reconnecting blocks to get to the
566 /// best chain) upon deserializing the object!
567 pub struct ChannelMonitor<Signer: Sign> {
569 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
571 inner: Mutex<ChannelMonitorImpl<Signer>>,
574 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
575 latest_update_id: u64,
576 commitment_transaction_number_obscure_factor: u64,
578 destination_script: Script,
579 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
580 counterparty_payment_script: Script,
581 shutdown_script: Option<Script>,
583 channel_keys_id: [u8; 32],
584 holder_revocation_basepoint: PublicKey,
585 funding_info: (OutPoint, Script),
586 current_counterparty_commitment_txid: Option<Txid>,
587 prev_counterparty_commitment_txid: Option<Txid>,
589 counterparty_commitment_params: CounterpartyCommitmentParameters,
590 funding_redeemscript: Script,
591 channel_value_satoshis: u64,
592 // first is the idx of the first of the two revocation points
593 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
595 on_holder_tx_csv: u16,
597 commitment_secrets: CounterpartyCommitmentSecrets,
598 /// The set of outpoints in each counterparty commitment transaction. We always need at least
599 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
600 /// transaction broadcast as we need to be able to construct the witness script in all cases.
601 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
602 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
603 /// Nor can we figure out their commitment numbers without the commitment transaction they are
604 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
605 /// commitment transactions which we find on-chain, mapping them to the commitment number which
606 /// can be used to derive the revocation key and claim the transactions.
607 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
608 /// Cache used to make pruning of payment_preimages faster.
609 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
610 /// counterparty transactions (ie should remain pretty small).
611 /// Serialized to disk but should generally not be sent to Watchtowers.
612 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
614 // We store two holder commitment transactions to avoid any race conditions where we may update
615 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
616 // various monitors for one channel being out of sync, and us broadcasting a holder
617 // transaction for which we have deleted claim information on some watchtowers.
618 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
619 current_holder_commitment_tx: HolderSignedTx,
621 // Used just for ChannelManager to make sure it has the latest channel data during
623 current_counterparty_commitment_number: u64,
624 // Used just for ChannelManager to make sure it has the latest channel data during
626 current_holder_commitment_number: u64,
628 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
630 pending_monitor_events: Vec<MonitorEvent>,
631 pending_events: Vec<Event>,
633 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
634 // which to take actions once they reach enough confirmations. Each entry includes the
635 // transaction's id and the height when the transaction was confirmed on chain.
636 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
638 // If we get serialized out and re-read, we need to make sure that the chain monitoring
639 // interface knows about the TXOs that we want to be notified of spends of. We could probably
640 // be smart and derive them from the above storage fields, but its much simpler and more
641 // Obviously Correct (tm) if we just keep track of them explicitly.
642 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
645 pub onchain_tx_handler: OnchainTxHandler<Signer>,
647 onchain_tx_handler: OnchainTxHandler<Signer>,
649 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
650 // channel has been force-closed. After this is set, no further holder commitment transaction
651 // updates may occur, and we panic!() if one is provided.
652 lockdown_from_offchain: bool,
654 // Set once we've signed a holder commitment transaction and handed it over to our
655 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
656 // may occur, and we fail any such monitor updates.
658 // In case of update rejection due to a locally already signed commitment transaction, we
659 // nevertheless store update content to track in case of concurrent broadcast by another
660 // remote monitor out-of-order with regards to the block view.
661 holder_tx_signed: bool,
663 funding_spend_confirmed: Option<Txid>,
664 /// The set of HTLCs which have been either claimed or failed on chain and have reached
665 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
666 /// spending CSV for revocable outputs).
667 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
669 // We simply modify best_block in Channel's block_connected so that serialization is
670 // consistent but hopefully the users' copy handles block_connected in a consistent way.
671 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
672 // their best_block from its state and not based on updated copies that didn't run through
673 // the full block_connected).
674 best_block: BestBlock,
676 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
679 /// Transaction outputs to watch for on-chain spends.
680 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
682 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
683 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
684 /// underlying object
685 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
686 fn eq(&self, other: &Self) -> bool {
687 let inner = self.inner.lock().unwrap();
688 let other = other.inner.lock().unwrap();
693 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
694 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
695 /// underlying object
696 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
697 fn eq(&self, other: &Self) -> bool {
698 if self.latest_update_id != other.latest_update_id ||
699 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
700 self.destination_script != other.destination_script ||
701 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
702 self.counterparty_payment_script != other.counterparty_payment_script ||
703 self.channel_keys_id != other.channel_keys_id ||
704 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
705 self.funding_info != other.funding_info ||
706 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
707 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
708 self.counterparty_commitment_params != other.counterparty_commitment_params ||
709 self.funding_redeemscript != other.funding_redeemscript ||
710 self.channel_value_satoshis != other.channel_value_satoshis ||
711 self.their_cur_revocation_points != other.their_cur_revocation_points ||
712 self.on_holder_tx_csv != other.on_holder_tx_csv ||
713 self.commitment_secrets != other.commitment_secrets ||
714 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
715 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
716 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
717 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
718 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
719 self.current_holder_commitment_number != other.current_holder_commitment_number ||
720 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
721 self.payment_preimages != other.payment_preimages ||
722 self.pending_monitor_events != other.pending_monitor_events ||
723 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
724 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
725 self.outputs_to_watch != other.outputs_to_watch ||
726 self.lockdown_from_offchain != other.lockdown_from_offchain ||
727 self.holder_tx_signed != other.holder_tx_signed ||
728 self.funding_spend_confirmed != other.funding_spend_confirmed ||
729 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
738 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
739 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
740 self.inner.lock().unwrap().write(writer)
744 // These are also used for ChannelMonitorUpdate, above.
745 const SERIALIZATION_VERSION: u8 = 1;
746 const MIN_SERIALIZATION_VERSION: u8 = 1;
748 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
749 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
750 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
752 self.latest_update_id.write(writer)?;
754 // Set in initial Channel-object creation, so should always be set by now:
755 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
757 self.destination_script.write(writer)?;
758 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
759 writer.write_all(&[0; 1])?;
760 broadcasted_holder_revokable_script.0.write(writer)?;
761 broadcasted_holder_revokable_script.1.write(writer)?;
762 broadcasted_holder_revokable_script.2.write(writer)?;
764 writer.write_all(&[1; 1])?;
767 self.counterparty_payment_script.write(writer)?;
768 match &self.shutdown_script {
769 Some(script) => script.write(writer)?,
770 None => Script::new().write(writer)?,
773 self.channel_keys_id.write(writer)?;
774 self.holder_revocation_basepoint.write(writer)?;
775 writer.write_all(&self.funding_info.0.txid[..])?;
776 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
777 self.funding_info.1.write(writer)?;
778 self.current_counterparty_commitment_txid.write(writer)?;
779 self.prev_counterparty_commitment_txid.write(writer)?;
781 self.counterparty_commitment_params.write(writer)?;
782 self.funding_redeemscript.write(writer)?;
783 self.channel_value_satoshis.write(writer)?;
785 match self.their_cur_revocation_points {
786 Some((idx, pubkey, second_option)) => {
787 writer.write_all(&byte_utils::be48_to_array(idx))?;
788 writer.write_all(&pubkey.serialize())?;
789 match second_option {
790 Some(second_pubkey) => {
791 writer.write_all(&second_pubkey.serialize())?;
794 writer.write_all(&[0; 33])?;
799 writer.write_all(&byte_utils::be48_to_array(0))?;
803 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
805 self.commitment_secrets.write(writer)?;
807 macro_rules! serialize_htlc_in_commitment {
808 ($htlc_output: expr) => {
809 writer.write_all(&[$htlc_output.offered as u8; 1])?;
810 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
811 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
812 writer.write_all(&$htlc_output.payment_hash.0[..])?;
813 $htlc_output.transaction_output_index.write(writer)?;
817 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
818 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
819 writer.write_all(&txid[..])?;
820 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
821 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
822 serialize_htlc_in_commitment!(htlc_output);
823 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
827 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
828 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
829 writer.write_all(&txid[..])?;
830 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
833 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
834 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
835 writer.write_all(&payment_hash.0[..])?;
836 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
839 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
840 writer.write_all(&[1; 1])?;
841 prev_holder_tx.write(writer)?;
843 writer.write_all(&[0; 1])?;
846 self.current_holder_commitment_tx.write(writer)?;
848 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
849 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
851 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
852 for payment_preimage in self.payment_preimages.values() {
853 writer.write_all(&payment_preimage.0[..])?;
856 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
857 for event in self.pending_monitor_events.iter() {
859 MonitorEvent::HTLCEvent(upd) => {
863 MonitorEvent::CommitmentTxBroadcasted(_) => 1u8.write(writer)?
867 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
868 for event in self.pending_events.iter() {
869 event.write(writer)?;
872 self.best_block.block_hash().write(writer)?;
873 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
875 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
876 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
877 entry.write(writer)?;
880 (self.outputs_to_watch.len() as u64).write(writer)?;
881 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
883 (idx_scripts.len() as u64).write(writer)?;
884 for (idx, script) in idx_scripts.iter() {
886 script.write(writer)?;
889 self.onchain_tx_handler.write(writer)?;
891 self.lockdown_from_offchain.write(writer)?;
892 self.holder_tx_signed.write(writer)?;
894 write_tlv_fields!(writer, {
895 (1, self.funding_spend_confirmed, option),
896 (3, self.htlcs_resolved_on_chain, vec_type),
903 impl<Signer: Sign> ChannelMonitor<Signer> {
904 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
905 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
906 channel_parameters: &ChannelTransactionParameters,
907 funding_redeemscript: Script, channel_value_satoshis: u64,
908 commitment_transaction_number_obscure_factor: u64,
909 initial_holder_commitment_tx: HolderCommitmentTransaction,
910 best_block: BestBlock) -> ChannelMonitor<Signer> {
912 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
913 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
914 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
916 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
917 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
918 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
919 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
921 let channel_keys_id = keys.channel_keys_id();
922 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
924 // block for Rust 1.34 compat
925 let (holder_commitment_tx, current_holder_commitment_number) = {
926 let trusted_tx = initial_holder_commitment_tx.trust();
927 let txid = trusted_tx.txid();
929 let tx_keys = trusted_tx.keys();
930 let holder_commitment_tx = HolderSignedTx {
932 revocation_key: tx_keys.revocation_key,
933 a_htlc_key: tx_keys.broadcaster_htlc_key,
934 b_htlc_key: tx_keys.countersignatory_htlc_key,
935 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
936 per_commitment_point: tx_keys.per_commitment_point,
937 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
938 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
939 feerate_per_kw: trusted_tx.feerate_per_kw(),
941 (holder_commitment_tx, trusted_tx.commitment_number())
944 let onchain_tx_handler =
945 OnchainTxHandler::new(destination_script.clone(), keys,
946 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
948 let mut outputs_to_watch = HashMap::new();
949 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
952 inner: Mutex::new(ChannelMonitorImpl {
954 commitment_transaction_number_obscure_factor,
956 destination_script: destination_script.clone(),
957 broadcasted_holder_revokable_script: None,
958 counterparty_payment_script,
962 holder_revocation_basepoint,
964 current_counterparty_commitment_txid: None,
965 prev_counterparty_commitment_txid: None,
967 counterparty_commitment_params,
968 funding_redeemscript,
969 channel_value_satoshis,
970 their_cur_revocation_points: None,
972 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
974 commitment_secrets: CounterpartyCommitmentSecrets::new(),
975 counterparty_claimable_outpoints: HashMap::new(),
976 counterparty_commitment_txn_on_chain: HashMap::new(),
977 counterparty_hash_commitment_number: HashMap::new(),
979 prev_holder_signed_commitment_tx: None,
980 current_holder_commitment_tx: holder_commitment_tx,
981 current_counterparty_commitment_number: 1 << 48,
982 current_holder_commitment_number,
984 payment_preimages: HashMap::new(),
985 pending_monitor_events: Vec::new(),
986 pending_events: Vec::new(),
988 onchain_events_awaiting_threshold_conf: Vec::new(),
993 lockdown_from_offchain: false,
994 holder_tx_signed: false,
995 funding_spend_confirmed: None,
996 htlcs_resolved_on_chain: Vec::new(),
1006 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1007 self.inner.lock().unwrap().provide_secret(idx, secret)
1010 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1011 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1012 /// possibly future revocation/preimage information) to claim outputs where possible.
1013 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1014 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1017 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1018 commitment_number: u64,
1019 their_revocation_point: PublicKey,
1021 ) where L::Target: Logger {
1022 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1023 txid, htlc_outputs, commitment_number, their_revocation_point, logger)
1027 fn provide_latest_holder_commitment_tx(
1029 holder_commitment_tx: HolderCommitmentTransaction,
1030 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1031 ) -> Result<(), MonitorUpdateError> {
1032 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
1033 holder_commitment_tx, htlc_outputs)
1037 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1039 payment_hash: &PaymentHash,
1040 payment_preimage: &PaymentPreimage,
1045 B::Target: BroadcasterInterface,
1046 F::Target: FeeEstimator,
1049 self.inner.lock().unwrap().provide_payment_preimage(
1050 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1053 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1058 B::Target: BroadcasterInterface,
1061 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1064 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1067 /// panics if the given update is not the next update by update_id.
1068 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1070 updates: &ChannelMonitorUpdate,
1074 ) -> Result<(), MonitorUpdateError>
1076 B::Target: BroadcasterInterface,
1077 F::Target: FeeEstimator,
1080 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1083 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1085 pub fn get_latest_update_id(&self) -> u64 {
1086 self.inner.lock().unwrap().get_latest_update_id()
1089 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1090 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1091 self.inner.lock().unwrap().get_funding_txo().clone()
1094 /// Gets a list of txids, with their output scripts (in the order they appear in the
1095 /// transaction), which we must learn about spends of via block_connected().
1096 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1097 self.inner.lock().unwrap().get_outputs_to_watch()
1098 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1101 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1102 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1103 /// have been registered.
1104 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1105 let lock = self.inner.lock().unwrap();
1106 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1107 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1108 for (index, script_pubkey) in outputs.iter() {
1109 assert!(*index <= u16::max_value() as u32);
1110 filter.register_output(WatchedOutput {
1112 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1113 script_pubkey: script_pubkey.clone(),
1119 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1120 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1121 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1122 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1125 /// Gets the list of pending events which were generated by previous actions, clearing the list
1128 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1129 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1130 /// no internal locking in ChannelMonitors.
1131 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1132 self.inner.lock().unwrap().get_and_clear_pending_events()
1135 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1136 self.inner.lock().unwrap().get_min_seen_secret()
1139 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1140 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1143 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1144 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1147 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1148 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1149 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1150 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1151 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1152 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1153 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1154 /// out-of-band the other node operator to coordinate with him if option is available to you.
1155 /// In any-case, choice is up to the user.
1156 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1157 where L::Target: Logger {
1158 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1161 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1162 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1163 /// revoked commitment transaction.
1164 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1165 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1166 where L::Target: Logger {
1167 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1170 /// Processes transactions in a newly connected block, which may result in any of the following:
1171 /// - update the monitor's state against resolved HTLCs
1172 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1173 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1174 /// - detect settled outputs for later spending
1175 /// - schedule and bump any in-flight claims
1177 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1178 /// [`get_outputs_to_watch`].
1180 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1181 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1183 header: &BlockHeader,
1184 txdata: &TransactionData,
1189 ) -> Vec<TransactionOutputs>
1191 B::Target: BroadcasterInterface,
1192 F::Target: FeeEstimator,
1195 self.inner.lock().unwrap().block_connected(
1196 header, txdata, height, broadcaster, fee_estimator, logger)
1199 /// Determines if the disconnected block contained any transactions of interest and updates
1201 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1203 header: &BlockHeader,
1209 B::Target: BroadcasterInterface,
1210 F::Target: FeeEstimator,
1213 self.inner.lock().unwrap().block_disconnected(
1214 header, height, broadcaster, fee_estimator, logger)
1217 /// Processes transactions confirmed in a block with the given header and height, returning new
1218 /// outputs to watch. See [`block_connected`] for details.
1220 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1221 /// blocks. See [`chain::Confirm`] for calling expectations.
1223 /// [`block_connected`]: Self::block_connected
1224 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1226 header: &BlockHeader,
1227 txdata: &TransactionData,
1232 ) -> Vec<TransactionOutputs>
1234 B::Target: BroadcasterInterface,
1235 F::Target: FeeEstimator,
1238 self.inner.lock().unwrap().transactions_confirmed(
1239 header, txdata, height, broadcaster, fee_estimator, logger)
1242 /// Processes a transaction that was reorganized out of the chain.
1244 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1245 /// than blocks. See [`chain::Confirm`] for calling expectations.
1247 /// [`block_disconnected`]: Self::block_disconnected
1248 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1255 B::Target: BroadcasterInterface,
1256 F::Target: FeeEstimator,
1259 self.inner.lock().unwrap().transaction_unconfirmed(
1260 txid, broadcaster, fee_estimator, logger);
1263 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1264 /// [`block_connected`] for details.
1266 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1267 /// blocks. See [`chain::Confirm`] for calling expectations.
1269 /// [`block_connected`]: Self::block_connected
1270 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1272 header: &BlockHeader,
1277 ) -> Vec<TransactionOutputs>
1279 B::Target: BroadcasterInterface,
1280 F::Target: FeeEstimator,
1283 self.inner.lock().unwrap().best_block_updated(
1284 header, height, broadcaster, fee_estimator, logger)
1287 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1288 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1289 let inner = self.inner.lock().unwrap();
1290 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1292 .map(|entry| entry.txid)
1293 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1295 txids.sort_unstable();
1300 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1301 /// [`chain::Confirm`] interfaces.
1302 pub fn current_best_block(&self) -> BestBlock {
1303 self.inner.lock().unwrap().best_block.clone()
1307 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1308 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1309 /// after ANTI_REORG_DELAY blocks.
1311 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1312 /// are the commitment transactions which are generated by us. The off-chain state machine in
1313 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1314 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1315 /// included in a remote commitment transaction are failed back if they are not present in the
1316 /// broadcasted commitment transaction.
1318 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1319 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1320 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1321 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1322 macro_rules! fail_unbroadcast_htlcs {
1323 ($self: expr, $commitment_tx_type: expr, $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1324 macro_rules! check_htlc_fails {
1325 ($txid: expr, $commitment_tx: expr) => {
1326 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1327 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1328 if let &Some(ref source) = source_option {
1329 // Check if the HTLC is present in the commitment transaction that was
1330 // broadcast, but not if it was below the dust limit, which we should
1331 // fail backwards immediately as there is no way for us to learn the
1332 // payment_preimage.
1333 // Note that if the dust limit were allowed to change between
1334 // commitment transactions we'd want to be check whether *any*
1335 // broadcastable commitment transaction has the HTLC in it, but it
1336 // cannot currently change after channel initialization, so we don't
1338 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1339 let mut matched_htlc = false;
1340 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1341 if broadcast_htlc.transaction_output_index.is_some() && Some(&**source) == *broadcast_source {
1342 matched_htlc = true;
1346 if matched_htlc { continue; }
1347 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1348 if entry.height != $commitment_tx_conf_height { return true; }
1350 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1351 *update_source != **source
1356 let entry = OnchainEventEntry {
1358 height: $commitment_tx_conf_height,
1359 event: OnchainEvent::HTLCUpdate {
1360 source: (**source).clone(),
1361 payment_hash: htlc.payment_hash.clone(),
1362 onchain_value_satoshis: Some(htlc.amount_msat / 1000),
1366 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction, waiting for confirmation (at height {})",
1367 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type, entry.confirmation_threshold());
1368 $self.onchain_events_awaiting_threshold_conf.push(entry);
1374 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1375 check_htlc_fails!(txid, "current");
1377 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1378 check_htlc_fails!(txid, "previous");
1383 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1384 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1385 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1386 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1387 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1388 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1389 return Err(MonitorUpdateError("Previous secret did not match new one"));
1392 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1393 // events for now-revoked/fulfilled HTLCs.
1394 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1395 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1400 if !self.payment_preimages.is_empty() {
1401 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1402 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1403 let min_idx = self.get_min_seen_secret();
1404 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1406 self.payment_preimages.retain(|&k, _| {
1407 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1408 if k == htlc.payment_hash {
1412 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1413 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1414 if k == htlc.payment_hash {
1419 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1426 counterparty_hash_commitment_number.remove(&k);
1435 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 {
1436 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1437 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1438 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1440 for &(ref htlc, _) in &htlc_outputs {
1441 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1444 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1445 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1446 self.current_counterparty_commitment_txid = Some(txid);
1447 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1448 self.current_counterparty_commitment_number = commitment_number;
1449 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1450 match self.their_cur_revocation_points {
1451 Some(old_points) => {
1452 if old_points.0 == commitment_number + 1 {
1453 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1454 } else if old_points.0 == commitment_number + 2 {
1455 if let Some(old_second_point) = old_points.2 {
1456 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1458 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1461 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1465 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1468 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1469 for htlc in htlc_outputs {
1470 if htlc.0.transaction_output_index.is_some() {
1476 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1477 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1478 /// is important that any clones of this channel monitor (including remote clones) by kept
1479 /// up-to-date as our holder commitment transaction is updated.
1480 /// Panics if set_on_holder_tx_csv has never been called.
1481 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1482 // block for Rust 1.34 compat
1483 let mut new_holder_commitment_tx = {
1484 let trusted_tx = holder_commitment_tx.trust();
1485 let txid = trusted_tx.txid();
1486 let tx_keys = trusted_tx.keys();
1487 self.current_holder_commitment_number = trusted_tx.commitment_number();
1490 revocation_key: tx_keys.revocation_key,
1491 a_htlc_key: tx_keys.broadcaster_htlc_key,
1492 b_htlc_key: tx_keys.countersignatory_htlc_key,
1493 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1494 per_commitment_point: tx_keys.per_commitment_point,
1496 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1497 feerate_per_kw: trusted_tx.feerate_per_kw(),
1500 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1501 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1502 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1503 if self.holder_tx_signed {
1504 return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1509 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1510 /// commitment_tx_infos which contain the payment hash have been revoked.
1511 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)
1512 where B::Target: BroadcasterInterface,
1513 F::Target: FeeEstimator,
1516 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1518 // If the channel is force closed, try to claim the output from this preimage.
1519 // First check if a counterparty commitment transaction has been broadcasted:
1520 macro_rules! claim_htlcs {
1521 ($commitment_number: expr, $txid: expr) => {
1522 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1523 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1526 if let Some(txid) = self.current_counterparty_commitment_txid {
1527 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1528 claim_htlcs!(*commitment_number, txid);
1532 if let Some(txid) = self.prev_counterparty_commitment_txid {
1533 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1534 claim_htlcs!(*commitment_number, txid);
1539 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1540 // claiming the HTLC output from each of the holder commitment transactions.
1541 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1542 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1543 // holder commitment transactions.
1544 if self.broadcasted_holder_revokable_script.is_some() {
1545 // Assume that the broadcasted commitment transaction confirmed in the current best
1546 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1548 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1549 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1550 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1551 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1552 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1557 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1558 where B::Target: BroadcasterInterface,
1561 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1562 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1563 broadcaster.broadcast_transaction(tx);
1565 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1568 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
1569 where B::Target: BroadcasterInterface,
1570 F::Target: FeeEstimator,
1573 // ChannelMonitor updates may be applied after force close if we receive a
1574 // preimage for a broadcasted commitment transaction HTLC output that we'd
1575 // like to claim on-chain. If this is the case, we no longer have guaranteed
1576 // access to the monitor's update ID, so we use a sentinel value instead.
1577 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1578 match updates.updates[0] {
1579 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1580 _ => panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage"),
1582 assert_eq!(updates.updates.len(), 1);
1583 } else if self.latest_update_id + 1 != updates.update_id {
1584 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1586 for update in updates.updates.iter() {
1588 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1589 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1590 if self.lockdown_from_offchain { panic!(); }
1591 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
1593 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1594 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1595 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1597 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1598 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1599 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1601 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1602 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1603 self.provide_secret(*idx, *secret)?
1605 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1606 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1607 self.lockdown_from_offchain = true;
1608 if *should_broadcast {
1609 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1610 } else if !self.holder_tx_signed {
1611 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");
1613 // If we generated a MonitorEvent::CommitmentTxBroadcasted, the ChannelManager
1614 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1615 // shouldn't print the scary warning above.
1616 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1619 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
1620 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
1621 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
1622 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
1627 self.latest_update_id = updates.update_id;
1631 pub fn get_latest_update_id(&self) -> u64 {
1632 self.latest_update_id
1635 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1639 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1640 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1641 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1642 // its trivial to do, double-check that here.
1643 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1644 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1646 &self.outputs_to_watch
1649 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1650 let mut ret = Vec::new();
1651 mem::swap(&mut ret, &mut self.pending_monitor_events);
1655 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1656 let mut ret = Vec::new();
1657 mem::swap(&mut ret, &mut self.pending_events);
1661 /// Can only fail if idx is < get_min_seen_secret
1662 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1663 self.commitment_secrets.get_secret(idx)
1666 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1667 self.commitment_secrets.get_min_seen_secret()
1670 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1671 self.current_counterparty_commitment_number
1674 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1675 self.current_holder_commitment_number
1678 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1679 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1680 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1681 /// HTLC-Success/HTLC-Timeout transactions.
1682 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1683 /// revoked counterparty commitment tx
1684 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1685 // Most secp and related errors trying to create keys means we have no hope of constructing
1686 // a spend transaction...so we return no transactions to broadcast
1687 let mut claimable_outpoints = Vec::new();
1688 let mut watch_outputs = Vec::new();
1690 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1691 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1693 macro_rules! ignore_error {
1694 ( $thing : expr ) => {
1697 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1702 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);
1703 if commitment_number >= self.get_min_seen_secret() {
1704 let secret = self.get_secret(commitment_number).unwrap();
1705 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1706 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1707 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
1708 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));
1710 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
1711 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1713 // First, process non-htlc outputs (to_holder & to_counterparty)
1714 for (idx, outp) in tx.output.iter().enumerate() {
1715 if outp.script_pubkey == revokeable_p2wsh {
1716 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);
1717 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);
1718 claimable_outpoints.push(justice_package);
1722 // Then, try to find revoked htlc outputs
1723 if let Some(ref per_commitment_data) = per_commitment_option {
1724 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1725 if let Some(transaction_output_index) = htlc.transaction_output_index {
1726 if transaction_output_index as usize >= tx.output.len() ||
1727 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1728 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1730 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());
1731 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
1732 claimable_outpoints.push(justice_package);
1737 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1738 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1739 // We're definitely a counterparty commitment transaction!
1740 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1741 for (idx, outp) in tx.output.iter().enumerate() {
1742 watch_outputs.push((idx as u32, outp.clone()));
1744 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1746 fail_unbroadcast_htlcs!(self, "revoked counterparty", height, [].iter().map(|a| *a), logger);
1748 } else if let Some(per_commitment_data) = per_commitment_option {
1749 // While this isn't useful yet, there is a potential race where if a counterparty
1750 // revokes a state at the same time as the commitment transaction for that state is
1751 // confirmed, and the watchtower receives the block before the user, the user could
1752 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1753 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1754 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1756 for (idx, outp) in tx.output.iter().enumerate() {
1757 watch_outputs.push((idx as u32, outp.clone()));
1759 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1761 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1762 fail_unbroadcast_htlcs!(self, "counterparty", height, per_commitment_data.iter().map(|(a, b)| (a, b.as_ref().map(|b| b.as_ref()))), logger);
1764 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
1765 for req in htlc_claim_reqs {
1766 claimable_outpoints.push(req);
1770 (claimable_outpoints, (commitment_txid, watch_outputs))
1773 fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
1774 let mut claimable_outpoints = Vec::new();
1775 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
1776 if let Some(revocation_points) = self.their_cur_revocation_points {
1777 let revocation_point_option =
1778 // If the counterparty commitment tx is the latest valid state, use their latest
1779 // per-commitment point
1780 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1781 else if let Some(point) = revocation_points.2.as_ref() {
1782 // If counterparty commitment tx is the state previous to the latest valid state, use
1783 // their previous per-commitment point (non-atomicity of revocation means it's valid for
1784 // them to temporarily have two valid commitment txns from our viewpoint)
1785 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1787 if let Some(revocation_point) = revocation_point_option {
1788 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
1789 if let Some(transaction_output_index) = htlc.transaction_output_index {
1790 if let Some(transaction) = tx {
1791 if transaction_output_index as usize >= transaction.output.len() ||
1792 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1793 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
1796 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1797 if preimage.is_some() || !htlc.offered {
1798 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())) };
1799 let aggregation = if !htlc.offered { false } else { true };
1800 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
1801 claimable_outpoints.push(counterparty_package);
1811 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1812 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 {
1813 let htlc_txid = tx.txid();
1814 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1815 return (Vec::new(), None)
1818 macro_rules! ignore_error {
1819 ( $thing : expr ) => {
1822 Err(_) => return (Vec::new(), None)
1827 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1828 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1829 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1831 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
1832 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);
1833 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);
1834 let claimable_outpoints = vec!(justice_package);
1835 let outputs = vec![(0, tx.output[0].clone())];
1836 (claimable_outpoints, Some((htlc_txid, outputs)))
1839 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
1840 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
1841 // script so we can detect whether a holder transaction has been seen on-chain.
1842 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
1843 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
1845 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
1846 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
1848 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1849 if let Some(transaction_output_index) = htlc.transaction_output_index {
1850 let htlc_output = if htlc.offered {
1851 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
1853 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1856 // We can't build an HTLC-Success transaction without the preimage
1859 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
1861 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
1862 claim_requests.push(htlc_package);
1866 (claim_requests, broadcasted_holder_revokable_script)
1869 // Returns holder HTLC outputs to watch and react to in case of spending.
1870 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
1871 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
1872 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1873 if let Some(transaction_output_index) = htlc.transaction_output_index {
1874 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
1880 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1881 /// revoked using data in holder_claimable_outpoints.
1882 /// Should not be used if check_spend_revoked_transaction succeeds.
1883 /// Returns None unless the transaction is definitely one of our commitment transactions.
1884 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
1885 let commitment_txid = tx.txid();
1886 let mut claim_requests = Vec::new();
1887 let mut watch_outputs = Vec::new();
1889 macro_rules! append_onchain_update {
1890 ($updates: expr, $to_watch: expr) => {
1891 claim_requests = $updates.0;
1892 self.broadcasted_holder_revokable_script = $updates.1;
1893 watch_outputs.append(&mut $to_watch);
1897 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1898 let mut is_holder_tx = false;
1900 if self.current_holder_commitment_tx.txid == commitment_txid {
1901 is_holder_tx = true;
1902 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
1903 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
1904 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
1905 append_onchain_update!(res, to_watch);
1906 fail_unbroadcast_htlcs!(self, "latest holder", height, self.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
1907 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1908 if holder_tx.txid == commitment_txid {
1909 is_holder_tx = true;
1910 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
1911 let res = self.get_broadcasted_holder_claims(holder_tx, height);
1912 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
1913 append_onchain_update!(res, to_watch);
1914 fail_unbroadcast_htlcs!(self, "previous holder", height, holder_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
1919 Some((claim_requests, (commitment_txid, watch_outputs)))
1925 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1926 log_debug!(logger, "Getting signed latest holder commitment transaction!");
1927 self.holder_tx_signed = true;
1928 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
1929 let txid = commitment_tx.txid();
1930 let mut holder_transactions = vec![commitment_tx];
1931 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1932 if let Some(vout) = htlc.0.transaction_output_index {
1933 let preimage = if !htlc.0.offered {
1934 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1935 // We can't build an HTLC-Success transaction without the preimage
1938 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
1939 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
1940 // current locktime requirements on-chain. We will broadcast them in
1941 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
1942 // Note that we add + 1 as transactions are broadcastable when they can be
1943 // confirmed in the next block.
1946 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
1947 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1948 holder_transactions.push(htlc_tx);
1952 // 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.
1953 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
1957 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1958 /// Note that this includes possibly-locktimed-in-the-future transactions!
1959 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1960 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
1961 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
1962 let txid = commitment_tx.txid();
1963 let mut holder_transactions = vec![commitment_tx];
1964 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1965 if let Some(vout) = htlc.0.transaction_output_index {
1966 let preimage = if !htlc.0.offered {
1967 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1968 // We can't build an HTLC-Success transaction without the preimage
1972 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
1973 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1974 holder_transactions.push(htlc_tx);
1981 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>
1982 where B::Target: BroadcasterInterface,
1983 F::Target: FeeEstimator,
1986 let block_hash = header.block_hash();
1987 self.best_block = BestBlock::new(block_hash, height);
1989 self.transactions_confirmed(header, txdata, height, broadcaster, fee_estimator, logger)
1992 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1994 header: &BlockHeader,
1999 ) -> Vec<TransactionOutputs>
2001 B::Target: BroadcasterInterface,
2002 F::Target: FeeEstimator,
2005 let block_hash = header.block_hash();
2007 if height > self.best_block.height() {
2008 self.best_block = BestBlock::new(block_hash, height);
2009 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2010 } else if block_hash != self.best_block.block_hash() {
2011 self.best_block = BestBlock::new(block_hash, height);
2012 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2013 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2015 } else { Vec::new() }
2018 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2020 header: &BlockHeader,
2021 txdata: &TransactionData,
2026 ) -> Vec<TransactionOutputs>
2028 B::Target: BroadcasterInterface,
2029 F::Target: FeeEstimator,
2032 let txn_matched = self.filter_block(txdata);
2033 for tx in &txn_matched {
2034 let mut output_val = 0;
2035 for out in tx.output.iter() {
2036 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2037 output_val += out.value;
2038 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2042 let block_hash = header.block_hash();
2044 let mut watch_outputs = Vec::new();
2045 let mut claimable_outpoints = Vec::new();
2046 for tx in &txn_matched {
2047 if tx.input.len() == 1 {
2048 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2049 // commitment transactions and HTLC transactions will all only ever have one input,
2050 // which is an easy way to filter out any potential non-matching txn for lazy
2052 let prevout = &tx.input[0].previous_output;
2053 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2054 let mut balance_spendable_csv = None;
2055 log_info!(logger, "Channel closed by funding output spend in txid {}.", log_bytes!(tx.txid()));
2056 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2057 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2058 if !new_outputs.1.is_empty() {
2059 watch_outputs.push(new_outputs);
2061 claimable_outpoints.append(&mut new_outpoints);
2062 if new_outpoints.is_empty() {
2063 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2064 if !new_outputs.1.is_empty() {
2065 watch_outputs.push(new_outputs);
2067 claimable_outpoints.append(&mut new_outpoints);
2068 balance_spendable_csv = Some(self.on_holder_tx_csv);
2072 let txid = tx.txid();
2073 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2076 event: OnchainEvent::FundingSpendConfirmation {
2077 on_local_output_csv: balance_spendable_csv,
2081 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2082 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2083 claimable_outpoints.append(&mut new_outpoints);
2084 if let Some(new_outputs) = new_outputs_option {
2085 watch_outputs.push(new_outputs);
2090 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2091 // can also be resolved in a few other ways which can have more than one output. Thus,
2092 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2093 self.is_resolving_htlc_output(&tx, height, &logger);
2095 self.is_paying_spendable_output(&tx, height, &logger);
2098 if height > self.best_block.height() {
2099 self.best_block = BestBlock::new(block_hash, height);
2102 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2105 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2106 /// `self.best_block` before calling if a new best blockchain tip is available. More
2107 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2108 /// complexity especially in `OnchainTx::update_claims_view`.
2110 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2111 /// confirmed at, even if it is not the current best height.
2112 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2115 txn_matched: Vec<&Transaction>,
2116 mut watch_outputs: Vec<TransactionOutputs>,
2117 mut claimable_outpoints: Vec<PackageTemplate>,
2121 ) -> Vec<TransactionOutputs>
2123 B::Target: BroadcasterInterface,
2124 F::Target: FeeEstimator,
2127 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2128 debug_assert!(self.best_block.height() >= conf_height);
2130 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2131 if should_broadcast {
2132 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2133 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());
2134 claimable_outpoints.push(commitment_package);
2135 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
2136 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2137 self.holder_tx_signed = true;
2138 // Because we're broadcasting a commitment transaction, we should construct the package
2139 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2140 // "not yet confirmed" things as discardable, so we cannot do that here.
2141 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2142 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2143 if !new_outputs.is_empty() {
2144 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2146 claimable_outpoints.append(&mut new_outpoints);
2149 // Find which on-chain events have reached their confirmation threshold.
2150 let onchain_events_awaiting_threshold_conf =
2151 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2152 let mut onchain_events_reaching_threshold_conf = Vec::new();
2153 for entry in onchain_events_awaiting_threshold_conf {
2154 if entry.has_reached_confirmation_threshold(&self.best_block) {
2155 onchain_events_reaching_threshold_conf.push(entry);
2157 self.onchain_events_awaiting_threshold_conf.push(entry);
2161 // Used to check for duplicate HTLC resolutions.
2162 #[cfg(debug_assertions)]
2163 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2165 .filter_map(|entry| match &entry.event {
2166 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2170 #[cfg(debug_assertions)]
2171 let mut matured_htlcs = Vec::new();
2173 // Produce actionable events from on-chain events having reached their threshold.
2174 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2176 OnchainEvent::HTLCUpdate { ref source, payment_hash, onchain_value_satoshis, input_idx } => {
2177 // Check for duplicate HTLC resolutions.
2178 #[cfg(debug_assertions)]
2181 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2182 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2183 call either transaction_unconfirmed for the conflicting transaction \
2184 or block_disconnected for a block containing it.");
2186 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2187 "A matured HTLC transaction conflicts with a maturing one; failed to \
2188 call either transaction_unconfirmed for the conflicting transaction \
2189 or block_disconnected for a block containing it.");
2190 matured_htlcs.push(source.clone());
2193 log_debug!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!(payment_hash.0));
2194 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2196 payment_preimage: None,
2197 source: source.clone(),
2198 onchain_value_satoshis,
2200 if let Some(idx) = input_idx {
2201 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx: idx, payment_preimage: None });
2204 OnchainEvent::MaturingOutput { descriptor } => {
2205 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2206 self.pending_events.push(Event::SpendableOutputs {
2207 outputs: vec![descriptor]
2210 OnchainEvent::HTLCSpendConfirmation { input_idx, preimage, .. } => {
2211 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC { input_idx, payment_preimage: preimage });
2213 OnchainEvent::FundingSpendConfirmation { .. } => {
2214 self.funding_spend_confirmed = Some(entry.txid);
2219 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2221 // Determine new outputs to watch by comparing against previously known outputs to watch,
2222 // updating the latter in the process.
2223 watch_outputs.retain(|&(ref txid, ref txouts)| {
2224 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2225 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2229 // If we see a transaction for which we registered outputs previously,
2230 // make sure the registered scriptpubkey at the expected index match
2231 // the actual transaction output one. We failed this case before #653.
2232 for tx in &txn_matched {
2233 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2234 for idx_and_script in outputs.iter() {
2235 assert!((idx_and_script.0 as usize) < tx.output.len());
2236 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2244 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2245 where B::Target: BroadcasterInterface,
2246 F::Target: FeeEstimator,
2249 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2252 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2253 //- maturing spendable output has transaction paying us has been disconnected
2254 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2256 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2258 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2261 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2268 B::Target: BroadcasterInterface,
2269 F::Target: FeeEstimator,
2272 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.txid != *txid);
2273 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2276 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2277 /// transactions thereof.
2278 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2279 let mut matched_txn = HashSet::new();
2280 txdata.iter().filter(|&&(_, tx)| {
2281 let mut matches = self.spends_watched_output(tx);
2282 for input in tx.input.iter() {
2283 if matches { break; }
2284 if matched_txn.contains(&input.previous_output.txid) {
2289 matched_txn.insert(tx.txid());
2292 }).map(|(_, tx)| *tx).collect()
2295 /// Checks if a given transaction spends any watched outputs.
2296 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2297 for input in tx.input.iter() {
2298 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2299 for (idx, _script_pubkey) in outputs.iter() {
2300 if *idx == input.previous_output.vout {
2303 // If the expected script is a known type, check that the witness
2304 // appears to be spending the correct type (ie that the match would
2305 // actually succeed in BIP 158/159-style filters).
2306 if _script_pubkey.is_v0_p2wsh() {
2307 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2308 } else if _script_pubkey.is_v0_p2wpkh() {
2309 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2310 } else { panic!(); }
2321 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2322 // We need to consider all HTLCs which are:
2323 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2324 // transactions and we'd end up in a race, or
2325 // * are in our latest holder commitment transaction, as this is the thing we will
2326 // broadcast if we go on-chain.
2327 // Note that we consider HTLCs which were below dust threshold here - while they don't
2328 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2329 // to the source, and if we don't fail the channel we will have to ensure that the next
2330 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2331 // easier to just fail the channel as this case should be rare enough anyway.
2332 let height = self.best_block.height();
2333 macro_rules! scan_commitment {
2334 ($htlcs: expr, $holder_tx: expr) => {
2335 for ref htlc in $htlcs {
2336 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2337 // chain with enough room to claim the HTLC without our counterparty being able to
2338 // time out the HTLC first.
2339 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2340 // concern is being able to claim the corresponding inbound HTLC (on another
2341 // channel) before it expires. In fact, we don't even really care if our
2342 // counterparty here claims such an outbound HTLC after it expired as long as we
2343 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2344 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2345 // we give ourselves a few blocks of headroom after expiration before going
2346 // on-chain for an expired HTLC.
2347 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2348 // from us until we've reached the point where we go on-chain with the
2349 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2350 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2351 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2352 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2353 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2354 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2355 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2356 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2357 // The final, above, condition is checked for statically in channelmanager
2358 // with CHECK_CLTV_EXPIRY_SANITY_2.
2359 let htlc_outbound = $holder_tx == htlc.offered;
2360 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2361 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2362 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2369 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2371 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2372 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2373 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2376 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2377 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2378 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2385 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2386 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2387 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2388 'outer_loop: for input in &tx.input {
2389 let mut payment_data = None;
2390 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2391 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2392 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2393 let accepted_timeout_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
2394 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && !revocation_sig_claim;
2395 let offered_timeout_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::OfferedHTLC);
2397 let mut payment_preimage = PaymentPreimage([0; 32]);
2398 if accepted_preimage_claim {
2399 payment_preimage.0.copy_from_slice(&input.witness[3]);
2400 } else if offered_preimage_claim {
2401 payment_preimage.0.copy_from_slice(&input.witness[1]);
2404 macro_rules! log_claim {
2405 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2406 let outbound_htlc = $holder_tx == $htlc.offered;
2407 // HTLCs must either be claimed by a matching script type or through the
2409 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2410 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
2411 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2412 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
2413 // Further, only exactly one of the possible spend paths should have been
2414 // matched by any HTLC spend:
2415 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
2416 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
2417 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
2418 revocation_sig_claim as u8, 1);
2419 if ($holder_tx && revocation_sig_claim) ||
2420 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2421 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2422 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2423 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2424 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2426 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2427 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2428 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2429 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2434 macro_rules! check_htlc_valid_counterparty {
2435 ($counterparty_txid: expr, $htlc_output: expr) => {
2436 if let Some(txid) = $counterparty_txid {
2437 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2438 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2439 if let &Some(ref source) = pending_source {
2440 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2441 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2450 macro_rules! scan_commitment {
2451 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2452 for (ref htlc_output, source_option) in $htlcs {
2453 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2454 if let Some(ref source) = source_option {
2455 log_claim!($tx_info, $holder_tx, htlc_output, true);
2456 // We have a resolution of an HTLC either from one of our latest
2457 // holder commitment transactions or an unrevoked counterparty commitment
2458 // transaction. This implies we either learned a preimage, the HTLC
2459 // has timed out, or we screwed up. In any case, we should now
2460 // resolve the source HTLC with the original sender.
2461 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2462 } else if !$holder_tx {
2463 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2464 if payment_data.is_none() {
2465 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2468 if payment_data.is_none() {
2469 log_claim!($tx_info, $holder_tx, htlc_output, false);
2470 let outbound_htlc = $holder_tx == htlc_output.offered;
2471 if !outbound_htlc || revocation_sig_claim {
2472 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2473 txid: tx.txid(), height,
2474 event: OnchainEvent::HTLCSpendConfirmation {
2475 input_idx: input.previous_output.vout,
2476 preimage: if accepted_preimage_claim || offered_preimage_claim {
2477 Some(payment_preimage) } else { None },
2478 // If this is a payment to us (!outbound_htlc, above),
2479 // wait for the CSV delay before dropping the HTLC from
2480 // claimable balance if the claim was an HTLC-Success
2482 on_to_local_output_csv: if accepted_preimage_claim {
2483 Some(self.on_holder_tx_csv) } else { None },
2487 // Outbound claims should always have payment_data, unless
2488 // we've already failed the HTLC as the commitment transaction
2489 // which was broadcasted was revoked. In that case, we should
2490 // spend the HTLC output here immediately, and expose that fact
2491 // as a ClaimableBalance, something which we do not yet do.
2492 // TODO: Track the above as claimable!
2494 continue 'outer_loop;
2501 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2502 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2503 "our latest holder commitment tx", true);
2505 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2506 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2507 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2508 "our previous holder commitment tx", true);
2511 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2512 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2513 "counterparty commitment tx", false);
2516 // Check that scan_commitment, above, decided there is some source worth relaying an
2517 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2518 if let Some((source, payment_hash, amount_msat)) = payment_data {
2519 if accepted_preimage_claim {
2520 if !self.pending_monitor_events.iter().any(
2521 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2522 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2525 event: OnchainEvent::HTLCSpendConfirmation {
2526 input_idx: input.previous_output.vout,
2527 preimage: Some(payment_preimage),
2528 on_to_local_output_csv: None,
2531 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2533 payment_preimage: Some(payment_preimage),
2535 onchain_value_satoshis: Some(amount_msat / 1000),
2538 } else if offered_preimage_claim {
2539 if !self.pending_monitor_events.iter().any(
2540 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2541 upd.source == source
2543 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2546 event: OnchainEvent::HTLCSpendConfirmation {
2547 input_idx: input.previous_output.vout,
2548 preimage: Some(payment_preimage),
2549 on_to_local_output_csv: None,
2552 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2554 payment_preimage: Some(payment_preimage),
2556 onchain_value_satoshis: Some(amount_msat / 1000),
2560 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2561 if entry.height != height { return true; }
2563 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
2564 *htlc_source != source
2569 let entry = OnchainEventEntry {
2572 event: OnchainEvent::HTLCUpdate {
2573 source, payment_hash,
2574 onchain_value_satoshis: Some(amount_msat / 1000),
2575 input_idx: Some(input.previous_output.vout),
2578 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());
2579 self.onchain_events_awaiting_threshold_conf.push(entry);
2585 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2586 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2587 let mut spendable_output = None;
2588 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2589 if i > ::core::u16::MAX as usize {
2590 // While it is possible that an output exists on chain which is greater than the
2591 // 2^16th output in a given transaction, this is only possible if the output is not
2592 // in a lightning transaction and was instead placed there by some third party who
2593 // wishes to give us money for no reason.
2594 // Namely, any lightning transactions which we pre-sign will never have anywhere
2595 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2596 // scripts are not longer than one byte in length and because they are inherently
2597 // non-standard due to their size.
2598 // Thus, it is completely safe to ignore such outputs, and while it may result in
2599 // us ignoring non-lightning fund to us, that is only possible if someone fills
2600 // nearly a full block with garbage just to hit this case.
2603 if outp.script_pubkey == self.destination_script {
2604 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2605 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2606 output: outp.clone(),
2610 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2611 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2612 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2613 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2614 per_commitment_point: broadcasted_holder_revokable_script.1,
2615 to_self_delay: self.on_holder_tx_csv,
2616 output: outp.clone(),
2617 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2618 channel_keys_id: self.channel_keys_id,
2619 channel_value_satoshis: self.channel_value_satoshis,
2624 if self.counterparty_payment_script == outp.script_pubkey {
2625 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2626 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2627 output: outp.clone(),
2628 channel_keys_id: self.channel_keys_id,
2629 channel_value_satoshis: self.channel_value_satoshis,
2633 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
2634 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2635 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2636 output: outp.clone(),
2641 if let Some(spendable_output) = spendable_output {
2642 let entry = OnchainEventEntry {
2645 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2647 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2648 self.onchain_events_awaiting_threshold_conf.push(entry);
2653 /// `Persist` defines behavior for persisting channel monitors: this could mean
2654 /// writing once to disk, and/or uploading to one or more backup services.
2656 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
2657 /// to disk/backups. And, on every update, you **must** persist either the
2658 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
2659 /// of situations such as revoking a transaction, then crashing before this
2660 /// revocation can be persisted, then unintentionally broadcasting a revoked
2661 /// transaction and losing money. This is a risk because previous channel states
2662 /// are toxic, so it's important that whatever channel state is persisted is
2663 /// kept up-to-date.
2664 pub trait Persist<ChannelSigner: Sign> {
2665 /// Persist a new channel's data. The data can be stored any way you want, but
2666 /// the identifier provided by Rust-Lightning is the channel's outpoint (and
2667 /// it is up to you to maintain a correct mapping between the outpoint and the
2668 /// stored channel data). Note that you **must** persist every new monitor to
2669 /// disk. See the `Persist` trait documentation for more details.
2671 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2672 /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2673 fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2675 /// Update one channel's data. The provided `ChannelMonitor` has already
2676 /// applied the given update.
2678 /// Note that on every update, you **must** persist either the
2679 /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
2680 /// the `Persist` trait documentation for more details.
2682 /// If an implementer chooses to persist the updates only, they need to make
2683 /// sure that all the updates are applied to the `ChannelMonitors` *before*
2684 /// the set of channel monitors is given to the `ChannelManager`
2685 /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
2686 /// applying a monitor update to a monitor. If full `ChannelMonitors` are
2687 /// persisted, then there is no need to persist individual updates.
2689 /// Note that there could be a performance tradeoff between persisting complete
2690 /// channel monitors on every update vs. persisting only updates and applying
2691 /// them in batches. The size of each monitor grows `O(number of state updates)`
2692 /// whereas updates are small and `O(1)`.
2694 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2695 /// [`ChannelMonitorUpdate::write`] for writing out an update, and
2696 /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2697 fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2700 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2702 T::Target: BroadcasterInterface,
2703 F::Target: FeeEstimator,
2706 fn block_connected(&self, block: &Block, height: u32) {
2707 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2708 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2711 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2712 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2716 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
2718 T::Target: BroadcasterInterface,
2719 F::Target: FeeEstimator,
2722 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
2723 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
2726 fn transaction_unconfirmed(&self, txid: &Txid) {
2727 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
2730 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
2731 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
2734 fn get_relevant_txids(&self) -> Vec<Txid> {
2735 self.0.get_relevant_txids()
2739 const MAX_ALLOC_SIZE: usize = 64*1024;
2741 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
2742 for (BlockHash, ChannelMonitor<Signer>) {
2743 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
2744 macro_rules! unwrap_obj {
2748 Err(_) => return Err(DecodeError::InvalidValue),
2753 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
2755 let latest_update_id: u64 = Readable::read(reader)?;
2756 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2758 let destination_script = Readable::read(reader)?;
2759 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2761 let revokable_address = Readable::read(reader)?;
2762 let per_commitment_point = Readable::read(reader)?;
2763 let revokable_script = Readable::read(reader)?;
2764 Some((revokable_address, per_commitment_point, revokable_script))
2767 _ => return Err(DecodeError::InvalidValue),
2769 let counterparty_payment_script = Readable::read(reader)?;
2770 let shutdown_script = {
2771 let script = <Script as Readable>::read(reader)?;
2772 if script.is_empty() { None } else { Some(script) }
2775 let channel_keys_id = Readable::read(reader)?;
2776 let holder_revocation_basepoint = Readable::read(reader)?;
2777 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2778 // barely-init'd ChannelMonitors that we can't do anything with.
2779 let outpoint = OutPoint {
2780 txid: Readable::read(reader)?,
2781 index: Readable::read(reader)?,
2783 let funding_info = (outpoint, Readable::read(reader)?);
2784 let current_counterparty_commitment_txid = Readable::read(reader)?;
2785 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2787 let counterparty_commitment_params = Readable::read(reader)?;
2788 let funding_redeemscript = Readable::read(reader)?;
2789 let channel_value_satoshis = Readable::read(reader)?;
2791 let their_cur_revocation_points = {
2792 let first_idx = <U48 as Readable>::read(reader)?.0;
2796 let first_point = Readable::read(reader)?;
2797 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2798 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2799 Some((first_idx, first_point, None))
2801 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2806 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2808 let commitment_secrets = Readable::read(reader)?;
2810 macro_rules! read_htlc_in_commitment {
2813 let offered: bool = Readable::read(reader)?;
2814 let amount_msat: u64 = Readable::read(reader)?;
2815 let cltv_expiry: u32 = Readable::read(reader)?;
2816 let payment_hash: PaymentHash = Readable::read(reader)?;
2817 let transaction_output_index: Option<u32> = Readable::read(reader)?;
2819 HTLCOutputInCommitment {
2820 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2826 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2827 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2828 for _ in 0..counterparty_claimable_outpoints_len {
2829 let txid: Txid = Readable::read(reader)?;
2830 let htlcs_count: u64 = Readable::read(reader)?;
2831 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2832 for _ in 0..htlcs_count {
2833 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2835 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2836 return Err(DecodeError::InvalidValue);
2840 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2841 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2842 for _ in 0..counterparty_commitment_txn_on_chain_len {
2843 let txid: Txid = Readable::read(reader)?;
2844 let commitment_number = <U48 as Readable>::read(reader)?.0;
2845 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
2846 return Err(DecodeError::InvalidValue);
2850 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2851 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2852 for _ in 0..counterparty_hash_commitment_number_len {
2853 let payment_hash: PaymentHash = Readable::read(reader)?;
2854 let commitment_number = <U48 as Readable>::read(reader)?.0;
2855 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2856 return Err(DecodeError::InvalidValue);
2860 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
2861 match <u8 as Readable>::read(reader)? {
2864 Some(Readable::read(reader)?)
2866 _ => return Err(DecodeError::InvalidValue),
2868 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
2870 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2871 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2873 let payment_preimages_len: u64 = Readable::read(reader)?;
2874 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2875 for _ in 0..payment_preimages_len {
2876 let preimage: PaymentPreimage = Readable::read(reader)?;
2877 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2878 if let Some(_) = payment_preimages.insert(hash, preimage) {
2879 return Err(DecodeError::InvalidValue);
2883 let pending_monitor_events_len: u64 = Readable::read(reader)?;
2884 let mut pending_monitor_events = Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2885 for _ in 0..pending_monitor_events_len {
2886 let ev = match <u8 as Readable>::read(reader)? {
2887 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
2888 1 => MonitorEvent::CommitmentTxBroadcasted(funding_info.0),
2889 _ => return Err(DecodeError::InvalidValue)
2891 pending_monitor_events.push(ev);
2894 let pending_events_len: u64 = Readable::read(reader)?;
2895 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
2896 for _ in 0..pending_events_len {
2897 if let Some(event) = MaybeReadable::read(reader)? {
2898 pending_events.push(event);
2902 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
2904 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2905 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2906 for _ in 0..waiting_threshold_conf_len {
2907 if let Some(val) = MaybeReadable::read(reader)? {
2908 onchain_events_awaiting_threshold_conf.push(val);
2912 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2913 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>>())));
2914 for _ in 0..outputs_to_watch_len {
2915 let txid = Readable::read(reader)?;
2916 let outputs_len: u64 = Readable::read(reader)?;
2917 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
2918 for _ in 0..outputs_len {
2919 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
2921 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2922 return Err(DecodeError::InvalidValue);
2925 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
2927 let lockdown_from_offchain = Readable::read(reader)?;
2928 let holder_tx_signed = Readable::read(reader)?;
2930 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
2931 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
2932 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
2933 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
2934 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
2935 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
2936 return Err(DecodeError::InvalidValue);
2940 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
2941 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
2942 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
2943 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
2944 return Err(DecodeError::InvalidValue);
2947 let mut funding_spend_confirmed = None;
2948 let mut htlcs_resolved_on_chain = Some(Vec::new());
2949 read_tlv_fields!(reader, {
2950 (1, funding_spend_confirmed, option),
2951 (3, htlcs_resolved_on_chain, vec_type),
2954 let mut secp_ctx = Secp256k1::new();
2955 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
2957 Ok((best_block.block_hash(), ChannelMonitor {
2958 inner: Mutex::new(ChannelMonitorImpl {
2960 commitment_transaction_number_obscure_factor,
2963 broadcasted_holder_revokable_script,
2964 counterparty_payment_script,
2968 holder_revocation_basepoint,
2970 current_counterparty_commitment_txid,
2971 prev_counterparty_commitment_txid,
2973 counterparty_commitment_params,
2974 funding_redeemscript,
2975 channel_value_satoshis,
2976 their_cur_revocation_points,
2981 counterparty_claimable_outpoints,
2982 counterparty_commitment_txn_on_chain,
2983 counterparty_hash_commitment_number,
2985 prev_holder_signed_commitment_tx,
2986 current_holder_commitment_tx,
2987 current_counterparty_commitment_number,
2988 current_holder_commitment_number,
2991 pending_monitor_events,
2994 onchain_events_awaiting_threshold_conf,
2999 lockdown_from_offchain,
3001 funding_spend_confirmed,
3002 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3014 use bitcoin::blockdata::script::{Script, Builder};
3015 use bitcoin::blockdata::opcodes;
3016 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3017 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3018 use bitcoin::util::bip143;
3019 use bitcoin::hashes::Hash;
3020 use bitcoin::hashes::sha256::Hash as Sha256;
3021 use bitcoin::hashes::hex::FromHex;
3022 use bitcoin::hash_types::Txid;
3023 use bitcoin::network::constants::Network;
3025 use chain::BestBlock;
3026 use chain::channelmonitor::ChannelMonitor;
3027 use chain::package::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
3028 use chain::transaction::OutPoint;
3029 use ln::{PaymentPreimage, PaymentHash};
3031 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3032 use ln::script::ShutdownScript;
3033 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3034 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
3035 use bitcoin::secp256k1::Secp256k1;
3036 use sync::{Arc, Mutex};
3037 use chain::keysinterface::InMemorySigner;
3041 fn test_prune_preimages() {
3042 let secp_ctx = Secp256k1::new();
3043 let logger = Arc::new(TestLogger::new());
3044 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3045 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: Mutex::new(253) });
3047 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3048 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3050 let mut preimages = Vec::new();
3053 let preimage = PaymentPreimage([i; 32]);
3054 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3055 preimages.push((preimage, hash));
3059 macro_rules! preimages_slice_to_htlc_outputs {
3060 ($preimages_slice: expr) => {
3062 let mut res = Vec::new();
3063 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3064 res.push((HTLCOutputInCommitment {
3068 payment_hash: preimage.1.clone(),
3069 transaction_output_index: Some(idx as u32),
3076 macro_rules! preimages_to_holder_htlcs {
3077 ($preimages_slice: expr) => {
3079 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3080 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3086 macro_rules! test_preimages_exist {
3087 ($preimages_slice: expr, $monitor: expr) => {
3088 for preimage in $preimages_slice {
3089 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3094 let keys = InMemorySigner::new(
3096 SecretKey::from_slice(&[41; 32]).unwrap(),
3097 SecretKey::from_slice(&[41; 32]).unwrap(),
3098 SecretKey::from_slice(&[41; 32]).unwrap(),
3099 SecretKey::from_slice(&[41; 32]).unwrap(),
3100 SecretKey::from_slice(&[41; 32]).unwrap(),
3106 let counterparty_pubkeys = ChannelPublicKeys {
3107 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3108 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3109 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3110 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3111 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3113 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
3114 let channel_parameters = ChannelTransactionParameters {
3115 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3116 holder_selected_contest_delay: 66,
3117 is_outbound_from_holder: true,
3118 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3119 pubkeys: counterparty_pubkeys,
3120 selected_contest_delay: 67,
3122 funding_outpoint: Some(funding_outpoint),
3124 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3126 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3127 let best_block = BestBlock::from_genesis(Network::Testnet);
3128 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3129 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3130 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3131 &channel_parameters,
3132 Script::new(), 46, 0,
3133 HolderCommitmentTransaction::dummy(), best_block);
3135 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3136 let dummy_txid = dummy_tx.txid();
3137 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3138 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3139 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3140 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3141 for &(ref preimage, ref hash) in preimages.iter() {
3142 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
3145 // Now provide a secret, pruning preimages 10-15
3146 let mut secret = [0; 32];
3147 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3148 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3149 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3150 test_preimages_exist!(&preimages[0..10], monitor);
3151 test_preimages_exist!(&preimages[15..20], monitor);
3153 // Now provide a further secret, pruning preimages 15-17
3154 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3155 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3156 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3157 test_preimages_exist!(&preimages[0..10], monitor);
3158 test_preimages_exist!(&preimages[17..20], monitor);
3160 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3161 // previous commitment tx's preimages too
3162 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3163 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3164 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3165 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3166 test_preimages_exist!(&preimages[0..10], monitor);
3167 test_preimages_exist!(&preimages[18..20], monitor);
3169 // But if we do it again, we'll prune 5-10
3170 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3171 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3172 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3173 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3174 test_preimages_exist!(&preimages[0..5], monitor);
3178 fn test_claim_txn_weight_computation() {
3179 // We test Claim txn weight, knowing that we want expected weigth and
3180 // not actual case to avoid sigs and time-lock delays hell variances.
3182 let secp_ctx = Secp256k1::new();
3183 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3184 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3185 let mut sum_actual_sigs = 0;
3187 macro_rules! sign_input {
3188 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr) => {
3189 let htlc = HTLCOutputInCommitment {
3190 offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
3192 cltv_expiry: 2 << 16,
3193 payment_hash: PaymentHash([1; 32]),
3194 transaction_output_index: Some($idx as u32),
3196 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, &pubkey, &pubkey, &pubkey) };
3197 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3198 let sig = secp_ctx.sign(&sighash, &privkey);
3199 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3200 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3201 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3202 if *$weight == WEIGHT_REVOKED_OUTPUT {
3203 $sighash_parts.access_witness($idx).push(vec!(1));
3204 } else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
3205 $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3206 } else if *$weight == WEIGHT_RECEIVED_HTLC {
3207 $sighash_parts.access_witness($idx).push(vec![0]);
3209 $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3211 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3212 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3213 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3214 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3218 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3219 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3221 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3222 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3224 claim_tx.input.push(TxIn {
3225 previous_output: BitcoinOutPoint {
3229 script_sig: Script::new(),
3230 sequence: 0xfffffffd,
3231 witness: Vec::new(),
3234 claim_tx.output.push(TxOut {
3235 script_pubkey: script_pubkey.clone(),
3238 let base_weight = claim_tx.get_weight();
3239 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3240 let mut inputs_total_weight = 2; // count segwit flags
3242 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3243 for (idx, inp) in inputs_weight.iter().enumerate() {
3244 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3245 inputs_total_weight += inp;
3248 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3250 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3251 claim_tx.input.clear();
3252 sum_actual_sigs = 0;
3254 claim_tx.input.push(TxIn {
3255 previous_output: BitcoinOutPoint {
3259 script_sig: Script::new(),
3260 sequence: 0xfffffffd,
3261 witness: Vec::new(),
3264 let base_weight = claim_tx.get_weight();
3265 let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3266 let mut inputs_total_weight = 2; // count segwit flags
3268 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3269 for (idx, inp) in inputs_weight.iter().enumerate() {
3270 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3271 inputs_total_weight += inp;
3274 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3276 // Justice tx with 1 revoked HTLC-Success tx output
3277 claim_tx.input.clear();
3278 sum_actual_sigs = 0;
3279 claim_tx.input.push(TxIn {
3280 previous_output: BitcoinOutPoint {
3284 script_sig: Script::new(),
3285 sequence: 0xfffffffd,
3286 witness: Vec::new(),
3288 let base_weight = claim_tx.get_weight();
3289 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3290 let mut inputs_total_weight = 2; // count segwit flags
3292 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3293 for (idx, inp) in inputs_weight.iter().enumerate() {
3294 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3295 inputs_total_weight += inp;
3298 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3301 // Further testing is done in the ChannelManager integration tests.