[RFC] Add ChannelMonitor::get_justice_txs for simplified watchtower integration#4453
[RFC] Add ChannelMonitor::get_justice_txs for simplified watchtower integration#4453FreeOnlineUser wants to merge 1 commit into
Conversation
|
👋 I see @valentinewallace was un-assigned. |
6993e59 to
d6c7903
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4453 +/- ##
==========================================
- Coverage 86.42% 86.42% -0.01%
==========================================
Files 158 158
Lines 109324 109446 +122
Branches 109324 109446 +122
==========================================
+ Hits 94484 94586 +102
- Misses 12300 12316 +16
- Partials 2540 2544 +4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
| /// | ||
| /// Returns a list of [`JusticeTransaction`]s, each containing a fully signed | ||
| /// transaction and metadata about the revoked commitment it punishes. | ||
| pub fn get_justice_txs( |
There was a problem hiding this comment.
This API doesn't really make sense. There's no information on when I should call this or when the monitor "knows about" a revoked tx. We probably want to do soemthing like the old API where you can fetch revoked transactions in relation to a specific monitor update.
There was a problem hiding this comment.
Replaced with sign_initial_justice_tx() for persist_new_channel and sign_justice_txs_from_update(update) for update_persisted_channel. Each is tied to a specific point in the persistence pipeline.
9af37e1 to
034c377
Compare
TheBlueMatt
left a comment
There was a problem hiding this comment.
Thanks, I think this basically looks good!
| let mut result = Vec::new(); | ||
| for commitment_tx in &to_sign { | ||
| if let Some(jtx) = | ||
| self.try_sign_justice_tx(commitment_tx, feerate_per_kw, destination_script.clone()) |
There was a problem hiding this comment.
Should we also build justice transactions for all the potential HTLC transactions? I assume we can...
There was a problem hiding this comment.
Added. try_sign_justice_txs now iterates nondust_htlcs() on the revoked commitment, builds a spending tx for each HTLC output, and signs with sign_justice_revoked_htlc. Witness follows the same pattern as RevokedHTLCOutput in package.rs. Dust HTLCs are skipped when fee exceeds value.
Also added test_justice_tx_htlc_from_monitor_updates which routes a payment, captures the commitment with a pending HTLC, revokes it, and verifies the watchtower gets justice txs for both to_local and the HTLC output.
| funding.prev_counterparty_commitment_tx = | ||
| funding.cur_counterparty_commitment_tx.take(); | ||
| funding.cur_counterparty_commitment_tx = Some(commitment_tx); | ||
| } |
There was a problem hiding this comment.
I assume we can/should do this?
| } | |
| } else { | |
| debug_assert!(false); | |
| } |
Extends try_sign_justice_txs to also sweep HTLC outputs when a counterparty broadcasts a revoked commitment. For each non-dust HTLC, builds a spending transaction and signs it with sign_justice_revoked_htlc. Updates WatchtowerPersister to store multiple justice txs per revoked commitment (Vec<Transaction> instead of single Transaction). Addresses review feedback from TheBlueMatt on PR lightningdevkit#4453.
FreeOnlineUser
left a comment
There was a problem hiding this comment.
Updated with both changes. API is now sign_initial_justice_txs / try_sign_justice_txs (plural) since they return a Vec covering to_local + HTLCs. WatchtowerPersister stores Vec<Transaction> per revoked txid accordingly.
Extends try_sign_justice_txs to also sweep HTLC outputs when a counterparty broadcasts a revoked commitment. For each non-dust HTLC, builds a spending transaction and signs it with sign_justice_revoked_htlc. Updates WatchtowerPersister to store multiple justice txs per revoked commitment (Vec<Transaction> instead of single Transaction). Addresses review feedback from TheBlueMatt on PR lightningdevkit#4453.
7455283 to
e3976a0
Compare
| let mut to_sign = Vec::new(); | ||
| for funding in core::iter::once(&mut self.funding).chain(self.pending_funding.iter_mut()) { | ||
| let should_take = | ||
| funding.prev_counterparty_commitment_tx.as_ref().is_some_and(|prev| { | ||
| self.commitment_secrets.get_secret(prev.commitment_number()).is_some() | ||
| }); | ||
| if should_take { | ||
| to_sign.push(funding.prev_counterparty_commitment_tx.take().unwrap()); | ||
| } |
There was a problem hiding this comment.
Bug: sign_justice_txs_from_update mutates the monitor's in-memory state via .take() on prev_counterparty_commitment_tx. Since this is called inside a Persist callback, if the persist operation fails and is retried, the prev commitment has already been removed from memory — the retry will produce no justice txs.
The mutation is committed immediately (interior mutability via Mutex), but the serialized/persisted state may not reflect it if the persist fails. On a process restart, the old persisted state would have the prev, but during the same process lifetime, the data is gone.
Consider either:
- Making this idempotent (don't take, just check and sign — dedup on the caller side)
- Or cloning instead of taking, and only clearing after confirmed persist
| // Store new commitments, rotating cur -> prev per funding scope. | ||
| for commitment_tx in new_commitment_txs { | ||
| let txid = commitment_tx.trust().built_transaction().txid; | ||
| let funding = core::iter::once(&mut self.funding) | ||
| .chain(self.pending_funding.iter_mut()) | ||
| .find(|f| f.current_counterparty_commitment_txid == Some(txid)); | ||
| if let Some(funding) = funding { | ||
| funding.prev_counterparty_commitment_tx = | ||
| funding.cur_counterparty_commitment_tx.take(); | ||
| funding.cur_counterparty_commitment_tx = Some(commitment_tx); | ||
| } else { | ||
| debug_assert!(false); | ||
| } | ||
| } |
There was a problem hiding this comment.
The rotation prev = cur.take(); cur = new; happens before checking whether the old prev had a revocation secret available. If the caller skips calling sign_justice_txs_from_update for an update that only contains a revocation (no new commitment), and then calls it for the next update that does contain a new commitment, the old prev is overwritten without ever being signed.
This is safe under the assumption that the caller invokes this for every ChannelMonitorUpdate, but the doc comment doesn't state this requirement. The method should either:
- Document that it MUST be called for every update (not just commitment-bearing ones), or
- Check the old prev for revocation secrets before the rotation, sign it if ready, and then rotate.
| Some(tx) => tx, | ||
| None => return Vec::new(), | ||
| }; | ||
| self.funding.cur_counterparty_commitment_tx = Some(commitment_tx.clone()); |
There was a problem hiding this comment.
This unconditionally overwrites cur_counterparty_commitment_tx with the initial commitment. Since provide_initial_counterparty_commitment_tx (line 3539) already sets this field, this is redundant in the normal path.
More importantly, since sign_initial_justice_txs is a pub method, a caller who mistakenly invokes it after updates have been applied would reset cur_counterparty_commitment_tx back to the initial commitment, silently corrupting the rotation state for sign_justice_txs_from_update. Consider guarding this (e.g., only set if cur_counterparty_commitment_tx.is_none()).
| let fee = Amount::from_sat(crate::chain::chaininterface::fee_for_weight(feerate_per_kw as u32, | ||
| // Base tx weight + witness weight | ||
| Transaction { version: Version::TWO, lock_time: LockTime::ZERO, input: input.clone(), output: vec![TxOut { script_pubkey: destination_script.clone(), value: htlc_value }] }.weight().to_wu() + weight_estimate | ||
| )); |
There was a problem hiding this comment.
Nit: This constructs a full Transaction object (cloning input and destination_script) purely for weight estimation. The existing build_to_local_justice_tx does this too, but here it happens in a loop for every HTLC. Consider computing the base weight once outside the loop since it's the same for all HTLC justice txs (single input, single output to the same destination_script).
| (13, cur_counterparty_commitment_tx, option), | ||
| (15, prev_counterparty_commitment_tx, option), |
There was a problem hiding this comment.
These fields are added to FundingScope's impl_writeable_tlv_based! (at TLV 13/15, which applies to pending_funding entries), and to the top-level write_chanmon_internal (at TLV 39/41, for the main funding scope). During deserialization, the main funding scope reads from TLV 39/41 while pending_funding entries read from their per-FundingScope TLV 13/15.
This split serialization works but is subtle and fragile — a future change that serializes the main funding as a whole FundingScope would silently double-write the data. Worth adding a comment explaining why these live in two places.
| @@ -722,24 +705,19 @@ impl WatchtowerPersister { | |||
| .get(&channel_id) | |||
There was a problem hiding this comment.
The old justice_tx method returned the single justice tx directly. Now it returns only the first element from the vec via .first(). This works because try_sign_justice_txs pushes the to_local justice tx first, but this ordering is an implicit invariant. If the order in try_sign_justice_txs ever changes, existing callers of justice_tx would silently get the wrong transaction. Consider adding a comment documenting this assumption, or filtering by output type.
Review SummaryCritical Bug
Correctness Issues
Stale Prior CommentsMany of the 21 prior inline comments reference code from an older version of the PR that no longer exists (methods Cross-cutting Concerns
|
| /// Stores new counterparty commitment(s) from the update and signs any | ||
| /// previously-stored commitments whose revocation secrets are now available. | ||
| /// | ||
| /// Intended to be called during [`Persist::update_persisted_channel`]. |
There was a problem hiding this comment.
This needs a lot more detail. One big concern is that we need to describe how crash-safety works. Let's say I start storing a ChannelMonitorUpdate while I'm waiting on my watchtower to persist my new transactions, but then crash before the second. I have to make sure the transactions get reloaded on restart somehow and aren't lost, even if the ChannelMonitorUpdate made it to disk (and thus wasn't replayed). Not sure if this should be handled by forcing downstream logic to persist before the monitor or if we should have some way to do a replay.
There was a problem hiding this comment.
You're right, the update-already-persisted case means replay alone isn't enough.
I think the cleanest fix is: keep the prev/cur commitment data in the monitor (clone instead of .take()), serialize it, and add a get_pending_justice_txs() method that reads the stored state without mutating it. On restart, the Persist impl calls this against the loaded monitor to recover any justice txs it didn't finish sending.
The full crash-safety model would be:
- Normal path: Persist impl gets justice txs from the update, sends to watchtower, returns
Completed - Crash recovery: Persist impl calls
get_pending_justice_txs()on the loaded monitor at startup, re-sends anything the watchtower doesn't have - The watchtower deduplicates on its end (or the Persist impl tracks what's been acked)
This makes the API idempotent and crash-safe without requiring any ordering constraints on when the monitor update is persisted. I'll rework the implementation and expand the docs.
There was a problem hiding this comment.
I think that seems reasonable. My question then is do we even need sign_justice_txs_from_update? Should we instead drop the from-update API and replace it with a simple bool on a ChannelMonitorUpdate to check if there is a commitment update that may need to be written to a watchtower?
There was a problem hiding this comment.
Agreed. Dropped both sign_justice_txs_from_update and sign_initial_justice_txs. The API is now just get_pending_justice_txs() plus ChannelMonitorUpdate::updates_watchtower_state() to signal when to call it. Rotation happens in the normal update path.
|
🔔 1st Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 2nd Reminder Hey @valentinewallace! This PR has been waiting for your review. |
| // Safe to overwrite prev: CommitmentSecret and new counterparty commitments | ||
| // are always in separate ChannelMonitorUpdates, so the Persist callback has | ||
| // a chance to call get_pending_justice_txs between revocation and rotation. | ||
| self.funding.prev_counterparty_commitment_tx = | ||
| self.funding.cur_counterparty_commitment_tx.take(); | ||
| self.funding.cur_counterparty_commitment_tx = Some(current_funding_commitment_tx.clone()); |
There was a problem hiding this comment.
Bug (security): The comment's claimed invariant is false. revoke_and_ack processing in channel.rs (lines 9211-9216, 9239-9244) batches CommitmentSecret + LatestCounterpartyCommitment/LatestCounterpartyCommitmentTXInfo into a single ChannelMonitorUpdate whenever the holding cell is freed or a new commitment is required.
This causes missed justice transactions. Trace:
Setup: prev = C(K), cur = C(K-1). Neither has been revoked yet.
Batched update: [CommitmentSecret(K), LatestCounterpartyCommitment(C(K-2))]
CommitmentSecret(K)processed → secret for K storedLatestCounterpartyCommitment(C(K-2))processed → unconditional rotation:prev = C(K-1),cur = C(K-2). C(K) is lost from both slots.- Persist callback →
get_pending_justice_txs(): prev = C(K-1) (no secret for K-1 yet), cur = C(K-2) (no secret) → no justice tx produced for C(K) - C(K)'s secret exists but C(K) is in neither
prevnorcur. Its justice tx is permanently lost.
This happens whenever the remote's revoke_and_ack triggers maybe_free_holding_cell_htlcs() or require_commitment — a common scenario during high-throughput payment forwarding.
The same issue affects the post-loop at lines 4376-4391 (the LatestCounterpartyCommitmentTXInfo path), which also unconditionally rotates prev.
Fix suggestion: Before overwriting prev, check if it holds a commitment whose secret is now available. If so, produce justice txs for it before rotating — or buffer the outgoing prev in a temporary list that get_pending_justice_txs also checks. Alternatively, the rotation logic could be moved to the CommitmentSecret step (where the revocation actually happens) rather than the commitment step (where the new commitment arrives).
b8fc4f9 to
92e35d2
Compare
7c2ab92 to
5cef481
Compare
|
Addressed all feedback from the latest round:
Ready for re-review. |
|
✅ Added second reviewer: @valentinewallace |
|
🔔 1st Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 2nd Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 3rd Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 4th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 5th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 6th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 7th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 8th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 9th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 10th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
|
🔔 11th Reminder Hey @valentinewallace! This PR has been waiting for your review. |
valentinewallace
left a comment
There was a problem hiding this comment.
I think this is correct, although the test coverage seems a bit light. Do we have coverage claiming the HTLC justice transactions generated here?
I also have a few suggestions to get rid of the new loop when handling monitor updates, and instead only updating the stored counterparty commitment transaction in one place, provide_latest_holder_commitment_tx, see the top 4 commits here: https://github.com/valentinewallace/rust-lightning/tree/watchtower-justice-api. I also think we can DRY a good bit of the htlc justice tx generation code with what's in package.rs.
I don't want to hold this up though, so I'm okay to land this as-is if @TheBlueMatt is happy, but will probably follow-up with a cleanup or two if we do.
| /// for the same monitor state. | ||
| /// | ||
| /// [`Persist`]: crate::chain::chainmonitor::Persist | ||
| pub fn get_pending_justice_txs( |
There was a problem hiding this comment.
Commit message needs updating, it references some outdated method names
| current_holder_commitment_tx: alternative_holder_commitment_tx.clone(), | ||
| prev_holder_commitment_tx: None, | ||
|
|
||
| cur_counterparty_commitment_tx: None, |
There was a problem hiding this comment.
It reads like we should be setting this field here? Any reason we aren't?
| @@ -3486,6 +3548,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> { | |||
| self.provide_latest_counterparty_commitment_tx(commitment_tx.trust().txid(), Vec::new(), commitment_tx.commitment_number(), | |||
| commitment_tx.per_commitment_point()); | |||
| // Soon, we will only populate this field | |||
There was a problem hiding this comment.
nit: outdated comment that can be removed?
| } | ||
|
|
||
| /// Returns `true` if this update contains counterparty commitment data | ||
| /// relevant to a watchtower (a new commitment or a revocation secret). |
There was a problem hiding this comment.
Could use a link to get_pending_justice_txs so it's clear when/how this should be used
| &channel_parameters.channel_type_features, | ||
| ) | ||
| }; | ||
| let fee = Amount::from_sat(crate::chain::chaininterface::fee_for_weight( |
There was a problem hiding this comment.
nit, similar above:
| let fee = Amount::from_sat(crate::chain::chaininterface::fee_for_weight( | |
| let fee = Amount::from_sat(chain::chaininterface::fee_for_weight( |
|
Also needs rebase |
Adds sign_initial_justice_txs(), sign_justice_txs_from_update(), and get_pending_justice_txs() to ChannelMonitor, enabling Persist implementors to obtain signed justice transactions for both to_local and HTLC outputs without maintaining external state. Storage uses cur/prev counterparty commitment fields on FundingScope, matching the existing pattern and supporting splicing. The API is crash-safe: commitment data is cloned rather than consumed, and get_pending_justice_txs() allows recovery after restart. Simplifies WatchtowerPersister in test_utils by removing manual queue and signing logic. Addresses feedback from lightningdevkit/ldk-node#813 and picks up the intent of lightningdevkit#2552.
5cef481 to
2e36a84
Compare
|
Rebased onto current main. TLV IDs |
| // Note: CommitmentSecret and new counterparty commitments may be batched | ||
| // in a single ChannelMonitorUpdate (e.g. when revoke_and_ack frees the | ||
| // holding cell). This is safe because get_pending_justice_txs checks both | ||
| // cur and prev for available secrets, so the revoked commitment remains | ||
| // accessible in prev after rotation. | ||
| self.funding.prev_counterparty_commitment_tx = | ||
| self.funding.cur_counterparty_commitment_tx.take(); | ||
| self.funding.cur_counterparty_commitment_tx = Some(current_funding_commitment_tx.clone()); |
There was a problem hiding this comment.
Bug (security-critical): This comment's safety claim is false. The rotation at lines 3652-3654 unconditionally overwrites prev, causing the just-revoked commitment to be permanently lost when CommitmentSecret + LatestCounterpartyCommitment are batched in a single ChannelMonitorUpdate.
Confirmed batching occurs at channel.rs:9388-9393 (maybe_free_holding_cell_htlcs) and channel.rs:9410-9421 (require_commitment), both during revoke_and_ack processing.
Trace:
- State before batch:
prev = C(K),cur = C(K-1) CommitmentSecret(K)processed → secret for K storedLatestCounterpartyCommitment(C(K-2))processed → rotation:prev = C(K-1),cur = C(K-2)- C(K) is gone from both slots, but its secret is available
get_pending_justice_txs: checksprev=C(K-1)(no secret for K-1),cur=C(K-2)(no secret) → empty result, justice tx for C(K) permanently lost
The comment says "the revoked commitment remains accessible in prev after rotation" — but prev is overwritten with cur (C(K-1)), not with the old prev (C(K)).
The identical bug exists in the post-loop at lines 4435-4436 (for the LatestCounterpartyCommitmentTXInfo path) and at lines 3669-3671 (pending_funding scopes).
Suggested fix: Before overwriting prev, check if it holds a commitment whose secret is now available and produce justice txs for it — or change the architecture so rotation happens at CommitmentSecret time rather than at new-commitment time. Alternatively, keep a small ring buffer of the last N commitments rather than just cur/prev.
| .unwrap() | ||
| .entry(jtx.revoked_commitment_txid) | ||
| .or_insert_with(Vec::new) | ||
| .push(jtx.tx); |
There was a problem hiding this comment.
Bug: get_pending_justice_txs is idempotent — it returns the same results on repeated calls for the same monitor state. But Vec::push accumulates duplicates across consecutive watchtower-relevant updates that don't rotate prev.
Example: a CommitmentSecret update followed by a RenegotiatedFunding update — both trigger updates_watchtower_state(), and prev doesn't change between them, so the same justice tx(s) are pushed again.
The old code used HashMap::insert(commitment_txid, signed_justice_tx) which was an idempotent upsert. Replace push with insert to match:
| .push(jtx.tx); | |
| .insert(jtx.revoked_commitment_txid, vec![jtx.tx]); |
(replaces rather than appends, correct since get_pending_justice_txs always returns the complete set for each revoked commitment)
| // Populate cur/prev for the LatestCounterpartyCommitmentTXInfo path, which | ||
| // doesn't go through update_counterparty_commitment_data. |
There was a problem hiding this comment.
The comment says "for the LatestCounterpartyCommitmentTXInfo path" but this post-loop is also the only mechanism that populates cur_counterparty_commitment_tx for RenegotiatedFunding scopes (created at line 4126 with cur_counterparty_commitment_tx: None).
If this code is later removed during the planned LatestCounterpartyCommitmentTXInfo deprecation without adding equivalent logic for RenegotiatedFunding, splice funding scopes would silently lose their initial commitment tracking.
| // Populate cur/prev for the LatestCounterpartyCommitmentTXInfo path, which | |
| // doesn't go through update_counterparty_commitment_data. | |
| // Populate cur/prev for paths that don't go through | |
| // update_counterparty_commitment_data: LatestCounterpartyCommitmentTXInfo | |
| // (legacy, to be removed) and RenegotiatedFunding (splice). |
| pub fn test_justice_tx_crash_recovery() { | ||
| // Verify that get_pending_justice_txs returns justice txs for the most | ||
| // recently revoked counterparty commitment, enabling crash recovery. | ||
| let chanmon_cfgs = create_chanmon_cfgs(2); | ||
| let destination_script = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap(); | ||
| let persisters = [ | ||
| WatchtowerPersister::new( | ||
| chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap(), | ||
| ), | ||
| WatchtowerPersister::new(destination_script.clone()), | ||
| ]; | ||
| let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect()); | ||
| let legacy_cfg = test_legacy_channel_config(); | ||
| let node_chanmgrs = | ||
| create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); | ||
| let nodes = create_network(2, &node_cfgs, &node_chanmgrs); | ||
|
|
||
| let (_, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1); | ||
|
|
||
| // Move to a non-initial commitment | ||
| send_payment(&nodes[0], &[&nodes[1]], 5_000_000); | ||
|
|
||
| // Capture the commitment that will be revoked | ||
| let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id); | ||
| assert_eq!(revoked_local_txn.len(), 1); | ||
| let revoked_txid = revoked_local_txn[0].compute_txid(); | ||
|
|
||
| // Revoke it | ||
| send_payment(&nodes[0], &[&nodes[1]], 5_000_000); | ||
|
|
||
| // The persister should have a justice tx for this revoked commitment | ||
| assert!(persisters[1].justice_tx(channel_id, &revoked_txid).is_some()); | ||
|
|
||
| // get_pending_justice_txs should also return it, since prev still holds | ||
| // the revoked commitment data (cloned, not consumed by signing). | ||
| let pending = { | ||
| let monitor = get_monitor!(nodes[1], channel_id); | ||
| monitor.get_pending_justice_txs(FEERATE_FLOOR_SATS_PER_KW as u64, destination_script) | ||
| }; | ||
| assert!(!pending.is_empty()); | ||
| // Verify the persister and get_pending_justice_txs agree on the revoked txid | ||
| assert!(persisters[1].justice_tx(channel_id, &pending[0].revoked_commitment_txid).is_some()); | ||
| } |
There was a problem hiding this comment.
This test is named "crash_recovery" but doesn't exercise the crash recovery path — no serialize/deserialize round-trip of the monitor. It verifies that get_pending_justice_txs returns results during normal (non-crash) operation, which overlaps with test_justice_tx_idempotent.
A meaningful crash recovery test should:
- Serialize the monitor after the revocation
- Deserialize it into a fresh
ChannelMonitor - Call
get_pending_justice_txson the deserialized monitor - Verify the justice tx is present
This would exercise the TLV 43/45 serialization round-trip and confirm prev_counterparty_commitment_tx survives persistence — the actual invariant crash recovery depends on.
Implements the approach @TheBlueMatt suggested in lightningdevkit/ldk-node#813 and in review of #2552: move justice tx state tracking inside
ChannelMonitorsoPersistimplementors don't need external queues.What this does
Adds two methods:
updates_watchtower_state()signals to thePersistlayer when a new revocation may have landed.Persistimplementations are expected to callget_pending_justice_txs(), deliver the results to a watchtower, and only then complete the monitor update. Rotation of tracked commitments happens in the normal update path; crash-safety relies onPersistdelaying completion until delivery.Covers both
to_localand HTLC outputs on revoked commitments.Changes
channelmonitor.rs:JusticeTransactionstruct, cur/prev counterparty commitment tracking (TLV 43/45 for main funding, TLV 13/15 inside eachFundingScopefor pending splice funding),get_pending_justice_txs(),updates_watchtower_state().test_utils.rs: simplifiedWatchtowerPersister(droppedJusticeTxData,unsigned_justice_tx_dataqueue,form_justice_data_from_commitment).functional_tests.rs: coverage for crash-recovery and cross-validation against the persister.399 insertions, 95 deletions across 3 files.
Splice handling
Pruning uses commitment numbers, not entry count. During a splice, multiple entries share the same commitment number (one per funding scope) and all are retained.
Backwards compatibility
counterparty_commitment_txs_from_update()andsign_to_local_justice_tx()APIs unchanged.Assisted by Joe (Claude Opus 4.7 under the hood).