Skip to content

swapkit: Consolidate asset swaps on tap-sdk v0.1.1 - #1225

Open
hieblmi wants to merge 11 commits into
lightninglabs:masterfrom
hieblmi:codex/shared-asset-swapkit
Open

hieblmi wants to merge 11 commits into
lightninglabs:masterfrom
hieblmi:codex/shared-asset-swapkit

Conversation

@hieblmi

@hieblmi hieblmi commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

In this PR, we add the shared contracts and SDK helpers for asset Loop In, asset Loop Out, and reservations. swapkit/ defines the Bitcoin spending policies, signing roles, witnesses, and weights. swapkit/tapsdk/ adapts those contracts to native tap-sdk transfer construction, checks independently agreed terms, binds signing to the approved package, and handles proofs and recovery. The consuming feature still owns its state machine, persistence, and the decision of when to release a signature or a preimage.

We build on the released tap-sdk v0.1.1 and Taproot Assets v0.8.9, on the pre-btcd-v2 dependency graph. New on-chain asset operations need a running tapd v0.8.9 or later: v0.8.9 upgrades the transition proof format, and older releases create proofs that upgraded nodes reject once it activates. Consuming Go modules must repeat the bounded legacy TLV decoder replacement from Loop's go.mod, as Go doesn't inherit dependency replacements.

This head is 386511e2b, 11 commits, rebased on master at 2ea616bdd. Since the last update we added the pay-to-anchor HTLC transaction with a direction-neutral builder + validator, hardening of malformed proofs, timelock ordering checks, and a cooperative spend check. We also folded four fixes into the commits that introduced the code: the spend probe, and the three error handling fixes below.

Contracts

All contracts have a cooperative MuSig2 path. Their unilateral refund policies are explicit:

Constructor Refund policy
NewDepositKit Sender CSV delay measured from funding confirmation
NewReservationKit Server/sender absolute CLTV height
NewSwapKit(SwapHTLCLegacyCSV) Sender CSV delay
NewSwapKit(SwapHTLCStaticLoopInV3) / SwapHTLCCLTV Sender absolute CLTV height

Both HTLC variants require the receiver's signature and the correct 32-byte preimage on success, with the existing one-block CSV. The reservation purchase flow in Loop #1229 preserves its quoted CSV delay by adapting NewDepositKit with explicit server/client key roles. NewReservationKit supplies the separate CLTV policy.

The default asset script descriptor preserves the fixed NUMS internal key and single OP_TRUE leaf through LegacyOPTrueOutput. The SDK supplied-key variant, SDKOPTrueOutput, requires explicit selection. Funded outputs retain their exact descriptors through spending and recovery.

The HTLC transaction pays no fee

The cooperative transaction that moves a deposit or a reservation into the HTLC is signed when the swap is set up, and may be published much later. It used to pay a fee that was fixed at signing time, and it couldn't be bumped: it had a single output, and the HTLC success leaf carries a one-block CSV, so no child can spend it while it's unconfirmed. A fee spike could keep it from confirming before the other party's refund opened, after the invoice was already paid or the preimage revealed.

We now build it as a zero-fee version 3 transaction: the HTLC sits at output zero and keeps the whole funding anchor value, and a zero-value pay-to-anchor output sits at index one. The publisher pays the fee with a child of that output and submits both as one package, so the fee is picked at broadcast time and can be raised without a new signature from the peer.

HTLCRequest builds the transaction for either direction from HTLCTerms, and ValidateHTLCPackage is the check a party runs on a peer's package before it co-signs. It accepts only the exact transaction HTLCRequest would build for the party's own terms, so another payment hash, expiry, key role, funding contract, extra input or output, or a transaction that pays its own fee are all rejected. FallbackRequest and NewSwap keep their role as the Loop In forms of the same two calls, with the terms taken from the offer and the deposit contract.

The fee child and the package submission stay with the swap flow. Submitting a package through lnd needs walletrpc.SubmitPackage (lnd v0.21.2 or later) and a bitcoind backend. Nothing in this PR calls it, so LoopMinRequiredLndVersion is unchanged; the flow that publishes a package will have to raise it.

Timelock ordering and cooperative spends

The contracts fix each refund height, but they left the ordering of those heights to the caller. LoopInTimelocks and LoopOutTimelocks check that ordering against the current tip. For Loop In, the deposit refund must open only after the HTLC refund plus a recovery window, and the server must still have its execution window before the HTLC refund. For Loop Out, the HTLC transaction must be able to confirm before the reservation refund, and the client's claim before the HTLC refund. ValidatePayment bounds the Lightning payment against the HTLC expiry for the server of either direction. The checks are pure and point-in-time: the caller passes the tip and repeats them before each release of authority.

A swap that settles off chain ends without the HTLC transaction, with both parties signing a direct spend of the funded output. ValidateCooperativeSpend is the funder's check of that package. The funder is paid by then, so the outputs aren't constrained. The check only makes sure the signature can't be used for anything else: the funded output must be the single input, the signed transaction must commit to the authenticated funding output's value and script, and the signing plan must be the funding contract's cooperative key path under the agreed session context.

Commits

See each commit message for a detailed description w.r.t the incremental changes. The first seven commits are unchanged from the last review: the shared leaf serializers, the contracts, the SDK connection, the tapd version floor and proof/prevout authentication, plan approval, signing, and presigned descendants.

The eighth commit is where the history was reshaped. It used to introduce recovery from observed spends together with a Loop In only fallback that fixed its fee, which a separate hardening commit then patched and two later commits rewrote. That commit now introduces the HTLC transaction once, in its final form (zero-fee, pay-to-anchor, both directions, with the prevout binding and asset lock time checks), next to the recovery helpers and their hardening. So the old commits 8 and 9 and the two HTLC commits that followed are one commit, and the tree is byte for byte what it was before the fold. Three smaller commits follow it: rejecting malformed proofs before reuse, the timelock ordering checks, and the cooperative spend check.

The fourth commit changed in place. LNDChain.Spend probes lnd for a spend of an output for a few seconds and should report ErrPending if it finds none. lnd ends the watch by reporting the probe's deadline on its error channel at about the moment the probe itself expires, and we selected between the two. So an unspent output came back as either pending or a raw DeadlineExceeded error, at random, and DiscoverPreimage, DiscoverOutcome, DiscoverOriginalRefund and FallbackProof failed intermittently while the watched output was unspent. A deadline on the error channel is now reported as pending. The unit test's notifier mock never sent anything on that channel, which is why it took a daemon-backed test to find it.

Package usage and validation boundaries are documented in the contract README and the SDK adapter README.

Error handling fixes

A review that ran the kit against injected faults of its own tapd and chain backend found three places where a local fault was reported as something else. None of them can be triggered by the counterparty, and no assets were at risk. They are fixed in the commits that introduced the functions.

LogAndExport treated an archived output proof that couldn't be decoded like a missing entry. With the transfer already in tapd's log it then returned ErrPending on every retry, as if a confirmation were outstanding. It now returns the decode error, and it neither waits nor logs the transfer again.

FundingProof skipped a matching wallet output when its proof export failed, and ended in ErrInvalid if no other candidate was ready. A single lost RPC reply therefore made a valid funding request look invalid. The failure is now returned as it is, and the node parameters are read once before the candidates instead of once per candidate.

FallbackProof declared the deposit's asset key, a wallet write, before it looked at the archive. A fully signed fallback now declares the key only when it is logged for the first time, so a proof that is archived already can be read while tapd's wallet accepts no writes. A fallback that still lacks its signature declares up front as before.

Known gap

VerifyGroupMembership takes the genesis proofs of a group anchor first, then of the issuances that will be used. On a tapd node that has never seen the group, the anchor issuance verifies, but a later issuance doesn't until the anchor has been registered with VerifyProofWithIssuance. VerifyGroupMembership doesn't register it and its docs don't say so. A caller has to make both calls in that order for now. Whether the function should register the anchor itself (a lasting write from a function named "verify") or just document the precondition is still open.

Testing

On 386511e2b every commit builds, and the swapkit, swapkit/tapsdk, internal/assetproof and internal/assetpolicy unit tests pass. The linter reports nothing on the lines this PR adds. The rebase only had to merge docs/release-notes/release-notes-next.md; the code delta against the previous head is exactly master's own.

The daemon-backed tests live in Nautilus #1712. It pins this head. It covers every subflow of asset Loop In and Loop Out with its own case against real lnd, tapd and bitcoind nodes, including the pay-to-anchor HTLC transaction submitted as a package to bitcoind, and it has a check that fails when an exported function of this kit has neither an integration case nor a stated reason. CI passed there on an earlier head, 7c37b1d6b. Its current head 906820a4c pins this head in a single dependency commit and moves four of its older cases onto the per-party fixture; CI is rerunning on it.

@hieblmi hieblmi added the no-changelog Skip the release notes CI check label Sep 2, 2026
@hieblmi
hieblmi force-pushed the codex/shared-asset-swapkit branch 4 times, most recently from c206f0d to 2814bf6 Compare September 3, 2026 05:54
@hieblmi hieblmi added asset loop out Taproot Asset Loop Out work and removed no-changelog Skip the release notes CI check labels Sep 3, 2026
@hieblmi hieblmi changed the title assets: Add shared asset HTLC kit assets: Add shared asset tooling Sep 3, 2026
@hieblmi hieblmi added the no-changelog Skip the release notes CI check label Sep 3, 2026
@hieblmi
hieblmi force-pushed the codex/shared-asset-swapkit branch 2 times, most recently from 4283082 to 50595de Compare September 3, 2026 08:12
@hieblmi hieblmi self-assigned this Sep 3, 2026
@hieblmi
hieblmi marked this pull request as ready for review September 3, 2026 12:22
@hieblmi

hieblmi commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

/gateway review

@lightninglabs-gateway

Copy link
Copy Markdown

👀 gateway review starting…

@starius starius left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Style — ~18 unexported funcs and ~14 test helpers have no godoc, against the convention. Non-test: canonicalAddressParams, cloneAddressParams (both copies), validateScripts, genBtcControlBlock, validateAsset (both), findUniqueInput (both), validateSweep (both), validateSequence, verifyTapscriptSignature (both), timeoutPathSibling, encodedTimeoutPathSibling, newHtlcSwapKit, validateProof.

Comment thread assets/tapkit.go Resolved
Comment thread assets/tapkit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/htlc/swapkit.go Resolved
@hieblmi

hieblmi commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 818876e also adds documentation to the unexported production and test helpers listed in the general review. Local verification passed: go test ./..., go test -race ./assets/..., go vet ./..., golangci-lint (0 issues), plus a Nautilus #1712 itest-package compile with integration tags.

@hieblmi
hieblmi requested a review from starius September 8, 2026 13:05
@hieblmi
hieblmi force-pushed the codex/shared-asset-swapkit branch from 818876e to 81e876c Compare September 8, 2026 14:33
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/htlc/swapkit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/htlc/swapkit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/htlc/swapkit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/deposit/kit.go Resolved
Comment thread assets/htlc/swapkit.go Resolved
Comment thread assets/htlc/script.go Resolved
@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@sputn1ck: review reminder
@hieblmi, remember to re-request review from reviewers when ready

@hieblmi
hieblmi force-pushed the codex/shared-asset-swapkit branch from 81e876c to dcd5af1 Compare September 17, 2026 08:44
@litbot-9000

Copy link
Copy Markdown
Collaborator

@hieblmi, remember to re-request review from reviewers when ready

@litbot-9000

Copy link
Copy Markdown
Collaborator

@sputn1ck: review reminder
@GeorgeTsagk: review reminder
@starius: review reminder
@bhandras: review reminder

@litbot-9000

Copy link
Copy Markdown
Collaborator

@starius: review reminder
@bhandras: review reminder

Route existing HTLC, static address and reservation scripts through
the same leaf serializers. Pin the quote templates so moving the
serialization cannot change signed numbers or zero-hash fee estimates.
Define the key roles, cooperative and unilateral paths, witnesses and
weight estimates for both directions. Exercise the legacy vectors and
execute the spend conditions against the Bitcoin script engine.
Build the adapter against released pre-btcd-v2 modules and retain the
bounded legacy TLV decoder. Map contracts into SDK plans and reuse the
authenticated wallet connection.

Define the shared runtime version floor and operation-scoped checks.
Taproot Assets v0.8.9 upgrades the transition proof format, and older
releases create proofs that upgraded nodes reject once it activates.
Warn about older backends during daemon initialization while leaving
ordinary payments and offline witness construction available.
Authenticate proof history, asset commitments, group issuances and
Bitcoin inputs before granting on-chain authority. Apply the shared
tapd floor at proof boundaries while keeping offline construction
available.

Distinguish invalid funding candidates from exact outputs waiting on
confirmations or a chain backend. Preserve retryable results when no
candidate is ready. A proof that the wallet failed to export, or node
parameters it failed to return, are reported as they are and never
make a funding request invalid.
Prepare confirmed inputs for native Build and check its allocations,
Bitcoin template, change policy and fee before granting authority.
Verify wallet-funded fees again after native Commit.
Check signing policy and the saved package before using LND, and
accept peer witnesses only for the approved transaction. Preserve
durable recovery while ephemeral signing sessions remain caller-owned.

Separate contract-input signing from finalization so wallet-funded
callers can sign fee inputs before sealing the final anchor transaction.
Bind native compact paths to approved signed parents. After parents
confirm, replace proof metadata with authenticated histories without
altering the transaction or final witnesses.
Build the cooperative transaction that moves a funded contract output
into an HTLC, and validate a peer's version of it before co-signing.
HTLCTerms describes the transfer from one party's own view: the funding
contract, the verified funded output and its proof, the HTLC contract
and the public MuSig2 session context. Both DepositKit and
ReservationKit satisfy the funding contract interface, so the same code
serves a client deposit for Loop In and a server reservation for Loop
Out. FallbackRequest and NewSwap are the Loop In forms, with the terms
taken from the offer and the deposit contract.

The transaction is signed when a swap is set up and may be published
much later, so it does not fix its own fee. It has no output a child
could spend unconfirmed, because the HTLC success leaf carries a
one-block CSV, and a fee spike could otherwise keep it from confirming
before the other party's refund opens. HTLCRequest therefore builds a
zero-fee version 3 transaction that keeps the whole funding anchor
value in the HTLC at output zero and adds a zero-value pay-to-anchor
output at index one. The publisher pays the fee with a child of that
output and submits both as one package. The SDK seals such a package
for external broadcast, so tapd only logs it and the caller submits the
package before FallbackProof or LogAndExport.

ValidateHTLCPackage accepts only the exact transaction HTLCRequest
builds for the party's own terms. It requires the funded output's
script, taproot root and value to match the funding contract and the
proof, binds the committed PSBT's signed previous output to that
output, and rejects a committed asset that carries its own lock time.
The SDK itself refuses to seal a pay-to-anchor parent whose claimed
input value or script differs from the asset input.

Recover contract spends through native SDK packages and exact output
proofs. Preserve the original contract descriptors, asset quantities
and confirmation evidence across claims and refunds. Recognize a
BIP-341 annex when matching the agreed leaf, reject an annex spend from
reconstruction rather than mis-slicing its witness, report a reorg
observed during outcome verification as retryable, and guard the
observed-spend discovery helpers against a chain that returns a block
without the watched spend.

Verify that a caller-provided asset witness commits to its input script
key before declaring it to tapd, so a peer cannot bind a wallet script
key to an unrelated internal key.

Make publication retries consult exact archived proofs and the tapd
transfer log before logging again. Report pending confirmations without
creating duplicate transfer records or repeating their anchor fees.
Report an archived proof that cannot be decoded as a fault of the
archive instead of a pending confirmation. A fully signed fallback
declares the deposit's asset key only when it is logged for the first
time, so that a proof that is archived already stays readable while
tapd's wallet accepts no writes.
VerifyGroupMembership re-encoded a decoded group proof, and the complete
anchor inventory derived an alt leaf's commitment key, both without
validating the asset first. A peer could supply a proof whose asset or
alt leaf omits its script key, panicking the caller inside the re-encode
or the commitment-key derivation before tapd was ever consulted.

Validate each decoded group asset and every disclosed alt leaf before
reuse so malformed evidence is rejected instead of crashing the process.
The contracts fix each refund height but leave their ordering to the
calling swap flow. A flow that gets the ordering wrong can pay an
invoice or reveal a preimage when its own on-chain exit can no longer
confirm before the counterparty's refund opens.

LoopInTimelocks requires the deposit refund to open only after the HTLC
refund plus a recovery window, and the server to still have its
execution window before the HTLC refund. LoopOutTimelocks requires the
fallback to confirm before the reservation refund and the client's
claim before the HTLC refund. ValidatePayment bounds the Lightning
payment against the HTLC expiry for the server of either direction.

The checks are pure and point-in-time: the caller supplies the current
tip and its margins, and repeats the check before each release of
authority.
A swap that settles off chain ends with both parties signing a direct
spend of the deposit or reservation to the party that would have
claimed the HTLC. The funder is paid by then and does not care where
the asset goes, but its signature must not be usable for anything else.
The kit had a check for the HTLC transaction and none for this one, so
every caller had to write it.

ValidateCooperativeSpend accepts a peer's package only if the funded
output is its single input, with no further asset, passive or wallet
input, if the signed transaction commits to the authenticated funding
output's own value and script, and if the signing plan is the funding
contract's cooperative key path under the agreed session context. The
outputs are not constrained.

The check that a funded output really is locked by its funding contract
moves out of the HTLC terms so that both validators share it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

asset loop out Taproot Asset Loop Out work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants