From 0866a74bc8833e1958d4c081244ef7bc0e56b8ae Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 21:14:58 +0100 Subject: [PATCH] tapassets: populate BIP-371 taproot metadata on plain OOR outputs Real tapd proof generation calls AddExclusionProofs on every non-asset P2TR output of an anchor transaction, requiring PSBT_OUT_TAP_INTERNAL_KEY and BIP-371 PSBT_OUT_TAP_TREE to prove that the output commits to no Taproot Asset tree. Plain Ark VTXO outputs on an OOR Ark transaction (sender carrier change and operator float change) are P2TR outputs with two-leaf Ark policy trees, so planOORArk previously caused tapd to fail with missing internal key on output 0. Populate TaprootInternalKey and depth-first BIP-371 TaprootTapTree on every plain P2TR output of the Ark anchor template passed to tap-sdk, and validate upfront that plain P2TR outputs carry a matching policy template before any checkpoint transition is committed. --- tapassets/AGENTS.md | 5 +- tapassets/CLAUDE.md | 5 +- tapassets/oor_transfer.go | 121 +++++++++++++++++++++ tapassets/oor_transfer_test.go | 190 +++++++++++++++++++++++++++++++++ 4 files changed, 319 insertions(+), 2 deletions(-) diff --git a/tapassets/AGENTS.md b/tapassets/AGENTS.md index 16f61901f..b29ef38ba 100644 --- a/tapassets/AGENTS.md +++ b/tapassets/AGENTS.md @@ -173,7 +173,10 @@ Durable journals retain committed packages for restart recovery. when the layout does not settle (`ErrOOROrderingUnresolved` after `maxOOROrderingNonces`). Two outputs may not pay the same value to the same script, where an asset output counts with its uncomposed policy - script. + script. Every plain (non-asset) P2TR output in `OORTransferRequest.Outputs` + must carry a matching `VTXOPolicyTemplate` so `planOORArk` can populate + BIP-371 `TaprootInternalKey` and `TaprootTapTree` on the anchor PSBT for + Taproot exclusion proofs. - **An OOR transfer keeps every new proof path within tap-sdk's bounds.** Each transfer adds two unconfirmed steps, and a merge nests the other VTXOs' paths one level deeper as co-input paths. `BuildOORTransfer` diff --git a/tapassets/CLAUDE.md b/tapassets/CLAUDE.md index 16f61901f..b29ef38ba 100644 --- a/tapassets/CLAUDE.md +++ b/tapassets/CLAUDE.md @@ -173,7 +173,10 @@ Durable journals retain committed packages for restart recovery. when the layout does not settle (`ErrOOROrderingUnresolved` after `maxOOROrderingNonces`). Two outputs may not pay the same value to the same script, where an asset output counts with its uncomposed policy - script. + script. Every plain (non-asset) P2TR output in `OORTransferRequest.Outputs` + must carry a matching `VTXOPolicyTemplate` so `planOORArk` can populate + BIP-371 `TaprootInternalKey` and `TaprootTapTree` on the anchor PSBT for + Taproot exclusion proofs. - **An OOR transfer keeps every new proof path within tap-sdk's bounds.** Each transfer adds two unconfirmed steps, and a merge nests the other VTXOs' paths one level deeper as co-input paths. `BuildOORTransfer` diff --git a/tapassets/oor_transfer.go b/tapassets/oor_transfer.go index cdba83608..f1aee3e2d 100644 --- a/tapassets/oor_transfer.go +++ b/tapassets/oor_transfer.go @@ -8,6 +8,7 @@ import ( "math" "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" @@ -344,6 +345,11 @@ func (r *OORTransferRequest) validate() error { if err := addOutput(output.Value, output.PkScript); err != nil { return err } + if _, _, err := plainOutputTaprootMetadata( + *output, + ); err != nil { + return fmt.Errorf("output %d: %w", idx, err) + } } return nil @@ -662,6 +668,27 @@ func planOORArk(req OORTransferRequest, nonce int, }) } + // Populate BIP-371 Taproot internal key and tap tree on every plain + // P2TR output so the asset engine can construct Taproot exclusion + // proofs when committing the Ark transaction. + for idx := range req.Outputs { + plain := &req.Outputs[idx] + internalKey, tapTree, err := plainOutputTaprootMetadata(*plain) + if err != nil { + return nil, fmt.Errorf("output %d: %w", idx, err) + } + if len(internalKey) == 0 { + continue + } + + index, err := oortx.RecipientOutputIndex(recipients, *plain) + if err != nil { + return nil, fmt.Errorf("output %d: %w", idx, err) + } + template.Outputs[index].TaprootInternalKey = internalKey + template.Outputs[index].TaprootTapTree = tapTree + } + anchorBytes, err := psbtutil.Serialize(template) if err != nil { return nil, err @@ -1223,6 +1250,100 @@ func policyAnchor(encoded []byte) (TreeLeafAnchor, error) { }, nil } +// plainOutputTaprootMetadata derives the BIP-371 PSBT Taproot internal key and +// depth-first tap tree for a plain (non-asset) P2TR output from its Ark policy +// template. Non-P2TR outputs need no exclusion proof metadata and return nil. +func plainOutputTaprootMetadata(output oortx.RecipientOutput) ([]byte, []byte, + error) { + + if !txscript.IsPayToTaproot(output.PkScript) { + return nil, nil, nil + } + if len(output.VTXOPolicyTemplate) == 0 { + return nil, nil, fmt.Errorf("plain P2TR output requires a " + + "policy template for taproot exclusion proof") + } + + template, err := arkscript.DecodePolicyTemplate( + output.VTXOPolicyTemplate, + ) + if err != nil { + return nil, nil, fmt.Errorf("decode plain output policy: %w", + err) + } + policy, err := template.Compile() + if err != nil { + return nil, nil, fmt.Errorf("compile plain output policy: %w", + err) + } + expectedScript, err := template.PkScript() + if err != nil { + return nil, nil, fmt.Errorf("derive plain output script: %w", + err) + } + if !bytes.Equal(expectedScript, output.PkScript) { + return nil, nil, fmt.Errorf("plain output policy script does " + + "not match pkScript") + } + + tapTree, err := encodeBIP371TapTree(policy) + if err != nil { + return nil, nil, fmt.Errorf("encode plain output BIP-371 tap "+ + "tree: %w", err) + } + + return schnorr.SerializePubKey(policy.InternalKey), tapTree, nil +} + +// encodeBIP371TapTree serializes a compiled Ark policy's script tree in the +// BIP-371 PSBT_OUT_TAP_TREE depth-first tuple format +// (depth || leaf_version || compact_size(script) || script). +func encodeBIP371TapTree(policy *arkscript.CompiledPolicy) ([]byte, error) { + if policy == nil || len(policy.Leaves) == 0 { + return nil, fmt.Errorf("compiled policy has no leaves") + } + + var buf bytes.Buffer + for idx, leaf := range policy.Leaves { + info, err := policy.SpendInfo(idx) + if err != nil { + return nil, fmt.Errorf("leaf %d spend info: %w", idx, + err) + } + cb, err := txscript.ParseControlBlock(info.ControlBlock) + if err != nil { + return nil, fmt.Errorf("leaf %d control block: %w", idx, + err) + } + if len(cb.InclusionProof)%chainhash.HashSize != 0 { + return nil, fmt.Errorf("leaf %d invalid inclusion "+ + "proof length %d", idx, len(cb.InclusionProof)) + } + depth := len(cb.InclusionProof) / chainhash.HashSize + if depth > txscript.ControlBlockMaxNodeCount { + return nil, fmt.Errorf("leaf %d depth %d exceeds "+ + "maximum %d", idx, depth, + txscript.ControlBlockMaxNodeCount) + } + + buf.WriteByte(byte(depth)) + buf.WriteByte(byte(leaf.Leaf.LeafVersion)) + err = wire.WriteVarInt( + &buf, 0, + uint64( + len(leaf.Leaf.Script), + ), + ) + if err != nil { + return nil, fmt.Errorf("leaf %d script length: %w", idx, + err) + } + buf.Write(leaf.Leaf.Script) + } + + return buf.Bytes(), nil +} + // composedPolicyScript returns the script of the policy leaves composed with // an asset root. func composedPolicyScript(internalKey *btcec.PublicKey, diff --git a/tapassets/oor_transfer_test.go b/tapassets/oor_transfer_test.go index 91431567c..2a00bdd32 100644 --- a/tapassets/oor_transfer_test.go +++ b/tapassets/oor_transfer_test.go @@ -5,13 +5,16 @@ import ( "context" "crypto/sha256" "fmt" + "io" "slices" "strings" "testing" "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" tapsdk "github.com/lightninglabs/tap-sdk" @@ -1028,3 +1031,190 @@ func TestCheckProofPathBounds(t *testing.T) { }) } } + +// TestBuildOORTransferPlainOutputExclusionMetadata verifies that planOORArk +// populates BIP-371 Taproot internal key and depth-first tap tree metadata on +// every plain P2TR output of the Ark anchor PSBT so the asset engine can +// generate Taproot exclusion proofs, and rejects plain P2TR outputs that omit +// or mismatch their policy template. +func TestBuildOORTransferPlainOutputExclusionMetadata(t *testing.T) { + t.Parallel() + + f := newOORFixture(t) + driver := &fakeOORDriver{} + req := f.request(t) + + _, err := buildOORTransfer(t.Context(), driver, req) + require.NoError(t, err) + require.Len(t, driver.requests, 2) + + arkReq := driver.requests[1] + arkPkt, err := psbt.NewFromRawBytes( + bytes.NewReader(arkReq.AnchorPSBT), false, + ) + require.NoError(t, err) + + assetIndices := make(map[uint32]struct{}, len(arkReq.Outputs)) + for _, out := range arkReq.Outputs { + assetIndices[out.AnchorOutputIndex] = struct{}{} + } + + var plainP2TRCount int + for idx, txOut := range arkPkt.UnsignedTx.TxOut { + if _, isAsset := assetIndices[uint32(idx)]; isAsset { + continue + } + if !txscript.IsPayToTaproot(txOut.PkScript) { + require.Empty(t, arkPkt.Outputs[idx].TaprootInternalKey) + require.Empty(t, arkPkt.Outputs[idx].TaprootTapTree) + continue + } + + plainP2TRCount++ + pOut := arkPkt.Outputs[idx] + require.Len(t, pOut.TaprootInternalKey, schnorr.PubKeyBytesLen) + require.NotEmpty(t, pOut.TaprootTapTree) + + internalKey, err := schnorr.ParsePubKey(pOut.TaprootInternalKey) + require.NoError(t, err) + + rootHash := parseTestBIP371TapTreeRoot(t, pOut.TaprootTapTree) + outputKey := txscript.ComputeTaprootOutputKey( + internalKey, rootHash[:], + ) + wantScript, err := txscript.PayToTaprootScript(outputKey) + require.NoError(t, err) + require.Equal(t, txOut.PkScript, wantScript) + } + require.Equal(t, len(req.Outputs), plainP2TRCount) + + // Missing policy template on a plain P2TR output fails before any + // checkpoint commit. + missingPolicy := f.request(t) + missingPolicy.Outputs[0].VTXOPolicyTemplate = nil + missingDriver := &fakeOORDriver{} + _, err = buildOORTransfer(t.Context(), missingDriver, missingPolicy) + require.ErrorContains(t, err, "requires a policy template") + require.Empty(t, missingDriver.requests) + + // Mismatched policy template on a plain P2TR output fails before any + // checkpoint commit. + wrongPolicy := f.request(t) + wrongPolicy.Outputs[0].VTXOPolicyTemplate = + wrongPolicy.Outputs[1].VTXOPolicyTemplate + wrongDriver := &fakeOORDriver{} + _, err = buildOORTransfer(t.Context(), wrongDriver, wrongPolicy) + require.ErrorContains(t, err, "does not match pkScript") + require.Empty(t, wrongDriver.requests) + + // Non-P2TR plain outputs (e.g. P2WPKH) do not require a policy + // template and receive no Taproot exclusion metadata. + nonTaproot := f.request(t) + p2wpkh := append([]byte{txscript.OP_0, 0x14}, make([]byte, 20)...) + nonTaproot.Outputs[0] = oortx.RecipientOutput{ + PkScript: p2wpkh, + Value: 1_000, + } + nonTaprootDriver := &fakeOORDriver{} + _, err = buildOORTransfer(t.Context(), nonTaprootDriver, nonTaproot) + require.NoError(t, err) + nonTaprootPkt, err := psbt.NewFromRawBytes( + bytes.NewReader(nonTaprootDriver.requests[1].AnchorPSBT), false, + ) + require.NoError(t, err) + var sawP2WPKH bool + for idx, txOut := range nonTaprootPkt.UnsignedTx.TxOut { + if !bytes.Equal(txOut.PkScript, p2wpkh) { + continue + } + sawP2WPKH = true + require.Empty(t, nonTaprootPkt.Outputs[idx].TaprootInternalKey) + require.Empty(t, nonTaprootPkt.Outputs[idx].TaprootTapTree) + } + require.True(t, sawP2WPKH) +} + +// TestEncodeBIP371TapTreeShapes verifies that encodeBIP371TapTree reproduces +// arkscript.BuildTree's root hash for 1, 2, 3, and 5 leaves. +func TestEncodeBIP371TapTreeShapes(t *testing.T) { + t.Parallel() + + for _, leafCount := range []int{1, 2, 3, 5} { + leaves := make([]arkscript.PolicyLeaf, leafCount) + for i := range leaves { + leaves[i] = arkscript.PolicyLeaf{ + Leaf: txscript.NewBaseTapLeaf( + []byte{txscript.OP_1 + byte(i)}, + ), + } + } + compiled, err := arkscript.BuildTree( + leaves, &arkscript.ARKNUMSKey, + ) + require.NoError(t, err) + + encoded, err := encodeBIP371TapTree(compiled) + require.NoError(t, err) + + gotRoot := parseTestBIP371TapTreeRoot(t, encoded) + require.Equal( + t, compiled.RootHash, gotRoot[:], "leafCount=%d", + leafCount, + ) + } +} + +// parseTestBIP371TapTreeRoot decodes a BIP-371 PSBT_OUT_TAP_TREE blob using +// the exact depth-first tuple grammar expected by Taproot exclusion proof +// builders and returns the reconstructed Taproot merkle root. +func parseTestBIP371TapTreeRoot(t *testing.T, encoded []byte) chainhash.Hash { + t.Helper() + + type bip371Leaf struct { + depth uint8 + leaf txscript.TapLeaf + } + + r := bytes.NewReader(encoded) + var leaves []bip371Leaf + for r.Len() > 0 { + depth, err := r.ReadByte() + require.NoError(t, err) + version, err := r.ReadByte() + require.NoError(t, err) + scriptLen, err := wire.ReadVarInt(r, 0) + require.NoError(t, err) + script := make([]byte, int(scriptLen)) + _, err = io.ReadFull(r, script) + require.NoError(t, err) + + leaves = append(leaves, bip371Leaf{ + depth: depth, + leaf: txscript.NewTapLeaf( + txscript.TapscriptLeafVersion(version), script, + ), + }) + } + require.NotEmpty(t, leaves) + + next := 0 + var parseNode func(depth uint8) txscript.TapNode + parseNode = func(depth uint8) txscript.TapNode { + require.Less(t, next, len(leaves)) + if leaves[next].depth == depth { + leaf := leaves[next].leaf + next++ + + return leaf + } + left := parseNode(depth + 1) + right := parseNode(depth + 1) + + return txscript.NewTapBranch(left, right) + } + + root := parseNode(0) + require.Equal(t, len(leaves), next) + + return root.TapHash() +}