Skip to content

tapchannel: support HTLC revocation sweeps - #1994

Open
GeorgeTsagk wants to merge 25 commits into
lightninglabs:mainfrom
GeorgeTsagk:htlc-revocation
Open

GeorgeTsagk wants to merge 25 commits into
lightninglabs:mainfrom
GeorgeTsagk:htlc-revocation

Conversation

@GeorgeTsagk

@GeorgeTsagk GeorgeTsagk commented Feb 16, 2026 •

Copy link
Copy Markdown
Member

Description

This PR adds support for sweeping revoked HTLC outputs in Taproot Asset channels.

The aux sweeper is extended with resolution logic for revoked offered/accepted HTLCs and second-level HTLC revocations. The signing path is updated to handle breach scenarios, where inputs are spent via key spend rather than script spend, with the HTLC index applied as a tweak to match the commitment's taproot internal key.

Additionally, the NotifyBroadcast interface gains a skipBroadcast flag. During breach resolution, LND crafts multiple competing justice transactions as a pinning mitigation. Rather than notifying tapd at time, LND now notifies after confirmation — the flag signals that the tx is already on-chain and proof finalization can proceed without re-broadcasting.

Depends on lightningnetwork/lnd#11112

Extra

A doc explaining the wire changes needed for tap HTLC revocation to work:

  • SIGHASH_DEFAULT: predictable 2nd level HTLC transactions (proof reconstruction)
  • sending your AuxSig during RevokeAndAck: reconstructing remote force-close asset witnesses for 2nd level HTLCs

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @GeorgeTsagk, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the 'tapchannel' functionality by introducing robust support for sweeping revoked HTLC outputs in Taproot Asset channels. It refines the auxiliary sweeper's resolution capabilities to manage various types of revoked HTLCs and adapts the signing path to correctly handle key spend operations required for breach recovery. Furthermore, it optimizes transaction broadcasting during breach events by allowing the system to skip broadcasting for already confirmed transactions, which is crucial for pinning mitigation.

Highlights

  • HTLC Revocation Sweeps: Implemented support for sweeping revoked HTLC outputs within Taproot Asset channels, enabling recovery in breach scenarios.
  • Auxiliary Sweeper Enhancements: Extended the auxiliary sweeper with specific resolution logic for offered, accepted, and second-level revoked HTLCs.
  • Breach Scenario Signing Path: Updated the signing process to correctly handle key spend for breach scenarios, applying the HTLC index as a tweak to the commitment's taproot internal key.
  • Conditional Transaction Broadcasting: Introduced a 'skipBroadcast' flag to the NotifyBroadcast interface, allowing tapd to avoid re-broadcasting transactions already on-chain during breach resolution.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • go.mod
    • Updated Go language version to 1.25.5.
    • Added temporary replace directives for 'github.com/lightningnetwork/lnd' and 'github.com/lightningnetwork/lnd/sqldb' to a specific commit by GeorgeTsagk.
  • go.sum
    • Updated checksums to reflect the Go version change and the new LND replace directives.
  • server.go
    • Modified the 'NotifyBroadcast' method signature to include a 'skipBroadcast' boolean parameter.
    • Updated the logging for 'NotifyBroadcast' to include the 'skipBroadcast' status.
    • Passed the new 'skipBroadcast' parameter to the underlying auxiliary sweeper's 'NotifyBroadcast' method.
  • tapchannel/aux_closer.go
    • Modified the 'shipChannelTxn' function signature to accept a 'skipBroadcast' boolean parameter.
    • Updated the creation of 'PreAnchoredParcel' to use the new 'skipBroadcast' parameter.
    • Passed 'false' for 'skipBroadcast' when calling 'shipChannelTxn' from 'FinalizeClose'.
  • tapchannel/aux_leaf_signer.go
    • Refactored 'applySignDescToVIn' to distinguish between key spend (breach scenarios) and script spend.
    • For key spend, it now applies 'DoubleTweak' (revocation key) first, then 'SingleTweak' (HTLC index) to the signing key.
    • Adjusted the return value for 'leafToSign' to be empty for key spend scenarios.
    • Updated comments to clarify the tweak application order for breach scenarios.
  • tapchannel/aux_sweeper.go
    • Added a 'skipBroadcast' field to the 'broadcastReq' struct.
    • Imported the 'encoding/binary' package.
    • Modified 'signSweepVpackets' to handle key spend scenarios for HTLC revocations, applying the HTLC index as a 'SingleTweak' and setting the correct 'signMethod' and 'signingKey' for verification.
    • Introduced 'htlcOfferedRevokeSweepDesc', 'htlcAcceptedRevokeSweepDesc', and 'htlcSecondLevelRevokeSweepDesc' functions to generate sweep descriptors for various revoked HTLC types, ensuring correct key tweaking.
    • Updated 'importCommitTx' to pass 'true' for 'skipBroadcast' when shipping commitment transactions, indicating they are already on-chain.
    • Added 'errNoHtlcID' error constant.
    • Extended the 'resolveContract' function to include new resolution types for 'TaprootHtlcOfferedRevoke', 'TaprootHtlcAcceptedRevoke', and 'TaprootHtlcSecondLevelRevoke', filtering assets by HTLC ID and generating appropriate sweep descriptors.
    • Modified 'registerAndBroadcastSweep' and 'NotifyBroadcast' to accept and pass through the 'skipBroadcast' parameter.
Activity
  • No specific activity (comments, reviews, progress updates) was provided in the context for this pull request.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for sweeping revoked HTLC outputs in Taproot Asset channels, a crucial feature for channel security. The changes are extensive, primarily affecting the tapchannel package. Key modifications include extending the auxiliary sweeper with resolution logic for various HTLC revocation scenarios and updating the signing path to handle breach scenarios via key-path spends. A skipBroadcast flag has also been added to the NotifyBroadcast interface to handle transactions that are already on-chain, such as justice transactions. The code is generally well-structured and includes detailed comments explaining the complex logic, especially around cryptographic tweaks. I've identified a couple of areas for improvement: one for enhancing code maintainability by reducing duplication, and another to make the HTLC lookup logic more robust. Overall, this is a solid contribution that adds significant functionality.

Comment thread tapchannel/aux_sweeper.go Outdated
Comment on lines +2205 to +2209
// If not found in outgoing, try incoming (accepted HTLCs).
if len(assetOutputs) == 0 {
htlcOutputs = commitState.IncomingHtlcAssets.Val
assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If the HTLC is not found in OutgoingHtlcAssets, the code proceeds to check IncomingHtlcAssets. However, if it's not found there either, assetOutputs will be empty, and the function will proceed without error, likely resulting in an empty resolution blob later on. It would be more robust to return an error if the HTLC cannot be found in either list, to make debugging easier in case of an unexpected state.

		if len(assetOutputs) == 0 {
			htlcOutputs = commitState.IncomingHtlcAssets.Val
			assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID)
			if len(assetOutputs) == 0 {
				return lfn.Errf[returnType](
					"htlc with id %d not found", htlcID,
				)
			}
		}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the very least should log here. Invariants further up the stack should prevent this though.

@coveralls

coveralls commented Feb 16, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 26172223053

Coverage decreased (-0.3%) to 34.502%

Details

  • Coverage decreased (-0.3%) from the base build.
  • Patch coverage: 1459 uncovered changes across 17 files (210 of 1669 lines covered, 12.58%).
  • 76 coverage regressions across 15 files.

Uncovered Changes

Top 10 Files by Coverage Impact Changed Covered %
tapchannel/aux_sweeper.go 1155 106 9.18%
tapchannel/aux_leaf_creator.go 101 0 0.0%
server.go 60 0 0.0%
tapchannel/aux_leaf_signer.go 115 66 57.39%
itest/custom_channels/helpers.go 45 0 0.0%
tapdb/assets_store.go 53 18 33.96%
tapfreighter/chain_porter.go 27 0 0.0%
proof/verifier.go 31 11 35.48%
tapfreighter/parcel.go 19 0 0.0%
itest/integrated_harness.go 12 0 0.0%

Coverage Regressions

76 previously-covered lines in 15 files lost coverage.

Top 10 Files by Coverage Loss Lines Losing Coverage Coverage
tappsbt/create.go 30 23.67%
tapgarden/caretaker.go 10 68.16%
address/address.go 5 66.67%
address/mock.go 4 87.5%
tapchannel/aux_leaf_signer.go 4 44.79%
tapdb/universe.go 4 77.11%
tapfreighter/interface.go 4 39.87%
asset/mock.go 3 65.89%
authmailbox/server.go 3 77.18%
asset/asset.go 2 46.74%

Coverage Stats

Coverage Status
Relevant Lines: 103634
Covered Lines: 35756
Line Coverage: 34.5%
Coverage Strength: 0.37 hits per line

💛 - Coveralls

@Roasbeef
Roasbeef self-requested a review February 24, 2026 19:50
@jtobin
jtobin requested a review from gijswijs February 24, 2026 19:52
Comment thread tapchannel/aux_leaf_signer.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Outdated
Comment on lines +2205 to +2209
// If not found in outgoing, try incoming (accepted HTLCs).
if len(assetOutputs) == 0 {
htlcOutputs = commitState.IncomingHtlcAssets.Val
assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the very least should log here. Invariants further up the stack should prevent this though.

Comment thread tapchannel/aux_leaf_signer.go Resolved
Comment thread tapchannel/aux_leaf_signer.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Outdated

// Now that we have the script tree, we'll make the control block
// needed to spend it using the revocation path.
ctrlBlock, err := tweakedScriptTree.CtrlBlockForPath(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add tests here.

AFIACT, this would fail in prod, as it's using an enum, but that value isn't handled by this func: https://github.com/lightningnetwork/lnd/blob/0b00c662318c4960a0f8f814e16e43155029ca35/input/script_utils.go#L1754-L1771

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah we should add unit level tests here to ensure that this func is able to sign+verify using the same routines used to create the txns+scripts in the first place.

Comment thread tapchannel/aux_sweeper.go Resolved
@github-project-automation github-project-automation Bot moved this from 🆕 New to 👀 In review in Taproot-Assets Project Board Feb 25, 2026
@GeorgeTsagk

GeorgeTsagk commented Mar 4, 2026 •

Copy link
Copy Markdown
Member Author

Added a gist explaining the 2nd level situation, focused around the sighash of the pre-signed 2nd level HTLC transaction: https://gist.github.com/GeorgeTsagk/9775947b6b9d8cc07cd23e038a246719

Will soon push a version using the sighash_all approach (HTLCs pay their own fee)

@GeorgeTsagk

Copy link
Copy Markdown
Member Author

Breach itest has now been moved here, no need for a Lit PR

@GeorgeTsagk

Copy link
Copy Markdown
Member Author

Had to update some of the test assertions

Now that we bump DefaultOnChainHtlcSat amount some of the test expectations had to reflect the change.

@GeorgeTsagk

Copy link
Copy Markdown
Member Author

Realized that some of the custom channels itests failures on CI aren't flakes: Some actual test assertions need to change since the HTLC anchor amount was bumped.

Will address them asap, shouldn't be a blocker for reviewers.

@gijswijs gijswijs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I did a thorough review of this PR.

The core cryptographic operations are sound but the surrounding infrastructure needs rework.

I've pointed out all issues with inline comments. I also have some nits wrt the commits (commitnit), which you'll find below:

Typos in commit message for commit d728fae:

The tricky part for taproot assets related to the call sequence of "NotifyBroadcast".

Shouldn't that read "is related"?

we need to signal to the NotifyBroadcast call that we do not wish to broadcast, as that is prone to fail.

prone to fail is an understatement. It will fail and makes no sense whatsoever.

Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread proof/verifier.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread tapchannel/aux_sweeper_test.go Resolved
Comment thread tapchannel/aux_sweeper.go Resolved
Comment thread itest/custom_channels/breach_test.go Resolved
@GeorgeTsagk

Copy link
Copy Markdown
Member Author

Rebased on main

@jtobin jtobin added this to the v0.8 milestone May 4, 2026
@GeorgeTsagk
GeorgeTsagk force-pushed the htlc-revocation branch 2 times, most recently from 8396516 to d3199c6 Compare November 26, 2026 09:33
@litbot-9000

Copy link
Copy Markdown
Collaborator

@jtobin: review reminder
@GeorgeTsagk, remember to re-request review from reviewers when ready

Points the lnd module and its submodules at the companion series on the
GeorgeTsagk/lnd fork:

  1. lightningnetwork/lnd#11094, deterministic second-level HTLCs
  2. lightningnetwork/lnd#11111, revocation AuxSigs in RevokeAndAck
  3. lightningnetwork/lnd#11112, breach-to-confirmation revocation flow

The pin is at the tip of part 3, which contains all three. It also adapts
the call sites that the new aux interfaces touch.

This is temporary and has to be dropped once the lnd series lands.
We add the missing cases for resolving contracts that correspond to
revoked offered/accepted HTLCs, and revoked HTLCs that have been taken
to the second level.

For signing, we distinguish between normal and breach scenarios: normal
force close sweeps use scriptspend (control block present), while breach
sweeps use keyspend (no control block). The breach path is auto-detected
by checking if both SingleTweak and DoubleTweak are present in the sign
descriptor.

We also supply the HTLC index as a single tweak, to be applied by the
signer later. This is crucial for matching the taproot internal key that
was placed in the commitment during creation.
A short intro: For sweeping revoked states the breach arbitrator of LND
crafts 3 different sweep transactions:
a) spendAll: spends commitment outputs (local, remote) and all HTLCs
b) spendCommitOuts: spends only the commitment outputs (local, remote)
c) spendHTLCs: spends only the HTLCs

Initially LND broadcasts version a) of the sweep. If that is not
confirmed within a few blocks(4) then it will broadcast b) and c). This
serves as a pinning attack mitigation.

The tricky part for taproot assets is related to the call sequence of
"NotifyBroadcast". That call finalizes the proofs for the transfer given
the txid of the transaction that contains it. Now, we have multiple
competing sweeps fighting to get in a block, so we are uncertain about
which one is going to make it on-chain.

By changing LND into calling NotifyBroadcast after confirming any sweep
transaction, we have a way of certainly telling which proofs need to be
crafted. Given that the transaction is already confirmed, re-broadcasting
it makes no sense and will simply fail, so we need to signal to the
NotifyBroadcast call that we do not wish to broadcast.

The new skipBroadcast flag serves as that signal, and is set by the
caller (LND).
Add a unit test that performs a full sign+verify round-trip for all
three revocation sweep descriptor types (offered, accepted, and
second-level HTLC). The test generates real key material, derives the
revocation signing key using the same routines used in production
(DeriveRevocationPrivKey + TweakPrivKey), and verifies the resulting
schnorr signature against the taproot output key from the sweep
descriptor.

This validates that the sweep descriptor functions produce script trees
whose taproot output keys are consistent with the private key
derivation path, ensuring that breach sweeps will produce valid
signatures at runtime.
…mitment caching

Introduce the DeterministicHTLCs feature bit (bits 4/5) which gates
deterministic second-level HTLC transactions. When negotiated,
second-level HTLCs use SigHashDefault instead of
SigHashSingle|AnyOneCanPay, and the revoking party includes
dual-path AuxSigs in RevokeAndAck for breach proof reconstruction.

Also add SigHashType caching in the commitment blob so the sighash
choice is recorded alongside the commitment state and can be
recovered at breach time without re-querying the feature store.
…HTLCs flag

Implement Server.HtlcSigHashType (lnwallet.AuxSigner interface) which
checks live feature negotiation state first, then falls back to decoding
the commitment blob's cached SigHashDefault flag. Includes a nil guard
for the startup race when tapd config is not yet initialized.

Thread the DeterministicHTLCs feature flag through the commitment and
leaf creation paths:

- aux_funding_controller: store flag from negotiated features
  in pendingAssetFunding and pass through to initial commitment blobs.
- aux_leaf_creator: query feature store to determine sighash type
  for each new commitment, and pass to allocation helpers.
- commitment.go: accept sigHashDefault parameter in
  GenerateCommitmentAllocations and CreateSecondLevelHtlcPackets.
Teach the revoked HTLC recovery flow to sweep second-level outputs back through
the aux channel machinery.

The sweep/import path can report an already-broadcast pre-anchored transfer
more than once. Without additional DB-side handling that strands duplicate
recovery transfers in pending state even though the BTC spend is already
confirmed.

Plumb second-level revoked HTLC sweeps through the aux sweeper and make the
asset-store side of the porter tolerant of repeated notifications by treating
pending transfer insertion as idempotent by anchor txid.
Update NotifyBroadcast callers and implementation to use the new
AuxNotifyOpts struct from lnd, replacing the bare skipBroadcast bool.
…close

Replace placeholder witnesses in importSecondLevelHtlcTx with real
asset-level signatures. When AuxSigDesc is available, sign with our
local HTLC key via SignVirtualPacket and insert the remote party's
pre-stored signature to produce a full 2-of-2 witness. The remote
signature is verified under the remote HTLC key before it is used. Use
the imported proof suffix (with correct inclusion proof, block header,
and merkle proof) for the sweep descriptor instead of hand-built stubs.
When AuxSigDesc is not available the import fails: a placeholder
witness could never pass proof verification.

Extend signSecondLevelImport to cover the non-breach success and
timeout paths in addition to the breach path: select
whoseCommit=Local for the non-breach types, choose the auxSigInsertIdx
(0 for non-breach, 1 for breach), and detect the preimage from
witness[2] under the taproot success layout (with witness[1] fallback
for legacy variants).

Extend resolveContract's switch case to handle the three second-level
witness types together (TaprootHtlcSecondLevelRevoke for breach,
TaprootHtlcAcceptedSuccessSecondLevel and
TaprootHtlcOfferedTimeoutSecondLevel for non-breach), picking the
correct asset bucket by the HTLC's direction (incoming for success,
outgoing for timeout, the direction lnd states on the request for
breach) and the matching cltvTimeout semantics. HTLC indexes are counted
per party, so an index regularly exists in both buckets and probing for
it would pick the wrong HTLC.

These flows rest on the pre-signed deterministic second-level tx, so a
second-level request for a commitment built without DeterministicHTLCs
returns an error and lnd keeps resolving that HTLC as before.

For the non-breach 2nd-level output sweep, build the sweep descriptor
at the asset level rather than the BTC level: drop the aux leaf from
the tap tree and tweak the internal key with the HTLC index, so the
control block derives to the asset's tweaked taproot script key
(= prevAsset.ScriptKey.PubKey). Construct the output-sweep blob via a
new buildSecondLevelOutputSweepBlob helper that follows the existing
needsSecondLevel placeholder-vPacket pattern, so the sweeper's
SetAnchorInternalKey / signSweepVpackets handoff at sweep time works
identically to a normal force-close output sweep.

Extend the existing re-anchor skip in resolveContract so it covers all
three second-level witness types: for any second-level sweep the
input proofs already point to the 2nd-level tx, so re-anchoring to the
commit tx would fail to find a matching commit output.
The default 30-second RPC timeout in lndclient is too short when the
integrated daemon restarts after many blocks have been mined while it
was offline. The chain sync during GetInfo can easily exceed 30 seconds
when catching up on 100+ blocks. Increase to 2 minutes to match
production configurations and prevent spurious restart failures during
integration tests.
…erministicHTLCs

Add a custom-channel breach integration test that exercises revoked HTLCs which
advance to second level before the honest party comes back online and sweeps
them.

Keep the default scenario small for normal suite runtime, but structure the
itest so it can be scaled up to stress the same recovery path. Higher-count
variants need additional setup discipline: the pre-breach rebalance must scale
with the requested number of in-flight HTLCs, the post-settlement keysend must
wait until HTLC cleanup has actually completed, and justice mining must accept
the variable set of justice transactions published once more HTLCs reach second
level.

Make the breach test configurable through TAPD_BREACH_HODL_INVOICES_PER_SIDE
while keeping the default at two HTLCs per side.

Also adapt the shared assertForceCloseSweeps helper for the
DeterministicHTLCs feature: when DeterministicHTLCs is negotiated, the
htlc success and timeout resolvers publish the pre-signed 2nd-level tx
directly to the mempool (SigHashDefault, baked-in fees), bypassing the
sweeper. Replace the assertSweepExists checks for
TAPROOT_HTLC_ACCEPTED_LOCAL_SUCCESS / TAPROOT_HTLC_LOCAL_OFFERED_TIMEOUT
with a mempool wait + mine, and drop the now-stale locateAssetTransfers
lookup for those pre-signed txids. The remote-timeout sweep
(TAPROOT_HTLC_OFFERED_REMOTE_TIMEOUT) remains sweeper-driven and is still
asserted via assertSweepExists.
Adapt to the lnd revocation-support API introduced in the depended-on
lnd PR: FetchLeavesFromRevocation now takes a RevocationLeavesReq, and
ResolutionReq carries second-level context in a SecondLevelInfo option
(SecondLevel) rather than the flat SecondLevelTx/SecondLevelTxBlockHeight
fields. Also migrate aux_sweeper_test.go to txscript/v2, and fix a
gofmt alignment plus stray //nolint:llll -> //nolint:lll typos.
… fee

Adapt to the lnd-side change that gives pre-signed second-level HTLC
transactions (SigHashDefault) a floor-rate baked-in fee plus a CPFP
anchor output at index 1, instead of a large fixed fee:

- tapchannel: account for the 2-output second-level tx shape in the aux
  leaf creation/signing and sweep allocations. The asset-bearing HTLC
  output sits at index 0 and its BTC value is reduced by the anchor
  amount; allocations and sweep descriptors are computed accordingly.
  The asset-bearing sweep output uses a fixed sweepAnchorOutputAmt of
  400 sats and the sweep budget excludes wallet-funded extra budget
  (ExtraBudgetForInputs) so the sweeper's accounting stays consistent
  with the actual output values.

- rfqmath: drop the 6x HTLC amount multiplier that padded HTLCs to
  absorb the old large baked-in fee, and bump DefaultOnChainHtlcSat to
  1200 sats so the on-chain HTLC value covers the floor fee plus the
  anchor with margin.

- lndservices+tapcfg: allow PsbtMaxFeeRatio above 1.0. CPFP sweeps of
  second-level anchors legitimately pay more in fees than the swept
  anchor value, since the anchor exists purely to pay for its parent
  package.

- server: pass the RevocationLeavesReq through to the tapchannel aux
  leaf creator unchanged.
Review follow-ups for the revocation sweep flow:

- applySignDescToVIn no longer re-derives the breach decision from
  tweak presence: callers pass an explicit isBreach flag sourced from
  the sweep descriptor context (resolution type, equivalently the
  absence of a control block), so there is a single source of truth
  for keyspend-vs-scriptspend key derivation.

- A second-level sweep allocation now treats a missing HTLC ID as a
  hard error instead of falling back to a bogus index that would make
  the downstream lookups silently return nothing.

- The breach second-level lookup logs a warning when an HTLC is found
  in neither the outgoing nor the incoming asset bucket: that means a
  BTC-only HTLC, which invariants further up the stack should have
  filtered out before asking for asset-level resolution.

- Comment cleanups: deduplicate the derivation comment in
  htlcAcceptedRevokeSweepDesc so it mirrors the offered variant, and
  punctuation normalization in comments added by this branch.
Two unit tests requested in review:

- TestPopulateSecondLevelLeaves covers the revocation-log to
  second-level aux leaf derivation: incoming asset HTLCs get a leaf
  committing to a CLTV timeout, outgoing ones get a leaf without it,
  BTC-only HTLCs and log entries without an HTLC index are skipped.

- TestApplySignDescTweakRoundTrip closes the loop between the
  sweeper's PSBT encoding and the wallet signer's decoding: the
  revocation and HTLC index tweaks packed as PSBT unknowns by
  applySignDescToVIn are replayed exactly like lnd's wallet signer
  applies them, and the resulting key must match both the manual
  derivation chain and the public key the sweeper verifies against.
A resolution request for a breached HTLC can arrive without an HTLC ID
when the revocation log predates the HtlcIndex record. Returning an
error from the revoke resolution types made lnd fail the entire
NewBreachRetribution, so the breach was never dispatched and no justice
transaction was built at all, including for the commitment outputs.
Return an empty asset resolution instead and log loudly: forgoing the
asset leg of a single HTLC is strictly better than forfeiting the whole
revoked commitment.

While here, make the first-level revoke paths shout when an HTLC ID is
missing from the expected asset bucket instead of silently producing an
empty resolution, distinguish the legitimate BTC-only HTLC case (no
asset bucket entry AND no aux leaf) from a genuinely unlocatable asset
HTLC, and correct the inverted perspective comment on the offered
revoke case.
Several fixes to the second-level HTLC import path:

Make importSecondLevelHtlcTx idempotent: when the parcel already exists
from a previous attempt, the freshly reconstructed packets still need
their proof suffixes populated, so only the final shipping step is
skipped. Previously the early return left the packets without suffixes
and no valid proofs to hand to the sweep.

Drop the placeholder witness fallback for missing AuxSigDesc. A {0x01}
witness can never pass proof verification, so pretending to continue
only deferred the failure. Fail loudly instead: the error goes back to
lnd, which retries the notification.

Verify the remote signature under the remote HTLC key of the request's
key ring, after checking that the key is one of the keys of the leaf
being spent. The previous check only looked at the first key of a
68-byte leaf, which rejected every success-path signature (success
leaves are longer). Compute the sighash with the signature's recorded
sighash type.

Carry the recorded sighash byte in the witness for non-default
signatures (BIP 342 requires the explicit flag byte on 65-byte sigs),
so legacy SINGLE|ANYONECANPAY witnesses survive proof import.

Tighten the preimage detection: only inspect the input that spends the
commitment transaction and only accept a witness element that hashes to
the HTLC's payment hash, instead of scanning every input for any
32-byte element. Derive the HTLC output index from the spending input's
index instead of assuming output zero, and only treat a second output
as the deterministic anchor when the commitment actually negotiated
SigHashDefault and the tx has the deterministic single-input shape.

Match second-level packets back to the commitment-level asset outputs
they spend via the packet input's PrevID instead of pairing the two
lists positionally: packet generation groups and orders by asset ID, so
grouped assets or multiple UTXOs per HTLC could be paired with the
wrong proof or dropped.

Also point the key-tweak comment at both lnd signer consumers
(maybeTweakPrivKey and maybeTweakPrivKeyPsbt) that must combine the
revocation and HTLC-index tweaks; the PSBT one is fixed in the lnd
series.

Look up the proof of a virtual input by asset ID as well as script key
and outpoint: the tranches of a grouped asset channel share the latter
two, and a failed lookup is now an error instead of a silently stale
proof.

Reject a commitment whose asset HTLC comes without a second-level
signature in VerifySecondLevelSigs. lnd hands over a job for every
HTLC, so a peer can no longer omit the signature we would need to
import the second-level transition.
Returning a hard zero from ExtraBudgetForInputs removed the fee budget
for every aux sweep, not just the second-level CPFP case the workaround
was aimed at. First-level asset sweeps carry a token BTC amount that is
unrelated to the asset value, so without extra budget the sweeper
cannot pull in wallet UTXOs and the sweep goes uneconomical exactly
when fees are high, losing the asset leg once the CLTV passes. Restore
the per-input budget for everything except second-level HTLC output
sweeps, which self-fund under DeterministicHTLCs and whose bundled
wallet inputs trip the anchor-related UTXO accounting drift the zero
was working around.
Values above 1.0 are legitimate for near-dust asset UTXOs, but with no
ceiling a fat-fingered value (50 instead of 5.0) would silently
authorize burning many times the output value in fees on every send.
Cap at 5.0, which matches lnd's own FundPsbt sanity-check ceiling: any
larger value would be rejected by lnd on every funding attempt anyway.
The default stays at 0.75, as values above 1.0 need an lnd whose
FundPsbt accepts them. Also update the sample-tapd.conf entry to
describe the new range.
SanityCheckAmounts and CreateAllocations hardcoded sigHashDefault=true
in their six HtlcIsDust calls while GenerateCommitmentAllocations
already receives the negotiated flag. For channels that did not
negotiate DeterministicHTLCs, tapd would apply the higher deterministic
dust threshold (second-level fee plus anchor) and could reject or omit
HTLCs that lnd includes in the commitment. Pass the flag through.
…blob

The live feature map is only populated once the peer has reconnected,
so around a restart the leaf creator could see an empty vector while
lnd already operates in the negotiated mode, making the two sides
construct different layouts for the same commitment. For the STXO
flags, mirror lnd's precedence: live negotiation first, the flags
cached in the previous commitment blob as the fallback.

The DeterministicHTLCs flag is not derived here at all. Whoever signs a
commitment decides its sighash mode and states it on the
commitment_signed, which can be retransmitted in a later connection
with different features negotiated: a commitment signed before both
peers upgraded has to be built as legacy by the receiver although the
feature is negotiated by then. lnd hands the mode of the commitment
being built to the leaf store, for the commitments it signs and the
ones it verifies, and that mode is what the allocations are generated
with and what the new blob records.
The sign and verify paths re-derived the second-level timeout from the
HTLC direction whenever the job's HtlcTimeout was None. The revocation
flow deliberately sends None for success-path signatures (the canonical
success transition has no locktime), so the fallback restored a timeout
there: signing and verification agreed with each other but diverged
from the transition the sweeper later reconstructs on the breach path.
The lnd series now sets HtlcTimeout explicitly for the CommitSig flow
as well, so the direction fallback is removed and None reliably means
no locktime. A test pins the None-vs-explicit locktime semantics of the
packet builder.
The 1200 sat on-chain HTLC amount pays for the pre-signed second-level
fee, its CPFP anchor and the eventual sweep, none of which exist on
channels that did not negotiate DeterministicHTLCs. Applying it
unconditionally raised the minimum quotable payment from ~354 to 1200
sats for peers that get nothing in return. Select the carrier value per
peer: the deterministic value when DeterministicHTLCs was negotiated,
the legacy just-above-dust value otherwise. Applied to the traffic
shaper (HTLC production and bandwidth minimum) and the sale policy
interceptor response. The RPC-facing minimum-transportable fields keep
the conservative deterministic value for now, as the marshal helpers
have no feature context; a follow-up can thread it per quote.
The tweak round-trip test modelled a signer that iterates the PSBT
unknowns in order and applies every tweak, which matches neither of
lnd's two real consumers, so it passed regardless of what
applySignDescToVIn produced. Export tapsend's AddKeyTweaks and drive
it directly, then assert both of lnd's derivation behaviors (the
SignDescriptor-based direct signer and the unknown-based PSBT signer,
in both unknown orderings) land on the expected key. Also close the
remaining gap in the revocation sweep desc test: the second-level
revoke descriptor must reproduce the exact asset-level script key that
createSecondLevelHtlcAllocations committed to at commitment
construction time.
Also assert that the leaf store builds a commitment with the sighash
mode lnd states in the request, for the leaves and the blob, whatever
the live feature negotiation and the previous commitment say.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: 👀 In review

Development

Successfully merging this pull request may close these issues.

7 participants