[1/3] aux revocation: add deterministic HTLCs #11094
🔴 PR Severity: CRITICAL
file classification | 23 files | 1205 lines changed (768 excluding tests)
<details>
<summary>🔴 <strong>Critical</strong> (14 files)</summary>
contractcourt/chain_arbitrator.go - on-chain dispute resolution coordinationcontractcourt/chain_watcher.go - on-chain dispute resolution coordinationcontractcourt/contract_resolver.go - on-chain dispute/breach resolution logiccontractcourt/htlc_success_resolver.go - HTLC breach/resolution handlingcontractcourt/htlc_timeout_resolver.go - HTLC breach/resolution handlinghtlcswitch/link.go - HTLC forwarding state machinehtlcswitch/mock.go - htlcswitch package support codelnwallet/aux_signer.go - commitment/signing logiclnwallet/chanfunding/coin_select.go - channel funding coin selectionlnwallet/channel.go - channel state, commitment transactionslnwallet/commitment.go - commitment transaction constructionlnwallet/mock.go - lnwallet package support codelnwallet/transactions.go - transaction construction/signingserver.go - core server coordination</details>
<details>
<summary>🟢 <strong>Low</strong> (9 files, tests only)</summary>
contractcourt/breach_arbitrator_test.gocontractcourt/contract_resolver_test.gohtlcswitch/mailbox_test.goinput/size_test.golnrpc/walletrpc/walletkit_server_test.golnwallet/aux_signer_test.golnwallet/channel_test.golnwallet/chanfunding/coin_select_test.golnwallet/transactions_test.go</details>
Analysis
This PR touches core contractcourt/, htlcswitch/, and lnwallet/* packages — on-chain breach/HTLC resolution, HTLC forwarding, and commitment transaction/signing logic — each of which is independently CRITICAL. The change spans multiple distinct critical packages (contractcourt, htlcswitch, lnwallet) and modifies ~768 non-test lines across 14 non-test files, well above the >500 line bump threshold, reinforcing the CRITICAL classification. Given the surface area (commitment transactions, HTLC resolvers, channel funding), this warrants expert review focused on correctness of on-chain resolution paths and signing logic.
---
<sub>To override, add a severity-override-{critical,high,medium,low} label.</sub>
<!-- pr-severity-bot -->
Added no-changelog label, will include one with the 3rd and final part of this PR series.
Still fits on one line.
nit: explain what the use case is for providing both. Is that the case where the blob didn't record what was actually used and we need the feature negotiation as a fallback?
I would mention the Sighash each channel is supposed to return, so that future me has a reminder what we are supposed to expect and why this test works.
| Channel | Sighash | Byte |
| ------------------- | ------------------------------ | ---- |
| legacy (no anchors) | SIGHASH_ALL | 0x01 |
| anchor / taproot | SIGHASH_SINGLE\|ANYONECANPAY | 0x83 |
| custom + negotiated | SIGHASH_DEFAULT | 0x00 |
In the next commit you change refactor this code block, but more importantly change it to chanState.LocalCommitment.CustomBlob. It would be cleaner if the refactor wasn't needed. (ultranit)
wrt changing the blob source, it took me a while to understand why you are changing it here. This is my understanding: commit 1 only used the resolved sighash to pick a SigHashType at the four signing/validation/resolution sites, each locally. Commit 2 promotes sigHashDefault into an input to dust classification, fee, and the anchor carve-out. It threads it through many new sites that have no remoteCommitView in scope, so for consistency we use chanState.LocalCommitment.CustomBlob everywhere. Is that a correct interpretation of what's happening?
I think this comment has it backwards. No regular lnd channel would ever match on 0x00 (SIGHASH_DEFAULT). legacy channels are SIGHASH_ALL and taproot channels are SIGHASH_SINGLE|ANYONECANPAY. (Old) Taproot Assets channels that didn't negotiate deterministic HTLCs would be correctly filtered out by this check, and I think the comment should explain that.
Would it make sense to have separate fee sanity checks for non-asset bearing Txs and asset-bearing Txs?
Not sure it the following math checks out, but hear me out:
The pre-signed second-level tx pays 1.1 sat/vB. The whole CPFP package (1477 wu) can be lifted by at most 330 sats → the combined package feerate stays ~2 sat/vB.
So in a heigh fee-env this would never hit the chain.
calculateBudget isn't good to use her, probably because of the value of the potential assets, but it feels like we should find a way to link the budget to the value of what's being caried in the Tx.
Overstating parentsFee understates the child top-up coming from CPFP. I don't think we can allow this TODO to remain here and assume that the approximation is close enough.
Wouldn't it be nice if the sweeper supported package relay? Broadcast the DeterministicHTLC and the CPFP feebump Tx in one go.
Let's not increase the scope, but a man can dream.
What if an anchor genuinely can't be swept? budget exhausted, deadline blown, persistent estimation failure, etc.
That outcome comes back on the resultChan which the resolver never reads.
Not sure what you could do about it, since a retry wouldn't help in that case either. Just flagging it here.
Probably worth the effort to track it under a WaitGroup and make the publish context-cancelable.
This should use the incoming-HTLC expiry, matching what the other timeout-path sweeps already do — h.incomingHTLCExpiryHeight at lines 495 (DeadlineHeight in sweepTimeoutTx) and 515.
There's a type wrinkle tho: h.incomingHTLCExpiryHeight is fn.Option[int32], but offerSecondLevelAnchorToSweeper takes deadlineHeight uint32. But I'm confident you'll be able to figure that one out. 😄
Not worth persuing, but this wouldn't survive a re-org. If a pre-signed HTLC is published but orged out, we won't retry.
This is also something noted in this PR: https://github.com/lightningnetwork/lnd/pull/10331
we'll actually need to re-create the channel arb and the chain watcher, the re-handle any contested outputs we may have had
But at https://github.com/georgetsagk/lnd/blob/544139aba9486ec92c981fc5de8e057185d5fbc6/lnwallet/channel.go#L9474 we don't take into account IsChanSigHashDefault() so the report can be 330 sats too generous.
I think we are nearly there with this PR. I did a real human-powered, thorough review of the code and found some issues, that I commented on inline. The below comment is about a commit message.
The commit message on the first commit claims to replace CustomBlob.IsSome() but I don't see that specific method being replaced anywhere. Where does that come from?
Expanded the doc here: when both are set, live feature negotiation is consulted first and the commitment blob acts as the fallback (e.g. right after a restart, before the peer reconnects).
Your interpretation is correct, and the refactor is gone: the first commit now introduces the final sigHashReq form directly.
chanfunding cannot tell asset-bearing txs apart, so instead the ratio now has a hard ceiling of 100.0 and FundPsbt logs a warning whenever a caller explicitly opts into a ratio above 1.0 (internal funding flows always pass the default).
Fixed by deriving the budget the same way as commitment anchor CPFP: calculateBudget over the second-level HTLC output value with the sweeper.budget.anchorcpfp(ratio) knobs, plus the anchor value; linking the budget to the real asset value is tracked in lightninglabs/taproot-assets#2242.
Agreed, a man can dream; keeping it out of scope here.
Ack, leaving this to the wider re-org handling story in #10331.
LGTM! 🦺
weird formatting
Why does this branch ignore the already-negotiated feePerKw? That fee rate is agreed through update_fee and stored with the commitment, so using it would remain deterministic for both parties during signing and reconstruction. Hard-coding FeePerKwFloor * 1.1 can leave the parent far below the channel fee. Since the CPFP anchor is only offered after standalone PublishTx succeeds, a mempool minimum above roughly 1.1 sat/vB would reject the parent before the fee-paying child is created. At minimum, could this derive the parent fee from feePerKw, with the auxiliary witness overhead accounted for explicitly, while package CPFP handles fee-market changes between signing and broadcast?
Could we validate the override here or return a narrower policy type? Downstream code only distinguishes SigHashDefault from everything else: SigHashDefault gets the fixed parent, anchor, and direct-publish path, while any other value gets the existing mutable sweeper path. But the raw value is still used for signing. For example, an override of SigHashAll would commit to the full transaction while the resolver would still let the sweeper rebuild it, invalidating the signature. It seems safer to accept only SigHashDefault or the channel default, or model the complete second-level policy explicitly.
We already resolved sigHashType above, but IsSigHashDefault resolves it through the external AuxSigner a second time. If the live negotiation lookup changes or is not strictly pure, the signature could use one sighash while dust, fees, and transaction shape use another. Could this instead derive sigHashDefault directly from the resolved sigHashType? The validation path around line 5064 has the same double lookup.
Once PublishTx succeeds, an onPublished error is only logged and this goroutine returns. Since this immutable floor-fee parent cannot be RBFed and the anchor is its only fee-bumping path, a transient SweepInput registration failure leaves the parent without CPFP until a restart. Should post-publish registration be retried or persisted separately from parent publication? This is distinct from a terminal result delivered after the sweeper has accepted the input.
Could this change be split out or point to the exact caller that requires it? The deterministic second-level anchor path uses Sweeper.SweepInput with a sweep budget; it does not call WalletKit.FundPsbt or this sanity check. As written, this globally relaxes the safety ceiling for every external FundPsbt caller without being exercised by the feature in this PR, and the tests do not include a successful ratio-above-one case. Which flow in this series needs the 100x ceiling?
Could we add table-driven coverage for the deterministic dust boundary here, rather than only testing the fee helpers? HtlcIsDust now subtracts both the second-level fee and AnchorSize; I would cover incoming/outgoing × local/remote at dustLimit + fee + AnchorSize - 1, exact equality, and +1. That would exercise the success/timeout mapping as well as the strict < dustLimit boundary. Also, are there corresponding litd/Taproot Assets itests already present or planned in the follow-up series that exercise negotiated SigHashDefault through force close, exact parent publication, and anchor CPFP? I could not find an lnd itest for this path, so a pointer or a tracked follow-up would help establish the end-to-end coverage.
Cool PR !!! I think we should adjust and not hard-code 1.1 sat for the second-level transactions. Why not use the Commitment Fee which should always be closer to the minMemPool fee.
Do you think using the P2Anchor instead of the 330 anchor would be more benefical, since we could use the value 0 sat ?
Went with the narrow version: ResolveHtlcSigHashType now accepts SigHashDefault as the only valid override and falls back to the channel's standard sighash flags for anything else, so an aux signer cannot steer us into signing a commitment-covering sighash while the resolvers still treat the tx as sweeper-malleable. Added TestResolveHtlcSigHashTypeRejectsUnknownOverride to pin it.
Added the table-driven boundary test (TestHtlcIsDustSigHashDefault): incoming/outgoing x local/remote at dustLimit + fee + AnchorSize - 1, at exact equality, and +1.
On end-to-end coverage: there is no lnd-native itest because nothing in lnd can negotiate SigHashDefault on its own, it needs an aux signer that advertises the feature. That coverage lives in the taproot-assets custom channel suite, which runs an lnd built from this branch: lightninglabs/taproot-assets#1994, cases force_close, htlc_force_close, htlc_force_close_mpp, group_tranches_htlc_force_close, breach and restart_coop_close. They cover negotiation, exact parent publication and anchor CPFP through both force close and breach, and they all pass against this stack.
Fair point that nothing in this series exercises it. The caller is tapd: LndRpcWalletAnchor.FundPsbt passes MaxFeeRatio 5.0 (lndservices.DefaultPsbtMaxFeeRatio) when funding the PSBTs that anchor asset outputs, whose BTC value sits near dust. The commit message now names that caller and states the change is independent of the anchor work here. I also added the missing positive coverage: a ratio-above-one case that succeeds, plus the same fee profile failing under DefaultMaxFeeRatio.
Happy to split it into its own PR if you prefer, it just needs to land before the taproot-assets side. Your call.
Thanks for the review. Answering the two points from the description here, the inline threads have the details.
On not hard-coding 1.1 sat and using the commitment fee instead: I implemented it, measured it, and reverted it. Short version is that the anchor exists precisely so the pre-signed parent does not have to predict the fee market at signing time, and on aux channels the HTLC's whole on-chain BTC value is 1200 sats which is already fully spent on the parent fee, the anchor, and a second-level output that must fund its own claiming sweep. At 1000 sat/kw the commitment-rate fee alone is 817 sats, at 2500 it exceeds the entire budget, so every asset HTLC gets trimmed to dust. Clamping it to what the HTLC can afford does not work either: the breach itest then strands the assets, because the output ends up at exactly the dust limit and cannot pay for the justice sweep. Numbers and logs are in the commitment.go thread.
On P2A instead of the 330 sat anchor: I agree with the direction, and it is the same answer as the fee question, since a 0-value anchor only works inside a TRUC/v3 package where the child pays for both. That also removes the one gap the current design has, a parent below the mempool minimum, and frees the 330 sats plus the parent fee, which would let taproot-assets drop its 1200 sat per-HTLC carrier to roughly 600 and lower the minimum asset payment we quote over RFQ.
I would rather not pull it into this series though. It changes the pre-signed transaction format, so it is a new negotiated variant rather than a drop-in, it needs machinery lnd does not have yet (no P2A script type, no v3 construction, no TRUC-aware sweeper, only SubmitPackage exists), and it changes the taproot-assets allocation and exclusion-proof layout that the companion series and its itests are built against. On top of that it is currently untestable end to end: both lnd's and taproot-assets' itest frameworks mine with btcd, which has no TRUC or ephemeral dust policy and no server-side submitpackage, so a 0-fee parent with a 0-value output would never be mined. Validating it needs a Core-mined harness, which is its own piece of work.
Happy to open a tracking issue for the P2A/TRUC variant so it does not get lost, and there is a cheaper intermediate step available: submitting parent plus child as a package with the existing anchor closes the mempool-minimum gap without any format change.
Overall, the core design looks good to me now. The fixed floor-fee parent plus CPFP anchor is a reasonable fit for the constrained Taproot Assets carrier, and the analysis in the review threads clarified the main trade-offs.
I think the PR still needs a small cleanup/rework pass before final approval:
SweepInput call errors, but cannot observe or repair the later sweeper admission/monitoring failures it was intended to handle. A reliable retry belongs in a follow-up with a proper acknowledgement or persistence boundary.SigHashDefault policy consistent across commitment construction, auxiliary leaf creation, signing, and verification. The commitment builder currently snapshots the result while other paths can consult live negotiation; either use one resolved value per commitment transition or demonstrate with a focused test why divergence cannot occur.maxFeeRatio relaxation if possible. Wherever it lands, cap the override at the concrete tapd requirement (5.0) rather than 100.0, and add a focused Taproot Assets test proving the realistic near-dust re-anchor flow needs a ratio above one.Once those points are addressed and the relevant tests are green, I think this should be ready for a final pass.
One remaining launch-state issue: both HTLC resolvers call markLaunched before publishPreSignedHtlcTx has successfully registered for block epochs. If RegisterBlockEpochNtfn returns an error, no publisher goroutine is started and PublishTx is never called, but the resolver remains marked launched. Every later Launch call then returns early, so the immutable second-level transaction is not retried until the resolver is reconstructed after an lnd restart. This is particularly risky for deadline-sensitive HTLCs because the SIGHASH_DEFAULT transaction cannot fall back to the normal sweeper reconstruction path.
Could we mark the resolver launched only after publisher setup succeeds, or clear the flag on synchronous setup failure? A focused test should make registration fail once, call Launch again after restoring the notifier, and verify that the transaction is published.
A separate reliability concern is the CPFP child that spends the second-level anchor. After the parent is published, an immediate SweepInput error and a later sweep-result error are only logged. There is no persistent retry or acknowledgement proving that the CPFP child was accepted into the mempool. Since SIGHASH_DEFAULT prevents rebuilding or RBF-bumping the parent, this anchor spend is its only fee-bumping path.
Could we add a durable acceptance/retry boundary here? A transient sweeper admission or publication failure should be retried until the child is accepted, the parent confirms, the deadline is reached, or shutdown occurs. The test should inject an initial failure, then verify a later retry publishes a child spending output 1 and that the child is observed in the mempool. If this is intentionally follow-up work, it would be good to link a focused issue that defines the persistence and retry semantics.
Could we mark the resolver launched only after publisher setup succeeds, or clear the flag on synchronous setup failure?
Done, went with clearing the flag: the SigHashDefault branch in both resolvers clears it when the publish setup fails synchronously, so the next Launch retries instead of no-op'ing until restart. TestHtlcTimeoutResolverLaunchRetry fails registration once, asserts the resolver is not marked launched, and verifies the second Launch publishes the tx.
Could we add a durable acceptance/retry boundary here?
Added, in process. The publisher goroutine now supervises the anchor offer instead of firing it once: an immediate SweepInput error is retried on the next block, and a failed sweep result re-offers on the next block. The loop ends when the sweep succeeds, the anchor is spent by someone else (which covers the anyone-can-spend path once the parent confirmed), or the resolver shuts down. A restart re-publishes the parent and re-offers the anchor from scratch, so the boundary survives restarts without new persisted state. TestPublishPreSignedHtlcTxAnchorSupervision covers the initial offer failure, the re-offer after a failed result, and both terminal outcomes.
@ziggie1984: review reminder
@ziggie1984: review reminder
@ziggie1984: review reminder
@ziggie1984: review reminder
Re-reviewed the current head (0dca236ae1) and traced the new publisher through SweepInput, handleNewInput, and the sweeper fee-bumper. The focused contractcourt tests pass. To be explicit up front: I am open to a first version that does not implement package relay. Package relay itself is not a blocking requirement for this PR. My blocking concern is that the immutable-parent lifecycle should be owned by the sweeper, with bounded/classified retries, so package publication can be added there as a follow-up without creating another transaction engine in contractcourt.
1. The CPFP path cannot rescue a parent that fails standalone admission. The parent is fixed near the relay floor and publishPreSignedHtlcTx does not offer output 1 to the sweeper until PublishTx(parent) succeeds. There are no SubmitPackage calls in contractcourt or sweep. If the dynamic mempool minimum is above the parent's ~1.1 sat/vB rate, the parent is rejected, the child is never constructed, and the anchor cannot do the job it was added for. The existing 330-sat anchor and transaction format can remain unchanged; parent+child package submission is sufficient to close this gap. I am fine deferring that package path to the next version
2. This introduces another long-lived transaction publication engine in contractcourt. publishPreSignedHtlcTx now owns block-driven publication, retries, anchor supervision, and shutdown while sweep.TxPublisher already owns publication, fee bumping, replacement, monitoring, and sweep state. This repeats the split ownership we are trying to remove with the UTXO nursery. Contractcourt should provide the exact immutable parent, anchor input, budget, and deadline; the sweeper should own how that operation reaches confirmation. The first implementation can retain sequential PublishTx(parent) followed by child publication for unsupported backends, with package submission added as the bitcoind strategy, but the lifecycle should live behind one sweeper API rather than becoming a second publisher here.
3. The retry contract is too broad and the registration boundary is weaker than the helper assumes. SweepInput returns after delivering a message to newInputs; spend-notification registration happens later in handleNewInput. The resolver correctly waits for the returned result rather than issuing concurrent attempts, but once an error arrives it retries every non-ErrRemoteSpend outcome on the next block, including outcomes the sweeper classified as fatal or budget-exhausted. waitBlock also discards the epoch height, so the supervisor cannot apply an explicit deadline termination policy. Please add an acknowledgement/state boundary for successful registration, classify retryable versus terminal results, and add tests showing transient failures retry while deadline/budget/fatal outcomes terminate according to the intended policy.
I do not think P2A/TRUC or a zero-fee parent belongs in this PR. Keeping the funded anchor and independently relayable parent is a reasonable cross-backend fallback. Again, a sequential first version is acceptable: the sweeper may initially publish the exact parent and then sweep the anchor, while a later bitcoind strategy submits parent+child as a package. The blocking concern is establishing that single sweeper-owned immutable-parent lifecycle now, before package persistence and reorg handling make the contractcourt helper another nursery-like subsystem.
Separately, the independent maxFeeRatio change should preferably be split. Its implementation now uses the requested 5.0 ceiling, but the commit message still says 100.0.
Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?
Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?
I misread the last big comment from you, it seemed to me that the points were highlighting the weak points of this approach, in an informative manner. I will address 2 and 3 from above.
Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?
Moved now. The sweeper gets PublishPreSignedTx: contractcourt hands over the exact tx, the anchor input with budget and deadline, and the sweeper owns the rest in its collector loop. Locktime gating and re-broadcast run on blockbeats, the anchor is registered inline once the parent is in the mempool, one final result comes back. The old contractcourt publisher is gone, resolvers only build the request. Package submission later slots into that one method.
On retries: only publication and anchor registration retry, both bounded by the HTLC deadline. A nil from the input handler is the registration ack. Results from the regular sweep machinery are final by construction (it already retries bumps and publication internally), so none of them is retried. Tests in sweep/presigned_test.go cover each step, the deadline, duplicates, shutdown and an end-to-end run through the live collector.
@ziggie1984: review reminder
@ziggie1984: review reminder
@ziggie1984: review reminder
waiting for a concept ACK from @yyforyongyu here.
@ziggie1984: review reminder
@yyforyongyu: review reminder
Reviewed as part of the full aux revocation stack (#11094 → #11111 → #11112, plus taproot-assets#1994 pinned at 2069f100d). Each finding is posted on the PR that introduces it.
The deterministic second-level construction itself holds. I ran a scratch two-party SigHashDefault state machine: both signed second-level txs pass txscript with StandardVerifyFlags (timeout 816 wu, 227 sat; success 876 wu, 243 sat, ≈1.11 sat/vB), and the sweep sign desc value matches TxOut[0]. Most of what's inline is about the sweeper lifecycle around those txs and about where the sighash mode comes from.
Test gaps (mutation-tested):
sweepOutputAmt -= AnchorSize in both resolution builders: all of ./lnwallet/ still passes.isSigHashDefault() hand-off in htlcSuccessResolver: all of ./contractcourt/ still passes.TestPreSignedTxAnchorOutcomes only feeds canned results.Description: the PR description doesn't mention the CPFP anchor, the baked-in floor fee, or the new UtxoSweeper.PublishPreSignedTx API, which together are most of the diff. The PR is labelled no-changelog, but the stack adds a release-notes entry.
_Posted by claudell (automated review agent) at georgetsagk's request._
Found a few issues aided by agents. I think this design works with the assumption that the wallet must remain enough utxos.
I've also started an iteration on whether we could perform an alternative design, maybe a future upgrade, still working on it, but can check https://gist.github.com/yyforyongyu/4547509e21781834fdb41aa2682d98ef#file-01-proposal-md
There is also an issue here, unless we support bounded CPFP-only batching here.
With NoInputBatch, each child can tie up a separate confirmed wallet UTXO. If a peer triggers many HTLC resolutions and those children stay unconfirmed, we could run out of funding inputs for urgent sweeps on other channels, even with plenty of BTC sitting in unconfirmed change. This seems to amplify the existing wallet-liquidity risk.
We'd need to preserve failure isolation: keep ordinary sweeps outside these batches and rebuild the child when one parent disappears. In a focused unit test, the healthy anchor gets reoffered before the deadline, but the same shared failure terminates its lifecycle after the deadline. That needs fixing, and we'd also need to verify wallet-input recovery when rebuilding the child.
I think we need to track it as follow-up. It should improve wallet funding efficiency without changing the asset proof rules.
The batching concern is real. The anchor keeps NoInputBatch so that a missing parent only fails its own child, and the wallet UTXO it ties up is the cost of that. Filed as #11576. The lifecycle no longer terminates at the deadline, so the shared failure past the deadline you hit in your test now reoffers the anchor like any other block.
@yyforyongyu: review reminder
@georgetsagk, remember to re-request review from reviewers when ready
gijswijs
GeorgeTsagk
Description
Punishing a revoked commitment on an asset channel requires more than the bitcoin-level justice sweep: the asset side needs a valid asset witness for whatever transaction the cheater actually confirms, including second-level HTLC spends.
Under the normal
SINGLE|ANYONECANPAYscheme those second-level transactions are malleable (the broadcaster can add fee inputs, batch, or RBF them), so their final form is unknowable in advance and no asset witness or proof chain could be prepared for them. With deterministic HTLCs both parties commit to the exact final second-level transaction viaSIGHASH_DEFAULT, so the revoking party can pre-sign asset-level signatures for both spend paths of every HTLC and hand them over in RevokeAndAck (this will be the next part), giving the honest party everything needed to claim the assets no matter which path a breach takes.Next PR: #11111