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;
359 if let OnchainEvent::MaturingOutput {
360 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
362 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
363 // it's broadcastable when we see the previous block.
364 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
369 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
370 best_block.height() >= self.confirmation_threshold()
374 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
375 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
378 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
379 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
380 /// only win from it, so it's never an OnchainEvent
383 payment_hash: PaymentHash,
384 onchain_value_satoshis: Option<u64>,
387 descriptor: SpendableOutputDescriptor,
391 impl Writeable for OnchainEventEntry {
392 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
393 write_tlv_fields!(writer, {
394 (0, self.txid, required),
395 (2, self.height, required),
396 (4, self.event, required),
402 impl MaybeReadable for OnchainEventEntry {
403 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
404 let mut txid = Default::default();
406 let mut event = None;
407 read_tlv_fields!(reader, {
409 (2, height, required),
410 (4, event, ignorable),
412 if let Some(ev) = event {
413 Ok(Some(Self { txid, height, event: ev }))
420 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
422 (0, source, required),
423 (1, onchain_value_satoshis, option),
424 (2, payment_hash, required),
426 (1, MaturingOutput) => {
427 (0, descriptor, required),
431 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
433 pub(crate) enum ChannelMonitorUpdateStep {
434 LatestHolderCommitmentTXInfo {
435 commitment_tx: HolderCommitmentTransaction,
436 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
438 LatestCounterpartyCommitmentTXInfo {
439 commitment_txid: Txid,
440 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
441 commitment_number: u64,
442 their_revocation_point: PublicKey,
445 payment_preimage: PaymentPreimage,
451 /// Used to indicate that the no future updates will occur, and likely that the latest holder
452 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
454 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
455 /// think we've fallen behind!
456 should_broadcast: bool,
459 scriptpubkey: Script,
463 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
464 (0, LatestHolderCommitmentTXInfo) => {
465 (0, commitment_tx, required),
466 (2, htlc_outputs, vec_type),
468 (1, LatestCounterpartyCommitmentTXInfo) => {
469 (0, commitment_txid, required),
470 (2, commitment_number, required),
471 (4, their_revocation_point, required),
472 (6, htlc_outputs, vec_type),
474 (2, PaymentPreimage) => {
475 (0, payment_preimage, required),
477 (3, CommitmentSecret) => {
479 (2, secret, required),
481 (4, ChannelForceClosed) => {
482 (0, should_broadcast, required),
484 (5, ShutdownScript) => {
485 (0, scriptpubkey, required),
489 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
490 /// on-chain transactions to ensure no loss of funds occurs.
492 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
493 /// information and are actively monitoring the chain.
495 /// Pending Events or updated HTLCs which have not yet been read out by
496 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
497 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
498 /// gotten are fully handled before re-serializing the new state.
500 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
501 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
502 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
503 /// returned block hash and the the current chain and then reconnecting blocks to get to the
504 /// best chain) upon deserializing the object!
505 pub struct ChannelMonitor<Signer: Sign> {
507 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
509 inner: Mutex<ChannelMonitorImpl<Signer>>,
512 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
513 latest_update_id: u64,
514 commitment_transaction_number_obscure_factor: u64,
516 destination_script: Script,
517 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
518 counterparty_payment_script: Script,
519 shutdown_script: Option<Script>,
521 channel_keys_id: [u8; 32],
522 holder_revocation_basepoint: PublicKey,
523 funding_info: (OutPoint, Script),
524 current_counterparty_commitment_txid: Option<Txid>,
525 prev_counterparty_commitment_txid: Option<Txid>,
527 counterparty_commitment_params: CounterpartyCommitmentParameters,
528 funding_redeemscript: Script,
529 channel_value_satoshis: u64,
530 // first is the idx of the first of the two revocation points
531 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
533 on_holder_tx_csv: u16,
535 commitment_secrets: CounterpartyCommitmentSecrets,
536 /// The set of outpoints in each counterparty commitment transaction. We always need at least
537 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
538 /// transaction broadcast as we need to be able to construct the witness script in all cases.
539 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
540 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
541 /// Nor can we figure out their commitment numbers without the commitment transaction they are
542 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
543 /// commitment transactions which we find on-chain, mapping them to the commitment number which
544 /// can be used to derive the revocation key and claim the transactions.
545 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
546 /// Cache used to make pruning of payment_preimages faster.
547 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
548 /// counterparty transactions (ie should remain pretty small).
549 /// Serialized to disk but should generally not be sent to Watchtowers.
550 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
552 // We store two holder commitment transactions to avoid any race conditions where we may update
553 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
554 // various monitors for one channel being out of sync, and us broadcasting a holder
555 // transaction for which we have deleted claim information on some watchtowers.
556 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
557 current_holder_commitment_tx: HolderSignedTx,
559 // Used just for ChannelManager to make sure it has the latest channel data during
561 current_counterparty_commitment_number: u64,
562 // Used just for ChannelManager to make sure it has the latest channel data during
564 current_holder_commitment_number: u64,
566 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
568 pending_monitor_events: Vec<MonitorEvent>,
569 pending_events: Vec<Event>,
571 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
572 // which to take actions once they reach enough confirmations. Each entry includes the
573 // transaction's id and the height when the transaction was confirmed on chain.
574 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
576 // If we get serialized out and re-read, we need to make sure that the chain monitoring
577 // interface knows about the TXOs that we want to be notified of spends of. We could probably
578 // be smart and derive them from the above storage fields, but its much simpler and more
579 // Obviously Correct (tm) if we just keep track of them explicitly.
580 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
583 pub onchain_tx_handler: OnchainTxHandler<Signer>,
585 onchain_tx_handler: OnchainTxHandler<Signer>,
587 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
588 // channel has been force-closed. After this is set, no further holder commitment transaction
589 // updates may occur, and we panic!() if one is provided.
590 lockdown_from_offchain: bool,
592 // Set once we've signed a holder commitment transaction and handed it over to our
593 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
594 // may occur, and we fail any such monitor updates.
596 // In case of update rejection due to a locally already signed commitment transaction, we
597 // nevertheless store update content to track in case of concurrent broadcast by another
598 // remote monitor out-of-order with regards to the block view.
599 holder_tx_signed: bool,
601 // We simply modify best_block in Channel's block_connected so that serialization is
602 // consistent but hopefully the users' copy handles block_connected in a consistent way.
603 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
604 // their best_block from its state and not based on updated copies that didn't run through
605 // the full block_connected).
606 best_block: BestBlock,
608 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
611 /// Transaction outputs to watch for on-chain spends.
612 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
614 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
615 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
616 /// underlying object
617 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
618 fn eq(&self, other: &Self) -> bool {
619 let inner = self.inner.lock().unwrap();
620 let other = other.inner.lock().unwrap();
625 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
626 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
627 /// underlying object
628 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
629 fn eq(&self, other: &Self) -> bool {
630 if self.latest_update_id != other.latest_update_id ||
631 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
632 self.destination_script != other.destination_script ||
633 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
634 self.counterparty_payment_script != other.counterparty_payment_script ||
635 self.channel_keys_id != other.channel_keys_id ||
636 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
637 self.funding_info != other.funding_info ||
638 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
639 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
640 self.counterparty_commitment_params != other.counterparty_commitment_params ||
641 self.funding_redeemscript != other.funding_redeemscript ||
642 self.channel_value_satoshis != other.channel_value_satoshis ||
643 self.their_cur_revocation_points != other.their_cur_revocation_points ||
644 self.on_holder_tx_csv != other.on_holder_tx_csv ||
645 self.commitment_secrets != other.commitment_secrets ||
646 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
647 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
648 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
649 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
650 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
651 self.current_holder_commitment_number != other.current_holder_commitment_number ||
652 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
653 self.payment_preimages != other.payment_preimages ||
654 self.pending_monitor_events != other.pending_monitor_events ||
655 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
656 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
657 self.outputs_to_watch != other.outputs_to_watch ||
658 self.lockdown_from_offchain != other.lockdown_from_offchain ||
659 self.holder_tx_signed != other.holder_tx_signed
668 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
669 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
670 self.inner.lock().unwrap().write(writer)
674 // These are also used for ChannelMonitorUpdate, above.
675 const SERIALIZATION_VERSION: u8 = 1;
676 const MIN_SERIALIZATION_VERSION: u8 = 1;
678 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
679 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
680 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
682 self.latest_update_id.write(writer)?;
684 // Set in initial Channel-object creation, so should always be set by now:
685 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
687 self.destination_script.write(writer)?;
688 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
689 writer.write_all(&[0; 1])?;
690 broadcasted_holder_revokable_script.0.write(writer)?;
691 broadcasted_holder_revokable_script.1.write(writer)?;
692 broadcasted_holder_revokable_script.2.write(writer)?;
694 writer.write_all(&[1; 1])?;
697 self.counterparty_payment_script.write(writer)?;
698 match &self.shutdown_script {
699 Some(script) => script.write(writer)?,
700 None => Script::new().write(writer)?,
703 self.channel_keys_id.write(writer)?;
704 self.holder_revocation_basepoint.write(writer)?;
705 writer.write_all(&self.funding_info.0.txid[..])?;
706 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
707 self.funding_info.1.write(writer)?;
708 self.current_counterparty_commitment_txid.write(writer)?;
709 self.prev_counterparty_commitment_txid.write(writer)?;
711 self.counterparty_commitment_params.write(writer)?;
712 self.funding_redeemscript.write(writer)?;
713 self.channel_value_satoshis.write(writer)?;
715 match self.their_cur_revocation_points {
716 Some((idx, pubkey, second_option)) => {
717 writer.write_all(&byte_utils::be48_to_array(idx))?;
718 writer.write_all(&pubkey.serialize())?;
719 match second_option {
720 Some(second_pubkey) => {
721 writer.write_all(&second_pubkey.serialize())?;
724 writer.write_all(&[0; 33])?;
729 writer.write_all(&byte_utils::be48_to_array(0))?;
733 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
735 self.commitment_secrets.write(writer)?;
737 macro_rules! serialize_htlc_in_commitment {
738 ($htlc_output: expr) => {
739 writer.write_all(&[$htlc_output.offered as u8; 1])?;
740 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
741 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
742 writer.write_all(&$htlc_output.payment_hash.0[..])?;
743 $htlc_output.transaction_output_index.write(writer)?;
747 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
748 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
749 writer.write_all(&txid[..])?;
750 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
751 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
752 serialize_htlc_in_commitment!(htlc_output);
753 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
757 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
758 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
759 writer.write_all(&txid[..])?;
760 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
763 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
764 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
765 writer.write_all(&payment_hash.0[..])?;
766 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
769 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
770 writer.write_all(&[1; 1])?;
771 prev_holder_tx.write(writer)?;
773 writer.write_all(&[0; 1])?;
776 self.current_holder_commitment_tx.write(writer)?;
778 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
779 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
781 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
782 for payment_preimage in self.payment_preimages.values() {
783 writer.write_all(&payment_preimage.0[..])?;
786 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
787 for event in self.pending_monitor_events.iter() {
789 MonitorEvent::HTLCEvent(upd) => {
793 MonitorEvent::CommitmentTxBroadcasted(_) => 1u8.write(writer)?
797 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
798 for event in self.pending_events.iter() {
799 event.write(writer)?;
802 self.best_block.block_hash().write(writer)?;
803 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
805 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
806 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
807 entry.write(writer)?;
810 (self.outputs_to_watch.len() as u64).write(writer)?;
811 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
813 (idx_scripts.len() as u64).write(writer)?;
814 for (idx, script) in idx_scripts.iter() {
816 script.write(writer)?;
819 self.onchain_tx_handler.write(writer)?;
821 self.lockdown_from_offchain.write(writer)?;
822 self.holder_tx_signed.write(writer)?;
824 write_tlv_fields!(writer, {});
830 impl<Signer: Sign> ChannelMonitor<Signer> {
831 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
832 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
833 channel_parameters: &ChannelTransactionParameters,
834 funding_redeemscript: Script, channel_value_satoshis: u64,
835 commitment_transaction_number_obscure_factor: u64,
836 initial_holder_commitment_tx: HolderCommitmentTransaction,
837 best_block: BestBlock) -> ChannelMonitor<Signer> {
839 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
840 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
841 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
843 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
844 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
845 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
846 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
848 let channel_keys_id = keys.channel_keys_id();
849 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
851 // block for Rust 1.34 compat
852 let (holder_commitment_tx, current_holder_commitment_number) = {
853 let trusted_tx = initial_holder_commitment_tx.trust();
854 let txid = trusted_tx.txid();
856 let tx_keys = trusted_tx.keys();
857 let holder_commitment_tx = HolderSignedTx {
859 revocation_key: tx_keys.revocation_key,
860 a_htlc_key: tx_keys.broadcaster_htlc_key,
861 b_htlc_key: tx_keys.countersignatory_htlc_key,
862 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
863 per_commitment_point: tx_keys.per_commitment_point,
864 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
865 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
866 feerate_per_kw: trusted_tx.feerate_per_kw(),
868 (holder_commitment_tx, trusted_tx.commitment_number())
871 let onchain_tx_handler =
872 OnchainTxHandler::new(destination_script.clone(), keys,
873 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
875 let mut outputs_to_watch = HashMap::new();
876 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
879 inner: Mutex::new(ChannelMonitorImpl {
881 commitment_transaction_number_obscure_factor,
883 destination_script: destination_script.clone(),
884 broadcasted_holder_revokable_script: None,
885 counterparty_payment_script,
889 holder_revocation_basepoint,
891 current_counterparty_commitment_txid: None,
892 prev_counterparty_commitment_txid: None,
894 counterparty_commitment_params,
895 funding_redeemscript,
896 channel_value_satoshis,
897 their_cur_revocation_points: None,
899 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
901 commitment_secrets: CounterpartyCommitmentSecrets::new(),
902 counterparty_claimable_outpoints: HashMap::new(),
903 counterparty_commitment_txn_on_chain: HashMap::new(),
904 counterparty_hash_commitment_number: HashMap::new(),
906 prev_holder_signed_commitment_tx: None,
907 current_holder_commitment_tx: holder_commitment_tx,
908 current_counterparty_commitment_number: 1 << 48,
909 current_holder_commitment_number,
911 payment_preimages: HashMap::new(),
912 pending_monitor_events: Vec::new(),
913 pending_events: Vec::new(),
915 onchain_events_awaiting_threshold_conf: Vec::new(),
920 lockdown_from_offchain: false,
921 holder_tx_signed: false,
931 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
932 self.inner.lock().unwrap().provide_secret(idx, secret)
935 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
936 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
937 /// possibly future revocation/preimage information) to claim outputs where possible.
938 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
939 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
942 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
943 commitment_number: u64,
944 their_revocation_point: PublicKey,
946 ) where L::Target: Logger {
947 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
948 txid, htlc_outputs, commitment_number, their_revocation_point, logger)
952 fn provide_latest_holder_commitment_tx(
954 holder_commitment_tx: HolderCommitmentTransaction,
955 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
956 ) -> Result<(), MonitorUpdateError> {
957 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
958 holder_commitment_tx, htlc_outputs)
962 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
964 payment_hash: &PaymentHash,
965 payment_preimage: &PaymentPreimage,
970 B::Target: BroadcasterInterface,
971 F::Target: FeeEstimator,
974 self.inner.lock().unwrap().provide_payment_preimage(
975 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
978 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
983 B::Target: BroadcasterInterface,
986 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
989 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
992 /// panics if the given update is not the next update by update_id.
993 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
995 updates: &ChannelMonitorUpdate,
999 ) -> Result<(), MonitorUpdateError>
1001 B::Target: BroadcasterInterface,
1002 F::Target: FeeEstimator,
1005 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1008 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1010 pub fn get_latest_update_id(&self) -> u64 {
1011 self.inner.lock().unwrap().get_latest_update_id()
1014 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1015 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1016 self.inner.lock().unwrap().get_funding_txo().clone()
1019 /// Gets a list of txids, with their output scripts (in the order they appear in the
1020 /// transaction), which we must learn about spends of via block_connected().
1021 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1022 self.inner.lock().unwrap().get_outputs_to_watch()
1023 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1026 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1027 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1028 /// have been registered.
1029 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1030 let lock = self.inner.lock().unwrap();
1031 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1032 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1033 for (index, script_pubkey) in outputs.iter() {
1034 assert!(*index <= u16::max_value() as u32);
1035 filter.register_output(WatchedOutput {
1037 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1038 script_pubkey: script_pubkey.clone(),
1044 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1045 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1046 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1047 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1050 /// Gets the list of pending events which were generated by previous actions, clearing the list
1053 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1054 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1055 /// no internal locking in ChannelMonitors.
1056 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1057 self.inner.lock().unwrap().get_and_clear_pending_events()
1060 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1061 self.inner.lock().unwrap().get_min_seen_secret()
1064 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1065 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1068 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1069 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1072 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1073 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1074 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1075 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1076 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1077 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1078 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1079 /// out-of-band the other node operator to coordinate with him if option is available to you.
1080 /// In any-case, choice is up to the user.
1081 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1082 where L::Target: Logger {
1083 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1086 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1087 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1088 /// revoked commitment transaction.
1089 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1090 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1091 where L::Target: Logger {
1092 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1095 /// Processes transactions in a newly connected block, which may result in any of the following:
1096 /// - update the monitor's state against resolved HTLCs
1097 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1098 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1099 /// - detect settled outputs for later spending
1100 /// - schedule and bump any in-flight claims
1102 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1103 /// [`get_outputs_to_watch`].
1105 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1106 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1108 header: &BlockHeader,
1109 txdata: &TransactionData,
1114 ) -> Vec<TransactionOutputs>
1116 B::Target: BroadcasterInterface,
1117 F::Target: FeeEstimator,
1120 self.inner.lock().unwrap().block_connected(
1121 header, txdata, height, broadcaster, fee_estimator, logger)
1124 /// Determines if the disconnected block contained any transactions of interest and updates
1126 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1128 header: &BlockHeader,
1134 B::Target: BroadcasterInterface,
1135 F::Target: FeeEstimator,
1138 self.inner.lock().unwrap().block_disconnected(
1139 header, height, broadcaster, fee_estimator, logger)
1142 /// Processes transactions confirmed in a block with the given header and height, returning new
1143 /// outputs to watch. See [`block_connected`] for details.
1145 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1146 /// blocks. See [`chain::Confirm`] for calling expectations.
1148 /// [`block_connected`]: Self::block_connected
1149 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1151 header: &BlockHeader,
1152 txdata: &TransactionData,
1157 ) -> Vec<TransactionOutputs>
1159 B::Target: BroadcasterInterface,
1160 F::Target: FeeEstimator,
1163 self.inner.lock().unwrap().transactions_confirmed(
1164 header, txdata, height, broadcaster, fee_estimator, logger)
1167 /// Processes a transaction that was reorganized out of the chain.
1169 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1170 /// than blocks. See [`chain::Confirm`] for calling expectations.
1172 /// [`block_disconnected`]: Self::block_disconnected
1173 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1180 B::Target: BroadcasterInterface,
1181 F::Target: FeeEstimator,
1184 self.inner.lock().unwrap().transaction_unconfirmed(
1185 txid, broadcaster, fee_estimator, logger);
1188 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1189 /// [`block_connected`] for details.
1191 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1192 /// blocks. See [`chain::Confirm`] for calling expectations.
1194 /// [`block_connected`]: Self::block_connected
1195 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1197 header: &BlockHeader,
1202 ) -> Vec<TransactionOutputs>
1204 B::Target: BroadcasterInterface,
1205 F::Target: FeeEstimator,
1208 self.inner.lock().unwrap().best_block_updated(
1209 header, height, broadcaster, fee_estimator, logger)
1212 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1213 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1214 let inner = self.inner.lock().unwrap();
1215 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1217 .map(|entry| entry.txid)
1218 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1220 txids.sort_unstable();
1225 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1226 /// [`chain::Confirm`] interfaces.
1227 pub fn current_best_block(&self) -> BestBlock {
1228 self.inner.lock().unwrap().best_block.clone()
1232 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1233 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1234 /// after ANTI_REORG_DELAY blocks.
1236 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1237 /// are the commitment transactions which are generated by us. The off-chain state machine in
1238 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1239 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1240 /// included in a remote commitment transaction are failed back if they are not present in the
1241 /// broadcasted commitment transaction.
1243 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1244 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1245 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1246 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1247 macro_rules! fail_unbroadcast_htlcs {
1248 ($self: expr, $commitment_tx_type: expr, $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1249 macro_rules! check_htlc_fails {
1250 ($txid: expr, $commitment_tx: expr) => {
1251 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1252 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1253 if let &Some(ref source) = source_option {
1254 // Check if the HTLC is present in the commitment transaction that was
1255 // broadcast, but not if it was below the dust limit, which we should
1256 // fail backwards immediately as there is no way for us to learn the
1257 // payment_preimage.
1258 // Note that if the dust limit were allowed to change between
1259 // commitment transactions we'd want to be check whether *any*
1260 // broadcastable commitment transaction has the HTLC in it, but it
1261 // cannot currently change after channel initialization, so we don't
1263 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1264 let mut matched_htlc = false;
1265 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1266 if broadcast_htlc.transaction_output_index.is_some() && Some(&**source) == *broadcast_source {
1267 matched_htlc = true;
1271 if matched_htlc { continue; }
1272 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1273 if entry.height != $commitment_tx_conf_height { return true; }
1275 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1276 *update_source != **source
1281 let entry = OnchainEventEntry {
1283 height: $commitment_tx_conf_height,
1284 event: OnchainEvent::HTLCUpdate {
1285 source: (**source).clone(),
1286 payment_hash: htlc.payment_hash.clone(),
1287 onchain_value_satoshis: Some(htlc.amount_msat / 1000),
1290 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction, waiting for confirmation (at height {})",
1291 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type, entry.confirmation_threshold());
1292 $self.onchain_events_awaiting_threshold_conf.push(entry);
1298 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1299 check_htlc_fails!(txid, "current");
1301 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1302 check_htlc_fails!(txid, "previous");
1307 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1308 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1309 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1310 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1311 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1312 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1313 return Err(MonitorUpdateError("Previous secret did not match new one"));
1316 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1317 // events for now-revoked/fulfilled HTLCs.
1318 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1319 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1324 if !self.payment_preimages.is_empty() {
1325 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1326 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1327 let min_idx = self.get_min_seen_secret();
1328 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1330 self.payment_preimages.retain(|&k, _| {
1331 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1332 if k == htlc.payment_hash {
1336 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1337 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1338 if k == htlc.payment_hash {
1343 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1350 counterparty_hash_commitment_number.remove(&k);
1359 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 {
1360 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1361 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1362 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1364 for &(ref htlc, _) in &htlc_outputs {
1365 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1368 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1369 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1370 self.current_counterparty_commitment_txid = Some(txid);
1371 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1372 self.current_counterparty_commitment_number = commitment_number;
1373 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1374 match self.their_cur_revocation_points {
1375 Some(old_points) => {
1376 if old_points.0 == commitment_number + 1 {
1377 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1378 } else if old_points.0 == commitment_number + 2 {
1379 if let Some(old_second_point) = old_points.2 {
1380 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1382 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1385 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1389 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1392 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1393 for htlc in htlc_outputs {
1394 if htlc.0.transaction_output_index.is_some() {
1400 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1401 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1402 /// is important that any clones of this channel monitor (including remote clones) by kept
1403 /// up-to-date as our holder commitment transaction is updated.
1404 /// Panics if set_on_holder_tx_csv has never been called.
1405 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1406 // block for Rust 1.34 compat
1407 let mut new_holder_commitment_tx = {
1408 let trusted_tx = holder_commitment_tx.trust();
1409 let txid = trusted_tx.txid();
1410 let tx_keys = trusted_tx.keys();
1411 self.current_holder_commitment_number = trusted_tx.commitment_number();
1414 revocation_key: tx_keys.revocation_key,
1415 a_htlc_key: tx_keys.broadcaster_htlc_key,
1416 b_htlc_key: tx_keys.countersignatory_htlc_key,
1417 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1418 per_commitment_point: tx_keys.per_commitment_point,
1420 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
1421 feerate_per_kw: trusted_tx.feerate_per_kw(),
1424 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1425 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1426 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1427 if self.holder_tx_signed {
1428 return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1433 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1434 /// commitment_tx_infos which contain the payment hash have been revoked.
1435 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)
1436 where B::Target: BroadcasterInterface,
1437 F::Target: FeeEstimator,
1440 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1442 // If the channel is force closed, try to claim the output from this preimage.
1443 // First check if a counterparty commitment transaction has been broadcasted:
1444 macro_rules! claim_htlcs {
1445 ($commitment_number: expr, $txid: expr) => {
1446 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1447 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1450 if let Some(txid) = self.current_counterparty_commitment_txid {
1451 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1452 claim_htlcs!(*commitment_number, txid);
1456 if let Some(txid) = self.prev_counterparty_commitment_txid {
1457 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1458 claim_htlcs!(*commitment_number, txid);
1463 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1464 // claiming the HTLC output from each of the holder commitment transactions.
1465 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1466 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1467 // holder commitment transactions.
1468 if self.broadcasted_holder_revokable_script.is_some() {
1469 // Assume that the broadcasted commitment transaction confirmed in the current best
1470 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
1472 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
1473 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1474 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1475 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
1476 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
1481 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1482 where B::Target: BroadcasterInterface,
1485 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1486 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
1487 broadcaster.broadcast_transaction(tx);
1489 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1492 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
1493 where B::Target: BroadcasterInterface,
1494 F::Target: FeeEstimator,
1497 // ChannelMonitor updates may be applied after force close if we receive a
1498 // preimage for a broadcasted commitment transaction HTLC output that we'd
1499 // like to claim on-chain. If this is the case, we no longer have guaranteed
1500 // access to the monitor's update ID, so we use a sentinel value instead.
1501 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1502 match updates.updates[0] {
1503 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1504 _ => panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage"),
1506 assert_eq!(updates.updates.len(), 1);
1507 } else if self.latest_update_id + 1 != updates.update_id {
1508 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1510 for update in updates.updates.iter() {
1512 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1513 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1514 if self.lockdown_from_offchain { panic!(); }
1515 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
1517 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1518 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1519 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1521 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1522 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1523 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1525 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1526 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1527 self.provide_secret(*idx, *secret)?
1529 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1530 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1531 self.lockdown_from_offchain = true;
1532 if *should_broadcast {
1533 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1534 } else if !self.holder_tx_signed {
1535 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");
1537 // If we generated a MonitorEvent::CommitmentTxBroadcasted, the ChannelManager
1538 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1539 // shouldn't print the scary warning above.
1540 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1543 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
1544 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
1545 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
1546 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
1551 self.latest_update_id = updates.update_id;
1555 pub fn get_latest_update_id(&self) -> u64 {
1556 self.latest_update_id
1559 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1563 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1564 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1565 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1566 // its trivial to do, double-check that here.
1567 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1568 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1570 &self.outputs_to_watch
1573 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1574 let mut ret = Vec::new();
1575 mem::swap(&mut ret, &mut self.pending_monitor_events);
1579 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1580 let mut ret = Vec::new();
1581 mem::swap(&mut ret, &mut self.pending_events);
1585 /// Can only fail if idx is < get_min_seen_secret
1586 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1587 self.commitment_secrets.get_secret(idx)
1590 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1591 self.commitment_secrets.get_min_seen_secret()
1594 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1595 self.current_counterparty_commitment_number
1598 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1599 self.current_holder_commitment_number
1602 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1603 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1604 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1605 /// HTLC-Success/HTLC-Timeout transactions.
1606 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1607 /// revoked counterparty commitment tx
1608 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1609 // Most secp and related errors trying to create keys means we have no hope of constructing
1610 // a spend transaction...so we return no transactions to broadcast
1611 let mut claimable_outpoints = Vec::new();
1612 let mut watch_outputs = Vec::new();
1614 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1615 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1617 macro_rules! ignore_error {
1618 ( $thing : expr ) => {
1621 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1626 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);
1627 if commitment_number >= self.get_min_seen_secret() {
1628 let secret = self.get_secret(commitment_number).unwrap();
1629 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1630 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1631 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
1632 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));
1634 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
1635 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1637 // First, process non-htlc outputs (to_holder & to_counterparty)
1638 for (idx, outp) in tx.output.iter().enumerate() {
1639 if outp.script_pubkey == revokeable_p2wsh {
1640 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);
1641 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);
1642 claimable_outpoints.push(justice_package);
1646 // Then, try to find revoked htlc outputs
1647 if let Some(ref per_commitment_data) = per_commitment_option {
1648 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1649 if let Some(transaction_output_index) = htlc.transaction_output_index {
1650 if transaction_output_index as usize >= tx.output.len() ||
1651 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1652 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1654 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());
1655 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
1656 claimable_outpoints.push(justice_package);
1661 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1662 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1663 // We're definitely a counterparty commitment transaction!
1664 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1665 for (idx, outp) in tx.output.iter().enumerate() {
1666 watch_outputs.push((idx as u32, outp.clone()));
1668 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1670 fail_unbroadcast_htlcs!(self, "revoked counterparty", height, [].iter().map(|a| *a), logger);
1672 } else if let Some(per_commitment_data) = per_commitment_option {
1673 // While this isn't useful yet, there is a potential race where if a counterparty
1674 // revokes a state at the same time as the commitment transaction for that state is
1675 // confirmed, and the watchtower receives the block before the user, the user could
1676 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1677 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1678 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1680 for (idx, outp) in tx.output.iter().enumerate() {
1681 watch_outputs.push((idx as u32, outp.clone()));
1683 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1685 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1686 fail_unbroadcast_htlcs!(self, "counterparty", height, per_commitment_data.iter().map(|(a, b)| (a, b.as_ref().map(|b| b.as_ref()))), logger);
1688 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
1689 for req in htlc_claim_reqs {
1690 claimable_outpoints.push(req);
1694 (claimable_outpoints, (commitment_txid, watch_outputs))
1697 fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<PackageTemplate> {
1698 let mut claimable_outpoints = Vec::new();
1699 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
1700 if let Some(revocation_points) = self.their_cur_revocation_points {
1701 let revocation_point_option =
1702 // If the counterparty commitment tx is the latest valid state, use their latest
1703 // per-commitment point
1704 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1705 else if let Some(point) = revocation_points.2.as_ref() {
1706 // If counterparty commitment tx is the state previous to the latest valid state, use
1707 // their previous per-commitment point (non-atomicity of revocation means it's valid for
1708 // them to temporarily have two valid commitment txns from our viewpoint)
1709 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1711 if let Some(revocation_point) = revocation_point_option {
1712 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
1713 if let Some(transaction_output_index) = htlc.transaction_output_index {
1714 if let Some(transaction) = tx {
1715 if transaction_output_index as usize >= transaction.output.len() ||
1716 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1717 return claimable_outpoints; // Corrupted per_commitment_data, fuck this user
1720 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1721 if preimage.is_some() || !htlc.offered {
1722 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())) };
1723 let aggregation = if !htlc.offered { false } else { true };
1724 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
1725 claimable_outpoints.push(counterparty_package);
1735 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1736 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 {
1737 let htlc_txid = tx.txid();
1738 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1739 return (Vec::new(), None)
1742 macro_rules! ignore_error {
1743 ( $thing : expr ) => {
1746 Err(_) => return (Vec::new(), None)
1751 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1752 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1753 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1755 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
1756 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);
1757 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);
1758 let claimable_outpoints = vec!(justice_package);
1759 let outputs = vec![(0, tx.output[0].clone())];
1760 (claimable_outpoints, Some((htlc_txid, outputs)))
1763 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
1764 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
1765 // script so we can detect whether a holder transaction has been seen on-chain.
1766 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
1767 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
1769 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
1770 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
1772 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1773 if let Some(transaction_output_index) = htlc.transaction_output_index {
1774 let htlc_output = if htlc.offered {
1775 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
1777 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1780 // We can't build an HTLC-Success transaction without the preimage
1783 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
1785 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
1786 claim_requests.push(htlc_package);
1790 (claim_requests, broadcasted_holder_revokable_script)
1793 // Returns holder HTLC outputs to watch and react to in case of spending.
1794 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
1795 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
1796 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1797 if let Some(transaction_output_index) = htlc.transaction_output_index {
1798 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
1804 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1805 /// revoked using data in holder_claimable_outpoints.
1806 /// Should not be used if check_spend_revoked_transaction succeeds.
1807 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<PackageTemplate>, TransactionOutputs) where L::Target: Logger {
1808 let commitment_txid = tx.txid();
1809 let mut claim_requests = Vec::new();
1810 let mut watch_outputs = Vec::new();
1812 macro_rules! append_onchain_update {
1813 ($updates: expr, $to_watch: expr) => {
1814 claim_requests = $updates.0;
1815 self.broadcasted_holder_revokable_script = $updates.1;
1816 watch_outputs.append(&mut $to_watch);
1820 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1821 let mut is_holder_tx = false;
1823 if self.current_holder_commitment_tx.txid == commitment_txid {
1824 is_holder_tx = true;
1825 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
1826 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
1827 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
1828 append_onchain_update!(res, to_watch);
1829 fail_unbroadcast_htlcs!(self, "latest holder", height, self.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
1830 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1831 if holder_tx.txid == commitment_txid {
1832 is_holder_tx = true;
1833 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
1834 let res = self.get_broadcasted_holder_claims(holder_tx, height);
1835 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
1836 append_onchain_update!(res, to_watch);
1837 fail_unbroadcast_htlcs!(self, "previous holder", height, holder_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())), logger);
1844 (claim_requests, (commitment_txid, watch_outputs))
1847 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1848 log_debug!(logger, "Getting signed latest holder commitment transaction!");
1849 self.holder_tx_signed = true;
1850 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
1851 let txid = commitment_tx.txid();
1852 let mut holder_transactions = vec![commitment_tx];
1853 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1854 if let Some(vout) = htlc.0.transaction_output_index {
1855 let preimage = if !htlc.0.offered {
1856 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1857 // We can't build an HTLC-Success transaction without the preimage
1860 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
1861 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
1862 // current locktime requirements on-chain. We will broadcast them in
1863 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
1864 // Note that we add + 1 as transactions are broadcastable when they can be
1865 // confirmed in the next block.
1868 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
1869 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1870 holder_transactions.push(htlc_tx);
1874 // 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.
1875 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
1879 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1880 /// Note that this includes possibly-locktimed-in-the-future transactions!
1881 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1882 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
1883 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
1884 let txid = commitment_tx.txid();
1885 let mut holder_transactions = vec![commitment_tx];
1886 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1887 if let Some(vout) = htlc.0.transaction_output_index {
1888 let preimage = if !htlc.0.offered {
1889 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1890 // We can't build an HTLC-Success transaction without the preimage
1894 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
1895 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1896 holder_transactions.push(htlc_tx);
1903 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>
1904 where B::Target: BroadcasterInterface,
1905 F::Target: FeeEstimator,
1908 let block_hash = header.block_hash();
1909 self.best_block = BestBlock::new(block_hash, height);
1911 self.transactions_confirmed(header, txdata, height, broadcaster, fee_estimator, logger)
1914 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1916 header: &BlockHeader,
1921 ) -> Vec<TransactionOutputs>
1923 B::Target: BroadcasterInterface,
1924 F::Target: FeeEstimator,
1927 let block_hash = header.block_hash();
1929 if height > self.best_block.height() {
1930 self.best_block = BestBlock::new(block_hash, height);
1931 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
1932 } else if block_hash != self.best_block.block_hash() {
1933 self.best_block = BestBlock::new(block_hash, height);
1934 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
1935 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
1937 } else { Vec::new() }
1940 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1942 header: &BlockHeader,
1943 txdata: &TransactionData,
1948 ) -> Vec<TransactionOutputs>
1950 B::Target: BroadcasterInterface,
1951 F::Target: FeeEstimator,
1954 let txn_matched = self.filter_block(txdata);
1955 for tx in &txn_matched {
1956 let mut output_val = 0;
1957 for out in tx.output.iter() {
1958 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1959 output_val += out.value;
1960 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1964 let block_hash = header.block_hash();
1966 let mut watch_outputs = Vec::new();
1967 let mut claimable_outpoints = Vec::new();
1968 for tx in &txn_matched {
1969 if tx.input.len() == 1 {
1970 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1971 // commitment transactions and HTLC transactions will all only ever have one input,
1972 // which is an easy way to filter out any potential non-matching txn for lazy
1974 let prevout = &tx.input[0].previous_output;
1975 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
1976 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1977 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
1978 if !new_outputs.1.is_empty() {
1979 watch_outputs.push(new_outputs);
1981 if new_outpoints.is_empty() {
1982 let (mut new_outpoints, new_outputs) = self.check_spend_holder_transaction(&tx, height, &logger);
1983 if !new_outputs.1.is_empty() {
1984 watch_outputs.push(new_outputs);
1986 claimable_outpoints.append(&mut new_outpoints);
1988 claimable_outpoints.append(&mut new_outpoints);
1991 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
1992 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
1993 claimable_outpoints.append(&mut new_outpoints);
1994 if let Some(new_outputs) = new_outputs_option {
1995 watch_outputs.push(new_outputs);
2000 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2001 // can also be resolved in a few other ways which can have more than one output. Thus,
2002 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2003 self.is_resolving_htlc_output(&tx, height, &logger);
2005 self.is_paying_spendable_output(&tx, height, &logger);
2008 if height > self.best_block.height() {
2009 self.best_block = BestBlock::new(block_hash, height);
2012 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2015 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2016 /// `self.best_block` before calling if a new best blockchain tip is available. More
2017 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2018 /// complexity especially in `OnchainTx::update_claims_view`.
2020 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2021 /// confirmed at, even if it is not the current best height.
2022 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2025 txn_matched: Vec<&Transaction>,
2026 mut watch_outputs: Vec<TransactionOutputs>,
2027 mut claimable_outpoints: Vec<PackageTemplate>,
2031 ) -> Vec<TransactionOutputs>
2033 B::Target: BroadcasterInterface,
2034 F::Target: FeeEstimator,
2037 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2038 debug_assert!(self.best_block.height() >= conf_height);
2040 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2041 if should_broadcast {
2042 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2043 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());
2044 claimable_outpoints.push(commitment_package);
2045 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
2046 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2047 self.holder_tx_signed = true;
2048 // Because we're broadcasting a commitment transaction, we should construct the package
2049 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2050 // "not yet confirmed" things as discardable, so we cannot do that here.
2051 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2052 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2053 if !new_outputs.is_empty() {
2054 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2056 claimable_outpoints.append(&mut new_outpoints);
2059 // Find which on-chain events have reached their confirmation threshold.
2060 let onchain_events_awaiting_threshold_conf =
2061 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2062 let mut onchain_events_reaching_threshold_conf = Vec::new();
2063 for entry in onchain_events_awaiting_threshold_conf {
2064 if entry.has_reached_confirmation_threshold(&self.best_block) {
2065 onchain_events_reaching_threshold_conf.push(entry);
2067 self.onchain_events_awaiting_threshold_conf.push(entry);
2071 // Used to check for duplicate HTLC resolutions.
2072 #[cfg(debug_assertions)]
2073 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2075 .filter_map(|entry| match &entry.event {
2076 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2077 OnchainEvent::MaturingOutput { .. } => None,
2080 #[cfg(debug_assertions)]
2081 let mut matured_htlcs = Vec::new();
2083 // Produce actionable events from on-chain events having reached their threshold.
2084 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2086 OnchainEvent::HTLCUpdate { ref source, payment_hash, onchain_value_satoshis } => {
2087 // Check for duplicate HTLC resolutions.
2088 #[cfg(debug_assertions)]
2091 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2092 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2093 call either transaction_unconfirmed for the conflicting transaction \
2094 or block_disconnected for a block containing it.");
2096 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2097 "A matured HTLC transaction conflicts with a maturing one; failed to \
2098 call either transaction_unconfirmed for the conflicting transaction \
2099 or block_disconnected for a block containing it.");
2100 matured_htlcs.push(source.clone());
2103 log_debug!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!(payment_hash.0));
2104 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2106 payment_preimage: None,
2107 source: source.clone(),
2108 onchain_value_satoshis,
2111 OnchainEvent::MaturingOutput { descriptor } => {
2112 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2113 self.pending_events.push(Event::SpendableOutputs {
2114 outputs: vec![descriptor]
2120 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2122 // Determine new outputs to watch by comparing against previously known outputs to watch,
2123 // updating the latter in the process.
2124 watch_outputs.retain(|&(ref txid, ref txouts)| {
2125 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2126 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2130 // If we see a transaction for which we registered outputs previously,
2131 // make sure the registered scriptpubkey at the expected index match
2132 // the actual transaction output one. We failed this case before #653.
2133 for tx in &txn_matched {
2134 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2135 for idx_and_script in outputs.iter() {
2136 assert!((idx_and_script.0 as usize) < tx.output.len());
2137 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2145 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2146 where B::Target: BroadcasterInterface,
2147 F::Target: FeeEstimator,
2150 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2153 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2154 //- maturing spendable output has transaction paying us has been disconnected
2155 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2157 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2159 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2162 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2169 B::Target: BroadcasterInterface,
2170 F::Target: FeeEstimator,
2173 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.txid != *txid);
2174 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2177 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2178 /// transactions thereof.
2179 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2180 let mut matched_txn = HashSet::new();
2181 txdata.iter().filter(|&&(_, tx)| {
2182 let mut matches = self.spends_watched_output(tx);
2183 for input in tx.input.iter() {
2184 if matches { break; }
2185 if matched_txn.contains(&input.previous_output.txid) {
2190 matched_txn.insert(tx.txid());
2193 }).map(|(_, tx)| *tx).collect()
2196 /// Checks if a given transaction spends any watched outputs.
2197 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2198 for input in tx.input.iter() {
2199 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2200 for (idx, _script_pubkey) in outputs.iter() {
2201 if *idx == input.previous_output.vout {
2204 // If the expected script is a known type, check that the witness
2205 // appears to be spending the correct type (ie that the match would
2206 // actually succeed in BIP 158/159-style filters).
2207 if _script_pubkey.is_v0_p2wsh() {
2208 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2209 } else if _script_pubkey.is_v0_p2wpkh() {
2210 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2211 } else { panic!(); }
2222 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
2223 // We need to consider all HTLCs which are:
2224 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2225 // transactions and we'd end up in a race, or
2226 // * are in our latest holder commitment transaction, as this is the thing we will
2227 // broadcast if we go on-chain.
2228 // Note that we consider HTLCs which were below dust threshold here - while they don't
2229 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2230 // to the source, and if we don't fail the channel we will have to ensure that the next
2231 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2232 // easier to just fail the channel as this case should be rare enough anyway.
2233 let height = self.best_block.height();
2234 macro_rules! scan_commitment {
2235 ($htlcs: expr, $holder_tx: expr) => {
2236 for ref htlc in $htlcs {
2237 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2238 // chain with enough room to claim the HTLC without our counterparty being able to
2239 // time out the HTLC first.
2240 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2241 // concern is being able to claim the corresponding inbound HTLC (on another
2242 // channel) before it expires. In fact, we don't even really care if our
2243 // counterparty here claims such an outbound HTLC after it expired as long as we
2244 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2245 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2246 // we give ourselves a few blocks of headroom after expiration before going
2247 // on-chain for an expired HTLC.
2248 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2249 // from us until we've reached the point where we go on-chain with the
2250 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2251 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2252 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2253 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2254 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2255 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2256 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2257 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2258 // The final, above, condition is checked for statically in channelmanager
2259 // with CHECK_CLTV_EXPIRY_SANITY_2.
2260 let htlc_outbound = $holder_tx == htlc.offered;
2261 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2262 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2263 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2270 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2272 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2273 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2274 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2277 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2278 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2279 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2286 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2287 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2288 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2289 'outer_loop: for input in &tx.input {
2290 let mut payment_data = None;
2291 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2292 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2293 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2294 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2296 macro_rules! log_claim {
2297 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2298 // We found the output in question, but aren't failing it backwards
2299 // as we have no corresponding source and no valid counterparty commitment txid
2300 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2301 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2302 let outbound_htlc = $holder_tx == $htlc.offered;
2303 if ($holder_tx && revocation_sig_claim) ||
2304 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2305 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2306 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2307 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2308 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2310 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2311 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2312 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2313 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2318 macro_rules! check_htlc_valid_counterparty {
2319 ($counterparty_txid: expr, $htlc_output: expr) => {
2320 if let Some(txid) = $counterparty_txid {
2321 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2322 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2323 if let &Some(ref source) = pending_source {
2324 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2325 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
2334 macro_rules! scan_commitment {
2335 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2336 for (ref htlc_output, source_option) in $htlcs {
2337 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2338 if let Some(ref source) = source_option {
2339 log_claim!($tx_info, $holder_tx, htlc_output, true);
2340 // We have a resolution of an HTLC either from one of our latest
2341 // holder commitment transactions or an unrevoked counterparty commitment
2342 // transaction. This implies we either learned a preimage, the HTLC
2343 // has timed out, or we screwed up. In any case, we should now
2344 // resolve the source HTLC with the original sender.
2345 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
2346 } else if !$holder_tx {
2347 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2348 if payment_data.is_none() {
2349 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2352 if payment_data.is_none() {
2353 log_claim!($tx_info, $holder_tx, htlc_output, false);
2354 continue 'outer_loop;
2361 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2362 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2363 "our latest holder commitment tx", true);
2365 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2366 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2367 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2368 "our previous holder commitment tx", true);
2371 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2372 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2373 "counterparty commitment tx", false);
2376 // Check that scan_commitment, above, decided there is some source worth relaying an
2377 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2378 if let Some((source, payment_hash, amount_msat)) = payment_data {
2379 let mut payment_preimage = PaymentPreimage([0; 32]);
2380 if accepted_preimage_claim {
2381 if !self.pending_monitor_events.iter().any(
2382 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2383 payment_preimage.0.copy_from_slice(&input.witness[3]);
2384 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2386 payment_preimage: Some(payment_preimage),
2388 onchain_value_satoshis: Some(amount_msat / 1000),
2391 } else if offered_preimage_claim {
2392 if !self.pending_monitor_events.iter().any(
2393 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2394 upd.source == source
2396 payment_preimage.0.copy_from_slice(&input.witness[1]);
2397 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2399 payment_preimage: Some(payment_preimage),
2401 onchain_value_satoshis: Some(amount_msat / 1000),
2405 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2406 if entry.height != height { return true; }
2408 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
2409 *htlc_source != source
2414 let entry = OnchainEventEntry {
2417 event: OnchainEvent::HTLCUpdate {
2418 source, payment_hash,
2419 onchain_value_satoshis: Some(amount_msat / 1000),
2422 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());
2423 self.onchain_events_awaiting_threshold_conf.push(entry);
2429 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2430 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2431 let mut spendable_output = None;
2432 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2433 if i > ::core::u16::MAX as usize {
2434 // While it is possible that an output exists on chain which is greater than the
2435 // 2^16th output in a given transaction, this is only possible if the output is not
2436 // in a lightning transaction and was instead placed there by some third party who
2437 // wishes to give us money for no reason.
2438 // Namely, any lightning transactions which we pre-sign will never have anywhere
2439 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2440 // scripts are not longer than one byte in length and because they are inherently
2441 // non-standard due to their size.
2442 // Thus, it is completely safe to ignore such outputs, and while it may result in
2443 // us ignoring non-lightning fund to us, that is only possible if someone fills
2444 // nearly a full block with garbage just to hit this case.
2447 if outp.script_pubkey == self.destination_script {
2448 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2449 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2450 output: outp.clone(),
2454 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2455 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2456 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2457 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2458 per_commitment_point: broadcasted_holder_revokable_script.1,
2459 to_self_delay: self.on_holder_tx_csv,
2460 output: outp.clone(),
2461 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2462 channel_keys_id: self.channel_keys_id,
2463 channel_value_satoshis: self.channel_value_satoshis,
2468 if self.counterparty_payment_script == outp.script_pubkey {
2469 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2470 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2471 output: outp.clone(),
2472 channel_keys_id: self.channel_keys_id,
2473 channel_value_satoshis: self.channel_value_satoshis,
2477 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
2478 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2479 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2480 output: outp.clone(),
2485 if let Some(spendable_output) = spendable_output {
2486 let entry = OnchainEventEntry {
2489 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2491 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2492 self.onchain_events_awaiting_threshold_conf.push(entry);
2497 /// `Persist` defines behavior for persisting channel monitors: this could mean
2498 /// writing once to disk, and/or uploading to one or more backup services.
2500 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
2501 /// to disk/backups. And, on every update, you **must** persist either the
2502 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
2503 /// of situations such as revoking a transaction, then crashing before this
2504 /// revocation can be persisted, then unintentionally broadcasting a revoked
2505 /// transaction and losing money. This is a risk because previous channel states
2506 /// are toxic, so it's important that whatever channel state is persisted is
2507 /// kept up-to-date.
2508 pub trait Persist<ChannelSigner: Sign> {
2509 /// Persist a new channel's data. The data can be stored any way you want, but
2510 /// the identifier provided by Rust-Lightning is the channel's outpoint (and
2511 /// it is up to you to maintain a correct mapping between the outpoint and the
2512 /// stored channel data). Note that you **must** persist every new monitor to
2513 /// disk. See the `Persist` trait documentation for more details.
2515 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2516 /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2517 fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2519 /// Update one channel's data. The provided `ChannelMonitor` has already
2520 /// applied the given update.
2522 /// Note that on every update, you **must** persist either the
2523 /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
2524 /// the `Persist` trait documentation for more details.
2526 /// If an implementer chooses to persist the updates only, they need to make
2527 /// sure that all the updates are applied to the `ChannelMonitors` *before*
2528 /// the set of channel monitors is given to the `ChannelManager`
2529 /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
2530 /// applying a monitor update to a monitor. If full `ChannelMonitors` are
2531 /// persisted, then there is no need to persist individual updates.
2533 /// Note that there could be a performance tradeoff between persisting complete
2534 /// channel monitors on every update vs. persisting only updates and applying
2535 /// them in batches. The size of each monitor grows `O(number of state updates)`
2536 /// whereas updates are small and `O(1)`.
2538 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2539 /// [`ChannelMonitorUpdate::write`] for writing out an update, and
2540 /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2541 fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2544 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2546 T::Target: BroadcasterInterface,
2547 F::Target: FeeEstimator,
2550 fn block_connected(&self, block: &Block, height: u32) {
2551 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2552 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2555 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2556 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2560 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
2562 T::Target: BroadcasterInterface,
2563 F::Target: FeeEstimator,
2566 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
2567 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
2570 fn transaction_unconfirmed(&self, txid: &Txid) {
2571 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
2574 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
2575 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
2578 fn get_relevant_txids(&self) -> Vec<Txid> {
2579 self.0.get_relevant_txids()
2583 const MAX_ALLOC_SIZE: usize = 64*1024;
2585 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
2586 for (BlockHash, ChannelMonitor<Signer>) {
2587 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
2588 macro_rules! unwrap_obj {
2592 Err(_) => return Err(DecodeError::InvalidValue),
2597 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
2599 let latest_update_id: u64 = Readable::read(reader)?;
2600 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2602 let destination_script = Readable::read(reader)?;
2603 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2605 let revokable_address = Readable::read(reader)?;
2606 let per_commitment_point = Readable::read(reader)?;
2607 let revokable_script = Readable::read(reader)?;
2608 Some((revokable_address, per_commitment_point, revokable_script))
2611 _ => return Err(DecodeError::InvalidValue),
2613 let counterparty_payment_script = Readable::read(reader)?;
2614 let shutdown_script = {
2615 let script = <Script as Readable>::read(reader)?;
2616 if script.is_empty() { None } else { Some(script) }
2619 let channel_keys_id = Readable::read(reader)?;
2620 let holder_revocation_basepoint = Readable::read(reader)?;
2621 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2622 // barely-init'd ChannelMonitors that we can't do anything with.
2623 let outpoint = OutPoint {
2624 txid: Readable::read(reader)?,
2625 index: Readable::read(reader)?,
2627 let funding_info = (outpoint, Readable::read(reader)?);
2628 let current_counterparty_commitment_txid = Readable::read(reader)?;
2629 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2631 let counterparty_commitment_params = Readable::read(reader)?;
2632 let funding_redeemscript = Readable::read(reader)?;
2633 let channel_value_satoshis = Readable::read(reader)?;
2635 let their_cur_revocation_points = {
2636 let first_idx = <U48 as Readable>::read(reader)?.0;
2640 let first_point = Readable::read(reader)?;
2641 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2642 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2643 Some((first_idx, first_point, None))
2645 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2650 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2652 let commitment_secrets = Readable::read(reader)?;
2654 macro_rules! read_htlc_in_commitment {
2657 let offered: bool = Readable::read(reader)?;
2658 let amount_msat: u64 = Readable::read(reader)?;
2659 let cltv_expiry: u32 = Readable::read(reader)?;
2660 let payment_hash: PaymentHash = Readable::read(reader)?;
2661 let transaction_output_index: Option<u32> = Readable::read(reader)?;
2663 HTLCOutputInCommitment {
2664 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2670 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2671 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2672 for _ in 0..counterparty_claimable_outpoints_len {
2673 let txid: Txid = Readable::read(reader)?;
2674 let htlcs_count: u64 = Readable::read(reader)?;
2675 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2676 for _ in 0..htlcs_count {
2677 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2679 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2680 return Err(DecodeError::InvalidValue);
2684 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2685 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2686 for _ in 0..counterparty_commitment_txn_on_chain_len {
2687 let txid: Txid = Readable::read(reader)?;
2688 let commitment_number = <U48 as Readable>::read(reader)?.0;
2689 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
2690 return Err(DecodeError::InvalidValue);
2694 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2695 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2696 for _ in 0..counterparty_hash_commitment_number_len {
2697 let payment_hash: PaymentHash = Readable::read(reader)?;
2698 let commitment_number = <U48 as Readable>::read(reader)?.0;
2699 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2700 return Err(DecodeError::InvalidValue);
2704 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
2705 match <u8 as Readable>::read(reader)? {
2708 Some(Readable::read(reader)?)
2710 _ => return Err(DecodeError::InvalidValue),
2712 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
2714 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2715 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2717 let payment_preimages_len: u64 = Readable::read(reader)?;
2718 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2719 for _ in 0..payment_preimages_len {
2720 let preimage: PaymentPreimage = Readable::read(reader)?;
2721 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2722 if let Some(_) = payment_preimages.insert(hash, preimage) {
2723 return Err(DecodeError::InvalidValue);
2727 let pending_monitor_events_len: u64 = Readable::read(reader)?;
2728 let mut pending_monitor_events = Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2729 for _ in 0..pending_monitor_events_len {
2730 let ev = match <u8 as Readable>::read(reader)? {
2731 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
2732 1 => MonitorEvent::CommitmentTxBroadcasted(funding_info.0),
2733 _ => return Err(DecodeError::InvalidValue)
2735 pending_monitor_events.push(ev);
2738 let pending_events_len: u64 = Readable::read(reader)?;
2739 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
2740 for _ in 0..pending_events_len {
2741 if let Some(event) = MaybeReadable::read(reader)? {
2742 pending_events.push(event);
2746 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
2748 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2749 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2750 for _ in 0..waiting_threshold_conf_len {
2751 if let Some(val) = MaybeReadable::read(reader)? {
2752 onchain_events_awaiting_threshold_conf.push(val);
2756 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2757 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>>())));
2758 for _ in 0..outputs_to_watch_len {
2759 let txid = Readable::read(reader)?;
2760 let outputs_len: u64 = Readable::read(reader)?;
2761 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
2762 for _ in 0..outputs_len {
2763 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
2765 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2766 return Err(DecodeError::InvalidValue);
2769 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
2771 let lockdown_from_offchain = Readable::read(reader)?;
2772 let holder_tx_signed = Readable::read(reader)?;
2774 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
2775 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
2776 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
2777 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
2778 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
2779 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
2780 return Err(DecodeError::InvalidValue);
2784 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
2785 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
2786 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
2787 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
2788 return Err(DecodeError::InvalidValue);
2791 read_tlv_fields!(reader, {});
2793 let mut secp_ctx = Secp256k1::new();
2794 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
2796 Ok((best_block.block_hash(), ChannelMonitor {
2797 inner: Mutex::new(ChannelMonitorImpl {
2799 commitment_transaction_number_obscure_factor,
2802 broadcasted_holder_revokable_script,
2803 counterparty_payment_script,
2807 holder_revocation_basepoint,
2809 current_counterparty_commitment_txid,
2810 prev_counterparty_commitment_txid,
2812 counterparty_commitment_params,
2813 funding_redeemscript,
2814 channel_value_satoshis,
2815 their_cur_revocation_points,
2820 counterparty_claimable_outpoints,
2821 counterparty_commitment_txn_on_chain,
2822 counterparty_hash_commitment_number,
2824 prev_holder_signed_commitment_tx,
2825 current_holder_commitment_tx,
2826 current_counterparty_commitment_number,
2827 current_holder_commitment_number,
2830 pending_monitor_events,
2833 onchain_events_awaiting_threshold_conf,
2838 lockdown_from_offchain,
2851 use bitcoin::blockdata::script::{Script, Builder};
2852 use bitcoin::blockdata::opcodes;
2853 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2854 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2855 use bitcoin::util::bip143;
2856 use bitcoin::hashes::Hash;
2857 use bitcoin::hashes::sha256::Hash as Sha256;
2858 use bitcoin::hashes::hex::FromHex;
2859 use bitcoin::hash_types::Txid;
2860 use bitcoin::network::constants::Network;
2862 use chain::BestBlock;
2863 use chain::channelmonitor::ChannelMonitor;
2864 use chain::package::{WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC, WEIGHT_REVOKED_OUTPUT};
2865 use chain::transaction::OutPoint;
2866 use ln::{PaymentPreimage, PaymentHash};
2868 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
2869 use ln::script::ShutdownScript;
2870 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
2871 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
2872 use bitcoin::secp256k1::Secp256k1;
2873 use sync::{Arc, Mutex};
2874 use chain::keysinterface::InMemorySigner;
2878 fn test_prune_preimages() {
2879 let secp_ctx = Secp256k1::new();
2880 let logger = Arc::new(TestLogger::new());
2881 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
2882 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: Mutex::new(253) });
2884 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2885 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2887 let mut preimages = Vec::new();
2890 let preimage = PaymentPreimage([i; 32]);
2891 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2892 preimages.push((preimage, hash));
2896 macro_rules! preimages_slice_to_htlc_outputs {
2897 ($preimages_slice: expr) => {
2899 let mut res = Vec::new();
2900 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2901 res.push((HTLCOutputInCommitment {
2905 payment_hash: preimage.1.clone(),
2906 transaction_output_index: Some(idx as u32),
2913 macro_rules! preimages_to_holder_htlcs {
2914 ($preimages_slice: expr) => {
2916 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2917 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2923 macro_rules! test_preimages_exist {
2924 ($preimages_slice: expr, $monitor: expr) => {
2925 for preimage in $preimages_slice {
2926 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
2931 let keys = InMemorySigner::new(
2933 SecretKey::from_slice(&[41; 32]).unwrap(),
2934 SecretKey::from_slice(&[41; 32]).unwrap(),
2935 SecretKey::from_slice(&[41; 32]).unwrap(),
2936 SecretKey::from_slice(&[41; 32]).unwrap(),
2937 SecretKey::from_slice(&[41; 32]).unwrap(),
2943 let counterparty_pubkeys = ChannelPublicKeys {
2944 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2945 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2946 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
2947 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
2948 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
2950 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
2951 let channel_parameters = ChannelTransactionParameters {
2952 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
2953 holder_selected_contest_delay: 66,
2954 is_outbound_from_holder: true,
2955 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
2956 pubkeys: counterparty_pubkeys,
2957 selected_contest_delay: 67,
2959 funding_outpoint: Some(funding_outpoint),
2961 // Prune with one old state and a holder commitment tx holding a few overlaps with the
2963 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2964 let best_block = BestBlock::from_genesis(Network::Testnet);
2965 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
2966 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
2967 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2968 &channel_parameters,
2969 Script::new(), 46, 0,
2970 HolderCommitmentTransaction::dummy(), best_block);
2972 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
2973 let dummy_txid = dummy_tx.txid();
2974 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
2975 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
2976 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
2977 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
2978 for &(ref preimage, ref hash) in preimages.iter() {
2979 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
2982 // Now provide a secret, pruning preimages 10-15
2983 let mut secret = [0; 32];
2984 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2985 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2986 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
2987 test_preimages_exist!(&preimages[0..10], monitor);
2988 test_preimages_exist!(&preimages[15..20], monitor);
2990 // Now provide a further secret, pruning preimages 15-17
2991 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2992 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2993 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
2994 test_preimages_exist!(&preimages[0..10], monitor);
2995 test_preimages_exist!(&preimages[17..20], monitor);
2997 // Now update holder commitment tx info, pruning only element 18 as we still care about the
2998 // previous commitment tx's preimages too
2999 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3000 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3001 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3002 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3003 test_preimages_exist!(&preimages[0..10], monitor);
3004 test_preimages_exist!(&preimages[18..20], monitor);
3006 // But if we do it again, we'll prune 5-10
3007 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3008 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3009 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3010 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3011 test_preimages_exist!(&preimages[0..5], monitor);
3015 fn test_claim_txn_weight_computation() {
3016 // We test Claim txn weight, knowing that we want expected weigth and
3017 // not actual case to avoid sigs and time-lock delays hell variances.
3019 let secp_ctx = Secp256k1::new();
3020 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3021 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3022 let mut sum_actual_sigs = 0;
3024 macro_rules! sign_input {
3025 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr) => {
3026 let htlc = HTLCOutputInCommitment {
3027 offered: if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_OFFERED_HTLC { true } else { false },
3029 cltv_expiry: 2 << 16,
3030 payment_hash: PaymentHash([1; 32]),
3031 transaction_output_index: Some($idx as u32),
3033 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) };
3034 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3035 let sig = secp_ctx.sign(&sighash, &privkey);
3036 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3037 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3038 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3039 if *$weight == WEIGHT_REVOKED_OUTPUT {
3040 $sighash_parts.access_witness($idx).push(vec!(1));
3041 } else if *$weight == WEIGHT_REVOKED_OFFERED_HTLC || *$weight == WEIGHT_REVOKED_RECEIVED_HTLC {
3042 $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3043 } else if *$weight == WEIGHT_RECEIVED_HTLC {
3044 $sighash_parts.access_witness($idx).push(vec![0]);
3046 $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3048 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3049 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3050 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3051 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3055 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3056 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3058 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3059 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3061 claim_tx.input.push(TxIn {
3062 previous_output: BitcoinOutPoint {
3066 script_sig: Script::new(),
3067 sequence: 0xfffffffd,
3068 witness: Vec::new(),
3071 claim_tx.output.push(TxOut {
3072 script_pubkey: script_pubkey.clone(),
3075 let base_weight = claim_tx.get_weight();
3076 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_OFFERED_HTLC, WEIGHT_REVOKED_RECEIVED_HTLC];
3077 let mut inputs_total_weight = 2; // count segwit flags
3079 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3080 for (idx, inp) in inputs_weight.iter().enumerate() {
3081 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3082 inputs_total_weight += inp;
3085 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3087 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3088 claim_tx.input.clear();
3089 sum_actual_sigs = 0;
3091 claim_tx.input.push(TxIn {
3092 previous_output: BitcoinOutPoint {
3096 script_sig: Script::new(),
3097 sequence: 0xfffffffd,
3098 witness: Vec::new(),
3101 let base_weight = claim_tx.get_weight();
3102 let inputs_weight = vec![WEIGHT_OFFERED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC, WEIGHT_RECEIVED_HTLC];
3103 let mut inputs_total_weight = 2; // count segwit flags
3105 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3106 for (idx, inp) in inputs_weight.iter().enumerate() {
3107 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3108 inputs_total_weight += inp;
3111 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
3113 // Justice tx with 1 revoked HTLC-Success tx output
3114 claim_tx.input.clear();
3115 sum_actual_sigs = 0;
3116 claim_tx.input.push(TxIn {
3117 previous_output: BitcoinOutPoint {
3121 script_sig: Script::new(),
3122 sequence: 0xfffffffd,
3123 witness: Vec::new(),
3125 let base_weight = claim_tx.get_weight();
3126 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
3127 let mut inputs_total_weight = 2; // count segwit flags
3129 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3130 for (idx, inp) in inputs_weight.iter().enumerate() {
3131 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3132 inputs_total_weight += inp;
3135 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
3138 // Further testing is done in the ChannelManager integration tests.